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
185 : ArgListEntry(nullptr, Node, Ty) {
186 if (Attr == Attribute::SExt)
187 IsSExt = true;
188 else if (Attr == Attribute::ZExt)
189 IsZExt = true;
190 else if (Attr != Attribute::None)
191 llvm_unreachable("Unexpected attribute left unhandled.");
192}
193
195 unsigned ArgIdx) {
196 setArgListEntryAttributes(*this, *Call, ArgIdx);
197}
198
200 unsigned ArgIdx) {
201 setArgListEntryAttributes(*this, Attrs, ArgIdx);
202}
203
206 const AttributeList &FuncAttrs,
208 // TODO: This assumes each parameter maps to exactly one operand node, which
209 // does not hold when an argument requires type splitting.
210 assert(Ops.size() == FuncTy->getNumParams() &&
211 "argument count does not match the function type");
212 ArgListTy Args;
213 Args.reserve(Ops.size());
214 for (unsigned I = 0, E = FuncTy->getNumParams(); I != E; ++I) {
215 ArgListEntry Entry(Ops[I], FuncTy->getParamType(I));
216 Entry.setAttributes(FuncAttrs, I);
217 Args.push_back(Entry);
218 }
219 return Args;
220}
221
222/// Generate a libcall taking the given operands as arguments and returning a
223/// result of type RetVT.
224std::pair<SDValue, SDValue>
225TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl,
227 MakeLibCallOptions CallOptions, const SDLoc &dl,
228 SDValue InChain) const {
229 if (LibcallImpl == RTLIB::Unsupported)
230 reportFatalInternalError("unsupported library call operation");
231
232 if (!InChain)
233 InChain = DAG.getEntryNode();
234
236 Args.reserve(Ops.size());
237
238 ArrayRef<Type *> OpsTypeOverrides = CallOptions.OpsTypeOverrides;
239 for (unsigned i = 0; i < Ops.size(); ++i) {
240 SDValue NewOp = Ops[i];
241 Type *Ty = i < OpsTypeOverrides.size() && OpsTypeOverrides[i]
242 ? OpsTypeOverrides[i]
243 : NewOp.getValueType().getTypeForEVT(*DAG.getContext());
244 TargetLowering::ArgListEntry Entry(NewOp, Ty);
245 if (CallOptions.IsSoften)
246 Entry.OrigTy =
247 CallOptions.OpsVTBeforeSoften[i].getTypeForEVT(*DAG.getContext());
248
249 Entry.IsSExt =
250 shouldSignExtendTypeInLibCall(Entry.Ty, CallOptions.IsSigned);
251 Entry.IsZExt = !Entry.IsSExt;
252
253 if (CallOptions.IsSoften &&
255 Entry.IsSExt = Entry.IsZExt = false;
256 }
257 Args.push_back(Entry);
258 }
259
260 SDValue Callee =
261 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
262
263 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
264 Type *OrigRetTy = RetTy;
266 bool signExtend = shouldSignExtendTypeInLibCall(RetTy, CallOptions.IsSigned);
267 bool zeroExtend = !signExtend;
268
269 if (CallOptions.IsSoften) {
270 OrigRetTy = CallOptions.RetVTBeforeSoften.getTypeForEVT(*DAG.getContext());
272 signExtend = zeroExtend = false;
273 }
274
275 CLI.setDebugLoc(dl)
276 .setChain(InChain)
277 .setLibCallee(getLibcallImplCallingConv(LibcallImpl), RetTy, OrigRetTy,
278 Callee, std::move(Args))
279 .setNoReturn(CallOptions.DoesNotReturn)
282 .setSExtResult(signExtend)
283 .setZExtResult(zeroExtend);
284 return LowerCallTo(CLI);
285}
286
288 LLVMContext &Context, std::vector<EVT> &MemOps, unsigned Limit,
289 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
290 const AttributeList &FuncAttributes, EVT *LargestVT) const {
291 EVT VT = getOptimalMemOpType(Context, Op, FuncAttributes);
292
293 if (VT == MVT::Other) {
294 // Use the largest integer type whose alignment constraints are satisfied.
295 VT = MVT::LAST_INTEGER_VALUETYPE;
296 if (Op.isFixedDstAlign()) {
297 bool LoadsFromSrc = Op.isMemcpyOrMemmove() && !Op.isMemcpyStrSrc();
298 while (VT != MVT::i8) {
299 unsigned VTSize = VT.getSizeInBits() / 8;
300 bool DstOk =
301 Op.getDstAlign() >= VTSize ||
302 allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign());
303 bool SrcOk =
304 !LoadsFromSrc || Op.getSrcAlign() >= VTSize ||
305 allowsMisalignedMemoryAccesses(VT, SrcAS, Op.getSrcAlign());
306 if (DstOk && SrcOk)
307 break;
309 }
310 }
311 assert(VT.isInteger());
312
313 // Find the largest legal integer type.
314 MVT LVT = MVT::LAST_INTEGER_VALUETYPE;
315 while (!isTypeLegal(LVT))
316 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
317 assert(LVT.isInteger());
318
319 // If the type we've chosen is larger than the largest legal integer type
320 // then use the largest legal type.
321 if (VT.bitsGT(LVT))
322 VT = LVT;
323 }
324
325 unsigned NumMemOps = 0;
326 uint64_t Size = Op.size();
327 while (Size) {
328 unsigned VTSize = VT.getSizeInBits() / 8;
329 while (VTSize > Size) {
330 // For now, only use non-vector load / store's for the left-over pieces.
331 EVT NewVT = VT;
332 unsigned NewVTSize;
333
334 bool Found = false;
335 if (VT.isVector() || VT.isFloatingPoint()) {
336 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
339 Found = true;
340 else if (NewVT == MVT::i64 &&
342 isSafeMemOpType(MVT::f64)) {
343 // i64 is usually not legal on 32-bit targets, but f64 may be.
344 NewVT = MVT::f64;
345 Found = true;
346 }
347 }
348
349 if (!Found) {
350 do {
351 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
352 if (NewVT == MVT::i8)
353 break;
354 } while (!isSafeMemOpType(NewVT.getSimpleVT()));
355 }
356 NewVTSize = NewVT.getSizeInBits() / 8;
357
358 // If the new VT cannot cover all of the remaining bits, then consider
359 // issuing a (or a pair of) unaligned and overlapping load / store.
360 unsigned Fast;
361 if (NumMemOps && !Op.isVolatile() && NewVTSize < Size &&
363 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
365 Fast)
366 VTSize = Size;
367 else {
368 VT = NewVT;
369 VTSize = NewVTSize;
370 }
371 }
372
373 if (++NumMemOps > Limit)
374 return false;
375
376 MemOps.push_back(VT);
377 Size -= VTSize;
378 }
379
380 return true;
381}
382
383/// Soften the operands of a comparison. This code is shared among BR_CC,
384/// SELECT_CC, and SETCC handlers.
386 SDValue &NewLHS, SDValue &NewRHS,
387 ISD::CondCode &CCCode,
388 const SDLoc &dl, const SDValue OldLHS,
389 const SDValue OldRHS) const {
390 SDValue Chain;
391 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS,
392 OldRHS, Chain);
393}
394
395/// Select the libcall and the condition code to test its result against 0 for
396/// an ordered floating-point compare. \p BoolLC is the boolean helper (result
397/// is 0/1). \p TriStateLC is the per-predicate three-way helper and \p
398/// GenericLC the generic single-symbol three-way helper (both return -1/0/1,
399/// tested against 0 with \p TriStateCC). The boolean form is preferred, then
400/// the per-predicate three-way, then the generic three-way.
401static std::pair<RTLIB::Libcall, ISD::CondCode>
402selectFPCmpLibcall(const LibcallLoweringInfo &Libcalls, RTLIB::Libcall BoolLC,
403 RTLIB::Libcall TriStateLC, RTLIB::Libcall GenericLC,
404 ISD::CondCode TriStateCC) {
405 if (Libcalls.getLibcallImpl(BoolLC) != RTLIB::Unsupported)
406 return {BoolLC, ISD::SETNE};
407 if (Libcalls.getLibcallImpl(TriStateLC) != RTLIB::Unsupported)
408 return {TriStateLC, TriStateCC};
409 return {GenericLC, TriStateCC};
410}
411
413 SDValue &NewLHS, SDValue &NewRHS,
414 ISD::CondCode &CCCode,
415 const SDLoc &dl, const SDValue OldLHS,
416 const SDValue OldRHS,
417 SDValue &Chain,
418 bool IsSignaling) const {
419 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc
420 // not supporting it. We can update this code when libgcc provides such
421 // functions.
422
423 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
424 && "Unsupported setcc type!");
425
426 // Expand into one or more soft-fp libcall(s).
427 ISD::CondCode OrigCCCode = CCCode;
428 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
430 bool ShouldInvertCC = false;
431
432 // Expand a compare libcall family name (e.g. OEQ, FCMP3_PRED_OEQ) to the
433 // RTLIB::Libcall for VT.
434#define FP_CMP_LIBCALL(BASE) \
435 RTLIB::getFPLibCall(VT, RTLIB::BASE##_F32, RTLIB::BASE##_F64, \
436 RTLIB::UNKNOWN_LIBCALL, RTLIB::BASE##_F128, \
437 RTLIB::BASE##_PPCF128)
438
439 switch (CCCode) {
440 case ISD::SETEQ:
441 case ISD::SETOEQ:
442 std::tie(LC1, CC1) = selectFPCmpLibcall(
443 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ), FP_CMP_LIBCALL(FCMP3_PRED_OEQ),
444 FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
445 break;
446 case ISD::SETNE:
447 case ISD::SETUNE:
448 std::tie(LC1, CC1) = selectFPCmpLibcall(
449 DAG.getLibcalls(), FP_CMP_LIBCALL(UNE), FP_CMP_LIBCALL(FCMP3_PRED_UNE),
450 FP_CMP_LIBCALL(FCMP3), ISD::SETNE);
451 // Some ABIs (e.g. AEABI) provide neither a not-equal nor a three-way
452 // compare; obtain not-equal (UNE = !OEQ) by inverting ordered-equal.
453 if (DAG.getLibcalls().getLibcallImpl(LC1) == RTLIB::Unsupported) {
454 std::tie(LC1, CC1) = selectFPCmpLibcall(
455 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ),
456 FP_CMP_LIBCALL(FCMP3_PRED_OEQ), FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
457 ShouldInvertCC = true;
458 }
459 break;
460 case ISD::SETGE:
461 case ISD::SETOGE:
462 std::tie(LC1, CC1) = selectFPCmpLibcall(
463 DAG.getLibcalls(), FP_CMP_LIBCALL(OGE), FP_CMP_LIBCALL(FCMP3_PRED_OGE),
464 FP_CMP_LIBCALL(FCMP3), ISD::SETGE);
465 break;
466 case ISD::SETLT:
467 case ISD::SETOLT:
468 std::tie(LC1, CC1) = selectFPCmpLibcall(
469 DAG.getLibcalls(), FP_CMP_LIBCALL(OLT), FP_CMP_LIBCALL(FCMP3_PRED_OLT),
470 FP_CMP_LIBCALL(FCMP3), ISD::SETLT);
471 break;
472 case ISD::SETLE:
473 case ISD::SETOLE:
474 std::tie(LC1, CC1) = selectFPCmpLibcall(
475 DAG.getLibcalls(), FP_CMP_LIBCALL(OLE), FP_CMP_LIBCALL(FCMP3_PRED_OLE),
476 FP_CMP_LIBCALL(FCMP3), ISD::SETLE);
477 break;
478 case ISD::SETGT:
479 case ISD::SETOGT:
480 std::tie(LC1, CC1) = selectFPCmpLibcall(
481 DAG.getLibcalls(), FP_CMP_LIBCALL(OGT), FP_CMP_LIBCALL(FCMP3_PRED_OGT),
482 FP_CMP_LIBCALL(FCMP3), ISD::SETGT);
483 break;
484 case ISD::SETO:
485 ShouldInvertCC = true;
486 [[fallthrough]];
487 case ISD::SETUO:
488 // Unordered is a boolean everywhere (__unordXf2 returns 0/1).
489 LC1 = FP_CMP_LIBCALL(UO);
490 CC1 = ISD::SETNE;
491 break;
492 case ISD::SETONE:
493 // SETONE = O && UNE
494 ShouldInvertCC = true;
495 [[fallthrough]];
496 case ISD::SETUEQ:
497 LC1 = FP_CMP_LIBCALL(UO);
498 CC1 = ISD::SETNE;
499 std::tie(LC2, CC2) = selectFPCmpLibcall(
500 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ), FP_CMP_LIBCALL(FCMP3_PRED_OEQ),
501 FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
502 break;
503 default:
504 // Invert CC for unordered comparisons, handled by the ordered inverse.
505 ShouldInvertCC = true;
506 switch (CCCode) {
507 case ISD::SETULT:
508 std::tie(LC1, CC1) = selectFPCmpLibcall(
509 DAG.getLibcalls(), FP_CMP_LIBCALL(OGE),
510 FP_CMP_LIBCALL(FCMP3_PRED_OGE), FP_CMP_LIBCALL(FCMP3), ISD::SETGE);
511 break;
512 case ISD::SETULE:
513 std::tie(LC1, CC1) = selectFPCmpLibcall(
514 DAG.getLibcalls(), FP_CMP_LIBCALL(OGT),
515 FP_CMP_LIBCALL(FCMP3_PRED_OGT), FP_CMP_LIBCALL(FCMP3), ISD::SETGT);
516 break;
517 case ISD::SETUGT:
518 std::tie(LC1, CC1) = selectFPCmpLibcall(
519 DAG.getLibcalls(), FP_CMP_LIBCALL(OLE),
520 FP_CMP_LIBCALL(FCMP3_PRED_OLE), FP_CMP_LIBCALL(FCMP3), ISD::SETLE);
521 break;
522 case ISD::SETUGE:
523 std::tie(LC1, CC1) = selectFPCmpLibcall(
524 DAG.getLibcalls(), FP_CMP_LIBCALL(OLT),
525 FP_CMP_LIBCALL(FCMP3_PRED_OLT), FP_CMP_LIBCALL(FCMP3), ISD::SETLT);
526 break;
527 default:
528 llvm_unreachable("Do not know how to soften this setcc!");
529 }
530 }
531
532#undef FP_CMP_LIBCALL
533
534 // Use the target specific return value for comparison lib calls.
536 SDValue Ops[2] = {NewLHS, NewRHS};
538 EVT OpsVT[2] = { OldLHS.getValueType(),
539 OldRHS.getValueType() };
540 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT);
541
542 auto ReportNoLibcall = [&]() {
543 DAG.getContext()->emitError(
544 Twine("no libcall available to soften floating-point ") +
545 ISD::getCondCodeName(OrigCCCode) + " compare with type " +
546 VT.getEVTString());
547 NewLHS = DAG.getPOISON(RetVT);
548 NewRHS = DAG.getConstant(0, dl, RetVT);
549 CCCode = ISD::SETNE;
550 };
551
552 // Check availability before makeLibCall, which fatally errors otherwise.
553 RTLIB::LibcallImpl LC1Impl = DAG.getLibcalls().getLibcallImpl(LC1);
554 if (LC1Impl == RTLIB::Unsupported) {
555 ReportNoLibcall();
556 return;
557 }
558
559 auto Call = makeLibCall(DAG, LC1Impl, RetVT, Ops, CallOptions, dl, Chain);
560 NewLHS = Call.first;
561 NewRHS = DAG.getConstant(0, dl, RetVT);
562
563 CCCode = CC1;
564 if (ShouldInvertCC) {
565 assert(RetVT.isInteger());
566 CCCode = getSetCCInverse(CCCode, RetVT);
567 }
568
569 if (LC2 == RTLIB::UNKNOWN_LIBCALL) {
570 // Update Chain.
571 Chain = Call.second;
572 } else {
573 RTLIB::LibcallImpl LC2Impl = DAG.getLibcalls().getLibcallImpl(LC2);
574 if (LC2Impl == RTLIB::Unsupported) {
575 ReportNoLibcall();
576 return;
577 }
578
579 assert(CCCode == (ShouldInvertCC ? ISD::SETEQ : ISD::SETNE) &&
580 "unordered call should be simple boolean");
581
582 EVT SetCCVT =
583 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT);
585 NewLHS = DAG.getNode(ISD::AssertZext, dl, RetVT, Call.first,
586 DAG.getValueType(MVT::i1));
587 }
588
589 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode);
590 auto Call2 = makeLibCall(DAG, LC2Impl, RetVT, Ops, CallOptions, dl, Chain);
591 CCCode = CC2;
592 if (ShouldInvertCC)
593 CCCode = getSetCCInverse(CCCode, RetVT);
594 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode);
595 if (Chain)
596 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second,
597 Call2.second);
598 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl,
599 Tmp.getValueType(), Tmp, NewLHS);
600 NewRHS = SDValue();
601 }
602}
603
604/// Return the entry encoding for a jump table in the current function. The
605/// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
607 // In non-pic modes, just use the address of a block.
610
611 // Otherwise, use a label difference.
613}
614
619
620/// This returns the relocation base for the given PIC jumptable, the same as
621/// getPICJumpTableRelocBase, but as an MCExpr.
622const MCExpr *
624 unsigned JTI,MCContext &Ctx) const{
625 // The normal PIC reloc base is the label at the start of the jump table.
626 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
627}
628
630 SDValue Addr, int JTI,
631 SelectionDAG &DAG) const {
632 SDValue Chain = Value;
633 // Jump table debug info is only needed if CodeView is enabled.
635 Chain = DAG.getJumpTableDebugInfo(JTI, Chain, dl);
636 }
637 return DAG.getNode(ISD::BRIND, dl, MVT::Other, Chain, Addr);
638}
639
640bool
642 const TargetMachine &TM = getTargetMachine();
643 const GlobalValue *GV = GA->getGlobal();
644
645 // If the address is not even local to this DSO we will have to load it from
646 // a got and then add the offset.
647 if (!TM.shouldAssumeDSOLocal(GV))
648 return false;
649
650 // If the code is position independent we will have to add a base register.
652 return false;
653
654 // Otherwise we can do it.
655 return true;
656}
657
658//===----------------------------------------------------------------------===//
659// Optimization Methods
660//===----------------------------------------------------------------------===//
661
662/// If the specified instruction has a constant integer operand and there are
663/// bits set in that constant that are not demanded, then clear those bits and
664/// return true.
666 const APInt &DemandedBits,
667 const APInt &DemandedElts,
668 TargetLoweringOpt &TLO) const {
669 SDLoc DL(Op);
670 unsigned Opcode = Op.getOpcode();
671
672 // Early-out if we've ended up calling an undemanded node, leave this to
673 // constant folding.
674 if (DemandedBits.isZero() || DemandedElts.isZero())
675 return false;
676
677 // Do target-specific constant optimization.
678 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
679 return TLO.New.getNode();
680
681 // FIXME: ISD::SELECT, ISD::SELECT_CC
682 switch (Opcode) {
683 default:
684 break;
685 case ISD::XOR:
686 case ISD::AND:
687 case ISD::OR: {
688 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
689 if (!Op1C || Op1C->isOpaque())
690 return false;
691
692 // If this is a 'not' op, don't touch it because that's a canonical form.
693 const APInt &C = Op1C->getAPIntValue();
694 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C))
695 return false;
696
697 if (!C.isSubsetOf(DemandedBits)) {
698 EVT VT = Op.getValueType();
699 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT);
700 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC,
701 Op->getFlags());
702 return TLO.CombineTo(Op, NewOp);
703 }
704
705 break;
706 }
707 }
708
709 return false;
710}
711
713 const APInt &DemandedBits,
714 TargetLoweringOpt &TLO) const {
715 EVT VT = Op.getValueType();
716 APInt DemandedElts = VT.isVector()
718 : APInt(1, 1);
719 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO);
720}
721
722/// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
723/// This uses isTruncateFree/isZExtFree and ANY_EXTEND for the widening cast,
724/// but it could be generalized for targets with other types of implicit
725/// widening casts.
727 const APInt &DemandedBits,
728 TargetLoweringOpt &TLO) const {
729 assert(Op.getNumOperands() == 2 &&
730 "ShrinkDemandedOp only supports binary operators!");
731 assert(Op.getNode()->getNumValues() == 1 &&
732 "ShrinkDemandedOp only supports nodes with one result!");
733
734 EVT VT = Op.getValueType();
735 SelectionDAG &DAG = TLO.DAG;
736 SDLoc dl(Op);
737
738 // Early return, as this function cannot handle vector types.
739 if (VT.isVector())
740 return false;
741
742 assert(Op.getOperand(0).getValueType().getScalarSizeInBits() == BitWidth &&
743 Op.getOperand(1).getValueType().getScalarSizeInBits() == BitWidth &&
744 "ShrinkDemandedOp only supports operands that have the same size!");
745
746 // Don't do this if the node has another user, which may require the
747 // full value.
748 if (!Op.getNode()->hasOneUse())
749 return false;
750
751 // Search for the smallest integer type with free casts to and from
752 // Op's type. For expedience, just check power-of-2 integer types.
753 unsigned DemandedSize = DemandedBits.getActiveBits();
754 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize);
755 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
756 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
757 if (isTruncateFree(Op, SmallVT) && isZExtFree(SmallVT, VT)) {
758 // We found a type with free casts.
759
760 // If the operation has the 'disjoint' flag, then the
761 // operands on the new node are also disjoint.
762 SDNodeFlags Flags(Op->getFlags().hasDisjoint() ? SDNodeFlags::Disjoint
764 unsigned Opcode = Op.getOpcode();
765 if (Opcode == ISD::PTRADD) {
766 // It isn't a ptradd anymore if it doesn't operate on the entire
767 // pointer.
768 Opcode = ISD::ADD;
769 }
770 SDValue X = DAG.getNode(
771 Opcode, dl, SmallVT,
772 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
773 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)), Flags);
774 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
775 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, VT, X);
776 return TLO.CombineTo(Op, Z);
777 }
778 }
779 return false;
780}
781
783 DAGCombinerInfo &DCI) const {
784 SelectionDAG &DAG = DCI.DAG;
785 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
786 !DCI.isBeforeLegalizeOps());
788
789 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
790 if (Simplified) {
791 DCI.AddToWorklist(Op.getNode());
793 }
794 return Simplified;
795}
796
798 const APInt &DemandedElts,
799 DAGCombinerInfo &DCI) const {
800 SelectionDAG &DAG = DCI.DAG;
801 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
802 !DCI.isBeforeLegalizeOps());
804
805 bool Simplified =
806 SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO);
807 if (Simplified) {
808 DCI.AddToWorklist(Op.getNode());
810 }
811 return Simplified;
812}
813
817 unsigned Depth,
818 bool AssumeSingleUse) const {
819 EVT VT = Op.getValueType();
820
821 // Since the number of lanes in a scalable vector is unknown at compile time,
822 // we track one bit which is implicitly broadcast to all lanes. This means
823 // that all lanes in a scalable vector are considered demanded.
824 APInt DemandedElts = VT.isFixedLengthVector()
826 : APInt(1, 1);
827 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
828 AssumeSingleUse);
829}
830
831// TODO: Under what circumstances can we create nodes? Constant folding?
833 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
834 SelectionDAG &DAG, unsigned Depth) const {
835 EVT VT = Op.getValueType();
836
837 // Limit search depth.
839 return SDValue();
840
841 // Ignore UNDEFs.
842 if (Op.isUndef())
843 return SDValue();
844
845 // Not demanding any bits/elts from Op.
846 if (DemandedBits == 0 || DemandedElts == 0)
847 return DAG.getUNDEF(VT);
848
849 bool IsLE = DAG.getDataLayout().isLittleEndian();
850 unsigned NumElts = DemandedElts.getBitWidth();
851 unsigned BitWidth = DemandedBits.getBitWidth();
852 KnownBits LHSKnown, RHSKnown;
853 switch (Op.getOpcode()) {
854 case ISD::Constant: {
855 const APInt &Value = Op->getAsAPIntVal();
856 if (!Value.isZero() && (Value & DemandedBits).isZero())
857 return DAG.getConstant(0, SDLoc(Op), VT);
858 break;
859 }
860 case ISD::BITCAST: {
861 if (VT.isScalableVector())
862 return SDValue();
863
864 SDValue Src = peekThroughBitcasts(Op.getOperand(0));
865 EVT SrcVT = Src.getValueType();
866 EVT DstVT = Op.getValueType();
867 if (SrcVT == DstVT)
868 return Src;
869
870 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
871 unsigned NumDstEltBits = DstVT.getScalarSizeInBits();
872 if (NumSrcEltBits == NumDstEltBits)
874 Src, DemandedBits, DemandedElts, DAG, Depth + 1))
875 return DAG.getBitcast(DstVT, V);
876
877 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) {
878 unsigned Scale = NumDstEltBits / NumSrcEltBits;
879 unsigned NumSrcElts = SrcVT.getVectorNumElements();
880 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
881 for (unsigned i = 0; i != Scale; ++i) {
882 unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
883 unsigned BitOffset = EltOffset * NumSrcEltBits;
884 DemandedSrcBits |= DemandedBits.extractBits(NumSrcEltBits, BitOffset);
885 }
886 // Recursive calls below may turn not demanded elements into poison, so we
887 // need to demand all smaller source elements that maps to a demanded
888 // destination element.
889 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
890
892 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
893 return DAG.getBitcast(DstVT, V);
894 }
895
896 // TODO - bigendian once we have test coverage.
897 if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) {
898 unsigned Scale = NumSrcEltBits / NumDstEltBits;
899 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
900 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
901 APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
902 for (unsigned i = 0; i != NumElts; ++i)
903 if (DemandedElts[i]) {
904 unsigned Offset = (i % Scale) * NumDstEltBits;
905 DemandedSrcBits.insertBits(DemandedBits, Offset);
906 DemandedSrcElts.setBit(i / Scale);
907 }
908
910 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
911 return DAG.getBitcast(DstVT, V);
912 }
913
914 break;
915 }
917 if (!VT.isScalableVector() && !DemandedElts[0])
918 return DAG.getPOISON(VT);
919 break;
920 }
921 case ISD::AND: {
922 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
923 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
924
925 // If all of the demanded bits are known 1 on one side, return the other.
926 // These bits cannot contribute to the result of the 'and' in this
927 // context.
928 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
929 return Op.getOperand(0);
930 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
931 return Op.getOperand(1);
932 break;
933 }
934 case ISD::OR: {
935 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
936 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
937
938 // If all of the demanded bits are known zero on one side, return the
939 // other. These bits cannot contribute to the result of the 'or' in this
940 // context.
941 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
942 return Op.getOperand(0);
943 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
944 return Op.getOperand(1);
945 break;
946 }
947 case ISD::XOR: {
948 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
949 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
950
951 // If all of the demanded bits are known zero on one side, return the
952 // other.
953 if (DemandedBits.isSubsetOf(RHSKnown.Zero))
954 return Op.getOperand(0);
955 if (DemandedBits.isSubsetOf(LHSKnown.Zero))
956 return Op.getOperand(1);
957 break;
958 }
959 case ISD::ADD:
960 case ISD::MUL:
961 case ISD::SMIN:
962 case ISD::SMAX:
963 case ISD::UMIN:
964 case ISD::UMAX: {
965 if (DAG.isIdentityElement(Op.getOpcode(), Op->getFlags(), Op.getOperand(1),
966 DemandedElts, 1, Depth + 1))
967 return Op.getOperand(0);
968
969 if (DAG.isIdentityElement(Op.getOpcode(), Op->getFlags(), Op.getOperand(0),
970 DemandedElts, 0, Depth + 1))
971 return Op.getOperand(1);
972 break;
973 }
974 case ISD::SHL: {
975 // If we are only demanding sign bits then we can use the shift source
976 // directly.
977 if (std::optional<unsigned> MaxSA =
978 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
979 SDValue Op0 = Op.getOperand(0);
980 unsigned ShAmt = *MaxSA;
981 unsigned NumSignBits =
982 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
983 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
984 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
985 return Op0;
986 }
987 break;
988 }
989 case ISD::SRL: {
990 // If we are only demanding sign bits then we can use the shift source
991 // directly.
992 if (std::optional<unsigned> MaxSA =
993 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
994 SDValue Op0 = Op.getOperand(0);
995 unsigned ShAmt = *MaxSA;
996 // Must already be signbits in DemandedBits bounds, and can't demand any
997 // shifted in zeroes.
998 if (DemandedBits.countl_zero() >= ShAmt) {
999 unsigned NumSignBits =
1000 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1001 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits))
1002 return Op0;
1003 }
1004 }
1005 break;
1006 }
1007 case ISD::SETCC: {
1008 SDValue Op0 = Op.getOperand(0);
1009 SDValue Op1 = Op.getOperand(1);
1010 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1011 // If (1) we only need the sign-bit, (2) the setcc operands are the same
1012 // width as the setcc result, and (3) the result of a setcc conforms to 0 or
1013 // -1, we may be able to bypass the setcc.
1014 if (DemandedBits.isSignMask() &&
1018 // If we're testing X < 0, then this compare isn't needed - just use X!
1019 // FIXME: We're limiting to integer types here, but this should also work
1020 // if we don't care about FP signed-zero. The use of SETLT with FP means
1021 // that we don't care about NaNs.
1022 if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
1024 return Op0;
1025 }
1026 break;
1027 }
1029 // If none of the extended bits are demanded, eliminate the sextinreg.
1030 SDValue Op0 = Op.getOperand(0);
1031 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1032 unsigned ExBits = ExVT.getScalarSizeInBits();
1033 if (DemandedBits.getActiveBits() <= ExBits &&
1035 return Op0;
1036 // If the input is already sign extended, just drop the extension.
1037 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1038 if (NumSignBits >= (BitWidth - ExBits + 1))
1039 return Op0;
1040 break;
1041 }
1045 if (VT.isScalableVector())
1046 return SDValue();
1047
1048 // If we only want the lowest element and none of extended bits, then we can
1049 // return the bitcasted source vector.
1050 SDValue Src = Op.getOperand(0);
1051 EVT SrcVT = Src.getValueType();
1052 EVT DstVT = Op.getValueType();
1053 if (IsLE && DemandedElts == 1 &&
1054 DstVT.getSizeInBits() == SrcVT.getSizeInBits() &&
1055 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) {
1056 return DAG.getBitcast(DstVT, Src);
1057 }
1058 break;
1059 }
1061 if (VT.isScalableVector())
1062 return SDValue();
1063
1064 // If we don't demand the inserted element, return the base vector.
1065 SDValue Vec = Op.getOperand(0);
1066 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1067 EVT VecVT = Vec.getValueType();
1068 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
1069 !DemandedElts[CIdx->getZExtValue()])
1070 return Vec;
1071 break;
1072 }
1073 case ISD::INSERT_SUBVECTOR: {
1074 if (VT.isScalableVector())
1075 return SDValue();
1076
1077 SDValue Vec = Op.getOperand(0);
1078 SDValue Sub = Op.getOperand(1);
1079 uint64_t Idx = Op.getConstantOperandVal(2);
1080 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1081 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1082 // If we don't demand the inserted subvector, return the base vector.
1083 if (DemandedSubElts == 0)
1084 return Vec;
1085 break;
1086 }
1087 case ISD::VECTOR_SHUFFLE: {
1088 assert(!VT.isScalableVector());
1089 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1090
1091 // If all the demanded elts are from one operand and are inline,
1092 // then we can use the operand directly.
1093 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true;
1094 for (unsigned i = 0; i != NumElts; ++i) {
1095 int M = ShuffleMask[i];
1096 if (M < 0 || !DemandedElts[i])
1097 continue;
1098 AllUndef = false;
1099 IdentityLHS &= (M == (int)i);
1100 IdentityRHS &= ((M - NumElts) == i);
1101 }
1102
1103 if (AllUndef)
1104 return DAG.getUNDEF(Op.getValueType());
1105 if (IdentityLHS)
1106 return Op.getOperand(0);
1107 if (IdentityRHS)
1108 return Op.getOperand(1);
1109 break;
1110 }
1111 default:
1112 // TODO: Probably okay to remove after audit; here to reduce change size
1113 // in initial enablement patch for scalable vectors
1114 if (VT.isScalableVector())
1115 return SDValue();
1116
1117 if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
1119 Op, DemandedBits, DemandedElts, DAG, Depth))
1120 return V;
1121 break;
1122 }
1123 return SDValue();
1124}
1125
1128 unsigned Depth) const {
1129 EVT VT = Op.getValueType();
1130 // Since the number of lanes in a scalable vector is unknown at compile time,
1131 // we track one bit which is implicitly broadcast to all lanes. This means
1132 // that all lanes in a scalable vector are considered demanded.
1133 APInt DemandedElts = VT.isFixedLengthVector()
1135 : APInt(1, 1);
1136 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
1137 Depth);
1138}
1139
1141 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG,
1142 unsigned Depth) const {
1143 APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits());
1144 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
1145 Depth);
1146}
1147
1148// Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1).
1149// or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1).
1152 const TargetLowering &TLI,
1153 const APInt &DemandedBits,
1154 const APInt &DemandedElts, unsigned Depth) {
1155 assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) &&
1156 "SRL or SRA node is required here!");
1157 // Is the right shift using an immediate value of 1?
1158 ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
1159 if (!N1C || !N1C->isOne())
1160 return SDValue();
1161
1162 // We are looking for an avgfloor
1163 // add(ext, ext)
1164 // or one of these as a avgceil
1165 // add(add(ext, ext), 1)
1166 // add(add(ext, 1), ext)
1167 // add(ext, add(ext, 1))
1168 SDValue Add = Op.getOperand(0);
1169 if (Add.getOpcode() != ISD::ADD)
1170 return SDValue();
1171
1172 SDValue ExtOpA = Add.getOperand(0);
1173 SDValue ExtOpB = Add.getOperand(1);
1174 SDValue Add2;
1175 auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3, SDValue A) {
1176 ConstantSDNode *ConstOp;
1177 if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) &&
1178 ConstOp->isOne()) {
1179 ExtOpA = Op1;
1180 ExtOpB = Op3;
1181 Add2 = A;
1182 return true;
1183 }
1184 if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) &&
1185 ConstOp->isOne()) {
1186 ExtOpA = Op1;
1187 ExtOpB = Op2;
1188 Add2 = A;
1189 return true;
1190 }
1191 return false;
1192 };
1193 bool IsCeil =
1194 (ExtOpA.getOpcode() == ISD::ADD &&
1195 MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB, ExtOpA)) ||
1196 (ExtOpB.getOpcode() == ISD::ADD &&
1197 MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA, ExtOpB));
1198
1199 // If the shift is signed (sra):
1200 // - Needs >= 2 sign bit for both operands.
1201 // - Needs >= 2 zero bits.
1202 // If the shift is unsigned (srl):
1203 // - Needs >= 1 zero bit for both operands.
1204 // - Needs 1 demanded bit zero and >= 2 sign bits.
1205 SelectionDAG &DAG = TLO.DAG;
1206 unsigned ShiftOpc = Op.getOpcode();
1207 bool IsSigned = false;
1208 unsigned KnownBits;
1209 unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth);
1210 unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth);
1211 unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1;
1212 unsigned NumZeroA =
1213 DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros();
1214 unsigned NumZeroB =
1215 DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros();
1216 unsigned NumZero = std::min(NumZeroA, NumZeroB);
1217
1218 switch (ShiftOpc) {
1219 default:
1220 llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG");
1221 case ISD::SRA: {
1222 if (NumZero >= 2 && NumSigned < NumZero) {
1223 IsSigned = false;
1224 KnownBits = NumZero;
1225 break;
1226 }
1227 if (NumSigned >= 1) {
1228 IsSigned = true;
1229 KnownBits = NumSigned;
1230 break;
1231 }
1232 return SDValue();
1233 }
1234 case ISD::SRL: {
1235 if (NumZero >= 1 && NumSigned < NumZero) {
1236 IsSigned = false;
1237 KnownBits = NumZero;
1238 break;
1239 }
1240 if (NumSigned >= 1 && DemandedBits.isSignBitClear()) {
1241 IsSigned = true;
1242 KnownBits = NumSigned;
1243 break;
1244 }
1245 return SDValue();
1246 }
1247 }
1248
1249 unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU)
1250 : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU);
1251
1252 // Find the smallest power-2 type that is legal for this vector size and
1253 // operation, given the original type size and the number of known sign/zero
1254 // bits.
1255 EVT VT = Op.getValueType();
1256 unsigned MinWidth =
1257 std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8);
1258 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), llvm::bit_ceil(MinWidth));
1260 return SDValue();
1261 if (VT.isVector())
1262 NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount());
1263 if (TLO.LegalTypes() && !TLI.isOperationLegal(AVGOpc, NVT)) {
1264 // If we could not transform, and (both) adds are nuw/nsw, we can use the
1265 // larger type size to do the transform.
1266 if (TLO.LegalOperations() && !TLI.isOperationLegal(AVGOpc, VT))
1267 return SDValue();
1268 if (DAG.willNotOverflowAdd(IsSigned, Add.getOperand(0),
1269 Add.getOperand(1)) &&
1270 (!Add2 || DAG.willNotOverflowAdd(IsSigned, Add2.getOperand(0),
1271 Add2.getOperand(1))))
1272 NVT = VT;
1273 else
1274 return SDValue();
1275 }
1276
1277 // Don't create a AVGFLOOR node with a scalar constant unless its legal as
1278 // this is likely to stop other folds (reassociation, value tracking etc.)
1279 if (!IsCeil && !TLI.isOperationLegal(AVGOpc, NVT) &&
1280 (isa<ConstantSDNode>(ExtOpA) || isa<ConstantSDNode>(ExtOpB)))
1281 return SDValue();
1282
1283 SDLoc DL(Op);
1284 SDValue ResultAVG =
1285 DAG.getNode(AVGOpc, DL, NVT, DAG.getExtOrTrunc(IsSigned, ExtOpA, DL, NVT),
1286 DAG.getExtOrTrunc(IsSigned, ExtOpB, DL, NVT));
1287 return DAG.getExtOrTrunc(IsSigned, ResultAVG, DL, VT);
1288}
1289
1290/// Look at Op. At this point, we know that only the OriginalDemandedBits of the
1291/// result of Op are ever used downstream. If we can use this information to
1292/// simplify Op, create a new simplified DAG node and return true, returning the
1293/// original and new nodes in Old and New. Otherwise, analyze the expression and
1294/// return a mask of Known bits for the expression (used to simplify the
1295/// caller). The Known bits may only be accurate for those bits in the
1296/// OriginalDemandedBits and OriginalDemandedElts.
1298 SDValue Op, const APInt &OriginalDemandedBits,
1299 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
1300 unsigned Depth, bool AssumeSingleUse) const {
1301 unsigned BitWidth = OriginalDemandedBits.getBitWidth();
1302 assert(Op.getScalarValueSizeInBits() == BitWidth &&
1303 "Mask size mismatches value type size!");
1304
1305 // Don't know anything.
1307
1308 EVT VT = Op.getValueType();
1309 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
1310 unsigned NumElts = OriginalDemandedElts.getBitWidth();
1311 assert((!VT.isFixedLengthVector() || NumElts == VT.getVectorNumElements()) &&
1312 "Unexpected vector size");
1313
1314 APInt DemandedBits = OriginalDemandedBits;
1315 APInt DemandedElts = OriginalDemandedElts;
1316 SDLoc dl(Op);
1317
1318 // Undef operand.
1319 if (Op.isUndef())
1320 return false;
1321
1322 // We can't simplify target constants.
1323 if (Op.getOpcode() == ISD::TargetConstant)
1324 return false;
1325
1326 if (Op.getOpcode() == ISD::Constant) {
1327 // We know all of the bits for a constant!
1328 Known = KnownBits::makeConstant(Op->getAsAPIntVal());
1329 return false;
1330 }
1331
1332 if (Op.getOpcode() == ISD::ConstantFP) {
1333 // We know all of the bits for a floating point constant!
1335 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt());
1336 return false;
1337 }
1338
1339 // Other users may use these bits.
1340 bool HasMultiUse = false;
1341 if (!AssumeSingleUse && !Op.getNode()->hasOneUse()) {
1343 // Limit search depth.
1344 return false;
1345 }
1346 // Allow multiple uses, just set the DemandedBits/Elts to all bits.
1348 DemandedElts = APInt::getAllOnes(NumElts);
1349 HasMultiUse = true;
1350 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
1351 // Not demanding any bits/elts from Op.
1352 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1353 } else if (Depth >= SelectionDAG::MaxRecursionDepth) {
1354 // Limit search depth.
1355 return false;
1356 }
1357
1358 // Before folding to the LHS, recheck bits excluded from its earlier demand
1359 // using the full result demand. Mask identifies these excluded bits.
1360 // KnownMask selects the Zero/One member of the recomputed LHS known bits
1361 // that must cover Mask & DemandedBits.
1362 auto TryFoldToLHS = [&](const APInt &Mask,
1363 const APInt KnownBits::*KnownMask) {
1364 SDValue LHS = Op.getOperand(0);
1365 APInt MaskedBits = Mask & DemandedBits;
1366 if (MaskedBits.isZero())
1367 return TLO.CombineTo(Op, LHS);
1368
1369 KnownBits LHSKnown;
1370 if (SimplifyDemandedBits(LHS, DemandedBits, DemandedElts, LHSKnown, TLO,
1371 Depth + 1))
1372 return true;
1373
1374 return MaskedBits.isSubsetOf(LHSKnown.*KnownMask) && TLO.CombineTo(Op, LHS);
1375 };
1376
1377 // Try reducing the RHS demand using LHS known bits.
1378 // KnownMask selects the LHS Zero/One bits that make RHS bits irrelevant.
1379 auto TryReduceRHSDemand = [&](const KnownBits &LHSKnown,
1380 const APInt KnownBits::*KnownMask) {
1381 SDValue RHS = Op.getOperand(1);
1382 if (!RHS.hasOneUse() || isConstOrConstSplat(RHS, DemandedElts))
1383 return false;
1384
1385 // Reuse LHS facts if the RHS did not reduce its earlier demand. Otherwise,
1386 // query independent facts to avoid using bits outside that demand.
1387 SDValue LHS = Op.getOperand(0);
1388 // Keep only the selected mask, then compute DemandedBits & ~Mask in place.
1389 // This avoids copying the unused KnownBits mask and extra APInt
1390 // temporaries, which can allocate memory for masks wider than one word.
1391 APInt RHSDemandedBits =
1392 DemandedBits.intersects(Known.*KnownMask)
1393 ? TLO.DAG.computeKnownBits(LHS, DemandedElts, Depth + 1).*KnownMask
1394 : LHSKnown.*KnownMask;
1395 RHSDemandedBits.flipAllBits();
1396 RHSDemandedBits &= DemandedBits;
1397 if (RHSDemandedBits == DemandedBits)
1398 return false;
1399
1400 // A failed retry must not replace Known with reduced-demand facts.
1401 KnownBits RetryKnown;
1402 return SimplifyDemandedBits(RHS, RHSDemandedBits, DemandedElts, RetryKnown,
1403 TLO, Depth + 1);
1404 };
1405
1406 KnownBits Known2;
1407 switch (Op.getOpcode()) {
1408 case ISD::SCALAR_TO_VECTOR: {
1409 if (VT.isScalableVector())
1410 return false;
1411 if (!DemandedElts[0])
1412 return TLO.CombineTo(Op, TLO.DAG.getPOISON(VT));
1413
1414 KnownBits SrcKnown;
1415 SDValue Src = Op.getOperand(0);
1416 unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
1417 APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth);
1418 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
1419 return true;
1420
1421 // Upper elements are poison, so only get the knownbits if we just demand
1422 // the bottom element.
1423 if (DemandedElts == 1)
1424 Known = SrcKnown.anyextOrTrunc(BitWidth);
1425 break;
1426 }
1427 case ISD::BUILD_VECTOR:
1428 // Collect the known bits that are shared by every demanded element.
1429 // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
1430 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1431 return false; // Don't fall through, will infinitely loop.
1432 case ISD::SPLAT_VECTOR: {
1433 SDValue Scl = Op.getOperand(0);
1434 APInt DemandedSclBits = DemandedBits.zextOrTrunc(Scl.getValueSizeInBits());
1435 KnownBits KnownScl;
1436 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1437 return true;
1438
1439 // Implicitly truncate the bits to match the official semantics of
1440 // SPLAT_VECTOR.
1441 Known = KnownScl.trunc(BitWidth);
1442 break;
1443 }
1444 case ISD::FREEZE: {
1445 SDValue N0 = Op.getOperand(0);
1447 N0, DemandedElts, UndefPoisonKind::UndefOrPoison, Depth + 1))
1448 return TLO.CombineTo(Op, N0);
1449 break;
1450 }
1451 case ISD::LOAD: {
1452 auto *LD = cast<LoadSDNode>(Op);
1453 if (getTargetConstantFromLoad(LD)) {
1454 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1455 return false; // Don't fall through, will infinitely loop.
1456 }
1457 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
1458 // If this is a ZEXTLoad and we are looking at the loaded value.
1459 EVT MemVT = LD->getMemoryVT();
1460 unsigned MemBits = MemVT.getScalarSizeInBits();
1461 Known.Zero.setBitsFrom(MemBits);
1462 return false; // Don't fall through, will infinitely loop.
1463 }
1464 break;
1465 }
1467 if (VT.isScalableVector())
1468 return false;
1469 SDValue Vec = Op.getOperand(0);
1470 SDValue Scl = Op.getOperand(1);
1471 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1472 EVT VecVT = Vec.getValueType();
1473
1474 // If index isn't constant, assume we need all vector elements AND the
1475 // inserted element.
1476 APInt DemandedVecElts(DemandedElts);
1477 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
1478 unsigned Idx = CIdx->getZExtValue();
1479 DemandedVecElts.clearBit(Idx);
1480
1481 // Inserted element is not required.
1482 if (!DemandedElts[Idx])
1483 return TLO.CombineTo(Op, Vec);
1484 }
1485
1486 KnownBits KnownScl;
1487 unsigned NumSclBits = Scl.getScalarValueSizeInBits();
1488 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
1489 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1490 return true;
1491
1492 Known = KnownScl.anyextOrTrunc(BitWidth);
1493
1494 KnownBits KnownVec;
1495 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
1496 Depth + 1))
1497 return true;
1498
1499 if (!!DemandedVecElts)
1500 Known = Known.intersectWith(KnownVec);
1501
1502 return false;
1503 }
1504 case ISD::INSERT_SUBVECTOR: {
1505 if (VT.isScalableVector())
1506 return false;
1507 // Demand any elements from the subvector and the remainder from the src its
1508 // inserted into.
1509 SDValue Src = Op.getOperand(0);
1510 SDValue Sub = Op.getOperand(1);
1511 uint64_t Idx = Op.getConstantOperandVal(2);
1512 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1513 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1514 APInt DemandedSrcElts = DemandedElts;
1515 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
1516
1517 KnownBits KnownSub, KnownSrc;
1518 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO,
1519 Depth + 1))
1520 return true;
1521 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO,
1522 Depth + 1))
1523 return true;
1524
1525 Known.setAllConflict();
1526 if (!!DemandedSubElts)
1527 Known = Known.intersectWith(KnownSub);
1528 if (!!DemandedSrcElts)
1529 Known = Known.intersectWith(KnownSrc);
1530
1531 // Attempt to avoid multi-use src if we don't need anything from it.
1532 if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() ||
1533 !DemandedSrcElts.isAllOnes()) {
1535 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1);
1537 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1538 if (NewSub || NewSrc) {
1539 NewSub = NewSub ? NewSub : Sub;
1540 NewSrc = NewSrc ? NewSrc : Src;
1541 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub,
1542 Op.getOperand(2));
1543 return TLO.CombineTo(Op, NewOp);
1544 }
1545 }
1546 break;
1547 }
1549 if (VT.isScalableVector())
1550 return false;
1551 // Offset the demanded elts by the subvector index.
1552 SDValue Src = Op.getOperand(0);
1553 if (Src.getValueType().isScalableVector())
1554 break;
1555 uint64_t Idx = Op.getConstantOperandVal(1);
1556 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1557 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
1558
1559 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO,
1560 Depth + 1))
1561 return true;
1562
1563 // Attempt to avoid multi-use src if we don't need anything from it.
1564 if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
1566 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1567 if (DemandedSrc) {
1568 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc,
1569 Op.getOperand(1));
1570 return TLO.CombineTo(Op, NewOp);
1571 }
1572 }
1573 break;
1574 }
1575 case ISD::CONCAT_VECTORS: {
1576 if (VT.isScalableVector())
1577 return false;
1578 Known.setAllConflict();
1579 EVT SubVT = Op.getOperand(0).getValueType();
1580 unsigned NumSubVecs = Op.getNumOperands();
1581 unsigned NumSubElts = SubVT.getVectorNumElements();
1582 for (unsigned i = 0; i != NumSubVecs; ++i) {
1583 APInt DemandedSubElts =
1584 DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1585 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
1586 Known2, TLO, Depth + 1))
1587 return true;
1588 // Known bits are shared by every demanded subvector element.
1589 if (!!DemandedSubElts)
1590 Known = Known.intersectWith(Known2);
1591 }
1592 break;
1593 }
1594 case ISD::VECTOR_SHUFFLE: {
1595 assert(!VT.isScalableVector());
1596 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1597
1598 // Collect demanded elements from shuffle operands..
1599 APInt DemandedLHS, DemandedRHS;
1600 if (!getShuffleDemandedElts(NumElts, ShuffleMask, DemandedElts, DemandedLHS,
1601 DemandedRHS))
1602 break;
1603
1604 if (!!DemandedLHS || !!DemandedRHS) {
1605 SDValue Op0 = Op.getOperand(0);
1606 SDValue Op1 = Op.getOperand(1);
1607
1608 Known.setAllConflict();
1609 if (!!DemandedLHS) {
1610 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO,
1611 Depth + 1))
1612 return true;
1613 Known = Known.intersectWith(Known2);
1614 }
1615 if (!!DemandedRHS) {
1616 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO,
1617 Depth + 1))
1618 return true;
1619 Known = Known.intersectWith(Known2);
1620 }
1621
1622 // Attempt to avoid multi-use ops if we don't need anything from them.
1624 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1);
1626 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1);
1627 if (DemandedOp0 || DemandedOp1) {
1628 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1629 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1630 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask);
1631 return TLO.CombineTo(Op, NewOp);
1632 }
1633 }
1634 break;
1635 }
1636 case ISD::AND: {
1637 SDValue Op0 = Op.getOperand(0);
1638 SDValue Op1 = Op.getOperand(1);
1639
1640 // If the RHS is a constant, check to see if the LHS would be zero without
1641 // using the bits from the RHS. Below, we use knowledge about the RHS to
1642 // simplify the LHS, here we're using information from the LHS to simplify
1643 // the RHS.
1644 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1, DemandedElts)) {
1645 // Do not increment Depth here; that can cause an infinite loop.
1646 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
1647 // If the LHS already has zeros where RHSC does, this 'and' is dead.
1648 if ((LHSKnown.Zero & DemandedBits) ==
1649 (~RHSC->getAPIntValue() & DemandedBits))
1650 return TLO.CombineTo(Op, Op0);
1651
1652 // If any of the set bits in the RHS are known zero on the LHS, shrink
1653 // the constant.
1654 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits,
1655 DemandedElts, TLO))
1656 return true;
1657
1658 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
1659 // constant, but if this 'and' is only clearing bits that were just set by
1660 // the xor, then this 'and' can be eliminated by shrinking the mask of
1661 // the xor. For example, for a 32-bit X:
1662 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
1663 if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
1664 LHSKnown.One == ~RHSC->getAPIntValue()) {
1665 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
1666 return TLO.CombineTo(Op, Xor);
1667 }
1668 }
1669
1670 // (X +/- Y) & Y --> ~X & Y when Y is a power of 2 (or zero).
1671 SDValue X, Y;
1672 if (sd_match(Op,
1673 m_And(m_Value(Y),
1675 m_Sub(m_Value(X), m_Deferred(Y)))))) &&
1676 TLO.DAG.isKnownToBeAPowerOfTwo(Y, DemandedElts, /*OrZero=*/true)) {
1677 return TLO.CombineTo(
1678 Op, TLO.DAG.getNode(ISD::AND, dl, VT, TLO.DAG.getNOT(dl, X, VT), Y));
1679 }
1680
1681 // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I)
1682 // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits).
1683 if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR && !VT.isScalableVector() &&
1684 (Op0.getOperand(0).isUndef() ||
1686 Op0->hasOneUse()) {
1687 unsigned NumSubElts =
1689 unsigned SubIdx = Op0.getConstantOperandVal(2);
1690 APInt DemandedSub =
1691 APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts);
1692 KnownBits KnownSubMask =
1693 TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1);
1694 if (DemandedBits.isSubsetOf(KnownSubMask.One)) {
1695 SDValue NewAnd =
1696 TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1);
1697 SDValue NewInsert =
1698 TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd,
1699 Op0.getOperand(1), Op0.getOperand(2));
1700 return TLO.CombineTo(Op, NewInsert);
1701 }
1702 }
1703
1704 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1705 Depth + 1))
1706 return true;
1707 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
1708 Known2, TLO, Depth + 1))
1709 return true;
1710
1711 // If all of the demanded bits are known one on one side, return the other.
1712 // These bits cannot contribute to the result of the 'and'.
1713 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) {
1714 if (TryFoldToLHS(Known.Zero, &KnownBits::Zero))
1715 return true;
1716 }
1717 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
1718 return TLO.CombineTo(Op, Op1);
1719 // If all of the demanded bits in the inputs are known zeros, return zero.
1720 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1721 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
1722 // If the RHS is a constant, see if we can simplify it.
1723 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts,
1724 TLO))
1725 return true;
1726 // If the operation can be done in a smaller type, do so.
1728 return true;
1729
1730 // Attempt to avoid multi-use ops if we don't need anything from them.
1731 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1733 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1735 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1736 if (DemandedOp0 || DemandedOp1) {
1737 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1738 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1739 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1740 return TLO.CombineTo(Op, NewOp);
1741 }
1742 }
1743
1744 if (TryReduceRHSDemand(Known2, &KnownBits::Zero))
1745 return true;
1746
1747 Known &= Known2;
1748 break;
1749 }
1750 case ISD::OR: {
1751 SDValue Op0 = Op.getOperand(0);
1752 SDValue Op1 = Op.getOperand(1);
1753 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1754 Depth + 1)) {
1755 Op->dropFlags(SDNodeFlags::Disjoint);
1756 return true;
1757 }
1758
1759 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
1760 Known2, TLO, Depth + 1)) {
1761 Op->dropFlags(SDNodeFlags::Disjoint);
1762 return true;
1763 }
1764
1765 // If all of the demanded bits are known zero on one side, return the other.
1766 // These bits cannot contribute to the result of the 'or'.
1767 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) {
1768 if (TryFoldToLHS(Known.One, &KnownBits::One)) {
1769 Op->dropFlags(SDNodeFlags::Disjoint);
1770 return true;
1771 }
1772 }
1773 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
1774 return TLO.CombineTo(Op, Op1);
1775 // If the RHS is a constant, see if we can simplify it.
1776 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1777 return true;
1778 // If the operation can be done in a smaller type, do so.
1780 return true;
1781
1782 // Attempt to avoid multi-use ops if we don't need anything from them.
1783 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1785 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1787 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1788 if (DemandedOp0 || DemandedOp1) {
1789 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1790 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1791 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1792 return TLO.CombineTo(Op, NewOp);
1793 }
1794 }
1795
1796 // (or (and X, C1), (and (or X, Y), C2)) -> (or (and X, C1|C2), (and Y, C2))
1797 // TODO: Use SimplifyMultipleUseDemandedBits to peek through masks.
1798 SDValue X, Y, C1, C2;
1801 m_Value(C2)))))) {
1802 if (SDValue C12 =
1803 TLO.DAG.FoldConstantArithmetic(ISD::OR, dl, VT, {C1, C2})) {
1804 SDValue MaskX = TLO.DAG.getNode(ISD::AND, dl, VT, X, C12);
1805 SDValue MaskY = TLO.DAG.getNode(ISD::AND, dl, VT, Y, C2);
1806 return TLO.CombineTo(Op,
1807 TLO.DAG.getNode(ISD::OR, dl, VT, MaskX, MaskY));
1808 }
1809 }
1810
1811 if (TryReduceRHSDemand(Known2, &KnownBits::One)) {
1812 Op->dropFlags(SDNodeFlags::Disjoint);
1813 return true;
1814 }
1815
1816 Known |= Known2;
1817 break;
1818 }
1819 case ISD::XOR: {
1820 SDValue Op0 = Op.getOperand(0);
1821 SDValue Op1 = Op.getOperand(1);
1822
1823 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1824 Depth + 1))
1825 return true;
1826 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1827 Depth + 1))
1828 return true;
1829
1830 // If all of the demanded bits are known zero on one side, return the other.
1831 // These bits cannot contribute to the result of the 'xor'.
1832 if (DemandedBits.isSubsetOf(Known.Zero))
1833 return TLO.CombineTo(Op, Op0);
1834 if (DemandedBits.isSubsetOf(Known2.Zero))
1835 return TLO.CombineTo(Op, Op1);
1836 // If the operation can be done in a smaller type, do so.
1838 return true;
1839
1840 // If all of the unknown bits are known to be zero on one side or the other
1841 // turn this into an *inclusive* or.
1842 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1843 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1844 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1845
1846 ConstantSDNode *C = isConstOrConstSplat(Op1, DemandedElts);
1847 if (C) {
1848 // If one side is a constant, and all of the set bits in the constant are
1849 // also known set on the other side, turn this into an AND, as we know
1850 // the bits will be cleared.
1851 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1852 // NB: it is okay if more bits are known than are requested
1853 if (C->getAPIntValue() == Known2.One) {
1854 SDValue ANDC =
1855 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1856 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1857 }
1858
1859 // If the RHS is a constant, see if we can change it. Don't alter a -1
1860 // constant because that's a 'not' op, and that is better for combining
1861 // and codegen.
1862 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) {
1863 // We're flipping all demanded bits. Flip the undemanded bits too.
1864 SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1865 return TLO.CombineTo(Op, New);
1866 }
1867
1868 unsigned Op0Opcode = Op0.getOpcode();
1869 if ((Op0Opcode == ISD::SRL || Op0Opcode == ISD::SHL) && Op0.hasOneUse()) {
1870 if (ConstantSDNode *ShiftC =
1871 isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) {
1872 // Don't crash on an oversized shift. We can not guarantee that a
1873 // bogus shift has been simplified to undef.
1874 if (ShiftC->getAPIntValue().ult(BitWidth)) {
1875 uint64_t ShiftAmt = ShiftC->getZExtValue();
1877 Ones = Op0Opcode == ISD::SHL ? Ones.shl(ShiftAmt)
1878 : Ones.lshr(ShiftAmt);
1879 if ((DemandedBits & C->getAPIntValue()) == (DemandedBits & Ones) &&
1881 // If the xor constant is a demanded mask, do a 'not' before the
1882 // shift:
1883 // xor (X << ShiftC), XorC --> (not X) << ShiftC
1884 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC
1885 SDValue Not = TLO.DAG.getNOT(dl, Op0.getOperand(0), VT);
1886 return TLO.CombineTo(Op, TLO.DAG.getNode(Op0Opcode, dl, VT, Not,
1887 Op0.getOperand(1)));
1888 }
1889 }
1890 }
1891 }
1892 }
1893
1894 // If we can't turn this into a 'not', try to shrink the constant.
1895 if (!C || !C->isAllOnes())
1896 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1897 return true;
1898
1899 // Attempt to avoid multi-use ops if we don't need anything from them.
1900 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1902 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1904 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1905 if (DemandedOp0 || DemandedOp1) {
1906 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1907 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1908 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1909 return TLO.CombineTo(Op, NewOp);
1910 }
1911 }
1912
1913 Known ^= Known2;
1914 break;
1915 }
1916 case ISD::SELECT:
1917 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1918 Known, TLO, Depth + 1))
1919 return true;
1920 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1921 Known2, TLO, Depth + 1))
1922 return true;
1923
1924 // If the operands are constants, see if we can simplify them.
1925 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1926 return true;
1927
1928 // Only known if known in both the LHS and RHS.
1929 Known = Known.intersectWith(Known2);
1930 break;
1931 case ISD::VSELECT:
1932 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1933 Known, TLO, Depth + 1))
1934 return true;
1935 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1936 Known2, TLO, Depth + 1))
1937 return true;
1938
1939 // Only known if known in both the LHS and RHS.
1940 Known = Known.intersectWith(Known2);
1941 break;
1942 case ISD::SELECT_CC:
1943 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, DemandedElts,
1944 Known, TLO, Depth + 1))
1945 return true;
1946 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1947 Known2, TLO, Depth + 1))
1948 return true;
1949
1950 // If the operands are constants, see if we can simplify them.
1951 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1952 return true;
1953
1954 // Only known if known in both the LHS and RHS.
1955 Known = Known.intersectWith(Known2);
1956 break;
1957 case ISD::SETCC: {
1958 SDValue Op0 = Op.getOperand(0);
1959 SDValue Op1 = Op.getOperand(1);
1960 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1961 // If we're testing X < 0, X >= 0, X <= -1 or X > -1
1962 // (X is of integer type) then we only need the sign mask of the previous
1963 // result
1964 if (Op1.getValueType().isInteger() &&
1965 (((CC == ISD::SETLT || CC == ISD::SETGE) && isNullOrNullSplat(Op1)) ||
1966 ((CC == ISD::SETLE || CC == ISD::SETGT) &&
1967 isAllOnesOrAllOnesSplat(Op1)))) {
1968 KnownBits KnownOp0;
1971 DemandedElts, KnownOp0, TLO, Depth + 1))
1972 return true;
1973 // If (1) we only need the sign-bit, (2) the setcc operands are the same
1974 // width as the setcc result, and (3) the result of a setcc conforms to 0
1975 // or -1, we may be able to bypass the setcc.
1976 if (DemandedBits.isSignMask() &&
1980 // If we remove a >= 0 or > -1 (for integers), we need to introduce a
1981 // NOT Operation
1982 if (CC == ISD::SETGE || CC == ISD::SETGT) {
1983 SDLoc DL(Op);
1984 EVT VT = Op0.getValueType();
1985 SDValue NotOp0 = TLO.DAG.getNOT(DL, Op0, VT);
1986 return TLO.CombineTo(Op, NotOp0);
1987 }
1988 return TLO.CombineTo(Op, Op0);
1989 }
1990 }
1991 if (getBooleanContents(Op0.getValueType()) ==
1993 BitWidth > 1)
1994 Known.Zero.setBitsFrom(1);
1995 break;
1996 }
1997 case ISD::SHL: {
1998 SDValue Op0 = Op.getOperand(0);
1999 SDValue Op1 = Op.getOperand(1);
2000 EVT ShiftVT = Op1.getValueType();
2001
2002 if (std::optional<unsigned> KnownSA =
2003 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2004 unsigned ShAmt = *KnownSA;
2005 if (ShAmt == 0)
2006 return TLO.CombineTo(Op, Op0);
2007
2008 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
2009 // single shift. We can do this if the bottom bits (which are shifted
2010 // out) are never demanded.
2011 // TODO - support non-uniform vector amounts.
2012 if (Op0.getOpcode() == ISD::SRL) {
2013 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) {
2014 if (std::optional<unsigned> InnerSA =
2015 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2016 unsigned C1 = *InnerSA;
2017 unsigned Opc = ISD::SHL;
2018 int Diff = ShAmt - C1;
2019 if (Diff < 0) {
2020 Diff = -Diff;
2021 Opc = ISD::SRL;
2022 }
2023 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
2024 return TLO.CombineTo(
2025 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
2026 }
2027 }
2028 }
2029
2030 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
2031 // are not demanded. This will likely allow the anyext to be folded away.
2032 // TODO - support non-uniform vector amounts.
2033 if (Op0.getOpcode() == ISD::ANY_EXTEND) {
2034 SDValue InnerOp = Op0.getOperand(0);
2035 EVT InnerVT = InnerOp.getValueType();
2036 unsigned InnerBits = InnerVT.getScalarSizeInBits();
2037 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
2038 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
2039 SDValue NarrowShl = TLO.DAG.getNode(
2040 ISD::SHL, dl, InnerVT, InnerOp,
2041 TLO.DAG.getShiftAmountConstant(ShAmt, InnerVT, dl));
2042 return TLO.CombineTo(
2043 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
2044 }
2045
2046 // Repeat the SHL optimization above in cases where an extension
2047 // intervenes: (shl (anyext (shr x, c1)), c2) to
2048 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
2049 // aren't demanded (as above) and that the shifted upper c1 bits of
2050 // x aren't demanded.
2051 // TODO - support non-uniform vector amounts.
2052 if (InnerOp.getOpcode() == ISD::SRL && Op0.hasOneUse() &&
2053 InnerOp.hasOneUse()) {
2054 if (std::optional<unsigned> SA2 = TLO.DAG.getValidShiftAmount(
2055 InnerOp, DemandedElts, Depth + 2)) {
2056 unsigned InnerShAmt = *SA2;
2057 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
2058 DemandedBits.getActiveBits() <=
2059 (InnerBits - InnerShAmt + ShAmt) &&
2060 DemandedBits.countr_zero() >= ShAmt) {
2061 SDValue NewSA =
2062 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT);
2063 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
2064 InnerOp.getOperand(0));
2065 return TLO.CombineTo(
2066 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
2067 }
2068 }
2069 }
2070 }
2071
2072 APInt InDemandedMask = DemandedBits.lshr(ShAmt);
2073 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2074 Depth + 1)) {
2075 // Disable the nsw and nuw flags. We can no longer guarantee that we
2076 // won't wrap after simplification.
2077 Op->dropFlags(SDNodeFlags::NoWrap);
2078 return true;
2079 }
2080 Known <<= ShAmt;
2081 // low bits known zero.
2082 Known.Zero.setLowBits(ShAmt);
2083
2084 // Attempt to avoid multi-use ops if we don't need anything from them.
2085 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2087 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2088 if (DemandedOp0) {
2089 SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1);
2090 return TLO.CombineTo(Op, NewOp);
2091 }
2092 }
2093
2094 // TODO: Can we merge this fold with the one below?
2095 // Try shrinking the operation as long as the shift amount will still be
2096 // in range.
2097 if (ShAmt < DemandedBits.getActiveBits() && !VT.isVector() &&
2098 Op.getNode()->hasOneUse()) {
2099 // Search for the smallest integer type with free casts to and from
2100 // Op's type. For expedience, just check power-of-2 integer types.
2101 unsigned DemandedSize = DemandedBits.getActiveBits();
2102 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize);
2103 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
2104 EVT SmallVT = EVT::getIntegerVT(*TLO.DAG.getContext(), SmallVTBits);
2105 if (isNarrowingProfitable(Op.getNode(), VT, SmallVT) &&
2106 isTypeDesirableForOp(ISD::SHL, SmallVT) &&
2107 isTruncateFree(VT, SmallVT) && isZExtFree(SmallVT, VT) &&
2108 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, SmallVT))) {
2109 assert(DemandedSize <= SmallVTBits &&
2110 "Narrowed below demanded bits?");
2111 // We found a type with free casts.
2112 SDValue NarrowShl = TLO.DAG.getNode(
2113 ISD::SHL, dl, SmallVT,
2114 TLO.DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
2115 TLO.DAG.getShiftAmountConstant(ShAmt, SmallVT, dl));
2116 return TLO.CombineTo(
2117 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
2118 }
2119 }
2120 }
2121
2122 // Narrow shift to lower half - similar to ShrinkDemandedOp.
2123 // (shl i64:x, K) -> (i64 zero_extend (shl (i32 (trunc i64:x)), K))
2124 // Only do this if we demand the upper half so the knownbits are correct.
2125 unsigned HalfWidth = BitWidth / 2;
2126 if ((BitWidth % 2) == 0 && !VT.isVector() && ShAmt < HalfWidth &&
2127 DemandedBits.countLeadingOnes() >= HalfWidth) {
2128 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), HalfWidth);
2129 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) &&
2130 isTypeDesirableForOp(ISD::SHL, HalfVT) &&
2131 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
2132 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, HalfVT))) {
2133 // If we're demanding the upper bits at all, we must ensure
2134 // that the upper bits of the shift result are known to be zero,
2135 // which is equivalent to the narrow shift being NUW.
2136 if (bool IsNUW = (Known.countMinLeadingZeros() >= HalfWidth)) {
2137 bool IsNSW = Known.countMinSignBits() > HalfWidth;
2138 SDNodeFlags Flags;
2139 Flags.setNoSignedWrap(IsNSW);
2140 Flags.setNoUnsignedWrap(IsNUW);
2141 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
2142 SDValue NewShiftAmt =
2143 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl);
2144 SDValue NewShift = TLO.DAG.getNode(ISD::SHL, dl, HalfVT, NewOp,
2145 NewShiftAmt, Flags);
2146 SDValue NewExt =
2147 TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift);
2148 return TLO.CombineTo(Op, NewExt);
2149 }
2150 }
2151 }
2152 } else {
2153 // This is a variable shift, so we can't shift the demand mask by a known
2154 // amount. But if we are not demanding high bits, then we are not
2155 // demanding those bits from the pre-shifted operand either.
2156 if (unsigned CTLZ = DemandedBits.countl_zero()) {
2157 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
2158 if (SimplifyDemandedBits(Op0, DemandedFromOp, DemandedElts, Known, TLO,
2159 Depth + 1)) {
2160 // Disable the nsw and nuw flags. We can no longer guarantee that we
2161 // won't wrap after simplification.
2162 Op->dropFlags(SDNodeFlags::NoWrap);
2163 return true;
2164 }
2165 Known.resetAll();
2166 }
2167 }
2168
2169 // If we are only demanding sign bits then we can use the shift source
2170 // directly.
2171 if (std::optional<unsigned> MaxSA =
2172 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
2173 unsigned ShAmt = *MaxSA;
2174 unsigned NumSignBits =
2175 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
2176 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
2177 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
2178 return TLO.CombineTo(Op, Op0);
2179 }
2180 break;
2181 }
2182 case ISD::SRL: {
2183 SDValue Op0 = Op.getOperand(0);
2184 SDValue Op1 = Op.getOperand(1);
2185 EVT ShiftVT = Op1.getValueType();
2186
2187 if (std::optional<unsigned> KnownSA =
2188 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2189 unsigned ShAmt = *KnownSA;
2190 if (ShAmt == 0)
2191 return TLO.CombineTo(Op, Op0);
2192
2193 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
2194 // single shift. We can do this if the top bits (which are shifted out)
2195 // are never demanded.
2196 // TODO - support non-uniform vector amounts.
2197 if (Op0.getOpcode() == ISD::SHL) {
2198 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
2199 if (std::optional<unsigned> InnerSA =
2200 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2201 unsigned C1 = *InnerSA;
2202 unsigned Opc = ISD::SRL;
2203 int Diff = ShAmt - C1;
2204 if (Diff < 0) {
2205 Diff = -Diff;
2206 Opc = ISD::SHL;
2207 }
2208 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
2209 return TLO.CombineTo(
2210 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
2211 }
2212 }
2213 }
2214
2215 // If this is (srl (sra X, C1), ShAmt), see if we can combine this into a
2216 // single sra. We can do this if the top bits are never demanded.
2217 if (Op0.getOpcode() == ISD::SRA && Op0.hasOneUse()) {
2218 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
2219 if (std::optional<unsigned> InnerSA =
2220 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2221 unsigned C1 = *InnerSA;
2222 // Clamp the combined shift amount if it exceeds the bit width.
2223 unsigned Combined = std::min(C1 + ShAmt, BitWidth - 1);
2224 SDValue NewSA = TLO.DAG.getConstant(Combined, dl, ShiftVT);
2225 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRA, dl, VT,
2226 Op0.getOperand(0), NewSA));
2227 }
2228 }
2229 }
2230
2231 APInt InDemandedMask = (DemandedBits << ShAmt);
2232
2233 // If the shift is exact, then it does demand the low bits (and knows that
2234 // they are zero).
2235 if (Op->getFlags().hasExact())
2236 InDemandedMask.setLowBits(ShAmt);
2237
2238 // Narrow shift to lower half - similar to ShrinkDemandedOp.
2239 // (srl i64:x, K) -> (i64 zero_extend (srl (i32 (trunc i64:x)), K))
2240 if ((BitWidth % 2) == 0 && !VT.isVector()) {
2242 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), BitWidth / 2);
2243 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) &&
2244 isTypeDesirableForOp(ISD::SRL, HalfVT) &&
2245 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
2246 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, HalfVT)) &&
2247 ((InDemandedMask.countLeadingZeros() >= (BitWidth / 2)) ||
2248 TLO.DAG.MaskedValueIsZero(Op0, HiBits))) {
2249 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
2250 SDValue NewShiftAmt =
2251 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl);
2252 SDValue NewShift =
2253 TLO.DAG.getNode(ISD::SRL, dl, HalfVT, NewOp, NewShiftAmt);
2254 return TLO.CombineTo(
2255 Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift));
2256 }
2257 }
2258
2259 // Compute the new bits that are at the top now.
2260 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2261 Depth + 1))
2262 return true;
2263 Known >>= ShAmt;
2264 // High bits known zero.
2265 Known.Zero.setHighBits(ShAmt);
2266
2267 // Attempt to avoid multi-use ops if we don't need anything from them.
2268 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2270 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2271 if (DemandedOp0) {
2272 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, DemandedOp0, Op1);
2273 return TLO.CombineTo(Op, NewOp);
2274 }
2275 }
2276 } else {
2277 // Use generic knownbits computation as it has support for non-uniform
2278 // shift amounts.
2279 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2280 }
2281
2282 // If we are only demanding sign bits then we can use the shift source
2283 // directly.
2284 if (std::optional<unsigned> MaxSA =
2285 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
2286 unsigned ShAmt = *MaxSA;
2287 // Must already be signbits in DemandedBits bounds, and can't demand any
2288 // shifted in zeroes.
2289 if (DemandedBits.countl_zero() >= ShAmt) {
2290 unsigned NumSignBits =
2291 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
2292 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits))
2293 return TLO.CombineTo(Op, Op0);
2294 }
2295 }
2296
2297 // Try to match AVG patterns (after shift simplification).
2298 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits,
2299 DemandedElts, Depth + 1))
2300 return TLO.CombineTo(Op, AVG);
2301
2302 break;
2303 }
2304 case ISD::SRA: {
2305 SDValue Op0 = Op.getOperand(0);
2306 SDValue Op1 = Op.getOperand(1);
2307 EVT ShiftVT = Op1.getValueType();
2308
2309 // If we only want bits that already match the signbit then we don't need
2310 // to shift.
2311 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countr_zero();
2312 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >=
2313 NumHiDemandedBits)
2314 return TLO.CombineTo(Op, Op0);
2315
2316 // If this is an arithmetic shift right and only the low-bit is set, we can
2317 // always convert this into a logical shr, even if the shift amount is
2318 // variable. The low bit of the shift cannot be an input sign bit unless
2319 // the shift amount is >= the size of the datatype, which is undefined.
2320 if (DemandedBits.isOne())
2321 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2322
2323 if (std::optional<unsigned> KnownSA =
2324 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2325 unsigned ShAmt = *KnownSA;
2326 if (ShAmt == 0)
2327 return TLO.CombineTo(Op, Op0);
2328
2329 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target
2330 // supports sext_inreg.
2331 if (Op0.getOpcode() == ISD::SHL) {
2332 if (std::optional<unsigned> InnerSA =
2333 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2334 unsigned LowBits = BitWidth - ShAmt;
2335 EVT ExtVT = VT.changeElementType(
2336 *TLO.DAG.getContext(),
2337 EVT::getIntegerVT(*TLO.DAG.getContext(), LowBits));
2338
2339 if (*InnerSA == ShAmt) {
2340 if (!TLO.LegalOperations() ||
2342 return TLO.CombineTo(
2343 Op, TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
2344 Op0.getOperand(0),
2345 TLO.DAG.getValueType(ExtVT)));
2346
2347 // Even if we can't convert to sext_inreg, we might be able to
2348 // remove this shift pair if the input is already sign extended.
2349 unsigned NumSignBits =
2350 TLO.DAG.ComputeNumSignBits(Op0.getOperand(0), DemandedElts);
2351 if (NumSignBits > ShAmt)
2352 return TLO.CombineTo(Op, Op0.getOperand(0));
2353 }
2354 }
2355 }
2356
2357 APInt InDemandedMask = (DemandedBits << ShAmt);
2358
2359 // If the shift is exact, then it does demand the low bits (and knows that
2360 // they are zero).
2361 if (Op->getFlags().hasExact())
2362 InDemandedMask.setLowBits(ShAmt);
2363
2364 // If any of the demanded bits are produced by the sign extension, we also
2365 // demand the input sign bit.
2366 if (DemandedBits.countl_zero() < ShAmt)
2367 InDemandedMask.setSignBit();
2368
2369 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2370 Depth + 1))
2371 return true;
2372 Known >>= ShAmt;
2373
2374 // If the input sign bit is known to be zero, or if none of the top bits
2375 // are demanded, turn this into an unsigned shift right.
2376 if (Known.Zero[BitWidth - ShAmt - 1] ||
2377 DemandedBits.countl_zero() >= ShAmt) {
2378 SDNodeFlags Flags;
2379 Flags.setExact(Op->getFlags().hasExact());
2380 return TLO.CombineTo(
2381 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
2382 }
2383
2384 int Log2 = DemandedBits.exactLogBase2();
2385 if (Log2 >= 0) {
2386 // The bit must come from the sign.
2387 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT);
2388 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
2389 }
2390
2391 if (Known.One[BitWidth - ShAmt - 1])
2392 // New bits are known one.
2393 Known.One.setHighBits(ShAmt);
2394
2395 // Attempt to avoid multi-use ops if we don't need anything from them.
2396 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2398 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2399 if (DemandedOp0) {
2400 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1);
2401 return TLO.CombineTo(Op, NewOp);
2402 }
2403 }
2404 }
2405
2406 // Try to match AVG patterns (after shift simplification).
2407 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits,
2408 DemandedElts, Depth + 1))
2409 return TLO.CombineTo(Op, AVG);
2410
2411 break;
2412 }
2413 case ISD::FSHL:
2414 case ISD::FSHR: {
2415 SDValue Op0 = Op.getOperand(0);
2416 SDValue Op1 = Op.getOperand(1);
2417 SDValue Op2 = Op.getOperand(2);
2418 bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
2419
2420 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
2421 unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2422
2423 // For fshl, 0-shift returns the 1st arg.
2424 // For fshr, 0-shift returns the 2nd arg.
2425 if (Amt == 0) {
2426 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
2427 Known, TLO, Depth + 1))
2428 return true;
2429 break;
2430 }
2431
2432 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
2433 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
2434 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
2435 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
2436 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2437 Depth + 1))
2438 return true;
2439 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
2440 Depth + 1))
2441 return true;
2442
2443 Known2 <<= (IsFSHL ? Amt : (BitWidth - Amt));
2444 Known >>= (IsFSHL ? (BitWidth - Amt) : Amt);
2445 Known = Known.unionWith(Known2);
2446
2447 // Attempt to avoid multi-use ops if we don't need anything from them.
2448 if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() ||
2449 !DemandedElts.isAllOnes()) {
2451 Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1);
2453 Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1);
2454 if (DemandedOp0 || DemandedOp1) {
2455 DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0;
2456 DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1;
2457 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0,
2458 DemandedOp1, Op2);
2459 return TLO.CombineTo(Op, NewOp);
2460 }
2461 }
2462 }
2463
2464 if (isPowerOf2_32(BitWidth)) {
2465 // Fold FSHR(Op0,Op1,Op2) -> SRL(Op1,Op2)
2466 // iff we're guaranteed not to use Op0.
2467 // TODO: Add FSHL equivalent?
2468 if (!IsFSHL && !DemandedBits.isAllOnes() &&
2469 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT))) {
2470 KnownBits KnownAmt =
2471 TLO.DAG.computeKnownBits(Op2, DemandedElts, Depth + 1);
2472 unsigned MaxShiftAmt =
2473 KnownAmt.getMaxValue().getLimitedValue(BitWidth - 1);
2474 // Check we don't demand any shifted bits outside Op1.
2475 if (DemandedBits.countl_zero() >= MaxShiftAmt) {
2476 EVT AmtVT = Op2.getValueType();
2477 SDValue NewAmt =
2478 TLO.DAG.getNode(ISD::AND, dl, AmtVT, Op2,
2479 TLO.DAG.getConstant(BitWidth - 1, dl, AmtVT));
2480 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, Op1, NewAmt);
2481 return TLO.CombineTo(Op, NewOp);
2482 }
2483 }
2484
2485 // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2486 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1);
2487 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, Known2, TLO,
2488 Depth + 1))
2489 return true;
2490 }
2491 break;
2492 }
2493 case ISD::ROTL:
2494 case ISD::ROTR: {
2495 SDValue Op0 = Op.getOperand(0);
2496 SDValue Op1 = Op.getOperand(1);
2497 bool IsROTL = (Op.getOpcode() == ISD::ROTL);
2498
2499 // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
2500 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1))
2501 return TLO.CombineTo(Op, Op0);
2502
2503 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
2504 unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2505 unsigned RevAmt = BitWidth - Amt;
2506
2507 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt))
2508 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt)
2509 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt);
2510 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2511 Depth + 1))
2512 return true;
2513
2514 // rot*(x, 0) --> x
2515 if (Amt == 0)
2516 return TLO.CombineTo(Op, Op0);
2517
2518 // See if we don't demand either half of the rotated bits.
2519 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) &&
2520 DemandedBits.countr_zero() >= (IsROTL ? Amt : RevAmt)) {
2521 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType());
2522 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1));
2523 }
2524 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) &&
2525 DemandedBits.countl_zero() >= (IsROTL ? RevAmt : Amt)) {
2526 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType());
2527 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2528 }
2529 }
2530
2531 // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2532 if (isPowerOf2_32(BitWidth)) {
2533 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1);
2534 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO,
2535 Depth + 1))
2536 return true;
2537 }
2538 break;
2539 }
2540 case ISD::SMIN:
2541 case ISD::SMAX:
2542 case ISD::UMIN:
2543 case ISD::UMAX: {
2544 unsigned Opc = Op.getOpcode();
2545 SDValue Op0 = Op.getOperand(0);
2546 SDValue Op1 = Op.getOperand(1);
2547
2548 // If we're only demanding signbits, then we can simplify to OR/AND node.
2549 unsigned BitOp =
2550 (Opc == ISD::SMIN || Opc == ISD::UMAX) ? ISD::OR : ISD::AND;
2551 unsigned NumSignBits =
2552 std::min(TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1),
2553 TLO.DAG.ComputeNumSignBits(Op1, DemandedElts, Depth + 1));
2554 unsigned NumDemandedUpperBits = BitWidth - DemandedBits.countr_zero();
2555 if (NumSignBits >= NumDemandedUpperBits)
2556 return TLO.CombineTo(Op, TLO.DAG.getNode(BitOp, SDLoc(Op), VT, Op0, Op1));
2557
2558 // Check if one arg is always less/greater than (or equal) to the other arg.
2559 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
2560 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
2561 switch (Opc) {
2562 case ISD::SMIN:
2563 if (std::optional<bool> IsSLE = KnownBits::sle(Known0, Known1))
2564 return TLO.CombineTo(Op, *IsSLE ? Op0 : Op1);
2565 if (std::optional<bool> IsSLT = KnownBits::slt(Known0, Known1))
2566 return TLO.CombineTo(Op, *IsSLT ? Op0 : Op1);
2567 Known = KnownBits::smin(Known0, Known1);
2568 break;
2569 case ISD::SMAX:
2570 if (std::optional<bool> IsSGE = KnownBits::sge(Known0, Known1))
2571 return TLO.CombineTo(Op, *IsSGE ? Op0 : Op1);
2572 if (std::optional<bool> IsSGT = KnownBits::sgt(Known0, Known1))
2573 return TLO.CombineTo(Op, *IsSGT ? Op0 : Op1);
2574 Known = KnownBits::smax(Known0, Known1);
2575 break;
2576 case ISD::UMIN:
2577 if (std::optional<bool> IsULE = KnownBits::ule(Known0, Known1))
2578 return TLO.CombineTo(Op, *IsULE ? Op0 : Op1);
2579 if (std::optional<bool> IsULT = KnownBits::ult(Known0, Known1))
2580 return TLO.CombineTo(Op, *IsULT ? Op0 : Op1);
2581 Known = KnownBits::umin(Known0, Known1);
2582 break;
2583 case ISD::UMAX:
2584 if (std::optional<bool> IsUGE = KnownBits::uge(Known0, Known1))
2585 return TLO.CombineTo(Op, *IsUGE ? Op0 : Op1);
2586 if (std::optional<bool> IsUGT = KnownBits::ugt(Known0, Known1))
2587 return TLO.CombineTo(Op, *IsUGT ? Op0 : Op1);
2588 Known = KnownBits::umax(Known0, Known1);
2589 break;
2590 }
2591 break;
2592 }
2593 case ISD::BITREVERSE: {
2594 SDValue Src = Op.getOperand(0);
2595 APInt DemandedSrcBits = DemandedBits.reverseBits();
2596 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2597 Depth + 1))
2598 return true;
2599 Known = Known2.reverseBits();
2600 break;
2601 }
2602 case ISD::BSWAP: {
2603 SDValue Src = Op.getOperand(0);
2604
2605 // If the only bits demanded come from one byte of the bswap result,
2606 // just shift the input byte into position to eliminate the bswap.
2607 unsigned NLZ = DemandedBits.countl_zero();
2608 unsigned NTZ = DemandedBits.countr_zero();
2609
2610 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
2611 // we need all the bits down to bit 8. Likewise, round NLZ. If we
2612 // have 14 leading zeros, round to 8.
2613 NLZ = alignDown(NLZ, 8);
2614 NTZ = alignDown(NTZ, 8);
2615 // If we need exactly one byte, we can do this transformation.
2616 if (BitWidth - NLZ - NTZ == 8) {
2617 // Replace this with either a left or right shift to get the byte into
2618 // the right place.
2619 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL;
2620 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) {
2621 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ;
2622 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
2623 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt);
2624 return TLO.CombineTo(Op, NewOp);
2625 }
2626 }
2627
2628 APInt DemandedSrcBits = DemandedBits.byteSwap();
2629 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2630 Depth + 1))
2631 return true;
2632 Known = Known2.byteSwap();
2633 break;
2634 }
2635 case ISD::CTPOP: {
2636 // If only 1 bit is demanded, replace with PARITY as long as we're before
2637 // op legalization.
2638 // FIXME: Limit to scalars for now.
2639 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector())
2640 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT,
2641 Op.getOperand(0)));
2642
2643 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2644 break;
2645 }
2646 case ISD::PDEP: {
2647 SDValue Op0 = Op.getOperand(0);
2648 SDValue Op1 = Op.getOperand(1);
2649
2650 unsigned DemandedBitsLZ = DemandedBits.countl_zero();
2651 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2652
2653 // If the demanded bits has leading zeroes, we don't demand those from the
2654 // mask.
2655 if (SimplifyDemandedBits(Op1, LoMask, Known, TLO, Depth + 1))
2656 return true;
2657
2658 // The number of possible 1s in the mask determines the number of LSBs of
2659 // operand 0 used. Undemanded bits from the mask don't matter so filter
2660 // them before counting.
2661 KnownBits Known2;
2662 uint64_t Count = (~Known.Zero & LoMask).popcount();
2663 APInt DemandedMask(APInt::getLowBitsSet(BitWidth, Count));
2664 if (SimplifyDemandedBits(Op0, DemandedMask, Known2, TLO, Depth + 1))
2665 return true;
2666
2667 // Zeroes are retained from the mask, but not ones.
2668 Known.One.clearAllBits();
2669 // The result will have at least as many trailing zeros as the non-mask
2670 // operand since bits can only map to the same or higher bit position.
2671 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
2672 break;
2673 }
2675 SDValue Op0 = Op.getOperand(0);
2676 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2677 unsigned ExVTBits = ExVT.getScalarSizeInBits();
2678
2679 // If we only care about the highest bit, don't bother shifting right.
2680 if (DemandedBits.isSignMask()) {
2681 unsigned MinSignedBits =
2682 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1);
2683 bool AlreadySignExtended = ExVTBits >= MinSignedBits;
2684 // However if the input is already sign extended we expect the sign
2685 // extension to be dropped altogether later and do not simplify.
2686 if (!AlreadySignExtended) {
2687 // Compute the correct shift amount type, which must be getShiftAmountTy
2688 // for scalar types after legalization.
2689 SDValue ShiftAmt =
2690 TLO.DAG.getShiftAmountConstant(BitWidth - ExVTBits, VT, dl);
2691 return TLO.CombineTo(Op,
2692 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
2693 }
2694 }
2695
2696 // If none of the extended bits are demanded, eliminate the sextinreg.
2697 if (DemandedBits.getActiveBits() <= ExVTBits)
2698 return TLO.CombineTo(Op, Op0);
2699
2700 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
2701
2702 // Since the sign extended bits are demanded, we know that the sign
2703 // bit is demanded.
2704 InputDemandedBits.setBit(ExVTBits - 1);
2705
2706 if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO,
2707 Depth + 1))
2708 return true;
2709
2710 // If the sign bit of the input is known set or clear, then we know the
2711 // top bits of the result.
2712
2713 // If the input sign bit is known zero, convert this into a zero extension.
2714 if (Known.Zero[ExVTBits - 1])
2715 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT));
2716
2717 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
2718 if (Known.One[ExVTBits - 1]) { // Input sign bit known set
2719 Known.One.setBitsFrom(ExVTBits);
2720 Known.Zero &= Mask;
2721 } else { // Input sign bit unknown
2722 Known.Zero &= Mask;
2723 Known.One &= Mask;
2724 }
2725 break;
2726 }
2727 case ISD::BUILD_PAIR: {
2728 EVT HalfVT = Op.getOperand(0).getValueType();
2729 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
2730
2731 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
2732 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
2733
2734 KnownBits KnownLo, KnownHi;
2735
2736 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
2737 return true;
2738
2739 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
2740 return true;
2741
2742 Known = KnownHi.concat(KnownLo);
2743 break;
2744 }
2746 if (VT.isScalableVector())
2747 return false;
2748 [[fallthrough]];
2749 case ISD::ZERO_EXTEND: {
2750 SDValue Src = Op.getOperand(0);
2751 EVT SrcVT = Src.getValueType();
2752 unsigned InBits = SrcVT.getScalarSizeInBits();
2753 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2754 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
2755
2756 // If none of the top bits are demanded, convert this into an any_extend.
2757 if (DemandedBits.getActiveBits() <= InBits) {
2758 // If we only need the non-extended bits of the bottom element
2759 // then we can just bitcast to the result.
2760 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2761 VT.getSizeInBits() == SrcVT.getSizeInBits())
2762 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2763
2764 unsigned Opc =
2766 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2767 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2768 }
2769
2770 APInt InDemandedBits = DemandedBits.trunc(InBits);
2771 APInt InDemandedElts = DemandedElts.zext(InElts);
2772 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2773 Depth + 1)) {
2774 Op->dropFlags(SDNodeFlags::NonNeg);
2775 return true;
2776 }
2777 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2778 Known = Known.zext(BitWidth);
2779
2780 // Attempt to avoid multi-use ops if we don't need anything from them.
2782 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2783 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2784 break;
2785 }
2787 if (VT.isScalableVector())
2788 return false;
2789 [[fallthrough]];
2790 case ISD::SIGN_EXTEND: {
2791 SDValue Src = Op.getOperand(0);
2792 EVT SrcVT = Src.getValueType();
2793 unsigned InBits = SrcVT.getScalarSizeInBits();
2794 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2795 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
2796
2797 APInt InDemandedElts = DemandedElts.zext(InElts);
2798 APInt InDemandedBits = DemandedBits.trunc(InBits);
2799
2800 // Since some of the sign extended bits are demanded, we know that the sign
2801 // bit is demanded.
2802 InDemandedBits.setBit(InBits - 1);
2803
2804 // If none of the top bits are demanded, convert this into an any_extend.
2805 if (DemandedBits.getActiveBits() <= InBits) {
2806 // If we only need the non-extended bits of the bottom element
2807 // then we can just bitcast to the result.
2808 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2809 VT.getSizeInBits() == SrcVT.getSizeInBits())
2810 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2811
2812 // Don't lose an all signbits 0/-1 splat on targets with 0/-1 booleans.
2814 TLO.DAG.ComputeNumSignBits(Src, InDemandedElts, Depth + 1) !=
2815 InBits) {
2816 unsigned Opc =
2818 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2819 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2820 }
2821 }
2822
2823 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2824 Depth + 1))
2825 return true;
2826 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2827
2828 // If the sign bit is known one, the top bits match.
2829 Known = Known.sext(BitWidth);
2830
2831 // If the sign bit is known zero, convert this to a zero extend.
2832 if (Known.isNonNegative()) {
2833 unsigned Opc =
2835 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) {
2836 SDNodeFlags Flags;
2837 if (!IsVecInReg)
2838 Flags |= SDNodeFlags::NonNeg;
2839 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src, Flags));
2840 }
2841 }
2842
2843 // Attempt to avoid multi-use ops if we don't need anything from them.
2845 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2846 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2847 break;
2848 }
2850 if (VT.isScalableVector())
2851 return false;
2852 [[fallthrough]];
2853 case ISD::ANY_EXTEND: {
2854 SDValue Src = Op.getOperand(0);
2855 EVT SrcVT = Src.getValueType();
2856 unsigned InBits = SrcVT.getScalarSizeInBits();
2857 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2858 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
2859
2860 // If we only need the bottom element then we can just bitcast.
2861 // TODO: Handle ANY_EXTEND?
2862 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2863 VT.getSizeInBits() == SrcVT.getSizeInBits())
2864 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2865
2866 APInt InDemandedBits = DemandedBits.trunc(InBits);
2867 APInt InDemandedElts = DemandedElts.zext(InElts);
2868 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2869 Depth + 1))
2870 return true;
2871 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2872 Known = Known.anyext(BitWidth);
2873
2874 // Attempt to avoid multi-use ops if we don't need anything from them.
2876 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2877 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2878 break;
2879 }
2880 case ISD::TRUNCATE: {
2881 SDValue Src = Op.getOperand(0);
2882
2883 // Simplify the input, using demanded bit information, and compute the known
2884 // zero/one bits live out.
2885 unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
2886 APInt TruncMask = DemandedBits.zext(OperandBitWidth);
2887 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO,
2888 Depth + 1)) {
2889 // Disable the nsw and nuw flags. We can no longer guarantee that we
2890 // won't wrap after simplification.
2891 Op->dropFlags(SDNodeFlags::NoWrap);
2892 return true;
2893 }
2894 Known = Known.trunc(BitWidth);
2895
2896 // Attempt to avoid multi-use ops if we don't need anything from them.
2898 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1))
2899 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc));
2900
2901 // If the input is only used by this truncate, see if we can shrink it based
2902 // on the known demanded bits.
2903 switch (Src.getOpcode()) {
2904 default:
2905 break;
2906 case ISD::SRL:
2907 // Shrink SRL by a constant if none of the high bits shifted in are
2908 // demanded.
2909 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
2910 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
2911 // undesirable.
2912 break;
2913
2914 if (Src.getNode()->hasOneUse()) {
2915 if (isTruncateFree(Src, VT) &&
2916 !isTruncateFree(Src.getValueType(), VT)) {
2917 // If truncate is only free at trunc(srl), do not turn it into
2918 // srl(trunc). The check is done by first check the truncate is free
2919 // at Src's opcode(srl), then check the truncate is not done by
2920 // referencing sub-register. In test, if both trunc(srl) and
2921 // srl(trunc)'s trunc are free, srl(trunc) performs better. If only
2922 // trunc(srl)'s trunc is free, trunc(srl) is better.
2923 break;
2924 }
2925
2926 std::optional<unsigned> ShAmtC =
2927 TLO.DAG.getValidShiftAmount(Src, DemandedElts, Depth + 2);
2928 if (!ShAmtC || *ShAmtC >= BitWidth)
2929 break;
2930 unsigned ShVal = *ShAmtC;
2931
2932 APInt HighBits =
2933 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
2934 HighBits.lshrInPlace(ShVal);
2935 HighBits = HighBits.trunc(BitWidth);
2936 if (!(HighBits & DemandedBits)) {
2937 // None of the shifted in bits are needed. Add a truncate of the
2938 // shift input, then shift it.
2939 SDValue NewShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl);
2940 SDValue NewTrunc =
2941 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
2942 return TLO.CombineTo(
2943 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt));
2944 }
2945 }
2946 break;
2947 }
2948
2949 break;
2950 }
2951 case ISD::AssertZext: {
2952 // AssertZext demands all of the high bits, plus any of the low bits
2953 // demanded by its users.
2954 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2956 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
2957 TLO, Depth + 1))
2958 return true;
2959
2960 Known.Zero |= ~InMask;
2961 Known.One &= (~Known.Zero);
2962 break;
2963 }
2965 SDValue Src = Op.getOperand(0);
2966 SDValue Idx = Op.getOperand(1);
2967 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount();
2968 unsigned EltBitWidth = Src.getScalarValueSizeInBits();
2969
2970 if (SrcEltCnt.isScalable())
2971 return false;
2972
2973 // Demand the bits from every vector element without a constant index.
2974 unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2975 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
2976 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
2977 if (CIdx->getAPIntValue().ult(NumSrcElts))
2978 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
2979
2980 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2981 // anything about the extended bits.
2982 APInt DemandedSrcBits = DemandedBits;
2983 if (BitWidth > EltBitWidth)
2984 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
2985
2986 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
2987 Depth + 1))
2988 return true;
2989
2990 // Attempt to avoid multi-use ops if we don't need anything from them.
2991 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
2992 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
2993 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
2994 SDValue NewOp =
2995 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx);
2996 return TLO.CombineTo(Op, NewOp);
2997 }
2998 }
2999
3000 Known = Known2;
3001 if (BitWidth > EltBitWidth)
3002 Known = Known.anyext(BitWidth);
3003 break;
3004 }
3005 case ISD::BITCAST: {
3006 if (VT.isScalableVector())
3007 return false;
3008 SDValue Src = Op.getOperand(0);
3009 EVT SrcVT = Src.getValueType();
3010 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
3011
3012 // If this is an FP->Int bitcast and if the sign bit is the only
3013 // thing demanded, turn this into a FGETSIGN.
3014 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
3015 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
3016 SrcVT.isFloatingPoint()) {
3018 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
3019 // place. We expect the SHL to be eliminated by other optimizations.
3020 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, VT, Src);
3021 unsigned ShVal = Op.getValueSizeInBits() - 1;
3022 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl);
3023 return TLO.CombineTo(Op,
3024 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
3025 }
3026 }
3027
3028 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
3029 // Demand the elt/bit if any of the original elts/bits are demanded.
3030 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) {
3031 unsigned Scale = BitWidth / NumSrcEltBits;
3032 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3033 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
3034 for (unsigned i = 0; i != Scale; ++i) {
3035 unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
3036 unsigned BitOffset = EltOffset * NumSrcEltBits;
3037 DemandedSrcBits |= DemandedBits.extractBits(NumSrcEltBits, BitOffset);
3038 }
3039 // Recursive calls below may turn not demanded elements into poison, so we
3040 // need to demand all smaller source elements that maps to a demanded
3041 // destination element.
3042 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3043
3044 APInt KnownSrcUndef, KnownSrcZero;
3045 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
3046 KnownSrcZero, TLO, Depth + 1))
3047 return true;
3048
3049 KnownBits KnownSrcBits;
3050 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
3051 KnownSrcBits, TLO, Depth + 1))
3052 return true;
3053 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) {
3054 // TODO - bigendian once we have test coverage.
3055 unsigned Scale = NumSrcEltBits / BitWidth;
3056 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
3057 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
3058 APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
3059 for (unsigned i = 0; i != NumElts; ++i)
3060 if (DemandedElts[i]) {
3061 unsigned Offset = (i % Scale) * BitWidth;
3062 DemandedSrcBits.insertBits(DemandedBits, Offset);
3063 DemandedSrcElts.setBit(i / Scale);
3064 }
3065
3066 if (SrcVT.isVector()) {
3067 APInt KnownSrcUndef, KnownSrcZero;
3068 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
3069 KnownSrcZero, TLO, Depth + 1))
3070 return true;
3071 }
3072
3073 KnownBits KnownSrcBits;
3074 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
3075 KnownSrcBits, TLO, Depth + 1))
3076 return true;
3077
3078 // Attempt to avoid multi-use ops if we don't need anything from them.
3079 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
3080 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
3081 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
3082 SDValue NewOp = TLO.DAG.getBitcast(VT, DemandedSrc);
3083 return TLO.CombineTo(Op, NewOp);
3084 }
3085 }
3086 }
3087
3088 // If this is a bitcast, let computeKnownBits handle it. Only do this on a
3089 // recursive call where Known may be useful to the caller.
3090 if (Depth > 0) {
3091 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
3092 return false;
3093 }
3094 break;
3095 }
3096 case ISD::MUL:
3097 if (DemandedBits.isPowerOf2()) {
3098 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
3099 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
3100 // odd (has LSB set), then the left-shifted low bit of X is the answer.
3101 unsigned CTZ = DemandedBits.countr_zero();
3102 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
3103 if (C && C->getAPIntValue().countr_zero() == CTZ) {
3104 SDValue AmtC = TLO.DAG.getShiftAmountConstant(CTZ, VT, dl);
3105 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC);
3106 return TLO.CombineTo(Op, Shl);
3107 }
3108 }
3109 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
3110 // X * X is odd iff X is odd.
3111 // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
3112 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) {
3113 SDValue One = TLO.DAG.getConstant(1, dl, VT);
3114 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One);
3115 return TLO.CombineTo(Op, And1);
3116 }
3117 [[fallthrough]];
3118 case ISD::PTRADD:
3119 if (Op.getOperand(0).getValueType() != Op.getOperand(1).getValueType())
3120 break;
3121 // PTRADD behaves like ADD if pointers are represented as integers.
3122 [[fallthrough]];
3123 case ISD::ADD:
3124 case ISD::SUB: {
3125 // Add, Sub, and Mul don't demand any bits in positions beyond that
3126 // of the highest bit demanded of them.
3127 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
3128 SDNodeFlags Flags = Op.getNode()->getFlags();
3129 unsigned DemandedBitsLZ = DemandedBits.countl_zero();
3130 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
3131 KnownBits KnownOp0, KnownOp1;
3132 auto GetDemandedBitsLHSMask = [&](APInt Demanded,
3133 const KnownBits &KnownRHS) {
3134 if (Op.getOpcode() == ISD::MUL)
3135 Demanded.clearHighBits(KnownRHS.countMinTrailingZeros());
3136 return Demanded;
3137 };
3138 if (SimplifyDemandedBits(Op1, LoMask, DemandedElts, KnownOp1, TLO,
3139 Depth + 1) ||
3140 SimplifyDemandedBits(Op0, GetDemandedBitsLHSMask(LoMask, KnownOp1),
3141 DemandedElts, KnownOp0, TLO, Depth + 1) ||
3142 // See if the operation should be performed at a smaller bit width.
3144 // Disable the nsw and nuw flags. We can no longer guarantee that we
3145 // won't wrap after simplification.
3146 Op->dropFlags(SDNodeFlags::NoWrap);
3147 return true;
3148 }
3149
3150 // neg x with only low bit demanded is simply x.
3151 if (Op.getOpcode() == ISD::SUB && DemandedBits.isOne() &&
3152 isNullConstant(Op0))
3153 return TLO.CombineTo(Op, Op1);
3154
3155 // Attempt to avoid multi-use ops if we don't need anything from them.
3156 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) {
3158 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
3160 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
3161 if (DemandedOp0 || DemandedOp1) {
3162 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
3163 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
3164 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1,
3165 Flags & ~SDNodeFlags::NoWrap);
3166 return TLO.CombineTo(Op, NewOp);
3167 }
3168 }
3169
3170 // If we have a constant operand, we may be able to turn it into -1 if we
3171 // do not demand the high bits. This can make the constant smaller to
3172 // encode, allow more general folding, or match specialized instruction
3173 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
3174 // is probably not useful (and could be detrimental).
3176 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
3177 if (C && !C->isAllOnes() && !C->isOne() &&
3178 (C->getAPIntValue() | HighMask).isAllOnes()) {
3179 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
3180 // Disable the nsw and nuw flags. We can no longer guarantee that we
3181 // won't wrap after simplification.
3182 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1,
3183 Flags & ~SDNodeFlags::NoWrap);
3184 return TLO.CombineTo(Op, NewOp);
3185 }
3186
3187 // Match a multiply with a disguised negated-power-of-2 and convert to a
3188 // an equivalent shift-left amount.
3189 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
3190 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned {
3191 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse())
3192 return 0;
3193
3194 // Don't touch opaque constants. Also, ignore zero and power-of-2
3195 // multiplies. Those will get folded later.
3196 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1));
3197 if (MulC && !MulC->isOpaque() && !MulC->isZero() &&
3198 !MulC->getAPIntValue().isPowerOf2()) {
3199 APInt UnmaskedC = MulC->getAPIntValue() | HighMask;
3200 if (UnmaskedC.isNegatedPowerOf2())
3201 return (-UnmaskedC).logBase2();
3202 }
3203 return 0;
3204 };
3205
3206 auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y,
3207 unsigned ShlAmt) {
3208 SDValue ShlAmtC = TLO.DAG.getShiftAmountConstant(ShlAmt, VT, dl);
3209 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC);
3210 SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl);
3211 return TLO.CombineTo(Op, Res);
3212 };
3213
3215 if (Op.getOpcode() == ISD::ADD) {
3216 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
3217 if (unsigned ShAmt = getShiftLeftAmt(Op0))
3218 return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt);
3219 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC))
3220 if (unsigned ShAmt = getShiftLeftAmt(Op1))
3221 return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt);
3222 }
3223 if (Op.getOpcode() == ISD::SUB) {
3224 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC))
3225 if (unsigned ShAmt = getShiftLeftAmt(Op1))
3226 return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt);
3227 }
3228 }
3229
3230 if (Op.getOpcode() == ISD::MUL) {
3231 Known = KnownBits::mul(KnownOp0, KnownOp1);
3232 } else { // Op.getOpcode() is either ISD::ADD, ISD::PTRADD, or ISD::SUB.
3234 Op.getOpcode() != ISD::SUB, Flags.hasNoSignedWrap(),
3235 Flags.hasNoUnsignedWrap(), KnownOp0, KnownOp1);
3236 }
3237 break;
3238 }
3239 case ISD::FABS: {
3240 SDValue Op0 = Op.getOperand(0);
3241 APInt SignMask = APInt::getSignMask(BitWidth);
3242
3243 if (!DemandedBits.intersects(SignMask))
3244 return TLO.CombineTo(Op, Op0);
3245
3246 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3247 Depth + 1))
3248 return true;
3249
3250 if (Known.isNonNegative())
3251 return TLO.CombineTo(Op, Op0);
3252 if (Known.isNegative())
3253 return TLO.CombineTo(
3254 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT, Op0, Op->getFlags()));
3255
3256 Known.Zero |= SignMask;
3257 Known.One &= ~SignMask;
3258
3259 break;
3260 }
3261 case ISD::FCOPYSIGN: {
3262 SDValue Op0 = Op.getOperand(0);
3263 SDValue Op1 = Op.getOperand(1);
3264
3265 unsigned BitWidth0 = Op0.getScalarValueSizeInBits();
3266 unsigned BitWidth1 = Op1.getScalarValueSizeInBits();
3267 APInt SignMask0 = APInt::getSignMask(BitWidth0);
3268 APInt SignMask1 = APInt::getSignMask(BitWidth1);
3269
3270 if (!DemandedBits.intersects(SignMask0))
3271 return TLO.CombineTo(Op, Op0);
3272
3273 if (SimplifyDemandedBits(Op0, ~SignMask0 & DemandedBits, DemandedElts,
3274 Known, TLO, Depth + 1) ||
3275 SimplifyDemandedBits(Op1, SignMask1, DemandedElts, Known2, TLO,
3276 Depth + 1))
3277 return true;
3278
3279 if (Known2.isNonNegative())
3280 return TLO.CombineTo(
3281 Op, TLO.DAG.getNode(ISD::FABS, dl, VT, Op0, Op->getFlags()));
3282
3283 if (Known2.isNegative())
3284 return TLO.CombineTo(
3285 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT,
3286 TLO.DAG.getNode(ISD::FABS, SDLoc(Op0), VT, Op0)));
3287
3288 Known.Zero &= ~SignMask0;
3289 Known.One &= ~SignMask0;
3290 break;
3291 }
3292 case ISD::FNEG: {
3293 SDValue Op0 = Op.getOperand(0);
3294 APInt SignMask = APInt::getSignMask(BitWidth);
3295
3296 if (!DemandedBits.intersects(SignMask))
3297 return TLO.CombineTo(Op, Op0);
3298
3299 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3300 Depth + 1))
3301 return true;
3302
3303 if (!Known.isSignUnknown()) {
3304 Known.Zero ^= SignMask;
3305 Known.One ^= SignMask;
3306 }
3307
3308 break;
3309 }
3310 default:
3311 // We also ask the target about intrinsics (which could be specific to it).
3312 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3313 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
3314 // TODO: Probably okay to remove after audit; here to reduce change size
3315 // in initial enablement patch for scalable vectors
3316 if (Op.getValueType().isScalableVector())
3317 break;
3319 Known, TLO, Depth))
3320 return true;
3321 break;
3322 }
3323
3324 // Just use computeKnownBits to compute output bits.
3325 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
3326 break;
3327 }
3328
3329 // If we know the value of all of the demanded bits, return this as a
3330 // constant.
3332 DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
3333 // Avoid folding to a constant if any OpaqueConstant is involved.
3334 if (llvm::any_of(Op->ops(), [](SDValue V) {
3335 auto *C = dyn_cast<ConstantSDNode>(V);
3336 return C && C->isOpaque();
3337 }))
3338 return false;
3339 if (VT.isInteger())
3340 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
3341 if (VT.isFloatingPoint())
3342 return TLO.CombineTo(
3344 dl, VT));
3345 }
3346
3347 // A multi use 'all demanded elts' simplify failed to find any knownbits.
3348 // Try again just for the original demanded elts.
3349 // Ensure we do this AFTER constant folding above.
3350 if (HasMultiUse && Known.isUnknown() && !OriginalDemandedElts.isAllOnes())
3351 Known = TLO.DAG.computeKnownBits(Op, OriginalDemandedElts, Depth);
3352
3353 return false;
3354}
3355
3357 const APInt &DemandedElts,
3358 DAGCombinerInfo &DCI) const {
3359 SelectionDAG &DAG = DCI.DAG;
3360 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
3361 !DCI.isBeforeLegalizeOps());
3362
3363 APInt KnownUndef, KnownZero;
3364 bool Simplified =
3365 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
3366 if (Simplified) {
3367 DCI.AddToWorklist(Op.getNode());
3368 DCI.CommitTargetLoweringOpt(TLO);
3369 }
3370
3371 return Simplified;
3372}
3373
3374/// Given a vector binary operation and known undefined elements for each input
3375/// operand, compute whether each element of the output is undefined.
3377 const APInt &UndefOp0,
3378 const APInt &UndefOp1) {
3379 EVT VT = BO.getValueType();
3381 "Vector binop only");
3382
3383 EVT EltVT = VT.getVectorElementType();
3384 unsigned NumElts = VT.isFixedLengthVector() ? VT.getVectorNumElements() : 1;
3385 assert(UndefOp0.getBitWidth() == NumElts &&
3386 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
3387
3388 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
3389 const APInt &UndefVals) {
3390 if (UndefVals[Index])
3391 return DAG.getUNDEF(EltVT);
3392
3393 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
3394 // Try hard to make sure that the getNode() call is not creating temporary
3395 // nodes. Ignore opaque integers because they do not constant fold.
3396 SDValue Elt = BV->getOperand(Index);
3397 auto *C = dyn_cast<ConstantSDNode>(Elt);
3398 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
3399 return Elt;
3400 }
3401
3402 return SDValue();
3403 };
3404
3405 APInt KnownUndef = APInt::getZero(NumElts);
3406 for (unsigned i = 0; i != NumElts; ++i) {
3407 // If both inputs for this element are either constant or undef and match
3408 // the element type, compute the constant/undef result for this element of
3409 // the vector.
3410 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
3411 // not handle FP constants. The code within getNode() should be refactored
3412 // to avoid the danger of creating a bogus temporary node here.
3413 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
3414 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
3415 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
3416 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
3417 KnownUndef.setBit(i);
3418 }
3419 return KnownUndef;
3420}
3421
3423 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
3424 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
3425 bool AssumeSingleUse) const {
3426 EVT VT = Op.getValueType();
3427 unsigned Opcode = Op.getOpcode();
3428 APInt DemandedElts = OriginalDemandedElts;
3429 unsigned NumElts = DemandedElts.getBitWidth();
3430 assert(VT.isVector() && "Expected vector op");
3431
3432 KnownUndef = KnownZero = APInt::getZero(NumElts);
3433
3435 return false;
3436
3437 // TODO: For now we assume we know nothing about scalable vectors.
3438 if (VT.isScalableVector())
3439 return false;
3440
3441 assert(VT.getVectorNumElements() == NumElts &&
3442 "Mask size mismatches value type element count!");
3443
3444 // Undef operand.
3445 if (Op.isUndef()) {
3446 KnownUndef.setAllBits();
3447 return false;
3448 }
3449
3450 // If Op has other users, assume that all elements are needed.
3451 if (!AssumeSingleUse && !Op.getNode()->hasOneUse())
3452 DemandedElts.setAllBits();
3453
3454 // Not demanding any elements from Op.
3455 if (DemandedElts == 0) {
3456 KnownUndef.setAllBits();
3457 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3458 }
3459
3460 // Limit search depth.
3462 return false;
3463
3464 SDLoc DL(Op);
3465 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3466 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
3467
3468 auto TryShrinkBinOp = [&](SDValue Op0, SDValue Op1) {
3469 unsigned ShrunkSize = getPreferredShrunkVectorSizeInBits(Op, DemandedElts);
3470 if (!ShrunkSize)
3471 return false;
3472
3473 assert(ShrunkSize % EltSizeInBits == 0 &&
3474 "Shrunk size not a multiple of element size");
3475 assert(ShrunkSize < VT.getSizeInBits() &&
3476 "Shrunk size must be < original vector size");
3477 assert(ShrunkSize >= EltSizeInBits * DemandedElts.getActiveBits() &&
3478 "Shrunk size must be >= demanded size");
3479
3480 EVT ShrunkVT = VT.changeVectorElementCount(
3481 *TLO.DAG.getContext(),
3482 ElementCount::getFixed(ShrunkSize / EltSizeInBits));
3483 Op0 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op0, 0);
3484 Op1 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op1, 0);
3485 SDValue NewOp =
3486 TLO.DAG.getNode(Opcode, DL, ShrunkVT, Op0, Op1, Op->getFlags());
3487 return TLO.CombineTo(
3488 Op, TLO.DAG.getInsertSubvector(DL, TLO.DAG.getUNDEF(VT), NewOp, 0));
3489 };
3490
3491 // Helper for demanding the specified elements and all the bits of both binary
3492 // operands.
3493 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
3494 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts,
3495 TLO.DAG, Depth + 1);
3496 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts,
3497 TLO.DAG, Depth + 1);
3498 if (NewOp0 || NewOp1) {
3499 SDValue NewOp =
3500 TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0,
3501 NewOp1 ? NewOp1 : Op1, Op->getFlags());
3502 return TLO.CombineTo(Op, NewOp);
3503 }
3504
3505 if (TryShrinkBinOp(Op0, Op1))
3506 return true;
3507
3508 return false;
3509 };
3510
3511 switch (Opcode) {
3512 case ISD::SCALAR_TO_VECTOR: {
3513 if (!DemandedElts[0])
3514 return TLO.CombineTo(Op, TLO.DAG.getPOISON(VT));
3515 // Upper elements are poison, not undef - don't mark them as KnownUndef.
3516 break;
3517 }
3518 case ISD::BITCAST: {
3519 SDValue Src = Op.getOperand(0);
3520 EVT SrcVT = Src.getValueType();
3521
3522 if (!SrcVT.isVector()) {
3523 // TODO - bigendian once we have test coverage.
3524 if (IsLE) {
3525 APInt DemandedSrcBits = APInt::getZero(SrcVT.getSizeInBits());
3526 unsigned EltSize = VT.getScalarSizeInBits();
3527 for (unsigned I = 0; I != NumElts; ++I) {
3528 if (DemandedElts[I]) {
3529 unsigned Offset = I * EltSize;
3530 DemandedSrcBits.setBits(Offset, Offset + EltSize);
3531 }
3532 }
3534 if (SimplifyDemandedBits(Src, DemandedSrcBits, Known, TLO, Depth + 1))
3535 return true;
3536 }
3537 break;
3538 }
3539
3540 // Fast handling of 'identity' bitcasts.
3541 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3542 if (NumSrcElts == NumElts)
3543 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
3544 KnownZero, TLO, Depth + 1);
3545
3546 APInt SrcDemandedElts, SrcZero, SrcUndef;
3547
3548 // Bitcast from 'large element' src vector to 'small element' vector, we
3549 // must demand a source element if any DemandedElt maps to it.
3550 if ((NumElts % NumSrcElts) == 0) {
3551 unsigned Scale = NumElts / NumSrcElts;
3552 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3553 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3554 TLO, Depth + 1))
3555 return true;
3556
3557 // Try calling SimplifyDemandedBits, converting demanded elts to the bits
3558 // of the large element.
3559 // TODO - bigendian once we have test coverage.
3560 if (IsLE) {
3561 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
3562 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits);
3563 for (unsigned i = 0; i != NumElts; ++i)
3564 if (DemandedElts[i]) {
3565 unsigned Ofs = (i % Scale) * EltSizeInBits;
3566 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
3567 }
3568
3570 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
3571 TLO, Depth + 1))
3572 return true;
3573
3574 // The bitcast has split each wide element into a number of
3575 // narrow subelements. We have just computed the Known bits
3576 // for wide elements. See if element splitting results in
3577 // some subelements being zero. Only for demanded elements!
3578 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) {
3579 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits)
3580 .isAllOnes())
3581 continue;
3582 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) {
3583 unsigned Elt = Scale * SrcElt + SubElt;
3584 // A wholly-undef source lane is reported as undef below; don't also
3585 // flag it as zero, keeping the undef and zero sets disjoint.
3586 if (DemandedElts[Elt] && !SrcUndef[SrcElt])
3587 KnownZero.setBit(Elt);
3588 }
3589 }
3590 }
3591
3592 // If the src element is zero/undef then all the output elements will be -
3593 // only demanded elements are guaranteed to be correct.
3594 for (unsigned i = 0; i != NumSrcElts; ++i) {
3595 if (SrcDemandedElts[i]) {
3596 if (SrcZero[i])
3597 KnownZero.setBits(i * Scale, (i + 1) * Scale);
3598 if (SrcUndef[i])
3599 KnownUndef.setBits(i * Scale, (i + 1) * Scale);
3600 }
3601 }
3602 }
3603
3604 // Bitcast from 'small element' src vector to 'large element' vector, we
3605 // demand all smaller source elements covered by the larger demanded element
3606 // of this vector.
3607 if ((NumSrcElts % NumElts) == 0) {
3608 unsigned Scale = NumSrcElts / NumElts;
3609 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3610 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3611 TLO, Depth + 1))
3612 return true;
3613
3614 // If all the src elements covering an output element are zero/undef, then
3615 // the output element will be as well, assuming it was demanded.
3616 for (unsigned i = 0; i != NumElts; ++i) {
3617 if (DemandedElts[i]) {
3618 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes())
3619 KnownZero.setBit(i);
3620 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes())
3621 KnownUndef.setBit(i);
3622 }
3623 }
3624 }
3625 break;
3626 }
3627 case ISD::FREEZE: {
3628 SDValue N0 = Op.getOperand(0);
3630 N0, DemandedElts, UndefPoisonKind::UndefOrPoison, Depth + 1))
3631 return TLO.CombineTo(Op, N0);
3632
3633 // TODO: Replace this with the general fold from DAGCombiner::visitFREEZE
3634 // freeze(op(x, ...)) -> op(freeze(x), ...).
3635 // Don't sink the freeze below SCALAR_TO_VECTOR when the scalar is a load
3636 // of a promoted (wider than the element) type: freeze(load) can never be
3637 // folded away (the loaded value may be poison in memory), and the extra
3638 // freeze node then blocks ISel patterns matching scalar_to_vector of a
3639 // load, e.g. the AArch64 scalar_to_vector(extload) -> ldr b/h forms.
3640 // freeze(scalar_to_vector(load)) is equivalent for the demanded element
3641 // zero, and ISel selects the freeze as a plain copy.
3642 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && DemandedElts == 1) {
3643 SDValue Scalar = N0.getOperand(0);
3644 bool IsPromotedLoad = Scalar.getOpcode() == ISD::LOAD &&
3645 Scalar.getValueType() != VT.getVectorElementType();
3646 if (!IsPromotedLoad)
3647 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT,
3648 TLO.DAG.getFreeze(Scalar)));
3649 }
3650 break;
3651 }
3652 case ISD::BUILD_VECTOR: {
3653 // Check all elements and simplify any unused elements with UNDEF.
3654 if (!DemandedElts.isAllOnes()) {
3655 // Don't simplify BROADCASTS.
3656 if (llvm::any_of(Op->op_values(),
3657 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
3659 bool Updated = false;
3660 for (unsigned i = 0; i != NumElts; ++i) {
3661 if (!DemandedElts[i] && !Ops[i].isUndef()) {
3662 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
3663 KnownUndef.setBit(i);
3664 Updated = true;
3665 }
3666 }
3667 if (Updated)
3668 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
3669 }
3670 }
3671 for (unsigned i = 0; i != NumElts; ++i) {
3672 SDValue SrcOp = Op.getOperand(i);
3673 if (SrcOp.isUndef()) {
3674 KnownUndef.setBit(i);
3675 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
3677 KnownZero.setBit(i);
3678 }
3679 }
3680 break;
3681 }
3682 case ISD::CONCAT_VECTORS: {
3683 EVT SubVT = Op.getOperand(0).getValueType();
3684 unsigned NumSubVecs = Op.getNumOperands();
3685 unsigned NumSubElts = SubVT.getVectorNumElements();
3686 for (unsigned i = 0; i != NumSubVecs; ++i) {
3687 SDValue SubOp = Op.getOperand(i);
3688 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3689 APInt SubUndef, SubZero;
3690 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
3691 Depth + 1))
3692 return true;
3693 KnownUndef.insertBits(SubUndef, i * NumSubElts);
3694 KnownZero.insertBits(SubZero, i * NumSubElts);
3695 }
3696
3697 // Attempt to avoid multi-use ops if we don't need anything from them.
3698 if (!DemandedElts.isAllOnes()) {
3699 bool FoundNewSub = false;
3700 SmallVector<SDValue, 2> DemandedSubOps;
3701 for (unsigned i = 0; i != NumSubVecs; ++i) {
3702 SDValue SubOp = Op.getOperand(i);
3703 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3705 SubOp, SubElts, TLO.DAG, Depth + 1);
3706 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp);
3707 FoundNewSub = NewSubOp ? true : FoundNewSub;
3708 }
3709 if (FoundNewSub) {
3710 SDValue NewOp =
3711 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps);
3712 return TLO.CombineTo(Op, NewOp);
3713 }
3714 }
3715 break;
3716 }
3717 case ISD::INSERT_SUBVECTOR: {
3718 // Demand any elements from the subvector and the remainder from the src it
3719 // is inserted into.
3720 SDValue Src = Op.getOperand(0);
3721 SDValue Sub = Op.getOperand(1);
3722 uint64_t Idx = Op.getConstantOperandVal(2);
3723 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3724 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3725 APInt DemandedSrcElts = DemandedElts;
3726 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3727
3728 // If none of the sub operand elements are demanded, bypass the insert.
3729 if (!DemandedSubElts)
3730 return TLO.CombineTo(Op, Src);
3731
3732 APInt SubUndef, SubZero;
3733 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
3734 Depth + 1))
3735 return true;
3736
3737 // If none of the src operand elements are demanded, replace it with undef.
3738 if (!DemandedSrcElts && !Src.isUndef())
3739 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
3740 TLO.DAG.getUNDEF(VT), Sub,
3741 Op.getOperand(2)));
3742
3743 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
3744 TLO, Depth + 1))
3745 return true;
3746 KnownUndef.insertBits(SubUndef, Idx);
3747 KnownZero.insertBits(SubZero, Idx);
3748
3749 // Attempt to avoid multi-use ops if we don't need anything from them.
3750 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) {
3752 Src, DemandedSrcElts, TLO.DAG, Depth + 1);
3754 Sub, DemandedSubElts, TLO.DAG, Depth + 1);
3755 if (NewSrc || NewSub) {
3756 NewSrc = NewSrc ? NewSrc : Src;
3757 NewSub = NewSub ? NewSub : Sub;
3758 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3759 NewSub, Op.getOperand(2));
3760 return TLO.CombineTo(Op, NewOp);
3761 }
3762 }
3763 break;
3764 }
3766 // Offset the demanded elts by the subvector index.
3767 SDValue Src = Op.getOperand(0);
3768 if (Src.getValueType().isScalableVector())
3769 break;
3770 uint64_t Idx = Op.getConstantOperandVal(1);
3771 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3772 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3773
3774 APInt SrcUndef, SrcZero;
3775 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3776 Depth + 1))
3777 return true;
3778 KnownUndef = SrcUndef.extractBits(NumElts, Idx);
3779 KnownZero = SrcZero.extractBits(NumElts, Idx);
3780
3781 // Attempt to avoid multi-use ops if we don't need anything from them.
3782 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(Src, DemandedSrcElts,
3783 TLO.DAG, Depth + 1);
3784 if (NewSrc) {
3785 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3786 Op.getOperand(1));
3787 return TLO.CombineTo(Op, NewOp);
3788 }
3789 break;
3790 }
3792 SDValue Vec = Op.getOperand(0);
3793 SDValue Scl = Op.getOperand(1);
3794 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3795
3796 // For a legal, constant insertion index, if we don't need this insertion
3797 // then strip it, else remove it from the demanded elts.
3798 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
3799 unsigned Idx = CIdx->getZExtValue();
3800 if (!DemandedElts[Idx])
3801 return TLO.CombineTo(Op, Vec);
3802
3803 APInt DemandedVecElts(DemandedElts);
3804 DemandedVecElts.clearBit(Idx);
3805 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
3806 KnownZero, TLO, Depth + 1))
3807 return true;
3808
3809 KnownUndef.setBitVal(Idx, Scl.isUndef());
3810
3811 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
3812 break;
3813 }
3814
3815 APInt VecUndef, VecZero;
3816 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
3817 Depth + 1))
3818 return true;
3819 // Without knowing the insertion index we can't set KnownUndef/KnownZero.
3820 break;
3821 }
3822 case ISD::VSELECT: {
3823 SDValue Sel = Op.getOperand(0);
3824 SDValue LHS = Op.getOperand(1);
3825 SDValue RHS = Op.getOperand(2);
3826
3827 // Try to transform the select condition based on the current demanded
3828 // elements.
3829 APInt UndefSel, ZeroSel;
3830 if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, ZeroSel, TLO,
3831 Depth + 1))
3832 return true;
3833
3834 // See if we can simplify either vselect operand.
3835 APInt DemandedLHS(DemandedElts);
3836 APInt DemandedRHS(DemandedElts);
3837 APInt UndefLHS, ZeroLHS;
3838 APInt UndefRHS, ZeroRHS;
3839 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3840 Depth + 1))
3841 return true;
3842 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3843 Depth + 1))
3844 return true;
3845
3846 KnownUndef = UndefLHS & UndefRHS;
3847 KnownZero = ZeroLHS & ZeroRHS;
3848
3849 // If we know that the selected element is always zero, we don't need the
3850 // select value element.
3851 APInt DemandedSel = DemandedElts & ~KnownZero;
3852 if (DemandedSel != DemandedElts)
3853 if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, ZeroSel, TLO,
3854 Depth + 1))
3855 return true;
3856
3857 break;
3858 }
3859 case ISD::VECTOR_SHUFFLE: {
3860 SDValue LHS = Op.getOperand(0);
3861 SDValue RHS = Op.getOperand(1);
3862 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
3863
3864 // Collect demanded elements from shuffle operands..
3865 APInt DemandedLHS(NumElts, 0);
3866 APInt DemandedRHS(NumElts, 0);
3867 for (unsigned i = 0; i != NumElts; ++i) {
3868 int M = ShuffleMask[i];
3869 if (M < 0 || !DemandedElts[i])
3870 continue;
3871 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
3872 if (M < (int)NumElts)
3873 DemandedLHS.setBit(M);
3874 else
3875 DemandedRHS.setBit(M - NumElts);
3876 }
3877
3878 // If either side isn't demanded, replace it by UNDEF. We handle this
3879 // explicitly here to also simplify in case of multiple uses (on the
3880 // contrary to the SimplifyDemandedVectorElts calls below).
3881 bool FoldLHS = !DemandedLHS && !LHS.isUndef();
3882 bool FoldRHS = !DemandedRHS && !RHS.isUndef();
3883 if (FoldLHS || FoldRHS) {
3884 LHS = FoldLHS ? TLO.DAG.getUNDEF(LHS.getValueType()) : LHS;
3885 RHS = FoldRHS ? TLO.DAG.getUNDEF(RHS.getValueType()) : RHS;
3886 SDValue NewOp =
3887 TLO.DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, ShuffleMask);
3888 return TLO.CombineTo(Op, NewOp);
3889 }
3890
3891 // See if we can simplify either shuffle operand.
3892 APInt UndefLHS, ZeroLHS;
3893 APInt UndefRHS, ZeroRHS;
3894 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3895 Depth + 1))
3896 return true;
3897 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3898 Depth + 1))
3899 return true;
3900
3901 // Simplify mask using undef elements from LHS/RHS.
3902 bool Updated = false;
3903 bool IdentityLHS = true, IdentityRHS = true;
3904 SmallVector<int, 32> NewMask(ShuffleMask);
3905 for (unsigned i = 0; i != NumElts; ++i) {
3906 int &M = NewMask[i];
3907 if (M < 0)
3908 continue;
3909 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
3910 (M >= (int)NumElts && UndefRHS[M - NumElts])) {
3911 Updated = true;
3912 M = -1;
3913 }
3914 IdentityLHS &= (M < 0) || (M == (int)i);
3915 IdentityRHS &= (M < 0) || ((M - NumElts) == i);
3916 }
3917
3918 // Update legal shuffle masks based on demanded elements if it won't reduce
3919 // to Identity which can cause premature removal of the shuffle mask.
3920 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
3921 SDValue LegalShuffle =
3922 buildLegalVectorShuffle(VT, DL, LHS, RHS, NewMask, TLO.DAG);
3923 if (LegalShuffle)
3924 return TLO.CombineTo(Op, LegalShuffle);
3925 }
3926
3927 // Propagate undef/zero elements from LHS/RHS.
3928 for (unsigned i = 0; i != NumElts; ++i) {
3929 int M = ShuffleMask[i];
3930 if (M < 0) {
3931 KnownUndef.setBit(i);
3932 } else if (M < (int)NumElts) {
3933 if (UndefLHS[M])
3934 KnownUndef.setBit(i);
3935 if (ZeroLHS[M])
3936 KnownZero.setBit(i);
3937 } else {
3938 if (UndefRHS[M - NumElts])
3939 KnownUndef.setBit(i);
3940 if (ZeroRHS[M - NumElts])
3941 KnownZero.setBit(i);
3942 }
3943 }
3944 break;
3945 }
3949 APInt SrcUndef, SrcZero;
3950 SDValue Src = Op.getOperand(0);
3951 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3952 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3953 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3954 Depth + 1))
3955 return true;
3956 KnownZero = SrcZero.zextOrTrunc(NumElts);
3957 KnownUndef = SrcUndef.zextOrTrunc(NumElts);
3958
3959 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
3960 Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
3961 DemandedSrcElts == 1) {
3962 // aext - if we just need the bottom element then we can bitcast.
3963 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
3964 }
3965
3966 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
3967 // zext(undef) upper bits are guaranteed to be zero.
3968 if (DemandedElts.isSubsetOf(KnownUndef))
3969 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3970 KnownUndef.clearAllBits();
3971
3972 // zext - if we just need the bottom element then we can mask:
3973 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
3974 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
3975 Op->isOnlyUserOf(Src.getNode()) &&
3976 Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
3977 SDLoc DL(Op);
3978 EVT SrcVT = Src.getValueType();
3979 EVT SrcSVT = SrcVT.getScalarType();
3980
3981 // If we're after type legalization and SrcSVT is not legal, use the
3982 // promoted type for creating constants to avoid creating nodes with
3983 // illegal types.
3984 if (TLO.LegalTypes())
3985 SrcSVT = getLegalTypeToTransformTo(*TLO.DAG.getContext(), SrcSVT);
3986
3987 SmallVector<SDValue> MaskElts;
3988 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
3989 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
3990 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
3991 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
3992 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
3993 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
3994 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
3995 }
3996 }
3997 }
3998 break;
3999 }
4000
4001 // TODO: There are more binop opcodes that could be handled here - MIN,
4002 // MAX, saturated math, etc.
4003 case ISD::ADD: {
4004 SDValue Op0 = Op.getOperand(0);
4005 SDValue Op1 = Op.getOperand(1);
4006 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
4007 APInt UndefLHS, ZeroLHS;
4008 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4009 Depth + 1, /*AssumeSingleUse*/ true))
4010 return true;
4011 }
4012 [[fallthrough]];
4013 }
4014 case ISD::AVGCEILS:
4015 case ISD::AVGCEILU:
4016 case ISD::AVGFLOORS:
4017 case ISD::AVGFLOORU:
4018 case ISD::OR:
4019 case ISD::XOR:
4020 case ISD::SUB:
4021 case ISD::FADD:
4022 case ISD::FSUB:
4023 case ISD::FMUL:
4024 case ISD::FDIV:
4025 case ISD::FREM:
4026 case ISD::PSEUDO_FMIN:
4027 case ISD::PSEUDO_FMAX: {
4028 SDValue Op0 = Op.getOperand(0);
4029 SDValue Op1 = Op.getOperand(1);
4030
4031 APInt UndefRHS, ZeroRHS;
4032 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
4033 Depth + 1))
4034 return true;
4035 APInt UndefLHS, ZeroLHS;
4036 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4037 Depth + 1))
4038 return true;
4039
4040 KnownZero = ZeroLHS & ZeroRHS;
4041 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
4042
4043 // Attempt to avoid multi-use ops if we don't need anything from them.
4044 // TODO - use KnownUndef to relax the demandedelts?
4045 if (!DemandedElts.isAllOnes())
4046 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4047 return true;
4048 break;
4049 }
4050 case ISD::SHL:
4051 case ISD::SRL:
4052 case ISD::SRA:
4053 case ISD::ROTL:
4054 case ISD::ROTR: {
4055 SDValue Op0 = Op.getOperand(0);
4056 SDValue Op1 = Op.getOperand(1);
4057
4058 APInt UndefRHS, ZeroRHS;
4059 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
4060 Depth + 1))
4061 return true;
4062 APInt UndefLHS, ZeroLHS;
4063 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4064 Depth + 1))
4065 return true;
4066
4067 KnownZero = ZeroLHS;
4068 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
4069
4070 // Attempt to avoid multi-use ops if we don't need anything from them.
4071 // TODO - use KnownUndef to relax the demandedelts?
4072 if (!DemandedElts.isAllOnes())
4073 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4074 return true;
4075 break;
4076 }
4077 case ISD::MUL:
4078 case ISD::MULHU:
4079 case ISD::MULHS:
4080 case ISD::AND: {
4081 SDValue Op0 = Op.getOperand(0);
4082 SDValue Op1 = Op.getOperand(1);
4083
4084 APInt SrcUndef, SrcZero;
4085 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
4086 Depth + 1))
4087 return true;
4088 // FIXME: If we know that a demanded element was zero in Op1 we don't need
4089 // to demand it in Op0 - its guaranteed to be zero. There is however a
4090 // restriction, as we must not make any of the originally demanded elements
4091 // more poisonous. We could reduce amount of elements demanded, but then we
4092 // also need a to inform SimplifyDemandedVectorElts that some elements must
4093 // not be made more poisonous.
4094 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
4095 TLO, Depth + 1))
4096 return true;
4097
4098 KnownUndef &= DemandedElts;
4099 KnownZero &= DemandedElts;
4100
4101 // If every element pair has a zero/undef/poison then just fold to zero.
4102 // fold (and x, undef/poison) -> 0 / (and x, 0) -> 0
4103 // fold (mul x, undef/poison) -> 0 / (mul x, 0) -> 0
4104 if (DemandedElts.isSubsetOf(SrcZero | KnownZero | SrcUndef | KnownUndef))
4105 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4106
4107 // If either side has a zero element, then the result element is zero, even
4108 // if the other is an UNDEF.
4109 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
4110 // and then handle 'and' nodes with the rest of the binop opcodes.
4111 KnownZero |= SrcZero;
4112 KnownUndef &= SrcUndef;
4113 KnownUndef &= ~KnownZero;
4114
4115 // Attempt to avoid multi-use ops if we don't need anything from them.
4116 if (!DemandedElts.isAllOnes())
4117 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4118 return true;
4119 break;
4120 }
4121 case ISD::TRUNCATE:
4122 case ISD::SIGN_EXTEND:
4123 case ISD::ZERO_EXTEND:
4124 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
4125 KnownZero, TLO, Depth + 1))
4126 return true;
4127
4128 if (!DemandedElts.isAllOnes())
4130 Op.getOperand(0), DemandedElts, TLO.DAG, Depth + 1))
4131 return TLO.CombineTo(Op, TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp));
4132
4133 if (Op.getOpcode() == ISD::ZERO_EXTEND) {
4134 // zext(undef) upper bits are guaranteed to be zero.
4135 if (DemandedElts.isSubsetOf(KnownUndef))
4136 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4137 KnownUndef.clearAllBits();
4138 }
4139 break;
4140 case ISD::SINT_TO_FP:
4141 case ISD::UINT_TO_FP:
4142 case ISD::FP_TO_SINT:
4143 case ISD::FP_TO_UINT:
4144 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
4145 KnownZero, TLO, Depth + 1))
4146 return true;
4147 // Don't fall through to generic undef -> undef handling.
4148 return false;
4149 default: {
4150 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
4151 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
4152 KnownZero, TLO, Depth))
4153 return true;
4154 } else {
4156 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
4157 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
4158 TLO, Depth, AssumeSingleUse))
4159 return true;
4160 }
4161 break;
4162 }
4163 }
4164
4165 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
4166
4167 // Constant fold all undef cases.
4168 // TODO: Handle zero cases as well.
4169 if (DemandedElts.isSubsetOf(KnownUndef))
4170 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
4171
4172 return false;
4173}
4174
4175/// Determine which of the bits specified in Mask are known to be either zero or
4176/// one and return them in the Known.
4179 const APInt &DemandedElts,
4180 const SelectionDAG &DAG,
4181 unsigned Depth) const {
4182 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4183 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4184 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4185 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4186 "Should use MaskedValueIsZero if you don't know whether Op"
4187 " is a target node!");
4188 Known.resetAll();
4189}
4190
4193 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4194 unsigned Depth) const {
4195 Known.resetAll();
4196}
4197
4200 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4201 unsigned Depth) const {
4202 Known.resetAll();
4203}
4204
4206 KnownBits &Known, const MachineFunction &, Align Alignment) const {
4207 // The low bits are known zero if the pointer is aligned.
4208 Known.Zero.setLowBits(Log2(Alignment));
4209}
4210
4212 SelectionDAG &DAG,
4213 const SDLoc &DL,
4214 Align Alignment) const {
4215 // Materialize leading-zero stack object pointer facts as AssertZext.
4216 // Alignment-derived low zero bits are not represented on the returned DAG
4217 // value here.
4218 EVT PtrVT = Ptr.getValueType();
4219
4220 unsigned RegSize = PtrVT.getScalarSizeInBits();
4223 Alignment);
4224
4225 unsigned NumZeroBits = Known.countMinLeadingZeros();
4226 if (!NumZeroBits)
4227 return Ptr;
4228
4229 EVT FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
4230 return DAG.getNode(ISD::AssertZext, DL, PtrVT, Ptr, DAG.getValueType(FromVT));
4231}
4232
4238
4239/// This method can be implemented by targets that want to expose additional
4240/// information about sign bits to the DAG Combiner.
4242 const APInt &,
4243 const SelectionDAG &,
4244 unsigned Depth) const {
4245 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4246 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4247 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4248 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4249 "Should use ComputeNumSignBits if you don't know whether Op"
4250 " is a target node!");
4251 return 1;
4252}
4253
4255 GISelValueTracking &Analysis, Register R, const APInt &DemandedElts,
4256 const MachineRegisterInfo &MRI, unsigned Depth) const {
4257 return 1;
4258}
4259
4261 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
4262 TargetLoweringOpt &TLO, unsigned Depth) const {
4263 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4264 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4265 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4266 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4267 "Should use SimplifyDemandedVectorElts if you don't know whether Op"
4268 " is a target node!");
4269 return false;
4270}
4271
4273 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4274 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
4275 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4276 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4277 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4278 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4279 "Should use SimplifyDemandedBits if you don't know whether Op"
4280 " is a target node!");
4281 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
4282 return false;
4283}
4284
4286 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4287 SelectionDAG &DAG, unsigned Depth) const {
4288 assert(
4289 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4290 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4291 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4292 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4293 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
4294 " is a target node!");
4295 return SDValue();
4296}
4297
4298SDValue
4301 SelectionDAG &DAG) const {
4302 bool LegalMask = isShuffleMaskLegal(Mask, VT);
4303 if (!LegalMask) {
4304 std::swap(N0, N1);
4306 LegalMask = isShuffleMaskLegal(Mask, VT);
4307 }
4308
4309 if (!LegalMask)
4310 return SDValue();
4311
4312 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
4313}
4314
4316 return nullptr;
4317}
4318
4320 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4321 UndefPoisonKind Kind, unsigned Depth) const {
4322 assert(
4323 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4324 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4325 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4326 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4327 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
4328 " is a target node!");
4329
4330 // If Op can't create undef/poison and none of its operands are undef/poison
4331 // then Op is never undef/poison.
4332 return !canCreateUndefOrPoisonForTargetNode(Op, DemandedElts, DAG, Kind,
4333 /*ConsiderFlags*/ true, Depth) &&
4334 all_of(Op->ops(), [&](SDValue V) {
4335 return DAG.isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
4336 });
4337}
4338
4340 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4341 UndefPoisonKind Kind, bool ConsiderFlags, unsigned Depth) const {
4342 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4343 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4344 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4345 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4346 "Should use canCreateUndefOrPoison if you don't know whether Op"
4347 " is a target node!");
4348 // Be conservative and return true.
4349 return true;
4350}
4351
4354 const APInt &DemandedElts,
4355 const SelectionDAG &DAG,
4356 unsigned Depth) const {
4357 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4358 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4359 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4360 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4361 "Should use computeKnownFPClass if you don't know whether Op"
4362 " is a target node!");
4363}
4364
4366 const APInt &DemandedElts,
4367 const SelectionDAG &DAG,
4368 bool SNaN,
4369 unsigned Depth) const {
4370 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4371 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4372 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4373 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4374 "Should use isKnownNeverNaN if you don't know whether Op"
4375 " is a target node!");
4376 return false;
4377}
4378
4380 const APInt &DemandedElts,
4381 APInt &UndefElts,
4382 const SelectionDAG &DAG,
4383 unsigned Depth) const {
4384 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4385 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4386 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4387 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4388 "Should use isSplatValue if you don't know whether Op"
4389 " is a target node!");
4390 return false;
4391}
4392
4393// FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
4394// work with truncating build vectors and vectors with elements of less than
4395// 8 bits.
4397 if (!N)
4398 return false;
4399
4400 unsigned EltWidth;
4401 APInt CVal;
4402 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
4403 /*AllowTruncation=*/true)) {
4404 CVal = CN->getAPIntValue();
4405 EltWidth = N.getValueType().getScalarSizeInBits();
4406 } else
4407 return false;
4408
4409 // If this is a truncating splat, truncate the splat value.
4410 // Otherwise, we may fail to match the expected values below.
4411 if (EltWidth < CVal.getBitWidth())
4412 CVal = CVal.trunc(EltWidth);
4413
4414 switch (getBooleanContents(N.getValueType())) {
4416 return CVal[0];
4418 return CVal.isOne();
4420 return CVal.isAllOnes();
4421 }
4422
4423 llvm_unreachable("Invalid boolean contents");
4424}
4425
4427 if (!N)
4428 return false;
4429
4431 if (!CN) {
4433 if (!BV)
4434 return false;
4435
4436 // Only interested in constant splats, we don't care about undef
4437 // elements in identifying boolean constants and getConstantSplatNode
4438 // returns NULL if all ops are undef;
4439 CN = BV->getConstantSplatNode();
4440 if (!CN)
4441 return false;
4442 }
4443
4444 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
4445 return !CN->getAPIntValue()[0];
4446
4447 return CN->isZero();
4448}
4449
4451 bool SExt) const {
4452 if (VT == MVT::i1)
4453 return N->isOne();
4454
4456 switch (Cnt) {
4458 // An extended value of 1 is always true, unless its original type is i1,
4459 // in which case it will be sign extended to -1.
4460 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
4463 return N->isAllOnes() && SExt;
4464 }
4465 llvm_unreachable("Unexpected enumeration.");
4466}
4467
4468/// This helper function of SimplifySetCC tries to optimize the comparison when
4469/// either operand of the SetCC node is a bitwise-and instruction.
4470SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
4471 ISD::CondCode Cond, const SDLoc &DL,
4472 DAGCombinerInfo &DCI) const {
4473 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
4474 std::swap(N0, N1);
4475
4476 SelectionDAG &DAG = DCI.DAG;
4477 EVT OpVT = N0.getValueType();
4478 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
4479 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4480 return SDValue();
4481
4482 // (X & Y) != 0 --> zextOrTrunc(X & Y)
4483 // iff everything but LSB is known zero:
4484 if (Cond == ISD::SETNE && isNullConstant(N1) &&
4487 unsigned NumEltBits = OpVT.getScalarSizeInBits();
4488 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
4489 if (DAG.MaskedValueIsZero(N0, UpperBits))
4490 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
4491 }
4492
4493 // Try to eliminate a power-of-2 mask constant by converting to a signbit
4494 // test in a narrow type that we can truncate to with no cost. Examples:
4495 // (i32 X & 32768) == 0 --> (trunc X to i16) >= 0
4496 // (i32 X & 32768) != 0 --> (trunc X to i16) < 0
4497 // TODO: This conservatively checks for type legality on the source and
4498 // destination types. That may inhibit optimizations, but it also
4499 // allows setcc->shift transforms that may be more beneficial.
4500 auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4501 if (AndC && isNullConstant(N1) && AndC->getAPIntValue().isPowerOf2() &&
4502 isTypeLegal(OpVT) && N0.hasOneUse()) {
4503 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(),
4504 AndC->getAPIntValue().getActiveBits());
4505 if (isTruncateFree(OpVT, NarrowVT) && isTypeLegal(NarrowVT)) {
4506 SDValue Trunc = DAG.getZExtOrTrunc(N0.getOperand(0), DL, NarrowVT);
4507 SDValue Zero = DAG.getConstant(0, DL, NarrowVT);
4508 return DAG.getSetCC(DL, VT, Trunc, Zero,
4510 }
4511 }
4512
4513 // Match these patterns in any of their permutations:
4514 // (X & Y) == Y
4515 // (X & Y) != Y
4516 SDValue X, Y;
4517 if (N0.getOperand(0) == N1) {
4518 X = N0.getOperand(1);
4519 Y = N0.getOperand(0);
4520 } else if (N0.getOperand(1) == N1) {
4521 X = N0.getOperand(0);
4522 Y = N0.getOperand(1);
4523 } else {
4524 return SDValue();
4525 }
4526
4527 // TODO: We should invert (X & Y) eq/ne 0 -> (X & Y) ne/eq Y if
4528 // `isXAndYEqZeroPreferableToXAndYEqY` is false. This is a bit difficult as
4529 // its liable to create and infinite loop.
4530 SDValue Zero = DAG.getConstant(0, DL, OpVT);
4531 if (isXAndYEqZeroPreferableToXAndYEqY(Cond, OpVT) &&
4533 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
4534 // Note that where Y is variable and is known to have at most one bit set
4535 // (for example, if it is Z & 1) we cannot do this; the expressions are not
4536 // equivalent when Y == 0.
4537 assert(OpVT.isInteger());
4539 if (DCI.isBeforeLegalizeOps() ||
4541 return DAG.getSetCC(DL, VT, N0, Zero, Cond);
4542 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
4543 // If the target supports an 'and-not' or 'and-complement' logic operation,
4544 // try to use that to make a comparison operation more efficient.
4545 // But don't do this transform if the mask is a single bit because there are
4546 // more efficient ways to deal with that case (for example, 'bt' on x86 or
4547 // 'rlwinm' on PPC).
4548
4549 // Bail out if the compare operand that we want to turn into a zero is
4550 // already a zero (otherwise, infinite loop).
4551 if (isNullConstant(Y))
4552 return SDValue();
4553
4554 // Transform this into: ~X & Y == 0.
4555 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
4556 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
4557 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
4558 }
4559
4560 return SDValue();
4561}
4562
4563/// This helper function of SimplifySetCC tries to optimize the comparison when
4564/// either operand of the SetCC node is a bitwise-or instruction.
4565/// For now, this just transforms (X | Y) ==/!= Y into X & ~Y ==/!= 0.
4566SDValue TargetLowering::foldSetCCWithOr(EVT VT, SDValue N0, SDValue N1,
4567 ISD::CondCode Cond, const SDLoc &DL,
4568 DAGCombinerInfo &DCI) const {
4569 if (N1.getOpcode() == ISD::OR && N0.getOpcode() != ISD::OR)
4570 std::swap(N0, N1);
4571
4572 SelectionDAG &DAG = DCI.DAG;
4573 EVT OpVT = N0.getValueType();
4574 if (!N0.hasOneUse() || !OpVT.isInteger() ||
4575 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4576 return SDValue();
4577
4578 // (X | Y) == Y
4579 // (X | Y) != Y
4580 SDValue X;
4581 if (sd_match(N0, m_Or(m_Value(X), m_Specific(N1))) && hasAndNotCompare(X)) {
4582 // If the target supports an 'and-not' or 'and-complement' logic operation,
4583 // try to use that to make a comparison operation more efficient.
4584
4585 // Bail out if the compare operand that we want to turn into a zero is
4586 // already a zero (otherwise, infinite loop).
4587 if (isNullConstant(N1))
4588 return SDValue();
4589
4590 // Transform this into: X & ~Y ==/!= 0.
4591 SDValue NotY = DAG.getNOT(SDLoc(N1), N1, OpVT);
4592 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, X, NotY);
4593 return DAG.getSetCC(DL, VT, NewAnd, DAG.getConstant(0, DL, OpVT), Cond);
4594 }
4595
4596 return SDValue();
4597}
4598
4599/// There are multiple IR patterns that could be checking whether certain
4600/// truncation of a signed number would be lossy or not. The pattern which is
4601/// best at IR level, may not lower optimally. Thus, we want to unfold it.
4602/// We are looking for the following pattern: (KeptBits is a constant)
4603/// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
4604/// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
4605/// KeptBits also can't be 1, that would have been folded to %x dstcond 0
4606/// We will unfold it into the natural trunc+sext pattern:
4607/// ((%x << C) a>> C) dstcond %x
4608/// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x)
4609SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
4610 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
4611 const SDLoc &DL) const {
4612 // We must be comparing with a constant.
4613 ConstantSDNode *C1;
4614 if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
4615 return SDValue();
4616
4617 // N0 should be: add %x, (1 << (KeptBits-1))
4618 if (N0->getOpcode() != ISD::ADD)
4619 return SDValue();
4620
4621 // And we must be 'add'ing a constant.
4622 ConstantSDNode *C01;
4623 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
4624 return SDValue();
4625
4626 SDValue X = N0->getOperand(0);
4627 EVT XVT = X.getValueType();
4628
4629 // Validate constants ...
4630
4631 APInt I1 = C1->getAPIntValue();
4632
4633 ISD::CondCode NewCond;
4634 if (Cond == ISD::CondCode::SETULT) {
4635 NewCond = ISD::CondCode::SETEQ;
4636 } else if (Cond == ISD::CondCode::SETULE) {
4637 NewCond = ISD::CondCode::SETEQ;
4638 // But need to 'canonicalize' the constant.
4639 I1 += 1;
4640 } else if (Cond == ISD::CondCode::SETUGT) {
4641 NewCond = ISD::CondCode::SETNE;
4642 // But need to 'canonicalize' the constant.
4643 I1 += 1;
4644 } else if (Cond == ISD::CondCode::SETUGE) {
4645 NewCond = ISD::CondCode::SETNE;
4646 } else
4647 return SDValue();
4648
4649 APInt I01 = C01->getAPIntValue();
4650
4651 auto checkConstants = [&I1, &I01]() -> bool {
4652 // Both of them must be power-of-two, and the constant from setcc is bigger.
4653 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
4654 };
4655
4656 if (checkConstants()) {
4657 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256
4658 } else {
4659 // What if we invert constants? (and the target predicate)
4660 I1.negate();
4661 I01.negate();
4662 assert(XVT.isInteger());
4663 NewCond = getSetCCInverse(NewCond, XVT);
4664 if (!checkConstants())
4665 return SDValue();
4666 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256
4667 }
4668
4669 // They are power-of-two, so which bit is set?
4670 const unsigned KeptBits = I1.logBase2();
4671 const unsigned KeptBitsMinusOne = I01.logBase2();
4672
4673 // Magic!
4674 if (KeptBits != (KeptBitsMinusOne + 1))
4675 return SDValue();
4676 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
4677
4678 // We don't want to do this in every single case.
4679 SelectionDAG &DAG = DCI.DAG;
4680 if (!shouldTransformSignedTruncationCheck(XVT, KeptBits))
4681 return SDValue();
4682
4683 // Unfold into: sext_inreg(%x) cond %x
4684 // Where 'cond' will be either 'eq' or 'ne'.
4685 SDValue SExtInReg = DAG.getNode(
4687 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), KeptBits)));
4688 return DAG.getSetCC(DL, SCCVT, SExtInReg, X, NewCond);
4689}
4690
4691// (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
4692SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
4693 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
4694 DAGCombinerInfo &DCI, const SDLoc &DL) const {
4696 "Should be a comparison with 0.");
4697 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4698 "Valid only for [in]equality comparisons.");
4699
4700 unsigned NewShiftOpcode;
4701 SDValue X, C, Y;
4702
4703 SelectionDAG &DAG = DCI.DAG;
4704
4705 // Look for '(C l>>/<< Y)'.
4706 auto Match = [&NewShiftOpcode, &X, &C, &Y, &DAG, this](SDValue V) {
4707 // The shift should be one-use.
4708 if (!V.hasOneUse())
4709 return false;
4710 unsigned OldShiftOpcode = V.getOpcode();
4711 switch (OldShiftOpcode) {
4712 case ISD::SHL:
4713 NewShiftOpcode = ISD::SRL;
4714 break;
4715 case ISD::SRL:
4716 NewShiftOpcode = ISD::SHL;
4717 break;
4718 default:
4719 return false; // must be a logical shift.
4720 }
4721 // We should be shifting a constant.
4722 // FIXME: best to use isConstantOrConstantVector().
4723 C = V.getOperand(0);
4724 ConstantSDNode *CC =
4725 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4726 if (!CC)
4727 return false;
4728 Y = V.getOperand(1);
4729
4730 ConstantSDNode *XC =
4731 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4733 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
4734 };
4735
4736 // LHS of comparison should be an one-use 'and'.
4737 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
4738 return SDValue();
4739
4740 X = N0.getOperand(0);
4741 SDValue Mask = N0.getOperand(1);
4742
4743 // 'and' is commutative!
4744 if (!Match(Mask)) {
4745 std::swap(X, Mask);
4746 if (!Match(Mask))
4747 return SDValue();
4748 }
4749
4750 EVT VT = X.getValueType();
4751
4752 // Produce:
4753 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
4754 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
4755 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
4756 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
4757 return T2;
4758}
4759
4760/// Try to fold an equality comparison with a {add/sub/xor} binary operation as
4761/// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
4762/// handle the commuted versions of these patterns.
4763SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
4764 ISD::CondCode Cond, const SDLoc &DL,
4765 DAGCombinerInfo &DCI) const {
4766 unsigned BOpcode = N0.getOpcode();
4767 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
4768 "Unexpected binop");
4769 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
4770
4771 // (X + Y) == X --> Y == 0
4772 // (X - Y) == X --> Y == 0
4773 // (X ^ Y) == X --> Y == 0
4774 SelectionDAG &DAG = DCI.DAG;
4775 EVT OpVT = N0.getValueType();
4776 SDValue X = N0.getOperand(0);
4777 SDValue Y = N0.getOperand(1);
4778 if (X == N1)
4779 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
4780
4781 if (Y != N1)
4782 return SDValue();
4783
4784 // (X + Y) == Y --> X == 0
4785 // (X ^ Y) == Y --> X == 0
4786 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
4787 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
4788
4789 // The shift would not be valid if the operands are boolean (i1).
4790 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
4791 return SDValue();
4792
4793 // (X - Y) == Y --> X == Y << 1
4794 SDValue One = DAG.getShiftAmountConstant(1, OpVT, DL);
4795 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
4796 if (!DCI.isCalledByLegalizer())
4797 DCI.AddToWorklist(YShl1.getNode());
4798 return DAG.getSetCC(DL, VT, X, YShl1, Cond);
4799}
4800
4802 SDValue N0, const APInt &C1,
4803 ISD::CondCode Cond, const SDLoc &dl,
4804 SelectionDAG &DAG) {
4805 // Look through truncs that don't change the value of a ctpop.
4806 // FIXME: Add vector support? Need to be careful with setcc result type below.
4807 SDValue CTPOP = N0;
4808 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
4810 CTPOP = N0.getOperand(0);
4811
4812 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
4813 return SDValue();
4814
4815 EVT CTVT = CTPOP.getValueType();
4816 SDValue CTOp = CTPOP.getOperand(0);
4817
4818 // Expand a power-of-2-or-zero comparison based on ctpop:
4819 // (ctpop x) u< 2 -> (x & x-1) == 0
4820 // (ctpop x) u> 1 -> (x & x-1) != 0
4821 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
4822 // Keep the CTPOP if it is a cheap vector op.
4823 if (CTVT.isVector() && TLI.isCtpopFast(CTVT))
4824 return SDValue();
4825
4826 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
4827 if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
4828 return SDValue();
4829 if (C1 == 0 && (Cond == ISD::SETULT))
4830 return SDValue(); // This is handled elsewhere.
4831
4832 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
4833
4834 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4835 SDValue Result = CTOp;
4836 for (unsigned i = 0; i < Passes; i++) {
4837 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
4838 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
4839 }
4841 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
4842 }
4843
4844 // Expand a power-of-2 comparison based on ctpop
4845 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
4846 // Keep the CTPOP if it is cheap.
4847 if (TLI.isCtpopFast(CTVT))
4848 return SDValue();
4849
4850 SDValue Zero = DAG.getConstant(0, dl, CTVT);
4851 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4852 assert(CTVT.isInteger());
4853 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
4854
4855 // Its not uncommon for known-never-zero X to exist in (ctpop X) eq/ne 1, so
4856 // check before emitting a potentially unnecessary op.
4857 if (DAG.isKnownNeverZero(CTOp)) {
4858 // (ctpop x) == 1 --> (x & x-1) == 0
4859 // (ctpop x) != 1 --> (x & x-1) != 0
4860 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
4861 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
4862 return RHS;
4863 }
4864
4865 // (ctpop x) == 1 --> (x ^ x-1) > x-1
4866 // (ctpop x) != 1 --> (x ^ x-1) <= x-1
4867 SDValue Xor = DAG.getNode(ISD::XOR, dl, CTVT, CTOp, Add);
4869 return DAG.getSetCC(dl, VT, Xor, Add, CmpCond);
4870 }
4871
4872 return SDValue();
4873}
4874
4876 ISD::CondCode Cond, const SDLoc &dl,
4877 SelectionDAG &DAG) {
4878 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4879 return SDValue();
4880
4881 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4882 if (!C1 || !(C1->isZero() || C1->isAllOnes()))
4883 return SDValue();
4884
4885 auto getRotateSource = [](SDValue X) {
4886 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR)
4887 return X.getOperand(0);
4888 return SDValue();
4889 };
4890
4891 // Peek through a rotated value compared against 0 or -1:
4892 // (rot X, Y) == 0/-1 --> X == 0/-1
4893 // (rot X, Y) != 0/-1 --> X != 0/-1
4894 if (SDValue R = getRotateSource(N0))
4895 return DAG.getSetCC(dl, VT, R, N1, Cond);
4896
4897 // Peek through an 'or' of a rotated value compared against 0:
4898 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0
4899 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0
4900 //
4901 // TODO: Add the 'and' with -1 sibling.
4902 // TODO: Recurse through a series of 'or' ops to find the rotate.
4903 EVT OpVT = N0.getValueType();
4904 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) {
4905 if (SDValue R = getRotateSource(N0.getOperand(0))) {
4906 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1));
4907 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4908 }
4909 if (SDValue R = getRotateSource(N0.getOperand(1))) {
4910 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0));
4911 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4912 }
4913 }
4914
4915 return SDValue();
4916}
4917
4919 ISD::CondCode Cond, const SDLoc &dl,
4920 SelectionDAG &DAG) {
4921 // If we are testing for all-bits-clear, we might be able to do that with
4922 // less shifting since bit-order does not matter.
4923 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4924 return SDValue();
4925
4926 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4927 if (!C1 || !C1->isZero())
4928 return SDValue();
4929
4930 if (!N0.hasOneUse() ||
4931 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR))
4932 return SDValue();
4933
4934 unsigned BitWidth = N0.getScalarValueSizeInBits();
4935 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2));
4936 if (!ShAmtC)
4937 return SDValue();
4938
4939 uint64_t ShAmt = ShAmtC->getAPIntValue().urem(BitWidth);
4940 if (ShAmt == 0)
4941 return SDValue();
4942
4943 // Canonicalize fshr as fshl to reduce pattern-matching.
4944 if (N0.getOpcode() == ISD::FSHR)
4945 ShAmt = BitWidth - ShAmt;
4946
4947 // Match an 'or' with a specific operand 'Other' in either commuted variant.
4948 SDValue X, Y;
4949 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) {
4950 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse())
4951 return false;
4952 if (Or.getOperand(0) == Other) {
4953 X = Or.getOperand(0);
4954 Y = Or.getOperand(1);
4955 return true;
4956 }
4957 if (Or.getOperand(1) == Other) {
4958 X = Or.getOperand(1);
4959 Y = Or.getOperand(0);
4960 return true;
4961 }
4962 return false;
4963 };
4964
4965 EVT OpVT = N0.getValueType();
4966 EVT ShAmtVT = N0.getOperand(2).getValueType();
4967 SDValue F0 = N0.getOperand(0);
4968 SDValue F1 = N0.getOperand(1);
4969 if (matchOr(F0, F1)) {
4970 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0
4971 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT);
4972 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt);
4973 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4974 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4975 }
4976 if (matchOr(F1, F0)) {
4977 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0
4978 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT);
4979 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt);
4980 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4981 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4982 }
4983
4984 return SDValue();
4985}
4986
4987/// Try to simplify a setcc built with the specified operands and cc. If it is
4988/// unable to simplify it, return a null SDValue.
4990 ISD::CondCode Cond, bool foldBooleans,
4991 DAGCombinerInfo &DCI,
4992 const SDLoc &dl) const {
4993 SelectionDAG &DAG = DCI.DAG;
4994 const DataLayout &Layout = DAG.getDataLayout();
4995 EVT OpVT = N0.getValueType();
4997
4998 // Constant fold or commute setcc.
4999 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
5000 return Fold;
5001
5002 bool N0ConstOrSplat =
5003 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
5004 bool N1ConstOrSplat =
5005 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
5006
5007 // Canonicalize toward having the constant on the RHS.
5008 // TODO: Handle non-splat vector constants. All undef causes trouble.
5009 // FIXME: We can't yet fold constant scalable vector splats, so avoid an
5010 // infinite loop here when we encounter one.
5012 if (N0ConstOrSplat && !N1ConstOrSplat &&
5013 (DCI.isBeforeLegalizeOps() ||
5014 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
5015 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
5016
5017 // If we have a subtract with the same 2 non-constant operands as this setcc
5018 // -- but in reverse order -- then try to commute the operands of this setcc
5019 // to match. A matching pair of setcc (cmp) and sub may be combined into 1
5020 // instruction on some targets.
5021 if (!N0ConstOrSplat && !N1ConstOrSplat &&
5022 (DCI.isBeforeLegalizeOps() ||
5023 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
5024 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
5025 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
5026 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
5027
5028 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG))
5029 return V;
5030
5031 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG))
5032 return V;
5033
5034 if (auto *N1C = isConstOrConstSplat(N1)) {
5035 const APInt &C1 = N1C->getAPIntValue();
5036
5037 // Optimize some CTPOP cases.
5038 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
5039 return V;
5040
5041 // For equality to 0 of a no-wrap multiply, decompose and test each op:
5042 // X * Y == 0 --> (X == 0) || (Y == 0)
5043 // X * Y != 0 --> (X != 0) && (Y != 0)
5044 // TODO: This bails out if minsize is set, but if the target doesn't have a
5045 // single instruction multiply for this type, it would likely be
5046 // smaller to decompose.
5047 if (C1.isZero() && (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5048 N0.getOpcode() == ISD::MUL && N0.hasOneUse() &&
5049 (N0->getFlags().hasNoUnsignedWrap() ||
5050 N0->getFlags().hasNoSignedWrap()) &&
5051 !Attr.hasFnAttr(Attribute::MinSize)) {
5052 SDValue IsXZero = DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
5053 SDValue IsYZero = DAG.getSetCC(dl, VT, N0.getOperand(1), N1, Cond);
5054 unsigned LogicOp = Cond == ISD::SETEQ ? ISD::OR : ISD::AND;
5055 return DAG.getNode(LogicOp, dl, VT, IsXZero, IsYZero);
5056 }
5057
5058 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
5059 // equality comparison, then we're just comparing whether X itself is
5060 // zero.
5061 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
5062 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
5064 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
5065 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5066 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
5067 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
5068 // (srl (ctlz x), 5) == 0 -> X != 0
5069 // (srl (ctlz x), 5) != 1 -> X != 0
5070 Cond = ISD::SETNE;
5071 } else {
5072 // (srl (ctlz x), 5) != 0 -> X == 0
5073 // (srl (ctlz x), 5) == 1 -> X == 0
5074 Cond = ISD::SETEQ;
5075 }
5076 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
5077 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
5078 Cond);
5079 }
5080 }
5081 }
5082 }
5083
5084 // setcc X, 0, setlt --> X (when X is all sign bits)
5085 // setcc X, 0, setne --> X (when X is all sign bits)
5086 //
5087 // When we know that X has 0 or -1 in each element (or scalar), this
5088 // comparison will produce X. This is only true when boolean contents are
5089 // represented via 0s and -1s.
5090 if (VT == OpVT &&
5091 // Check that the result of setcc is 0 and -1.
5093 // Match only for checks X < 0 and X != 0
5094 (Cond == ISD::SETLT || Cond == ISD::SETNE) && isNullOrNullSplat(N1) &&
5095 // The identity holds iff we know all sign bits for all lanes.
5097 return N0;
5098
5099 // FIXME: Support vectors.
5100 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5101 const APInt &C1 = N1C->getAPIntValue();
5102
5103 // (zext x) == C --> x == (trunc C)
5104 // (sext x) == C --> x == (trunc C)
5105 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5106 DCI.isBeforeLegalize() && N0->hasOneUse()) {
5107 unsigned MinBits = N0.getValueSizeInBits();
5108 SDValue PreExt;
5109 bool Signed = false;
5110 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
5111 // ZExt
5112 MinBits = N0->getOperand(0).getValueSizeInBits();
5113 PreExt = N0->getOperand(0);
5114 } else if (N0->getOpcode() == ISD::AND) {
5115 // DAGCombine turns costly ZExts into ANDs
5116 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
5117 if ((C->getAPIntValue()+1).isPowerOf2()) {
5118 MinBits = C->getAPIntValue().countr_one();
5119 PreExt = N0->getOperand(0);
5120 }
5121 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
5122 // SExt
5123 MinBits = N0->getOperand(0).getValueSizeInBits();
5124 PreExt = N0->getOperand(0);
5125 Signed = true;
5126 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
5127 // ZEXTLOAD / SEXTLOAD
5128 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
5129 MinBits = LN0->getMemoryVT().getSizeInBits();
5130 PreExt = N0;
5131 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
5132 Signed = true;
5133 MinBits = LN0->getMemoryVT().getSizeInBits();
5134 PreExt = N0;
5135 }
5136 }
5137
5138 // Figure out how many bits we need to preserve this constant.
5139 unsigned ReqdBits = Signed ? C1.getSignificantBits() : C1.getActiveBits();
5140
5141 // Make sure we're not losing bits from the constant.
5142 if (MinBits > 0 &&
5143 MinBits < C1.getBitWidth() &&
5144 MinBits >= ReqdBits) {
5145 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
5146 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
5147 // Will get folded away.
5148 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
5149 if (MinBits == 1 && C1 == 1)
5150 // Invert the condition.
5151 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
5153 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
5154 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
5155 }
5156
5157 // If truncating the setcc operands is not desirable, we can still
5158 // simplify the expression in some cases:
5159 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
5160 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
5161 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
5162 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
5163 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
5164 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
5165 SDValue TopSetCC = N0->getOperand(0);
5166 unsigned N0Opc = N0->getOpcode();
5167 bool SExt = (N0Opc == ISD::SIGN_EXTEND);
5168 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
5169 TopSetCC.getOpcode() == ISD::SETCC &&
5170 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
5171 (isConstFalseVal(N1) ||
5172 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
5173
5174 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
5175 (!N1C->isZero() && Cond == ISD::SETNE);
5176
5177 if (!Inverse)
5178 return TopSetCC;
5179
5181 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
5182 TopSetCC.getOperand(0).getValueType());
5183 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
5184 TopSetCC.getOperand(1),
5185 InvCond);
5186 }
5187 }
5188 }
5189
5190 // If the LHS is '(and load, const)', the RHS is 0, the test is for
5191 // equality or unsigned, and all 1 bits of the const are in the same
5192 // partial word, see if we can shorten the load.
5193 if (DCI.isBeforeLegalize() &&
5195 N0.getOpcode() == ISD::AND && C1 == 0 &&
5196 N0.getNode()->hasOneUse() &&
5197 isa<LoadSDNode>(N0.getOperand(0)) &&
5198 N0.getOperand(0).getNode()->hasOneUse() &&
5200 auto *Lod = cast<LoadSDNode>(N0.getOperand(0));
5201 APInt bestMask;
5202 unsigned bestWidth = 0, bestOffset = 0;
5203 if (Lod->isSimple() && Lod->isUnindexed() &&
5204 (Lod->getMemoryVT().isByteSized() ||
5205 isPaddedAtMostSignificantBitsWhenStored(Lod->getMemoryVT()))) {
5206 unsigned memWidth = Lod->getMemoryVT().getStoreSizeInBits();
5207 unsigned origWidth = N0.getValueSizeInBits();
5208 unsigned maskWidth = origWidth;
5209 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
5210 // 8 bits, but have to be careful...
5211 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
5212 origWidth = Lod->getMemoryVT().getSizeInBits();
5213 const APInt &Mask = N0.getConstantOperandAPInt(1);
5214 // Only consider power-of-2 widths (and at least one byte) as candiates
5215 // for the narrowed load.
5216 for (unsigned width = 8; width < origWidth; width *= 2) {
5217 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), width);
5218 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
5219 // Avoid accessing any padding here for now (we could use memWidth
5220 // instead of origWidth here otherwise).
5221 unsigned maxOffset = origWidth - width;
5222 for (unsigned offset = 0; offset <= maxOffset; offset += 8) {
5223 if (Mask.isSubsetOf(newMask)) {
5224 unsigned ptrOffset =
5225 Layout.isLittleEndian() ? offset : memWidth - width - offset;
5226 unsigned IsFast = 0;
5227 assert((ptrOffset % 8) == 0 && "Non-Bytealigned pointer offset");
5228 Align NewAlign = commonAlignment(Lod->getAlign(), ptrOffset / 8);
5230 ptrOffset / 8) &&
5232 *DAG.getContext(), Layout, newVT, Lod->getAddressSpace(),
5233 NewAlign, Lod->getMemOperand()->getFlags(), &IsFast) &&
5234 IsFast) {
5235 bestOffset = ptrOffset / 8;
5236 bestMask = Mask.lshr(offset);
5237 bestWidth = width;
5238 break;
5239 }
5240 }
5241 newMask <<= 8;
5242 }
5243 if (bestWidth)
5244 break;
5245 }
5246 }
5247 if (bestWidth) {
5248 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
5249 SDValue Ptr = Lod->getBasePtr();
5250 if (bestOffset != 0)
5251 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(bestOffset));
5252 SDValue NewLoad =
5253 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
5254 Lod->getPointerInfo().getWithOffset(bestOffset),
5255 Lod->getBaseAlign(), MachineMemOperand::MONone,
5256 Lod->getMMOMetadataForSubAccess());
5257 SDValue And =
5258 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
5259 DAG.getConstant(bestMask.trunc(bestWidth), dl, newVT));
5260 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0LL, dl, newVT), Cond);
5261 }
5262 }
5263
5264 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
5265 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
5266 unsigned InSize = N0.getOperand(0).getValueSizeInBits();
5267
5268 // If the comparison constant has bits in the upper part, the
5269 // zero-extended value could never match.
5271 C1.getBitWidth() - InSize))) {
5272 switch (Cond) {
5273 case ISD::SETUGT:
5274 case ISD::SETUGE:
5275 case ISD::SETEQ:
5276 return DAG.getConstant(0, dl, VT);
5277 case ISD::SETULT:
5278 case ISD::SETULE:
5279 case ISD::SETNE:
5280 return DAG.getConstant(1, dl, VT);
5281 case ISD::SETGT:
5282 case ISD::SETGE:
5283 // True if the sign bit of C1 is set.
5284 return DAG.getConstant(C1.isNegative(), dl, VT);
5285 case ISD::SETLT:
5286 case ISD::SETLE:
5287 // True if the sign bit of C1 isn't set.
5288 return DAG.getConstant(C1.isNonNegative(), dl, VT);
5289 default:
5290 break;
5291 }
5292 }
5293
5294 // Otherwise, we can perform the comparison with the low bits.
5295 switch (Cond) {
5296 case ISD::SETEQ:
5297 case ISD::SETNE:
5298 case ISD::SETUGT:
5299 case ISD::SETUGE:
5300 case ISD::SETULT:
5301 case ISD::SETULE: {
5302 EVT newVT = N0.getOperand(0).getValueType();
5303 // FIXME: Should use isNarrowingProfitable.
5304 if (DCI.isBeforeLegalizeOps() ||
5305 (isOperationLegal(ISD::SETCC, newVT) &&
5306 isCondCodeLegal(Cond, newVT.getSimpleVT()) &&
5308 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
5309 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
5310
5311 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
5312 NewConst, Cond);
5313 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
5314 }
5315 break;
5316 }
5317 default:
5318 break; // todo, be more careful with signed comparisons
5319 }
5320 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5321 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5323 OpVT)) {
5324 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
5325 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
5326 EVT ExtDstTy = N0.getValueType();
5327 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
5328
5329 // If the constant doesn't fit into the number of bits for the source of
5330 // the sign extension, it is impossible for both sides to be equal.
5331 if (C1.getSignificantBits() > ExtSrcTyBits)
5332 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
5333
5334 assert(ExtDstTy == N0.getOperand(0).getValueType() &&
5335 ExtDstTy != ExtSrcTy && "Unexpected types!");
5336 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
5337 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
5338 DAG.getConstant(Imm, dl, ExtDstTy));
5339 if (!DCI.isCalledByLegalizer())
5340 DCI.AddToWorklist(ZextOp.getNode());
5341 // Otherwise, make this a use of a zext.
5342 return DAG.getSetCC(dl, VT, ZextOp,
5343 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
5344 } else if ((N1C->isZero() || N1C->isOne()) &&
5345 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5346 // SETCC (X), [0|1], [EQ|NE] -> X if X is known 0/1. i1 types are
5347 // excluded as they are handled below whilst checking for foldBooleans.
5348 if ((N0.getOpcode() == ISD::SETCC || VT.getScalarType() != MVT::i1) &&
5349 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
5350 (N0.getValueType() == MVT::i1 ||
5354 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
5355 if (TrueWhenTrue)
5356 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
5357 // Invert the condition.
5358 if (N0.getOpcode() == ISD::SETCC) {
5361 if (DCI.isBeforeLegalizeOps() ||
5363 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
5364 }
5365 }
5366
5367 if ((N0.getOpcode() == ISD::XOR ||
5368 (N0.getOpcode() == ISD::AND &&
5369 N0.getOperand(0).getOpcode() == ISD::XOR &&
5370 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
5371 isOneConstant(N0.getOperand(1))) {
5372 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
5373 // can only do this if the top bits are known zero.
5374 unsigned BitWidth = N0.getValueSizeInBits();
5375 if (DAG.MaskedValueIsZero(N0,
5377 BitWidth-1))) {
5378 // Okay, get the un-inverted input value.
5379 SDValue Val;
5380 if (N0.getOpcode() == ISD::XOR) {
5381 Val = N0.getOperand(0);
5382 } else {
5383 assert(N0.getOpcode() == ISD::AND &&
5384 N0.getOperand(0).getOpcode() == ISD::XOR);
5385 // ((X^1)&1)^1 -> X & 1
5386 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
5387 N0.getOperand(0).getOperand(0),
5388 N0.getOperand(1));
5389 }
5390
5391 return DAG.getSetCC(dl, VT, Val, N1,
5393 }
5394 } else if (N1C->isOne()) {
5395 SDValue Op0 = N0;
5396 if (Op0.getOpcode() == ISD::TRUNCATE)
5397 Op0 = Op0.getOperand(0);
5398
5399 if ((Op0.getOpcode() == ISD::XOR) &&
5400 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
5401 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
5402 SDValue XorLHS = Op0.getOperand(0);
5403 SDValue XorRHS = Op0.getOperand(1);
5404 // Ensure that the input setccs return an i1 type or 0/1 value.
5405 if (Op0.getValueType() == MVT::i1 ||
5410 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
5412 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
5413 }
5414 }
5415 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
5416 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
5417 if (Op0.getValueType().bitsGT(VT))
5418 Op0 = DAG.getNode(ISD::AND, dl, VT,
5419 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
5420 DAG.getConstant(1, dl, VT));
5421 else if (Op0.getValueType().bitsLT(VT))
5422 Op0 = DAG.getNode(ISD::AND, dl, VT,
5423 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
5424 DAG.getConstant(1, dl, VT));
5425
5426 return DAG.getSetCC(dl, VT, Op0,
5427 DAG.getConstant(0, dl, Op0.getValueType()),
5429 }
5430 if (Op0.getOpcode() == ISD::AssertZext &&
5431 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
5432 return DAG.getSetCC(dl, VT, Op0,
5433 DAG.getConstant(0, dl, Op0.getValueType()),
5435 }
5436 }
5437
5438 // Given:
5439 // icmp eq/ne (urem %x, %y), 0
5440 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
5441 // icmp eq/ne %x, 0
5442 if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
5443 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5444 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
5445 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
5446 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
5447 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
5448 }
5449
5450 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
5451 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
5452 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5454 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
5455 N1C->isAllOnes()) {
5456 return DAG.getSetCC(dl, VT, N0.getOperand(0),
5457 DAG.getConstant(0, dl, OpVT),
5459 }
5460
5461 // fold (setcc (trunc x) c) -> (setcc x c)
5462 if (N0.getOpcode() == ISD::TRUNCATE &&
5464 (N0->getFlags().hasNoSignedWrap() &&
5467 EVT NewVT = N0.getOperand(0).getValueType();
5468 SDValue NewConst = DAG.getConstant(
5470 ? C1.sext(NewVT.getSizeInBits())
5471 : C1.zext(NewVT.getSizeInBits()),
5472 dl, NewVT);
5473 return DAG.getSetCC(dl, VT, N0.getOperand(0), NewConst, Cond);
5474 }
5475
5476 if (SDValue V =
5477 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
5478 return V;
5479 }
5480
5481 // These simplifications apply to splat vectors as well.
5482 // TODO: Handle more splat vector cases.
5483 if (auto *N1C = isConstOrConstSplat(N1)) {
5484 const APInt &C1 = N1C->getAPIntValue();
5485
5486 APInt MinVal, MaxVal;
5487 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
5489 MinVal = APInt::getSignedMinValue(OperandBitSize);
5490 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
5491 } else {
5492 MinVal = APInt::getMinValue(OperandBitSize);
5493 MaxVal = APInt::getMaxValue(OperandBitSize);
5494 }
5495
5496 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
5497 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
5498 // X >= MIN --> true
5499 if (C1 == MinVal)
5500 return DAG.getBoolConstant(true, dl, VT, OpVT);
5501
5502 if (!VT.isVector()) { // TODO: Support this for vectors.
5503 // X >= C0 --> X > (C0 - 1)
5504 APInt C = C1 - 1;
5506 if ((DCI.isBeforeLegalizeOps() ||
5507 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5508 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5509 isLegalICmpImmediate(C.getSExtValue())))) {
5510 return DAG.getSetCC(dl, VT, N0,
5511 DAG.getConstant(C, dl, N1.getValueType()),
5512 NewCC);
5513 }
5514 }
5515 }
5516
5517 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
5518 // X <= MAX --> true
5519 if (C1 == MaxVal)
5520 return DAG.getBoolConstant(true, dl, VT, OpVT);
5521
5522 // X <= C0 --> X < (C0 + 1)
5523 if (!VT.isVector()) { // TODO: Support this for vectors.
5524 APInt C = C1 + 1;
5526 if ((DCI.isBeforeLegalizeOps() ||
5527 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5528 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5529 isLegalICmpImmediate(C.getSExtValue())))) {
5530 return DAG.getSetCC(dl, VT, N0,
5531 DAG.getConstant(C, dl, N1.getValueType()),
5532 NewCC);
5533 }
5534 }
5535 }
5536
5537 if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
5538 if (C1 == MinVal)
5539 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
5540
5541 // TODO: Support this for vectors after legalize ops.
5542 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5543 // Canonicalize setlt X, Max --> setne X, Max
5544 if (C1 == MaxVal)
5545 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5546
5547 // If we have setult X, 1, turn it into seteq X, 0
5548 if (C1 == MinVal+1)
5549 return DAG.getSetCC(dl, VT, N0,
5550 DAG.getConstant(MinVal, dl, N0.getValueType()),
5551 ISD::SETEQ);
5552 }
5553 }
5554
5555 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
5556 if (C1 == MaxVal)
5557 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
5558
5559 // TODO: Support this for vectors after legalize ops.
5560 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5561 // Canonicalize setgt X, Min --> setne X, Min
5562 if (C1 == MinVal)
5563 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5564
5565 // If we have setugt X, Max-1, turn it into seteq X, Max
5566 if (C1 == MaxVal-1)
5567 return DAG.getSetCC(dl, VT, N0,
5568 DAG.getConstant(MaxVal, dl, N0.getValueType()),
5569 ISD::SETEQ);
5570 }
5571 }
5572
5573 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
5574 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
5575 if (C1.isZero())
5576 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
5577 VT, N0, N1, Cond, DCI, dl))
5578 return CC;
5579
5580 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
5581 // For example, when high 32-bits of i64 X are known clear:
5582 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0
5583 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1
5584 bool CmpZero = N1C->isZero();
5585 bool CmpNegOne = N1C->isAllOnes();
5586 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
5587 // Match or(lo,shl(hi,bw/2)) pattern.
5588 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
5589 unsigned EltBits = V.getScalarValueSizeInBits();
5590 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
5591 return false;
5592 SDValue LHS = V.getOperand(0);
5593 SDValue RHS = V.getOperand(1);
5594 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
5595 // Unshifted element must have zero upperbits.
5596 if (RHS.getOpcode() == ISD::SHL &&
5597 isa<ConstantSDNode>(RHS.getOperand(1)) &&
5598 RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5599 DAG.MaskedValueIsZero(LHS, HiBits)) {
5600 Lo = LHS;
5601 Hi = RHS.getOperand(0);
5602 return true;
5603 }
5604 if (LHS.getOpcode() == ISD::SHL &&
5605 isa<ConstantSDNode>(LHS.getOperand(1)) &&
5606 LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5607 DAG.MaskedValueIsZero(RHS, HiBits)) {
5608 Lo = RHS;
5609 Hi = LHS.getOperand(0);
5610 return true;
5611 }
5612 return false;
5613 };
5614
5615 auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
5616 unsigned EltBits = N0.getScalarValueSizeInBits();
5617 unsigned HalfBits = EltBits / 2;
5618 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
5619 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
5620 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
5621 SDValue NewN0 =
5622 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
5623 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
5624 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
5625 };
5626
5627 SDValue Lo, Hi;
5628 if (IsConcat(N0, Lo, Hi))
5629 return MergeConcat(Lo, Hi);
5630
5631 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
5632 SDValue Lo0, Lo1, Hi0, Hi1;
5633 if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
5634 IsConcat(N0.getOperand(1), Lo1, Hi1)) {
5635 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
5636 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
5637 }
5638 }
5639 }
5640 }
5641
5642 // If we have "setcc X, C0", check to see if we can shrink the immediate
5643 // by changing cc.
5644 // TODO: Support this for vectors after legalize ops.
5645 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5646 // SETUGT X, SINTMAX -> SETLT X, 0
5647 // SETUGE X, SINTMIN -> SETLT X, 0
5648 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
5649 (Cond == ISD::SETUGE && C1.isMinSignedValue()))
5650 return DAG.getSetCC(dl, VT, N0,
5651 DAG.getConstant(0, dl, N1.getValueType()),
5652 ISD::SETLT);
5653
5654 // SETULT X, SINTMIN -> SETGT X, -1
5655 // SETULE X, SINTMAX -> SETGT X, -1
5656 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
5657 (Cond == ISD::SETULE && C1.isMaxSignedValue()))
5658 return DAG.getSetCC(dl, VT, N0,
5659 DAG.getAllOnesConstant(dl, N1.getValueType()),
5660 ISD::SETGT);
5661 }
5662 }
5663
5664 // Back to non-vector simplifications.
5665 // TODO: Can we do these for vector splats?
5666 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5667 const APInt &C1 = N1C->getAPIntValue();
5668 EVT ShValTy = N0.getValueType();
5669
5670 // Fold bit comparisons when we can. This will result in an
5671 // incorrect value when boolean false is negative one, unless
5672 // the bitsize is 1 in which case the false value is the same
5673 // in practice regardless of the representation.
5674 if ((VT.getSizeInBits() == 1 ||
5676 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5677 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
5678 N0.getOpcode() == ISD::AND) {
5679 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5680 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
5681 // Perform the xform if the AND RHS is a single bit.
5682 unsigned ShCt = AndRHS->getAPIntValue().logBase2();
5683 if (AndRHS->getAPIntValue().isPowerOf2() &&
5684 !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5685 return DAG.getNode(
5686 ISD::TRUNCATE, dl, VT,
5687 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5688 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5689 }
5690 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
5691 // (X & 8) == 8 --> (X & 8) >> 3
5692 // Perform the xform if C1 is a single bit.
5693 unsigned ShCt = C1.logBase2();
5694 if (C1.isPowerOf2() && !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5695 return DAG.getNode(
5696 ISD::TRUNCATE, dl, VT,
5697 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5698 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5699 }
5700 }
5701 }
5702 }
5703
5704 if (C1.getSignificantBits() <= 64 &&
5706 // (X & -256) == 256 -> (X >> 8) == 1
5707 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5708 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
5709 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5710 const APInt &AndRHSC = AndRHS->getAPIntValue();
5711 if (AndRHSC.isNegatedPowerOf2() && C1.isSubsetOf(AndRHSC)) {
5712 unsigned ShiftBits = AndRHSC.countr_zero();
5713 if (!shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5714 // If using an unsigned shift doesn't yield a legal compare
5715 // immediate, try using sra instead.
5716 APInt NewC = C1.lshr(ShiftBits);
5717 if (NewC.getSignificantBits() <= 64 &&
5719 APInt SignedC = C1.ashr(ShiftBits);
5720 if (SignedC.getSignificantBits() <= 64 &&
5722 SDValue Shift = DAG.getNode(
5723 ISD::SRA, dl, ShValTy, N0.getOperand(0),
5724 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5725 SDValue CmpRHS = DAG.getConstant(SignedC, dl, ShValTy);
5726 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5727 }
5728 }
5729 SDValue Shift = DAG.getNode(
5730 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5731 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5732 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5733 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5734 }
5735 }
5736 }
5737 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
5738 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
5739 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
5740 // X < 0x100000000 -> (X >> 32) < 1
5741 // X >= 0x100000000 -> (X >> 32) >= 1
5742 // X <= 0x0ffffffff -> (X >> 32) < 1
5743 // X > 0x0ffffffff -> (X >> 32) >= 1
5744 unsigned ShiftBits;
5745 APInt NewC = C1;
5746 ISD::CondCode NewCond = Cond;
5747 if (AdjOne) {
5748 ShiftBits = C1.countr_one();
5749 NewC = NewC + 1;
5750 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
5751 } else {
5752 ShiftBits = C1.countr_zero();
5753 }
5754 APInt RangeWidth = NewC;
5755 NewC.lshrInPlace(ShiftBits);
5756 if (ShiftBits && NewC.getSignificantBits() <= 64 &&
5758 !shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5759 // If this is an offset range check, try to move the offset after the
5760 // shift to avoid preserving the pre-shift add with a mask.
5761 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse()) {
5762 if (auto *AddC = isConstOrConstSplat(N0.getOperand(1))) {
5763 const APInt &AddVal = AddC->getAPIntValue();
5764 if (AddVal.countr_zero() >= ShiftBits) {
5765 APInt RangeLower = -AddVal;
5766 bool Overflow;
5767 (void)RangeLower.uadd_ov(RangeWidth, Overflow);
5768 if (!RangeWidth.isZero() && !Overflow) {
5769 SDValue Shift = DAG.getNode(
5770 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5771 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5772 APInt Offset = -RangeLower.lshr(ShiftBits);
5773 SDValue ShiftedAdd =
5774 DAG.getNode(ISD::ADD, dl, ShValTy, Shift,
5775 DAG.getConstant(Offset, dl, ShValTy));
5776 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5777 return DAG.getSetCC(dl, VT, ShiftedAdd, CmpRHS, NewCond);
5778 }
5779 }
5780 }
5781 }
5782 SDValue Shift =
5783 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5784 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5785 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5786 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
5787 }
5788 }
5789 }
5790 }
5791
5793 auto *CFP = cast<ConstantFPSDNode>(N1);
5794 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
5795
5796 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
5797 // constant if knowing that the operand is non-nan is enough. We prefer to
5798 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
5799 // materialize 0.0.
5800 if (Cond == ISD::SETO || Cond == ISD::SETUO)
5801 return DAG.getSetCC(dl, VT, N0, N0, Cond);
5802
5803 // setcc (fneg x), C -> setcc swap(pred) x, -C
5804 if (N0.getOpcode() == ISD::FNEG) {
5806 if (DCI.isBeforeLegalizeOps() ||
5807 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
5808 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
5809 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
5810 }
5811 }
5812
5813 // setueq/setoeq X, (fabs Inf) -> is_fpclass X, fcInf
5815 !isFPImmLegal(CFP->getValueAPF(), CFP->getValueType(0))) {
5816 bool IsFabs = N0.getOpcode() == ISD::FABS;
5817 SDValue Op = IsFabs ? N0.getOperand(0) : N0;
5818 if ((Cond == ISD::SETOEQ || Cond == ISD::SETUEQ) && CFP->isInfinity()) {
5819 FPClassTest Flag = CFP->isNegative() ? (IsFabs ? fcNone : fcNegInf)
5820 : (IsFabs ? fcInf : fcPosInf);
5821 if (Cond == ISD::SETUEQ)
5822 Flag |= fcNan;
5823 return DAG.getNode(ISD::IS_FPCLASS, dl, VT, Op,
5824 DAG.getTargetConstant(Flag, dl, MVT::i32));
5825 }
5826 }
5827
5828 // If the condition is not legal, see if we can find an equivalent one
5829 // which is legal.
5831 // If the comparison was an awkward floating-point == or != and one of
5832 // the comparison operands is infinity or negative infinity, convert the
5833 // condition to a less-awkward <= or >=.
5834 if (CFP->getValueAPF().isInfinity()) {
5835 bool IsNegInf = CFP->getValueAPF().isNegative();
5837 switch (Cond) {
5838 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
5839 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
5840 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
5841 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
5842 default: break;
5843 }
5844 if (NewCond != ISD::SETCC_INVALID &&
5845 isCondCodeLegal(NewCond, N0.getSimpleValueType()))
5846 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5847 }
5848 }
5849 }
5850
5851 if (N0 == N1) {
5852 // The sext(setcc()) => setcc() optimization relies on the appropriate
5853 // constant being emitted.
5854 assert(!N0.getValueType().isInteger() &&
5855 "Integer types should be handled by FoldSetCC");
5856
5857 bool EqTrue = ISD::isTrueWhenEqual(Cond);
5858 unsigned UOF = ISD::getUnorderedFlavor(Cond);
5859 if (UOF == 2) // FP operators that are undefined on NaNs.
5860 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5861 if (UOF == unsigned(EqTrue))
5862 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5863 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
5864 // if it is not already.
5865 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
5866 if (NewCond != Cond &&
5867 (DCI.isBeforeLegalizeOps() ||
5868 isCondCodeLegal(NewCond, N0.getSimpleValueType())))
5869 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5870 }
5871
5872 // ~X > ~Y --> Y > X
5873 // ~X < ~Y --> Y < X
5874 // ~X < C --> X > ~C
5875 // ~X > C --> X < ~C
5876 if ((isSignedIntSetCC(Cond) || isUnsignedIntSetCC(Cond)) &&
5877 N0.getValueType().isInteger()) {
5878 if (isBitwiseNot(N0)) {
5879 if (isBitwiseNot(N1))
5880 return DAG.getSetCC(dl, VT, N1.getOperand(0), N0.getOperand(0), Cond);
5881
5884 SDValue Not = DAG.getNOT(dl, N1, OpVT);
5885 return DAG.getSetCC(dl, VT, Not, N0.getOperand(0), Cond);
5886 }
5887 }
5888 }
5889
5890 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5891 N0.getValueType().isInteger()) {
5892 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
5893 N0.getOpcode() == ISD::XOR) {
5894 // Simplify (X+Y) == (X+Z) --> Y == Z
5895 if (N0.getOpcode() == N1.getOpcode()) {
5896 if (N0.getOperand(0) == N1.getOperand(0))
5897 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
5898 if (N0.getOperand(1) == N1.getOperand(1))
5899 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
5900 if (isCommutativeBinOp(N0.getOpcode())) {
5901 // If X op Y == Y op X, try other combinations.
5902 if (N0.getOperand(0) == N1.getOperand(1))
5903 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
5904 Cond);
5905 if (N0.getOperand(1) == N1.getOperand(0))
5906 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
5907 Cond);
5908 }
5909 }
5910
5911 // If RHS is a legal immediate value for a compare instruction, we need
5912 // to be careful about increasing register pressure needlessly.
5913 bool LegalRHSImm = false;
5914
5915 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
5916 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5917 // Turn (X+C1) == C2 --> X == C2-C1
5918 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse())
5919 return DAG.getSetCC(
5920 dl, VT, N0.getOperand(0),
5921 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(),
5922 dl, N0.getValueType()),
5923 Cond);
5924
5925 // Turn (X^C1) == C2 --> X == C1^C2
5926 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse())
5927 return DAG.getSetCC(
5928 dl, VT, N0.getOperand(0),
5929 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(),
5930 dl, N0.getValueType()),
5931 Cond);
5932 }
5933
5934 // Turn (C1-X) == C2 --> X == C1-C2
5935 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
5936 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse())
5937 return DAG.getSetCC(
5938 dl, VT, N0.getOperand(1),
5939 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(),
5940 dl, N0.getValueType()),
5941 Cond);
5942
5943 // Could RHSC fold directly into a compare?
5944 if (RHSC->getValueType(0).getSizeInBits() <= 64)
5945 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
5946 }
5947
5948 // (X+Y) == X --> Y == 0 and similar folds.
5949 // Don't do this if X is an immediate that can fold into a cmp
5950 // instruction and X+Y has other uses. It could be an induction variable
5951 // chain, and the transform would increase register pressure.
5952 if (!LegalRHSImm || N0.hasOneUse())
5953 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
5954 return V;
5955 }
5956
5957 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
5958 N1.getOpcode() == ISD::XOR)
5959 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
5960 return V;
5961
5962 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
5963 return V;
5964
5965 if (SDValue V = foldSetCCWithOr(VT, N0, N1, Cond, dl, DCI))
5966 return V;
5967 }
5968
5969 // Fold remainder of division by a constant.
5970 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
5971 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5972 // When division is cheap or optimizing for minimum size,
5973 // fall through to DIVREM creation by skipping this fold.
5974 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
5975 if (N0.getOpcode() == ISD::UREM) {
5976 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
5977 return Folded;
5978 } else if (N0.getOpcode() == ISD::SREM) {
5979 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
5980 return Folded;
5981 }
5982 }
5983 }
5984
5985 // Fold away ALL boolean setcc's.
5986 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
5987 SDValue Temp;
5988 switch (Cond) {
5989 default: llvm_unreachable("Unknown integer setcc!");
5990 case ISD::SETEQ: // X == Y -> ~(X^Y)
5991 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
5992 N0 = DAG.getNOT(dl, Temp, OpVT);
5993 if (!DCI.isCalledByLegalizer())
5994 DCI.AddToWorklist(Temp.getNode());
5995 break;
5996 case ISD::SETNE: // X != Y --> (X^Y)
5997 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
5998 break;
5999 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
6000 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
6001 Temp = DAG.getNOT(dl, N0, OpVT);
6002 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
6003 if (!DCI.isCalledByLegalizer())
6004 DCI.AddToWorklist(Temp.getNode());
6005 break;
6006 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
6007 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
6008 Temp = DAG.getNOT(dl, N1, OpVT);
6009 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
6010 if (!DCI.isCalledByLegalizer())
6011 DCI.AddToWorklist(Temp.getNode());
6012 break;
6013 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
6014 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
6015 Temp = DAG.getNOT(dl, N0, OpVT);
6016 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
6017 if (!DCI.isCalledByLegalizer())
6018 DCI.AddToWorklist(Temp.getNode());
6019 break;
6020 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
6021 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
6022 Temp = DAG.getNOT(dl, N1, OpVT);
6023 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
6024 break;
6025 }
6026 if (VT.getScalarType() != MVT::i1) {
6027 if (!DCI.isCalledByLegalizer())
6028 DCI.AddToWorklist(N0.getNode());
6029 // FIXME: If running after legalize, we probably can't do this.
6031 N0 = DAG.getNode(ExtendCode, dl, VT, N0);
6032 }
6033 return N0;
6034 }
6035
6036 // Fold (setcc (trunc x) (trunc y)) -> (setcc x y)
6037 if (N0.getOpcode() == ISD::TRUNCATE && N1.getOpcode() == ISD::TRUNCATE &&
6038 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
6040 N1->getFlags().hasNoUnsignedWrap()) ||
6042 N1->getFlags().hasNoSignedWrap())) &&
6044 if (VT.getScalarType() == MVT::i1)
6045 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
6046 // For (legal) non vXi1 cases - ensure we adjust the cmp and result types.
6047 EVT OldCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6048 N0.getValueType());
6049 if (VT == OldCCVT) {
6050 EVT NewCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6051 N0.getOperand(0).getValueType());
6052 return DAG.getBoolExtOrTrunc(
6053 DAG.getSetCC(dl, NewCCVT, N0.getOperand(0), N1.getOperand(0), Cond),
6054 dl, VT, N0.getOperand(0).getValueType());
6055 }
6056 }
6057
6058 // Fold (setcc (sub nsw a, b), zero, s??) -> (setcc a, b, s??)
6059 // TODO: Remove that .isVector() check
6060 if (VT.isVector() && isZeroOrZeroSplat(N1) && N0.getOpcode() == ISD::SUB &&
6062 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), Cond);
6063 }
6064
6065 // Could not fold it.
6066 return SDValue();
6067}
6068
6069/// Returns true (and the GlobalValue and the offset) if the node is a
6070/// GlobalAddress + offset.
6072 int64_t &Offset) const {
6073
6074 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
6075
6076 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
6077 GA = GASD->getGlobal();
6078 Offset += GASD->getOffset();
6079 return true;
6080 }
6081
6082 if (N->isAnyAdd()) {
6083 SDValue N1 = N->getOperand(0);
6084 SDValue N2 = N->getOperand(1);
6085 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
6086 if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
6087 Offset += V->getSExtValue();
6088 return true;
6089 }
6090 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
6091 if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
6092 Offset += V->getSExtValue();
6093 return true;
6094 }
6095 }
6096 }
6097
6098 return false;
6099}
6100
6102 DAGCombinerInfo &DCI) const {
6103 // Default implementation: no optimization.
6104 return SDValue();
6105}
6106
6107//===----------------------------------------------------------------------===//
6108// Inline Assembler Implementation Methods
6109//===----------------------------------------------------------------------===//
6110
6113 unsigned S = Constraint.size();
6114
6115 if (S == 1) {
6116 switch (Constraint[0]) {
6117 default: break;
6118 case 'r':
6119 return C_RegisterClass;
6120 case 'm': // memory
6121 case 'o': // offsetable
6122 case 'V': // not offsetable
6123 return C_Memory;
6124 case 'p': // Address.
6125 return C_Address;
6126 case 'n': // Simple Integer
6127 case 'E': // Floating Point Constant
6128 case 'F': // Floating Point Constant
6129 return C_Immediate;
6130 case 'i': // Simple Integer or Relocatable Constant
6131 case 's': // Relocatable Constant
6132 case 'X': // Allow ANY value.
6133 case 'I': // Target registers.
6134 case 'J':
6135 case 'K':
6136 case 'L':
6137 case 'M':
6138 case 'N':
6139 case 'O':
6140 case 'P':
6141 case '<':
6142 case '>':
6143 return C_Other;
6144 }
6145 }
6146
6147 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
6148 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
6149 return C_Memory;
6150 return C_Register;
6151 }
6152 return C_Unknown;
6153}
6154
6155/// Try to replace an X constraint, which matches anything, with another that
6156/// has more specific requirements based on the type of the corresponding
6157/// operand.
6158const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6159 if (ConstraintVT.isInteger())
6160 return "r";
6161 if (ConstraintVT.isFloatingPoint())
6162 return "f"; // works for many targets
6163 return nullptr;
6164}
6165
6167 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
6168 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
6169 return SDValue();
6170}
6171
6172/// Lower the specified operand into the Ops vector.
6173/// If it is invalid, don't add anything to Ops.
6175 StringRef Constraint,
6176 std::vector<SDValue> &Ops,
6177 SelectionDAG &DAG) const {
6178
6179 if (Constraint.size() > 1)
6180 return;
6181
6182 char ConstraintLetter = Constraint[0];
6183 switch (ConstraintLetter) {
6184 default: break;
6185 case 'X': // Allows any operand
6186 case 'i': // Simple Integer or Relocatable Constant
6187 case 'n': // Simple Integer
6188 case 's': { // Relocatable Constant
6189
6191 uint64_t Offset = 0;
6192
6193 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
6194 // etc., since getelementpointer is variadic. We can't use
6195 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
6196 // while in this case the GA may be furthest from the root node which is
6197 // likely an ISD::ADD.
6198 while (true) {
6199 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
6200 // gcc prints these as sign extended. Sign extend value to 64 bits
6201 // now; without this it would get ZExt'd later in
6202 // ScheduleDAGSDNodes::EmitNode, which is very generic.
6203 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
6204 BooleanContent BCont = getBooleanContents(MVT::i64);
6205 ISD::NodeType ExtOpc =
6206 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
6207 int64_t ExtVal =
6208 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
6209 Ops.push_back(
6210 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
6211 return;
6212 }
6213 if (ConstraintLetter != 'n') {
6214 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6215 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6216 GA->getValueType(0),
6217 Offset + GA->getOffset()));
6218 return;
6219 }
6220 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
6221 Ops.push_back(DAG.getTargetBlockAddress(
6222 BA->getBlockAddress(), BA->getValueType(0),
6223 Offset + BA->getOffset(), BA->getTargetFlags()));
6224 return;
6225 }
6227 Ops.push_back(Op);
6228 return;
6229 }
6230 }
6231 const unsigned OpCode = Op.getOpcode();
6232 if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
6233 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
6234 Op = Op.getOperand(1);
6235 // Subtraction is not commutative.
6236 else if (OpCode == ISD::ADD &&
6237 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
6238 Op = Op.getOperand(0);
6239 else
6240 return;
6241 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
6242 continue;
6243 }
6244 return;
6245 }
6246 break;
6247 }
6248 }
6249}
6250
6254
6255std::pair<unsigned, const TargetRegisterClass *>
6257 StringRef Constraint,
6258 MVT VT) const {
6259 if (!Constraint.starts_with("{"))
6260 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
6261 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
6262
6263 // Remove the braces from around the name.
6264 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
6265
6266 std::pair<unsigned, const TargetRegisterClass *> R =
6267 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
6268
6269 // Figure out which register class contains this reg.
6270 for (const TargetRegisterClass &RC : RI->regclasses()) {
6271 // If none of the value types for this register class are valid, we
6272 // can't use it. For example, 64-bit reg classes on 32-bit targets.
6273 if (!isLegalRC(*RI, RC))
6274 continue;
6275
6276 for (const MCPhysReg &PR : RC) {
6277 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
6278 std::pair<unsigned, const TargetRegisterClass *> S =
6279 std::make_pair(PR, &RC);
6280
6281 // If this register class has the requested value type, return it,
6282 // otherwise keep searching and return the first class found
6283 // if no other is found which explicitly has the requested type.
6284 if (RI->isTypeLegalForClass(RC, VT))
6285 return S;
6286 if (!R.second)
6287 R = S;
6288 }
6289 }
6290 }
6291
6292 return R;
6293}
6294
6295//===----------------------------------------------------------------------===//
6296// Constraint Selection.
6297
6298/// Return true of this is an input operand that is a matching constraint like
6299/// "4".
6301 assert(!ConstraintCode.empty() && "No known constraint!");
6302 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
6303}
6304
6305/// If this is an input matching constraint, this method returns the output
6306/// operand it matches.
6308 assert(!ConstraintCode.empty() && "No known constraint!");
6309 return atoi(ConstraintCode.c_str());
6310}
6311
6312/// Split up the constraint string from the inline assembly value into the
6313/// specific constraints and their prefixes, and also tie in the associated
6314/// operand values.
6315/// If this returns an empty vector, and if the constraint string itself
6316/// isn't empty, there was an error parsing.
6319 const TargetRegisterInfo *TRI,
6320 const CallBase &Call) const {
6321 /// Information about all of the constraints.
6322 AsmOperandInfoVector ConstraintOperands;
6323 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
6324 unsigned maCount = 0; // Largest number of multiple alternative constraints.
6325
6326 // Do a prepass over the constraints, canonicalizing them, and building up the
6327 // ConstraintOperands list.
6328 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6329 unsigned ResNo = 0; // ResNo - The result number of the next output.
6330 unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number.
6331
6332 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
6333 ConstraintOperands.emplace_back(std::move(CI));
6334 AsmOperandInfo &OpInfo = ConstraintOperands.back();
6335
6336 // Update multiple alternative constraint count.
6337 if (OpInfo.multipleAlternatives.size() > maCount)
6338 maCount = OpInfo.multipleAlternatives.size();
6339
6340 OpInfo.ConstraintVT = MVT::Other;
6341
6342 // Compute the value type for each operand.
6343 switch (OpInfo.Type) {
6344 case InlineAsm::isOutput: {
6345 // Indirect outputs just consume an argument.
6346 if (OpInfo.isIndirect) {
6347 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6348 break;
6349 }
6350
6351 // The return value of the call is this value. As such, there is no
6352 // corresponding argument.
6353 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
6354 EVT VT;
6355 if (auto *STy = dyn_cast<StructType>(Call.getType())) {
6356 VT = getAsmOperandValueType(DL, STy->getElementType(ResNo));
6357 } else {
6358 assert(ResNo == 0 && "Asm only has one result!");
6359 VT = getAsmOperandValueType(DL, Call.getType());
6360 }
6361 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6362 ++ResNo;
6363 break;
6364 }
6365 case InlineAsm::isInput:
6366 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6367 break;
6368 case InlineAsm::isLabel:
6369 OpInfo.CallOperandVal = cast<CallBrInst>(&Call)->getIndirectDest(LabelNo);
6370 ++LabelNo;
6371 continue;
6373 // Nothing to do.
6374 break;
6375 }
6376
6377 if (OpInfo.CallOperandVal) {
6378 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
6379 if (OpInfo.isIndirect) {
6380 OpTy = Call.getParamElementType(ArgNo);
6381 assert(OpTy && "Indirect operand must have elementtype attribute");
6382 }
6383
6384 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6386 if (STy->getNumElements() == 1)
6387 OpTy = STy->getElementType(0);
6388
6389 // If OpTy is not a single value, it may be a struct/union that we
6390 // can tile with integers.
6391 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6392 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6393 switch (BitSize) {
6394 default: break;
6395 case 1:
6396 case 8:
6397 case 16:
6398 case 32:
6399 case 64:
6400 case 128:
6401 OpTy = IntegerType::get(OpTy->getContext(), BitSize);
6402 break;
6403 }
6404 }
6405
6406 EVT VT = getAsmOperandValueType(DL, OpTy, true);
6407 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6408 ArgNo++;
6409 }
6410 }
6411
6412 // If we have multiple alternative constraints, select the best alternative.
6413 if (!ConstraintOperands.empty()) {
6414 if (maCount) {
6415 unsigned bestMAIndex = 0;
6416 int bestWeight = -1;
6417 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
6418 int weight = -1;
6419 unsigned maIndex;
6420 // Compute the sums of the weights for each alternative, keeping track
6421 // of the best (highest weight) one so far.
6422 for (maIndex = 0; maIndex < maCount; ++maIndex) {
6423 int weightSum = 0;
6424 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6425 cIndex != eIndex; ++cIndex) {
6426 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6427 if (OpInfo.Type == InlineAsm::isClobber)
6428 continue;
6429
6430 // If this is an output operand with a matching input operand,
6431 // look up the matching input. If their types mismatch, e.g. one
6432 // is an integer, the other is floating point, or their sizes are
6433 // different, flag it as an maCantMatch.
6434 if (OpInfo.hasMatchingInput()) {
6435 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6436 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6437 if ((OpInfo.ConstraintVT.isInteger() !=
6438 Input.ConstraintVT.isInteger()) ||
6439 (OpInfo.ConstraintVT.getSizeInBits() !=
6440 Input.ConstraintVT.getSizeInBits())) {
6441 weightSum = -1; // Can't match.
6442 break;
6443 }
6444 }
6445 }
6446 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
6447 if (weight == -1) {
6448 weightSum = -1;
6449 break;
6450 }
6451 weightSum += weight;
6452 }
6453 // Update best.
6454 if (weightSum > bestWeight) {
6455 bestWeight = weightSum;
6456 bestMAIndex = maIndex;
6457 }
6458 }
6459
6460 // Now select chosen alternative in each constraint.
6461 for (AsmOperandInfo &cInfo : ConstraintOperands)
6462 if (cInfo.Type != InlineAsm::isClobber)
6463 cInfo.selectAlternative(bestMAIndex);
6464 }
6465 }
6466
6467 // Check and hook up tied operands, choose constraint code to use.
6468 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6469 cIndex != eIndex; ++cIndex) {
6470 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6471
6472 // If this is an output operand with a matching input operand, look up the
6473 // matching input. If their types mismatch, e.g. one is an integer, the
6474 // other is floating point, or their sizes are different, flag it as an
6475 // error.
6476 if (OpInfo.hasMatchingInput()) {
6477 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6478
6479 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6480 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6481 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6482 OpInfo.ConstraintVT);
6483 std::pair<unsigned, const TargetRegisterClass *> InputRC =
6484 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
6485 Input.ConstraintVT);
6486 const bool OutOpIsIntOrFP = OpInfo.ConstraintVT.isInteger() ||
6487 OpInfo.ConstraintVT.isFloatingPoint();
6488 const bool InOpIsIntOrFP = Input.ConstraintVT.isInteger() ||
6489 Input.ConstraintVT.isFloatingPoint();
6490 if ((OutOpIsIntOrFP != InOpIsIntOrFP) ||
6491 (MatchRC.second != InputRC.second)) {
6492 report_fatal_error("Unsupported asm: input constraint"
6493 " with a matching output constraint of"
6494 " incompatible type!");
6495 }
6496 }
6497 }
6498 }
6499
6500 return ConstraintOperands;
6501}
6502
6503/// Return a number indicating our preference for chosing a type of constraint
6504/// over another, for the purpose of sorting them. Immediates are almost always
6505/// preferrable (when they can be emitted). A higher return value means a
6506/// stronger preference for one constraint type relative to another.
6507/// FIXME: We should prefer registers over memory but doing so may lead to
6508/// unrecoverable register exhaustion later.
6509/// https://github.com/llvm/llvm-project/issues/20571
6511 switch (CT) {
6514 return 4;
6517 return 3;
6519 return 2;
6521 return 1;
6523 return 0;
6524 }
6525 llvm_unreachable("Invalid constraint type");
6526}
6527
6528/// Examine constraint type and operand type and determine a weight value.
6529/// This object must already have been set up with the operand type
6530/// and the current alternative constraint selected.
6533 AsmOperandInfo &info, int maIndex) const {
6535 if (maIndex >= (int)info.multipleAlternatives.size())
6536 rCodes = &info.Codes;
6537 else
6538 rCodes = &info.multipleAlternatives[maIndex].Codes;
6539 ConstraintWeight BestWeight = CW_Invalid;
6540
6541 // Loop over the options, keeping track of the most general one.
6542 for (const std::string &rCode : *rCodes) {
6543 ConstraintWeight weight =
6544 getSingleConstraintMatchWeight(info, rCode.c_str());
6545 if (weight > BestWeight)
6546 BestWeight = weight;
6547 }
6548
6549 return BestWeight;
6550}
6551
6552/// Examine constraint type and operand type and determine a weight value.
6553/// This object must already have been set up with the operand type
6554/// and the current alternative constraint selected.
6557 AsmOperandInfo &info, const char *constraint) const {
6559 Value *CallOperandVal = info.CallOperandVal;
6560 // If we don't have a value, we can't do a match,
6561 // but allow it at the lowest weight.
6562 if (!CallOperandVal)
6563 return CW_Default;
6564 // Look at the constraint type.
6565 switch (*constraint) {
6566 case 'i': // immediate integer.
6567 case 'n': // immediate integer with a known value.
6568 if (isa<ConstantInt>(CallOperandVal))
6569 weight = CW_Constant;
6570 break;
6571 case 's': // non-explicit intregal immediate.
6572 if (isa<GlobalValue>(CallOperandVal))
6573 weight = CW_Constant;
6574 break;
6575 case 'E': // immediate float if host format.
6576 case 'F': // immediate float.
6577 if (isa<ConstantFP>(CallOperandVal))
6578 weight = CW_Constant;
6579 break;
6580 case '<': // memory operand with autodecrement.
6581 case '>': // memory operand with autoincrement.
6582 case 'm': // memory operand.
6583 case 'o': // offsettable memory operand
6584 case 'V': // non-offsettable memory operand
6585 weight = CW_Memory;
6586 break;
6587 case 'r': // general register.
6588 case 'g': // general register, memory operand or immediate integer.
6589 // note: Clang converts "g" to "imr".
6590 if (CallOperandVal->getType()->isIntegerTy())
6591 weight = CW_Register;
6592 break;
6593 case 'X': // any operand.
6594 default:
6595 weight = CW_Default;
6596 break;
6597 }
6598 return weight;
6599}
6600
6601/// If there are multiple different constraints that we could pick for this
6602/// operand (e.g. "imr") try to pick the 'best' one.
6603/// This is somewhat tricky: constraints (TargetLowering::ConstraintType) fall
6604/// into seven classes:
6605/// Register -> one specific register
6606/// RegisterClass -> a group of regs
6607/// Memory -> memory
6608/// Address -> a symbolic memory reference
6609/// Immediate -> immediate values
6610/// Other -> magic values (such as "Flag Output Operands")
6611/// Unknown -> something we don't recognize yet and can't handle
6612/// Ideally, we would pick the most specific constraint possible: if we have
6613/// something that fits into a register, we would pick it. The problem here
6614/// is that if we have something that could either be in a register or in
6615/// memory that use of the register could cause selection of *other*
6616/// operands to fail: they might only succeed if we pick memory. Because of
6617/// this the heuristic we use is:
6618///
6619/// 1) If there is an 'other' constraint, and if the operand is valid for
6620/// that constraint, use it. This makes us take advantage of 'i'
6621/// constraints when available.
6622/// 2) Otherwise, pick the most general constraint present. This prefers
6623/// 'm' over 'r', for example.
6624///
6626 TargetLowering::AsmOperandInfo &OpInfo) const {
6627 ConstraintGroup Ret;
6628
6629 Ret.reserve(OpInfo.Codes.size());
6630 for (StringRef Code : OpInfo.Codes) {
6632
6633 // Indirect 'other' or 'immediate' constraints are not allowed.
6634 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
6635 CType == TargetLowering::C_Register ||
6637 continue;
6638
6639 // Things with matching constraints can only be registers, per gcc
6640 // documentation. This mainly affects "g" constraints.
6641 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
6642 continue;
6643
6644 Ret.emplace_back(Code, CType);
6645 }
6646
6648 return getConstraintPiority(a.second) > getConstraintPiority(b.second);
6649 });
6650
6651 return Ret;
6652}
6653
6654/// If we have an immediate, see if we can lower it. Return true if we can,
6655/// false otherwise.
6657 SDValue Op, SelectionDAG *DAG,
6658 const TargetLowering &TLI) {
6659
6660 assert((P.second == TargetLowering::C_Other ||
6661 P.second == TargetLowering::C_Immediate) &&
6662 "need immediate or other");
6663
6664 if (!Op.getNode())
6665 return false;
6666
6667 std::vector<SDValue> ResultOps;
6668 TLI.LowerAsmOperandForConstraint(Op, P.first, ResultOps, *DAG);
6669 return !ResultOps.empty();
6670}
6671
6672/// Determines the constraint code and constraint type to use for the specific
6673/// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
6675 SDValue Op,
6676 SelectionDAG *DAG) const {
6677 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
6678
6679 // Single-letter constraints ('r') are very common.
6680 if (OpInfo.Codes.size() == 1) {
6681 OpInfo.ConstraintCode = OpInfo.Codes[0];
6682 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6683 } else {
6685 if (G.empty())
6686 return;
6687
6688 unsigned BestIdx = 0;
6689 for (const unsigned E = G.size();
6690 BestIdx < E && (G[BestIdx].second == TargetLowering::C_Other ||
6691 G[BestIdx].second == TargetLowering::C_Immediate);
6692 ++BestIdx) {
6693 if (lowerImmediateIfPossible(G[BestIdx], Op, DAG, *this))
6694 break;
6695 // If we're out of constraints, just pick the first one.
6696 if (BestIdx + 1 == E) {
6697 BestIdx = 0;
6698 break;
6699 }
6700 }
6701
6702 OpInfo.ConstraintCode = G[BestIdx].first;
6703 OpInfo.ConstraintType = G[BestIdx].second;
6704 }
6705
6706 // 'X' matches anything.
6707 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
6708 // Constants are handled elsewhere. For Functions, the type here is the
6709 // type of the result, which is not what we want to look at; leave them
6710 // alone.
6711 Value *v = OpInfo.CallOperandVal;
6712 if (isa<ConstantInt>(v) || isa<Function>(v)) {
6713 return;
6714 }
6715
6716 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
6717 OpInfo.ConstraintCode = "i";
6718 return;
6719 }
6720
6721 // Otherwise, try to resolve it to something we know about by looking at
6722 // the actual operand type.
6723 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
6724 OpInfo.ConstraintCode = Repl;
6725 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6726 }
6727 }
6728}
6729
6730/// Given an exact SDIV by a constant, create a multiplication
6731/// with the multiplicative inverse of the constant.
6732/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6734 const SDLoc &dl, SelectionDAG &DAG,
6735 SmallVectorImpl<SDNode *> &Created) {
6736 SDValue Op0 = N->getOperand(0);
6737 SDValue Op1 = N->getOperand(1);
6738 EVT VT = N->getValueType(0);
6739 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6740 EVT ShSVT = ShVT.getScalarType();
6741
6742 bool UseSRA = false;
6743 SmallVector<SDValue, 16> Shifts, Factors;
6744
6745 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6746 if (C->isZero())
6747 return false;
6748
6749 EVT CT = C->getValueType(0);
6750 APInt Divisor = C->getAPIntValue();
6751 unsigned Shift = Divisor.countr_zero();
6752 if (Shift) {
6753 Divisor.ashrInPlace(Shift);
6754 UseSRA = true;
6755 }
6756 APInt Factor = Divisor.multiplicativeInverse();
6757 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6758 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6759 return true;
6760 };
6761
6762 // Collect all magic values from the build vector.
6763 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
6764 return SDValue();
6765
6766 SDValue Shift, Factor;
6767 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6768 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6769 Factor = DAG.getBuildVector(VT, dl, Factors);
6770 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6771 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6772 "Expected matchUnaryPredicate to return one element for scalable "
6773 "vectors");
6774 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6775 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6776 } else {
6777 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6778 Shift = Shifts[0];
6779 Factor = Factors[0];
6780 }
6781
6782 SDValue Res = Op0;
6783 if (UseSRA) {
6784 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, SDNodeFlags::Exact);
6785 Created.push_back(Res.getNode());
6786 }
6787
6788 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6789}
6790
6791/// Given an exact UDIV by a constant, create a multiplication
6792/// with the multiplicative inverse of the constant.
6793/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6795 const SDLoc &dl, SelectionDAG &DAG,
6796 SmallVectorImpl<SDNode *> &Created) {
6797 EVT VT = N->getValueType(0);
6798 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6799 EVT ShSVT = ShVT.getScalarType();
6800
6801 bool UseSRL = false;
6802 SmallVector<SDValue, 16> Shifts, Factors;
6803
6804 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
6805 if (C->isZero())
6806 return false;
6807
6808 EVT CT = C->getValueType(0);
6809 APInt Divisor = C->getAPIntValue();
6810 unsigned Shift = Divisor.countr_zero();
6811 if (Shift) {
6812 Divisor.lshrInPlace(Shift);
6813 UseSRL = true;
6814 }
6815 // Calculate the multiplicative inverse modulo BW.
6816 APInt Factor = Divisor.multiplicativeInverse();
6817 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6818 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6819 return true;
6820 };
6821
6822 SDValue Op1 = N->getOperand(1);
6823
6824 // Collect all magic values from the build vector.
6825 if (!ISD::matchUnaryPredicate(Op1, BuildUDIVPattern))
6826 return SDValue();
6827
6828 SDValue Shift, Factor;
6829 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6830 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6831 Factor = DAG.getBuildVector(VT, dl, Factors);
6832 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6833 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6834 "Expected matchUnaryPredicate to return one element for scalable "
6835 "vectors");
6836 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6837 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6838 } else {
6839 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6840 Shift = Shifts[0];
6841 Factor = Factors[0];
6842 }
6843
6844 SDValue Res = N->getOperand(0);
6845 if (UseSRL) {
6846 Res = DAG.getNode(ISD::SRL, dl, VT, Res, Shift, SDNodeFlags::Exact);
6847 Created.push_back(Res.getNode());
6848 }
6849
6850 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6851}
6852
6854 SelectionDAG &DAG,
6855 SmallVectorImpl<SDNode *> &Created) const {
6857 if (isIntDivCheap(N->getValueType(0), Attr))
6858 return SDValue(N, 0); // Lower SDIV as SDIV
6859 return SDValue();
6860}
6861
6862SDValue
6864 SelectionDAG &DAG,
6865 SmallVectorImpl<SDNode *> &Created) const {
6867 if (isIntDivCheap(N->getValueType(0), Attr))
6868 return SDValue(N, 0); // Lower SREM as SREM
6869 return SDValue();
6870}
6871
6872/// Build sdiv by power-of-2 with conditional move instructions
6873/// Ref: "Hacker's Delight" by Henry Warren 10-1
6874/// If conditional move/branch is preferred, we lower sdiv x, +/-2**k into:
6875/// bgez x, label
6876/// add x, x, 2**k-1
6877/// label:
6878/// sra res, x, k
6879/// neg res, res (when the divisor is negative)
6881 SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
6882 SmallVectorImpl<SDNode *> &Created) const {
6883 unsigned Lg2 = Divisor.countr_zero();
6884 EVT VT = N->getValueType(0);
6885
6886 SDLoc DL(N);
6887 SDValue N0 = N->getOperand(0);
6888 SDValue Zero = DAG.getConstant(0, DL, VT);
6889 APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
6890 SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
6891
6892 // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
6893 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6894 SDValue Cmp = DAG.getSetCC(DL, CCVT, N0, Zero, ISD::SETLT);
6895 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
6896 SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
6897
6898 Created.push_back(Cmp.getNode());
6899 Created.push_back(Add.getNode());
6900 Created.push_back(CMov.getNode());
6901
6902 // Divide by pow2.
6903 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, CMov,
6904 DAG.getShiftAmountConstant(Lg2, VT, DL));
6905
6906 // If we're dividing by a positive value, we're done. Otherwise, we must
6907 // negate the result.
6908 if (Divisor.isNonNegative())
6909 return SRA;
6910
6911 Created.push_back(SRA.getNode());
6912 return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
6913}
6914
6915/// Given an ISD::SDIV node expressing a divide by constant,
6916/// return a DAG expression to select that will generate the same value by
6917/// multiplying by a magic number.
6918/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
6920 bool IsAfterLegalization,
6921 bool IsAfterLegalTypes,
6922 SmallVectorImpl<SDNode *> &Created) const {
6923 SDLoc dl(N);
6924
6925 // If the sdiv has an 'exact' bit we can use a simpler lowering.
6926 if (N->getFlags().hasExact())
6927 return BuildExactSDIV(*this, N, dl, DAG, Created);
6928
6929 EVT VT = N->getValueType(0);
6930 EVT SVT = VT.getScalarType();
6931 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
6932 EVT ShSVT = ShVT.getScalarType();
6933 unsigned EltBits = VT.getScalarSizeInBits();
6934 EVT MulVT;
6935
6936 // Check to see if we can do this.
6937 // FIXME: We should be more aggressive here.
6938 EVT QueryVT = VT;
6939 if (VT.isVector()) {
6940 // If the vector type will be legalized to a vector type with the same
6941 // element type, allow the transform before type legalization if MULHS or
6942 // SMUL_LOHI are supported.
6943 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
6944 if (!QueryVT.isVector() ||
6946 return SDValue();
6947 } else if (!isTypeLegal(VT)) {
6948 // Limit this to simple scalars for now.
6949 if (!VT.isSimple())
6950 return SDValue();
6951
6952 // If this type will be promoted to a large enough type with a legal
6953 // multiply operation, we can go ahead and do this transform.
6955 return SDValue();
6956
6957 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
6958 if (MulVT.getSizeInBits() < (2 * EltBits) ||
6959 !isOperationLegal(ISD::MUL, MulVT))
6960 return SDValue();
6961 }
6962
6963 bool HasMULHS =
6964 isOperationLegalOrCustom(ISD::MULHS, QueryVT, IsAfterLegalization);
6965 bool HasSMUL_LOHI =
6966 isOperationLegalOrCustom(ISD::SMUL_LOHI, QueryVT, IsAfterLegalization);
6967
6968 if (isTypeLegal(VT) && !HasMULHS && !HasSMUL_LOHI && MulVT == EVT()) {
6969 // If type twice as wide legal, widen and use a mul plus a shift.
6970 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
6971 // Some targets like AMDGPU try to go from SDIV to SDIVREM which is then
6972 // custom lowered. This is very expensive so avoid it at all costs for
6973 // constant divisors.
6974 if ((!IsAfterLegalTypes && isOperationExpand(ISD::SDIV, VT) &&
6977 MulVT = WideVT;
6978 }
6979
6980 if (!HasMULHS && !HasSMUL_LOHI && MulVT == EVT())
6981 return SDValue();
6982
6983 // If we're after type legalization and SVT is not legal, use the
6984 // promoted type for creating constants to avoid creating nodes with
6985 // illegal types.
6986 if (IsAfterLegalTypes && VT.isVector()) {
6987 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
6988 if (SVT.bitsLT(VT.getScalarType()))
6989 return SDValue();
6990 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
6991 if (ShSVT.bitsLT(ShVT.getScalarType()))
6992 return SDValue();
6993 }
6994 const unsigned SVTBits = SVT.getSizeInBits();
6995
6996 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
6997
6998 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6999 if (C->isZero())
7000 return false;
7001 // Truncate the divisor to the target scalar type in case it was promoted
7002 // during type legalization.
7003 APInt Divisor = C->getAPIntValue().trunc(EltBits);
7005 int NumeratorFactor = 0;
7006 int ShiftMask = -1;
7007
7008 if (Divisor.isOne() || Divisor.isAllOnes()) {
7009 // If d is +1/-1, we just multiply the numerator by +1/-1.
7010 NumeratorFactor = Divisor.getSExtValue();
7011 magics.Magic = 0;
7012 magics.ShiftAmount = 0;
7013 ShiftMask = 0;
7014 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
7015 // If d > 0 and m < 0, add the numerator.
7016 NumeratorFactor = 1;
7017 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
7018 // If d < 0 and m > 0, subtract the numerator.
7019 NumeratorFactor = -1;
7020 }
7021
7022 MagicFactors.push_back(
7023 DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT));
7024 Factors.push_back(DAG.getSignedConstant(NumeratorFactor, dl, SVT));
7025 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
7026 ShiftMasks.push_back(DAG.getSignedConstant(ShiftMask, dl, SVT));
7027 return true;
7028 };
7029
7030 SDValue N0 = N->getOperand(0);
7031 SDValue N1 = N->getOperand(1);
7032
7033 // Collect the shifts / magic values from each element.
7034 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern, /*AllowUndefs=*/false,
7035 /*AllowTruncation=*/true))
7036 return SDValue();
7037
7038 SDValue MagicFactor, Factor, Shift, ShiftMask;
7039 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
7040 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
7041 Factor = DAG.getBuildVector(VT, dl, Factors);
7042 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
7043 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
7044 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
7045 assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
7046 Shifts.size() == 1 && ShiftMasks.size() == 1 &&
7047 "Expected matchUnaryPredicate to return one element for scalable "
7048 "vectors");
7049 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
7050 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
7051 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
7052 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
7053 } else {
7054 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
7055 MagicFactor = MagicFactors[0];
7056 Factor = Factors[0];
7057 Shift = Shifts[0];
7058 ShiftMask = ShiftMasks[0];
7059 }
7060
7061 // Multiply the numerator (operand 0) by the magic value.
7062 auto GetMULHS = [&](SDValue X, SDValue Y) {
7063 if (HasMULHS)
7064 return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
7065 if (HasSMUL_LOHI) {
7066 SDValue LoHi =
7067 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
7068 return LoHi.getValue(1);
7069 }
7070
7071 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
7072 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
7073 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
7074 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
7075 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
7076 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
7077 };
7078
7079 SDValue Q = GetMULHS(N0, MagicFactor);
7080 if (!Q)
7081 return SDValue();
7082
7083 Created.push_back(Q.getNode());
7084
7085 // (Optionally) Add/subtract the numerator using Factor.
7086 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
7087 Created.push_back(Factor.getNode());
7088 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
7089 Created.push_back(Q.getNode());
7090
7091 // Shift right algebraic by shift value.
7092 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
7093 Created.push_back(Q.getNode());
7094
7095 // Extract the sign bit, mask it and add it to the quotient.
7096 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
7097 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
7098 Created.push_back(T.getNode());
7099 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
7100 Created.push_back(T.getNode());
7101 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
7102}
7103
7104/// Given an ISD::UDIV node expressing a divide by constant,
7105/// return a DAG expression to select that will generate the same value by
7106/// multiplying by a magic number.
7107/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
7109 bool IsAfterLegalization,
7110 bool IsAfterLegalTypes,
7111 SmallVectorImpl<SDNode *> &Created) const {
7112 SDLoc dl(N);
7113
7114 // If the udiv has an 'exact' bit we can use a simpler lowering.
7115 if (N->getFlags().hasExact())
7116 return BuildExactUDIV(*this, N, dl, DAG, Created);
7117
7118 EVT VT = N->getValueType(0);
7119 EVT SVT = VT.getScalarType();
7120 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7121 EVT ShSVT = ShVT.getScalarType();
7122 unsigned EltBits = VT.getScalarSizeInBits();
7123 EVT MulVT;
7124
7125 // Check to see if we can do this.
7126 // FIXME: We should be more aggressive here.
7127 EVT QueryVT = VT;
7128 if (VT.isVector()) {
7129 // If the vector type will be legalized to a vector type with the same
7130 // element type, allow the transform before type legalization if MULHU or
7131 // UMUL_LOHI are supported.
7132 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
7133 if (!QueryVT.isVector() ||
7135 return SDValue();
7136 } else if (!isTypeLegal(VT)) {
7137 // Limit this to simple scalars for now.
7138 if (!VT.isSimple())
7139 return SDValue();
7140
7141 // If this type will be promoted to a large enough type with a legal
7142 // multiply operation, we can go ahead and do this transform.
7144 return SDValue();
7145
7146 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
7147 if (MulVT.getSizeInBits() < (2 * EltBits) ||
7148 !isOperationLegal(ISD::MUL, MulVT))
7149 return SDValue();
7150 }
7151
7152 bool HasMULHU =
7153 isOperationLegalOrCustom(ISD::MULHU, QueryVT, IsAfterLegalization);
7154 bool HasUMUL_LOHI =
7155 isOperationLegalOrCustom(ISD::UMUL_LOHI, QueryVT, IsAfterLegalization);
7156
7157 if (isTypeLegal(VT) && !HasMULHU && !HasUMUL_LOHI && MulVT == EVT()) {
7158 // If type twice as wide legal, widen and use a mul plus a shift.
7159 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
7160 // Some targets like AMDGPU try to go from UDIV to UDIVREM which is then
7161 // custom lowered. This is very expensive so avoid it at all costs for
7162 // constant divisors.
7163 if ((!IsAfterLegalTypes && isOperationExpand(ISD::UDIV, VT) &&
7166 MulVT = WideVT;
7167 }
7168
7169 if (!HasMULHU && !HasUMUL_LOHI && MulVT == EVT())
7170 return SDValue();
7171
7172 SDValue N0 = N->getOperand(0);
7173 SDValue N1 = N->getOperand(1);
7174
7175 // Try to use leading zeros of the dividend to reduce the multiplier and
7176 // avoid expensive fixups.
7177 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
7178
7179 // If we're after type legalization and SVT is not legal, use the
7180 // promoted type for creating constants to avoid creating nodes with
7181 // illegal types.
7182 if (IsAfterLegalTypes && VT.isVector()) {
7183 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
7184 if (SVT.bitsLT(VT.getScalarType()))
7185 return SDValue();
7186 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
7187 if (ShSVT.bitsLT(ShVT.getScalarType()))
7188 return SDValue();
7189 }
7190 const unsigned SVTBits = SVT.getSizeInBits();
7191
7192 // Allow i32 to be widened to i64 for uncooperative divisors if i64 MULHU or
7193 // UMUL_LOHI is supported.
7194 const EVT WideSVT = MVT::i64;
7195 const bool HasWideMULHU =
7196 VT == MVT::i32 &&
7197 isOperationLegalOrCustom(ISD::MULHU, WideSVT, IsAfterLegalization);
7198 const bool HasWideUMUL_LOHI =
7199 VT == MVT::i32 &&
7200 isOperationLegalOrCustom(ISD::UMUL_LOHI, WideSVT, IsAfterLegalization);
7201 const bool AllowWiden = (HasWideMULHU || HasWideUMUL_LOHI);
7202
7203 // For even divisors with a 33-bit magic number, the widened high-multiply
7204 // path is only worthwhile over the even-divisor rewrite on targets that
7205 // zero-extend i32 to i64 for free (e.g. x86-64 and AArch64). Elsewhere (e.g.
7206 // RISC-V) keep the even-divisor rewrite, which avoids the explicit extension.
7207 const bool AllowEvenToWiden = AllowWiden && isZExtFree(VT, WideSVT);
7208
7209 bool UseNPQ = false, UsePreShift = false, UsePostShift = false;
7210 bool UseWiden = false;
7211 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
7212
7213 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
7214 if (C->isZero())
7215 return false;
7216 // Truncate the divisor to the target scalar type in case it was promoted
7217 // during type legalization.
7218 APInt Divisor = C->getAPIntValue().trunc(EltBits);
7219
7220 SDValue PreShift, MagicFactor, NPQFactor, PostShift;
7221
7222 // Magic algorithm doesn't work for division by 1. We need to emit a select
7223 // at the end.
7224 if (Divisor.isOne()) {
7225 PreShift = PostShift = DAG.getUNDEF(ShSVT);
7226 MagicFactor = NPQFactor = DAG.getUNDEF(SVT);
7227 } else {
7230 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()),
7231 /*AllowEvenDivisorOptimization=*/!AllowEvenToWiden,
7232 /*AllowWidenOptimization=*/AllowWiden);
7233
7234 if (magics.Widen) {
7235 UseWiden = true;
7236 MagicFactor = DAG.getConstant(magics.Magic, dl, WideSVT);
7237 } else {
7238 MagicFactor = DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT);
7239 }
7240
7241 assert(magics.PreShift < Divisor.getBitWidth() &&
7242 "We shouldn't generate an undefined shift!");
7243 assert(magics.PostShift < Divisor.getBitWidth() &&
7244 "We shouldn't generate an undefined shift!");
7245 assert((!magics.IsAdd || magics.PreShift == 0) &&
7246 "Unexpected pre-shift");
7247 PreShift = DAG.getConstant(magics.PreShift, dl, ShSVT);
7248 PostShift = DAG.getConstant(magics.PostShift, dl, ShSVT);
7249 NPQFactor = DAG.getConstant(
7250 magics.IsAdd ? APInt::getOneBitSet(SVTBits, EltBits - 1)
7251 : APInt::getZero(SVTBits),
7252 dl, SVT);
7253 UseNPQ |= magics.IsAdd;
7254 UsePreShift |= magics.PreShift != 0;
7255 UsePostShift |= magics.PostShift != 0;
7256 }
7257
7258 PreShifts.push_back(PreShift);
7259 MagicFactors.push_back(MagicFactor);
7260 NPQFactors.push_back(NPQFactor);
7261 PostShifts.push_back(PostShift);
7262 return true;
7263 };
7264
7265 // Collect the shifts/magic values from each element.
7266 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern, /*AllowUndefs=*/false,
7267 /*AllowTruncation=*/true))
7268 return SDValue();
7269
7270 SDValue PreShift, PostShift, MagicFactor, NPQFactor;
7271 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
7272 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
7273 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
7274 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
7275 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
7276 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
7277 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
7278 NPQFactors.size() == 1 && PostShifts.size() == 1 &&
7279 "Expected matchUnaryPredicate to return one for scalable vectors");
7280 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
7281 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
7282 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
7283 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
7284 } else {
7285 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
7286 PreShift = PreShifts[0];
7287 MagicFactor = MagicFactors[0];
7288 PostShift = PostShifts[0];
7289 }
7290
7291 if (UseWiden) {
7292 // Compute: (WideSVT(x) * MagicFactor) >> WideSVTBits.
7293 SDValue WideN0 = DAG.getNode(ISD::ZERO_EXTEND, dl, WideSVT, N0);
7294
7295 // Perform WideSVTxWideSVT -> 2*WideSVT multiplication and extract high
7296 // WideSVT bits
7297 SDValue High;
7298 if (HasWideMULHU) {
7299 High = DAG.getNode(ISD::MULHU, dl, WideSVT, WideN0, MagicFactor);
7300 } else {
7301 assert(HasWideUMUL_LOHI);
7302 SDValue LoHi =
7303 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(WideSVT, WideSVT),
7304 WideN0, MagicFactor);
7305 High = LoHi.getValue(1);
7306 }
7307
7308 Created.push_back(High.getNode());
7309 return DAG.getNode(ISD::TRUNCATE, dl, VT, High);
7310 }
7311
7312 SDValue Q = N0;
7313 if (UsePreShift) {
7314 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
7315 Created.push_back(Q.getNode());
7316 }
7317
7318 auto GetMULHU = [&](SDValue X, SDValue Y) {
7319 if (HasMULHU)
7320 return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
7321 if (HasUMUL_LOHI) {
7322 SDValue LoHi =
7323 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
7324 return LoHi.getValue(1);
7325 }
7326
7327 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
7328 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
7329 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
7330 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
7331 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
7332 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
7333 };
7334
7335 // Multiply the numerator (operand 0) by the magic value.
7336 Q = GetMULHU(Q, MagicFactor);
7337 if (!Q)
7338 return SDValue();
7339
7340 Created.push_back(Q.getNode());
7341
7342 if (UseNPQ) {
7343 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
7344 Created.push_back(NPQ.getNode());
7345
7346 // For vectors we might have a mix of non-NPQ/NPQ paths, so use
7347 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
7348 if (VT.isVector())
7349 NPQ = GetMULHU(NPQ, NPQFactor);
7350 else
7351 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
7352
7353 Created.push_back(NPQ.getNode());
7354
7355 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
7356 Created.push_back(Q.getNode());
7357 }
7358
7359 if (UsePostShift) {
7360 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
7361 Created.push_back(Q.getNode());
7362 }
7363
7364 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7365
7366 SDValue One = DAG.getConstant(1, dl, VT);
7367 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
7368 return DAG.getSelect(dl, VT, IsOne, N0, Q);
7369}
7370
7371/// If all values in Values that *don't* match the predicate are same 'splat'
7372/// value, then replace all values with that splat value.
7373/// Else, if AlternativeReplacement was provided, then replace all values that
7374/// do match predicate with AlternativeReplacement value.
7375static void
7377 std::function<bool(SDValue)> Predicate,
7378 SDValue AlternativeReplacement = SDValue()) {
7379 SDValue Replacement;
7380 // Is there a value for which the Predicate does *NOT* match? What is it?
7381 auto SplatValue = llvm::find_if_not(Values, Predicate);
7382 if (SplatValue != Values.end()) {
7383 // Does Values consist only of SplatValue's and values matching Predicate?
7384 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
7385 return Value == *SplatValue || Predicate(Value);
7386 })) // Then we shall replace values matching predicate with SplatValue.
7387 Replacement = *SplatValue;
7388 }
7389 if (!Replacement) {
7390 // Oops, we did not find the "baseline" splat value.
7391 if (!AlternativeReplacement)
7392 return; // Nothing to do.
7393 // Let's replace with provided value then.
7394 Replacement = AlternativeReplacement;
7395 }
7396 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
7397}
7398
7399/// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
7400/// where the divisor and comparison target are constants,
7401/// return a DAG expression that will generate the same comparison result
7402/// using only multiplications, additions and shifts/rotations.
7403/// Ref: "Hacker's Delight" 10-17.
7404SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
7405 SDValue CompTargetNode,
7407 DAGCombinerInfo &DCI,
7408 const SDLoc &DL) const {
7410 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7411 DCI, DL, Built)) {
7412 for (SDNode *N : Built)
7413 DCI.AddToWorklist(N);
7414 return Folded;
7415 }
7416
7417 return SDValue();
7418}
7419
7420SDValue
7421TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
7422 SDValue CompTargetNode, ISD::CondCode Cond,
7423 DAGCombinerInfo &DCI, const SDLoc &DL,
7424 SmallVectorImpl<SDNode *> &Created) const {
7425 // fold (seteq/ne (urem N, D), C) ->
7426 // (setule/ugt (rotr (mul (sub N, C), P), K), Q)
7427 // - D must be constant, with D = D0 * 2^K where D0 is odd
7428 // - P is the multiplicative inverse of D0 modulo 2^W
7429 // - Q = floor(((2^W) - 1) / D)
7430 // where W is the width of the common type of N and D.
7431 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7432 "Only applicable for (in)equality comparisons.");
7433
7434 SelectionDAG &DAG = DCI.DAG;
7435
7436 EVT VT = REMNode.getValueType();
7437 EVT SVT = VT.getScalarType();
7438 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7439 EVT ShSVT = ShVT.getScalarType();
7440
7441 // If MUL is unavailable, we cannot proceed in any case.
7442 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7443 return SDValue();
7444
7445 bool ComparingWithAllZeros = true;
7446 bool AllComparisonsWithNonZerosAreTautological = true;
7447 bool HadTautologicalLanes = false;
7448 bool AllLanesAreTautological = true;
7449 bool HadEvenDivisor = false;
7450 bool AllDivisorsArePowerOfTwo = true;
7451 bool HadTautologicalInvertedLanes = false;
7452 SmallVector<SDValue, 16> PAmts, KAmts, QAmts;
7453
7454 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
7455 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7456 if (CDiv->isZero())
7457 return false;
7458
7459 const APInt &D = CDiv->getAPIntValue();
7460 const APInt &Cmp = CCmp->getAPIntValue();
7461
7462 ComparingWithAllZeros &= Cmp.isZero();
7463
7464 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7465 // if C2 is not less than C1, the comparison is always false.
7466 // But we will only be able to produce the comparison that will give the
7467 // opposive tautological answer. So this lane would need to be fixed up.
7468 bool TautologicalInvertedLane = D.ule(Cmp);
7469 HadTautologicalInvertedLanes |= TautologicalInvertedLane;
7470
7471 // If all lanes are tautological (either all divisors are ones, or divisor
7472 // is not greater than the constant we are comparing with),
7473 // we will prefer to avoid the fold.
7474 bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
7475 HadTautologicalLanes |= TautologicalLane;
7476 AllLanesAreTautological &= TautologicalLane;
7477
7478 // If we are comparing with non-zero, we need'll need to subtract said
7479 // comparison value from the LHS. But there is no point in doing that if
7480 // every lane where we are comparing with non-zero is tautological..
7481 if (!Cmp.isZero())
7482 AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
7483
7484 // Decompose D into D0 * 2^K
7485 unsigned K = D.countr_zero();
7486 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7487 APInt D0 = D.lshr(K);
7488
7489 // D is even if it has trailing zeros.
7490 HadEvenDivisor |= (K != 0);
7491 // D is a power-of-two if D0 is one.
7492 // If all divisors are power-of-two, we will prefer to avoid the fold.
7493 AllDivisorsArePowerOfTwo &= D0.isOne();
7494
7495 // P = inv(D0, 2^W)
7496 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7497 unsigned W = D.getBitWidth();
7498 APInt P = D0.multiplicativeInverse();
7499 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7500
7501 // Q = floor((2^W - 1) u/ D)
7502 // R = ((2^W - 1) u% D)
7503 APInt Q, R;
7505
7506 // If we are comparing with zero, then that comparison constant is okay,
7507 // else it may need to be one less than that.
7508 if (Cmp.ugt(R))
7509 Q -= 1;
7510
7512 "We are expecting that K is always less than all-ones for ShSVT");
7513
7514 // If the lane is tautological the result can be constant-folded.
7515 if (TautologicalLane) {
7516 // Set P and K amount to a bogus values so we can try to splat them.
7517 P = 0;
7518 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7519 // And ensure that comparison constant is tautological,
7520 // it will always compare true/false.
7521 Q.setAllBits();
7522 } else {
7523 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7524 }
7525
7526 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7527 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7528 return true;
7529 };
7530
7531 SDValue N = REMNode.getOperand(0);
7532 SDValue D = REMNode.getOperand(1);
7533
7534 // Collect the values from each element.
7535 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
7536 return SDValue();
7537
7538 // If all lanes are tautological, the result can be constant-folded.
7539 if (AllLanesAreTautological)
7540 return SDValue();
7541
7542 // If this is a urem by a powers-of-two, avoid the fold since it can be
7543 // best implemented as a bit test.
7544 if (AllDivisorsArePowerOfTwo)
7545 return SDValue();
7546
7547 SDValue PVal, KVal, QVal;
7548 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7549 if (HadTautologicalLanes) {
7550 // Try to turn PAmts into a splat, since we don't care about the values
7551 // that are currently '0'. If we can't, just keep '0'`s.
7553 // Try to turn KAmts into a splat, since we don't care about the values
7554 // that are currently '-1'. If we can't, change them to '0'`s.
7556 DAG.getConstant(0, DL, ShSVT));
7557 }
7558
7559 PVal = DAG.getBuildVector(VT, DL, PAmts);
7560 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7561 QVal = DAG.getBuildVector(VT, DL, QAmts);
7562 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7563 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
7564 "Expected matchBinaryPredicate to return one element for "
7565 "SPLAT_VECTORs");
7566 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7567 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7568 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7569 } else {
7570 PVal = PAmts[0];
7571 KVal = KAmts[0];
7572 QVal = QAmts[0];
7573 }
7574
7575 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
7576 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
7577 return SDValue(); // FIXME: Could/should use `ISD::ADD`?
7578 assert(CompTargetNode.getValueType() == N.getValueType() &&
7579 "Expecting that the types on LHS and RHS of comparisons match.");
7580 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
7581 }
7582
7583 // (mul N, P)
7584 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7585 Created.push_back(Op0.getNode());
7586
7587 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7588 // divisors as a performance improvement, since rotating by 0 is a no-op.
7589 if (HadEvenDivisor) {
7590 // We need ROTR to do this.
7591 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7592 return SDValue();
7593 // UREM: (rotr (mul N, P), K)
7594 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7595 Created.push_back(Op0.getNode());
7596 }
7597
7598 // UREM: (setule/setugt (rotr (mul N, P), K), Q)
7599 SDValue NewCC =
7600 DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7602 if (!HadTautologicalInvertedLanes)
7603 return NewCC;
7604
7605 // If any lanes previously compared always-false, the NewCC will give
7606 // always-true result for them, so we need to fixup those lanes.
7607 // Or the other way around for inequality predicate.
7608 assert(VT.isVector() && "Can/should only get here for vectors.");
7609 Created.push_back(NewCC.getNode());
7610
7611 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7612 // if C2 is not less than C1, the comparison is always false.
7613 // But we have produced the comparison that will give the
7614 // opposive tautological answer. So these lanes would need to be fixed up.
7615 SDValue TautologicalInvertedChannels =
7616 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
7617 Created.push_back(TautologicalInvertedChannels.getNode());
7618
7619 // NOTE: we avoid letting illegal types through even if we're before legalize
7620 // ops – legalization has a hard time producing good code for this.
7621 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
7622 // If we have a vector select, let's replace the comparison results in the
7623 // affected lanes with the correct tautological result.
7624 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
7625 DL, SETCCVT, SETCCVT);
7626 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
7627 Replacement, NewCC);
7628 }
7629
7630 // Else, we can just invert the comparison result in the appropriate lanes.
7631 //
7632 // NOTE: see the note above VSELECT above.
7633 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
7634 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
7635 TautologicalInvertedChannels);
7636
7637 return SDValue(); // Don't know how to lower.
7638}
7639
7640/// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
7641/// where the divisor is constant and the comparison target is zero,
7642/// return a DAG expression that will generate the same comparison result
7643/// using only multiplications, additions and shifts/rotations.
7644/// Ref: "Hacker's Delight" 10-17.
7645SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
7646 SDValue CompTargetNode,
7648 DAGCombinerInfo &DCI,
7649 const SDLoc &DL) const {
7651 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7652 DCI, DL, Built)) {
7653 assert(Built.size() <= 7 && "Max size prediction failed.");
7654 for (SDNode *N : Built)
7655 DCI.AddToWorklist(N);
7656 return Folded;
7657 }
7658
7659 return SDValue();
7660}
7661
7662SDValue
7663TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
7664 SDValue CompTargetNode, ISD::CondCode Cond,
7665 DAGCombinerInfo &DCI, const SDLoc &DL,
7666 SmallVectorImpl<SDNode *> &Created) const {
7667 // Derived from Hacker's Delight, 2nd Edition, by Hank Warren. Section 10-17.
7668 // Fold:
7669 // (seteq/ne (srem N, D), 0)
7670 // To:
7671 // (setule/ugt (rotr (add (mul N, P), A), K), Q)
7672 //
7673 // - D must be constant, with D = D0 * 2^K where D0 is odd
7674 // - P is the multiplicative inverse of D0 modulo 2^W
7675 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
7676 // - Q = floor((2 * A) / (2^K))
7677 // where W is the width of the common type of N and D.
7678 //
7679 // When D is a power of two (and thus D0 is 1), the normal
7680 // formula for A and Q don't apply, because the derivation
7681 // depends on D not dividing 2^(W-1), and thus theorem ZRS
7682 // does not apply. This specifically fails when N = INT_MIN.
7683 //
7684 // Instead, for power-of-two D, we use:
7685 // - A = 0
7686 // | -> No offset needed. We're effectively treating it the same as urem.
7687 // - Q = 2^(W-K) - 1
7688 // |-> Test that the top K bits are zero after rotation
7689 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7690 "Only applicable for (in)equality comparisons.");
7691
7692 SelectionDAG &DAG = DCI.DAG;
7693
7694 EVT VT = REMNode.getValueType();
7695 EVT SVT = VT.getScalarType();
7696 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7697 EVT ShSVT = ShVT.getScalarType();
7698
7699 // If we are after ops legalization, and MUL is unavailable, we can not
7700 // proceed.
7701 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7702 return SDValue();
7703
7704 // TODO: Could support comparing with non-zero too.
7705 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
7706 if (!CompTarget || !CompTarget->isZero())
7707 return SDValue();
7708
7709 bool HadOneDivisor = false;
7710 bool AllDivisorsAreOnes = true;
7711 bool HadEvenDivisor = false;
7712 bool AllDivisorsArePowerOfTwo = true;
7713 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
7714
7715 auto BuildSREMPattern = [&](ConstantSDNode *C) {
7716 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7717 if (C->isZero())
7718 return false;
7719
7720 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
7721
7722 // WARNING: this fold is only valid for positive divisors!
7723 // `rem %X, -C` is equivalent to `rem %X, C`
7724 APInt D = C->getAPIntValue().abs();
7725
7726 // If all divisors are ones, we will prefer to avoid the fold.
7727 HadOneDivisor |= D.isOne();
7728 AllDivisorsAreOnes &= D.isOne();
7729
7730 // Decompose D into D0 * 2^K
7731 unsigned K = D.countr_zero();
7732 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7733 APInt D0 = D.lshr(K);
7734
7735 // D is even if it has trailing zeros.
7736 HadEvenDivisor |= (K != 0);
7737
7738 // D is a power-of-two if D0 is one. This includes INT_MIN.
7739 // If all divisors are power-of-two, we will prefer to avoid the fold.
7740 AllDivisorsArePowerOfTwo &= D0.isOne();
7741
7742 // P = inv(D0, 2^W)
7743 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7744 unsigned W = D.getBitWidth();
7745 APInt P = D0.multiplicativeInverse();
7746 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7747
7748 // A = floor((2^(W - 1) - 1) / D0) & -2^K
7749 APInt A = APInt::getSignedMaxValue(W).udiv(D0);
7750 A.clearLowBits(K);
7751
7752 // Q = floor((2 * A) / (2^K))
7753 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
7754
7756 "We are expecting that A is always less than all-ones for SVT");
7758 "We are expecting that K is always less than all-ones for ShSVT");
7759
7760 // If D was a power of two, apply the alternate constant derivation.
7761 if (D0.isOne()) {
7762 // A = 0
7763 A = APInt(W, 0);
7764 // - Q = 2^(W-K) - 1
7765 Q = APInt::getLowBitsSet(W, W - K);
7766 }
7767
7768 // If the divisor is 1 the result can be constant-folded.
7769 if (D.isOne()) {
7770 // Set P, A and K to a bogus values so we can try to splat them.
7771 P = 0;
7772 A.setAllBits();
7773 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7774
7775 // x ?% 1 == 0 <--> true <--> x u<= -1
7776 Q.setAllBits();
7777 } else {
7778 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7779 }
7780
7781 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7782 AAmts.push_back(DAG.getConstant(A, DL, SVT));
7783 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7784 return true;
7785 };
7786
7787 SDValue N = REMNode.getOperand(0);
7788 SDValue D = REMNode.getOperand(1);
7789
7790 // Collect the values from each element.
7791 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
7792 return SDValue();
7793
7794 // If this is a srem by a one, avoid the fold since it can be constant-folded.
7795 if (AllDivisorsAreOnes)
7796 return SDValue();
7797
7798 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
7799 // since it can be best implemented as a bit test.
7800 if (AllDivisorsArePowerOfTwo)
7801 return SDValue();
7802
7803 SDValue PVal, AVal, KVal, QVal;
7804 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7805 if (HadOneDivisor) {
7806 // Try to turn PAmts into a splat, since we don't care about the values
7807 // that are currently '0'. If we can't, just keep '0'`s.
7809 // Try to turn AAmts into a splat, since we don't care about the
7810 // values that are currently '-1'. If we can't, change them to '0'`s.
7812 DAG.getConstant(0, DL, SVT));
7813 // Try to turn KAmts into a splat, since we don't care about the values
7814 // that are currently '-1'. If we can't, change them to '0'`s.
7816 DAG.getConstant(0, DL, ShSVT));
7817 }
7818
7819 PVal = DAG.getBuildVector(VT, DL, PAmts);
7820 AVal = DAG.getBuildVector(VT, DL, AAmts);
7821 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7822 QVal = DAG.getBuildVector(VT, DL, QAmts);
7823 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7824 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
7825 QAmts.size() == 1 &&
7826 "Expected matchUnaryPredicate to return one element for scalable "
7827 "vectors");
7828 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7829 AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
7830 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7831 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7832 } else {
7833 assert(isa<ConstantSDNode>(D) && "Expected a constant");
7834 PVal = PAmts[0];
7835 AVal = AAmts[0];
7836 KVal = KAmts[0];
7837 QVal = QAmts[0];
7838 }
7839
7840 // (mul N, P)
7841 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7842 Created.push_back(Op0.getNode());
7843
7844 // We need ADD to do this.
7845 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
7846 return SDValue();
7847
7848 // (add (mul N, P), A)
7849 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
7850 Created.push_back(Op0.getNode());
7851
7852 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7853 // divisors as a performance improvement, since rotating by 0 is a no-op.
7854 if (HadEvenDivisor) {
7855 // We need ROTR to do this.
7856 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7857 return SDValue();
7858 // SREM: (rotr (add (mul N, P), A), K)
7859 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7860 Created.push_back(Op0.getNode());
7861 }
7862
7863 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
7864 return DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7866}
7867
7869 const DenormalMode &Mode,
7870 SDNodeFlags Flags) const {
7871 SDLoc DL(Op);
7872 EVT VT = Op.getValueType();
7873 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7874 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
7875
7876 // This is specifically a check for the handling of denormal inputs, not the
7877 // result.
7878 if (Mode.Input == DenormalMode::PreserveSign ||
7879 Mode.Input == DenormalMode::PositiveZero) {
7880 // Test = X == 0.0
7881 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ, /*Chain=*/{},
7882 /*Signaling=*/false, Flags);
7883 }
7884
7885 // Testing it with denormal inputs to avoid wrong estimate.
7886 //
7887 // Test = fabs(X) < SmallestNormal
7888 const fltSemantics &FltSem = VT.getFltSemantics();
7889 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
7890 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
7891 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op, Flags);
7892 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT, /*Chain=*/{},
7893 /*Signaling=*/false, Flags);
7894}
7895
7897 bool LegalOps, bool OptForSize,
7899 unsigned Depth) const {
7900 // fneg is removable even if it has multiple uses.
7901 if (Op.getOpcode() == ISD::FNEG) {
7903 return Op.getOperand(0);
7904 }
7905
7906 // Don't recurse exponentially.
7908 return SDValue();
7909
7910 // Pre-increment recursion depth for use in recursive calls.
7911 ++Depth;
7912 const SDNodeFlags Flags = Op->getFlags();
7913 EVT VT = Op.getValueType();
7914 unsigned Opcode = Op.getOpcode();
7915
7916 // Don't allow anything with multiple uses unless we know it is free.
7917 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
7918 bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
7919 isFPExtFree(VT, Op.getOperand(0).getValueType());
7920 if (!IsFreeExtend)
7921 return SDValue();
7922 }
7923
7924 auto RemoveDeadNode = [&](SDValue N) {
7925 if (N && N.getNode()->use_empty())
7926 DAG.RemoveDeadNode(N.getNode());
7927 };
7928
7929 SDLoc DL(Op);
7930
7931 // Because getNegatedExpression can delete nodes we need a handle to keep
7932 // temporary nodes alive in case the recursion manages to create an identical
7933 // node.
7934 std::list<HandleSDNode> Handles;
7935
7936 switch (Opcode) {
7937 case ISD::ConstantFP: {
7938 // Don't invert constant FP values after legalization unless the target says
7939 // the negated constant is legal.
7940 bool IsOpLegal =
7942 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
7943 OptForSize);
7944
7945 if (LegalOps && !IsOpLegal)
7946 break;
7947
7948 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
7949 V.changeSign();
7950 SDValue CFP = DAG.getConstantFP(V, DL, VT);
7951
7952 // If we already have the use of the negated floating constant, it is free
7953 // to negate it even it has multiple uses.
7954 if (!Op.hasOneUse() && CFP.use_empty())
7955 break;
7957 return CFP;
7958 }
7959 case ISD::SPLAT_VECTOR: {
7960 // fold splat_vector(fneg(X)) -> splat_vector(-X)
7961 SDValue X = Op.getOperand(0);
7963 break;
7964
7965 SDValue NegX = getCheaperNegatedExpression(X, DAG, LegalOps, OptForSize);
7966 if (!NegX)
7967 break;
7969 return DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, NegX);
7970 }
7971 case ISD::BUILD_VECTOR: {
7972 // Only permit BUILD_VECTOR of constants.
7973 if (llvm::any_of(Op->op_values(), [&](SDValue N) {
7974 return !N.isUndef() && !isa<ConstantFPSDNode>(N);
7975 }))
7976 break;
7977
7978 bool IsOpLegal =
7981 llvm::all_of(Op->op_values(), [&](SDValue N) {
7982 return N.isUndef() ||
7983 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
7984 OptForSize);
7985 });
7986
7987 if (LegalOps && !IsOpLegal)
7988 break;
7989
7991 for (SDValue C : Op->op_values()) {
7992 if (C.isUndef()) {
7993 Ops.push_back(C);
7994 continue;
7995 }
7996 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
7997 V.changeSign();
7998 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
7999 }
8001 return DAG.getBuildVector(VT, DL, Ops);
8002 }
8003 case ISD::FADD: {
8004 if (!Flags.hasNoSignedZeros())
8005 break;
8006
8007 // After operation legalization, it might not be legal to create new FSUBs.
8008 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
8009 break;
8010 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8011
8012 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
8014 SDValue NegX =
8015 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8016 // Prevent this node from being deleted by the next call.
8017 if (NegX)
8018 Handles.emplace_back(NegX);
8019
8020 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
8022 SDValue NegY =
8023 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8024
8025 // We're done with the handles.
8026 Handles.clear();
8027
8028 // Negate the X if its cost is less or equal than Y.
8029 if (NegX && (CostX <= CostY)) {
8030 Cost = CostX;
8031 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
8032 if (NegY != N)
8033 RemoveDeadNode(NegY);
8034 return N;
8035 }
8036
8037 // Negate the Y if it is not expensive.
8038 if (NegY) {
8039 Cost = CostY;
8040 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
8041 if (NegX != N)
8042 RemoveDeadNode(NegX);
8043 return N;
8044 }
8045 break;
8046 }
8047 case ISD::FSUB: {
8048 // We can't turn -(A-B) into B-A when we honor signed zeros.
8049 if (!Flags.hasNoSignedZeros())
8050 break;
8051
8052 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8053 // fold (fneg (fsub 0, Y)) -> Y
8054 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
8055 if (C->isZero()) {
8057 return Y;
8058 }
8059
8060 // fold (fneg (fsub X, Y)) -> (fsub Y, X)
8062 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
8063 }
8064 case ISD::FMUL:
8065 case ISD::FDIV: {
8066 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8067
8068 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
8070 SDValue NegX =
8071 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8072 // Prevent this node from being deleted by the next call.
8073 if (NegX)
8074 Handles.emplace_back(NegX);
8075
8076 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
8078 SDValue NegY =
8079 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8080
8081 // We're done with the handles.
8082 Handles.clear();
8083
8084 // Negate the X if its cost is less or equal than Y.
8085 if (NegX && (CostX <= CostY)) {
8086 Cost = CostX;
8087 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
8088 if (NegY != N)
8089 RemoveDeadNode(NegY);
8090 return N;
8091 }
8092
8093 // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
8094 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
8095 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
8096 break;
8097
8098 // Negate the Y if it is not expensive.
8099 if (NegY) {
8100 Cost = CostY;
8101 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
8102 if (NegX != N)
8103 RemoveDeadNode(NegX);
8104 return N;
8105 }
8106 break;
8107 }
8108 case ISD::FMA:
8109 case ISD::FMULADD:
8110 case ISD::FMAD: {
8111 if (!Flags.hasNoSignedZeros())
8112 break;
8113
8114 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
8116 SDValue NegZ =
8117 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
8118 // Give up if fail to negate the Z.
8119 if (!NegZ)
8120 break;
8121
8122 // Prevent this node from being deleted by the next two calls.
8123 Handles.emplace_back(NegZ);
8124
8125 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
8127 SDValue NegX =
8128 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8129 // Prevent this node from being deleted by the next call.
8130 if (NegX)
8131 Handles.emplace_back(NegX);
8132
8133 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
8135 SDValue NegY =
8136 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8137
8138 // We're done with the handles.
8139 Handles.clear();
8140
8141 // Negate the X if its cost is less or equal than Y.
8142 if (NegX && (CostX <= CostY)) {
8143 Cost = std::min(CostX, CostZ);
8144 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
8145 if (NegY != N)
8146 RemoveDeadNode(NegY);
8147 return N;
8148 }
8149
8150 // Negate the Y if it is not expensive.
8151 if (NegY) {
8152 Cost = std::min(CostY, CostZ);
8153 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
8154 if (NegX != N)
8155 RemoveDeadNode(NegX);
8156 return N;
8157 }
8158 break;
8159 }
8160
8161 case ISD::FP_EXTEND:
8162 case ISD::FSIN:
8163 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
8164 OptForSize, Cost, Depth))
8165 return DAG.getNode(Opcode, DL, VT, NegV);
8166 break;
8167 case ISD::FP_ROUND:
8168 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
8169 OptForSize, Cost, Depth))
8170 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
8171 break;
8172 case ISD::SELECT:
8173 case ISD::VSELECT: {
8174 // fold (fneg (select C, LHS, RHS)) -> (select C, (fneg LHS), (fneg RHS))
8175 // iff at least one cost is cheaper and the other is neutral/cheaper
8176 SDValue LHS = Op.getOperand(1);
8178 SDValue NegLHS =
8179 getNegatedExpression(LHS, DAG, LegalOps, OptForSize, CostLHS, Depth);
8180 if (!NegLHS || CostLHS > NegatibleCost::Neutral) {
8181 RemoveDeadNode(NegLHS);
8182 break;
8183 }
8184
8185 // Prevent this node from being deleted by the next call.
8186 Handles.emplace_back(NegLHS);
8187
8188 SDValue RHS = Op.getOperand(2);
8190 SDValue NegRHS =
8191 getNegatedExpression(RHS, DAG, LegalOps, OptForSize, CostRHS, Depth);
8192
8193 // We're done with the handles.
8194 Handles.clear();
8195
8196 if (!NegRHS || CostRHS > NegatibleCost::Neutral ||
8197 (CostLHS != NegatibleCost::Cheaper &&
8198 CostRHS != NegatibleCost::Cheaper)) {
8199 RemoveDeadNode(NegLHS);
8200 RemoveDeadNode(NegRHS);
8201 break;
8202 }
8203
8204 Cost = std::min(CostLHS, CostRHS);
8205 return DAG.getSelect(DL, VT, Op.getOperand(0), NegLHS, NegRHS);
8206 }
8207 }
8208
8209 return SDValue();
8210}
8211
8212//===----------------------------------------------------------------------===//
8213// Legalization Utilities
8214//===----------------------------------------------------------------------===//
8215
8216bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
8217 SDValue LHS, SDValue RHS,
8219 EVT HiLoVT, SelectionDAG &DAG,
8220 MulExpansionKind Kind, SDValue LL,
8221 SDValue LH, SDValue RL, SDValue RH) const {
8222 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
8223 Opcode == ISD::SMUL_LOHI);
8224
8225 bool HasMULHS = (Kind == MulExpansionKind::Always) ||
8227 bool HasMULHU = (Kind == MulExpansionKind::Always) ||
8229 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8231 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8233
8234 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
8235 return false;
8236
8237 unsigned OuterBitSize = VT.getScalarSizeInBits();
8238 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
8239
8240 // LL, LH, RL, and RH must be either all NULL or all set to a value.
8241 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
8242 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
8243
8244 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
8245 bool Signed) -> bool {
8246 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
8247 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
8248 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
8249 Hi = Lo.getValue(1);
8250 return true;
8251 }
8252 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
8253 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
8254 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
8255 return true;
8256 }
8257 return false;
8258 };
8259
8260 SDValue Lo, Hi;
8261
8262 if (!LL.getNode() && !RL.getNode() &&
8264 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
8265 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
8266 }
8267
8268 if (!LL.getNode())
8269 return false;
8270
8271 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
8272 if (DAG.MaskedValueIsZero(LHS, HighMask) &&
8273 DAG.MaskedValueIsZero(RHS, HighMask)) {
8274 // The inputs are both zero-extended.
8275 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
8276 Result.push_back(Lo);
8277 Result.push_back(Hi);
8278 if (Opcode != ISD::MUL) {
8279 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8280 Result.push_back(Zero);
8281 Result.push_back(Zero);
8282 }
8283 return true;
8284 }
8285 }
8286
8287 if (!VT.isVector() && Opcode == ISD::MUL &&
8288 DAG.ComputeMaxSignificantBits(LHS) <= InnerBitSize &&
8289 DAG.ComputeMaxSignificantBits(RHS) <= InnerBitSize) {
8290 // The input values are both sign-extended.
8291 // TODO non-MUL case?
8292 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
8293 Result.push_back(Lo);
8294 Result.push_back(Hi);
8295 return true;
8296 }
8297 }
8298
8299 unsigned ShiftAmount = OuterBitSize - InnerBitSize;
8300 SDValue Shift = DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
8301
8302 if (!LH.getNode() && !RH.getNode() &&
8305 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
8306 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
8307 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
8308 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
8309 }
8310
8311 if (!LH.getNode())
8312 return false;
8313
8314 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
8315 return false;
8316
8317 Result.push_back(Lo);
8318
8319 if (Opcode == ISD::MUL) {
8320 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
8321 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
8322 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
8323 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
8324 Result.push_back(Hi);
8325 return true;
8326 }
8327
8328 // Compute the full width result.
8329 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
8330 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
8331 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8332 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
8333 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
8334 };
8335
8336 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8337 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
8338 return false;
8339
8340 // This is effectively the add part of a multiply-add of half-sized operands,
8341 // so it cannot overflow.
8342 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8343
8344 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
8345 return false;
8346
8347 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8348 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8349
8350 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
8352 if (UseGlue)
8353 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
8354 Merge(Lo, Hi));
8355 else
8356 Next = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(VT, BoolType), Next,
8357 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
8358
8359 SDValue Carry = Next.getValue(1);
8360 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8361 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8362
8363 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
8364 return false;
8365
8366 if (UseGlue)
8367 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
8368 Carry);
8369 else
8370 Hi = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
8371 Zero, Carry);
8372
8373 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8374
8375 if (Opcode == ISD::SMUL_LOHI) {
8376 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8377 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
8378 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
8379
8380 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8381 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
8382 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
8383 }
8384
8385 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8386 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8387 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8388 return true;
8389}
8390
8392 SelectionDAG &DAG, MulExpansionKind Kind,
8393 SDValue LL, SDValue LH, SDValue RL,
8394 SDValue RH) const {
8396 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
8397 N->getOperand(0), N->getOperand(1), Result, HiLoVT,
8398 DAG, Kind, LL, LH, RL, RH);
8399 if (Ok) {
8400 assert(Result.size() == 2);
8401 Lo = Result[0];
8402 Hi = Result[1];
8403 }
8404 return Ok;
8405}
8406
8407// Optimize unsigned division or remainder by constants for types twice as large
8408// as a legal VT.
8409//
8410// If (1 << (BitWidth / 2)) % Constant == 1, then the remainder
8411// can be computed
8412// as:
8413// Sum = __builtin_uadd_overflow(Lo, High, &Sum);
8414// Remainder = Sum % Constant;
8415//
8416// If (1 << (BitWidth / 2)) % Constant != 1, we can search for a smaller value
8417// W such that W != (BitWidth / 2) and (1 << W) % Constant == 1. We can break
8418// High:Low into 3 chunks of W bits and compute remainder as
8419// Sum = Chunk0 + Chunk1 + Chunk2;
8420// Remainder = Sum % Constant;
8421//
8422// This is based on "Remainder by Summing Digits" from Hacker's Delight.
8423//
8424// For division, we can compute the remainder using the algorithm described
8425// above, subtract it from the dividend to get an exact multiple of Constant.
8426// Then multiply that exact multiply by the multiplicative inverse modulo
8427// (1 << (BitWidth / 2)) to get the quotient.
8428
8429// If Constant is even, we can shift right the dividend and the divisor by the
8430// number of trailing zeros in Constant before applying the remainder algorithm.
8431// If we're after the quotient, we can subtract this value from the shifted
8432// dividend and multiply by the multiplicative inverse of the shifted divisor.
8433// If we want the remainder, we shift the value left by the number of trailing
8434// zeros and add the bits that were shifted out of the dividend.
8435bool TargetLowering::expandUDIVREMByConstantViaUREMDecomposition(
8436 SDNode *N, APInt Divisor, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
8437 SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8438 unsigned Opcode = N->getOpcode();
8439 EVT VT = N->getValueType(0);
8440
8441 unsigned BitWidth = Divisor.getBitWidth();
8442 unsigned HBitWidth = BitWidth / 2;
8444 HiLoVT.getScalarSizeInBits() == HBitWidth && "Unexpected VTs");
8445
8446 // If the divisor is even, shift it until it becomes odd.
8447 unsigned TrailingZeros = 0;
8448 if (!Divisor[0]) {
8449 TrailingZeros = Divisor.countr_zero();
8450 Divisor.lshrInPlace(TrailingZeros);
8451 }
8452
8453 // After removing trailing zeros, the divisor needs to be less than
8454 // (1 << HBitWidth).
8455 APInt HalfMaxPlus1 = APInt::getOneBitSet(BitWidth, HBitWidth);
8456 if (Divisor.uge(HalfMaxPlus1))
8457 return false;
8458
8459 // Look for the largest chunk width W such that (1 << W) % Divisor == 1 or
8460 // (1 << W) % Divisor == -1.
8461 unsigned BestChunkWidth = 0, AltChunkWidth = 0;
8462 for (unsigned I = HBitWidth, E = HBitWidth / 2; I > E; --I) {
8463 // Skip HBitWidth-1, it doesn't have enough bits for carries.
8464 if (I == HBitWidth - 1)
8465 continue;
8466
8467 APInt Mod = APInt::getOneBitSet(Divisor.getBitWidth(), I).urem(Divisor);
8468
8469 if (Mod.isOne()) {
8470 BestChunkWidth = I;
8471 break;
8472 }
8473
8474 // We have an alternate strategy for Remainder == Divisor - 1.
8475 // FIXME: Support HBitWidth.
8476 if (I != HBitWidth && Mod == Divisor - 1)
8477 AltChunkWidth = I;
8478 }
8479
8480 bool Alternate = false;
8481 if (!BestChunkWidth) {
8482 if (!AltChunkWidth)
8483 return false;
8484 Alternate = true;
8485 BestChunkWidth = AltChunkWidth;
8486 }
8487
8488 SDLoc dl(N);
8489
8490 assert(!LL == !LH && "Expected both input halves or no input halves!");
8491 if (!LL)
8492 std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT);
8493
8494 bool HasFSHR = isOperationLegal(ISD::FSHR, HiLoVT);
8495
8496 auto GetFSHR = [&](SDValue Lo, SDValue Hi, unsigned ShiftAmt) {
8497 assert(ShiftAmt > 0 && ShiftAmt < HBitWidth);
8498 if (HasFSHR)
8499 return DAG.getNode(ISD::FSHR, dl, HiLoVT, Hi, Lo,
8500 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8501 return DAG.getNode(
8502 ISD::OR, dl, HiLoVT,
8503 DAG.getNode(ISD::SRL, dl, HiLoVT, Lo,
8504 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl)),
8505 DAG.getNode(
8506 ISD::SHL, dl, HiLoVT, Hi,
8507 DAG.getShiftAmountConstant(HBitWidth - ShiftAmt, HiLoVT, dl)));
8508 };
8509
8510 // Helper to perform a right shift on a 128-bit value split into two halves.
8511 // Handles shifts >= HBitWidth by moving Hi to Lo and shifting Hi.
8512 auto ShiftRight = [&](SDValue &Lo, SDValue &Hi, unsigned ShiftAmt) {
8513 if (ShiftAmt == 0)
8514 return;
8515 if (ShiftAmt < HBitWidth) {
8516 Lo = GetFSHR(Lo, Hi, ShiftAmt);
8517 Hi = DAG.getNode(ISD::SRL, dl, HiLoVT, Hi,
8518 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8519 } else if (ShiftAmt == HBitWidth) {
8520 Lo = Hi;
8521 Hi = DAG.getConstant(0, dl, HiLoVT);
8522 } else {
8523 Lo = DAG.getNode(
8524 ISD::SRL, dl, HiLoVT, Hi,
8525 DAG.getShiftAmountConstant(ShiftAmt - HBitWidth, HiLoVT, dl));
8526 Hi = DAG.getConstant(0, dl, HiLoVT);
8527 }
8528 };
8529
8530 // Shift the input by the number of TrailingZeros in the divisor. The
8531 // shifted out bits will be added to the remainder later.
8532 SDValue PartialRemL, PartialRemH;
8533 if (TrailingZeros && Opcode != ISD::UDIV) {
8534 // Save the shifted off bits if we need the remainder.
8535 if (TrailingZeros < HBitWidth) {
8536 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
8537 PartialRemL = DAG.getNode(ISD::AND, dl, HiLoVT, LL,
8538 DAG.getConstant(Mask, dl, HiLoVT));
8539 } else if (TrailingZeros == HBitWidth) {
8540 // All of LL is part of the remainder.
8541 PartialRemL = LL;
8542 } else {
8543 // TrailingZeros > HBitWidth: LL and part of LH are the remainder.
8544 PartialRemL = LL;
8545 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros - HBitWidth);
8546 PartialRemH = DAG.getNode(ISD::AND, dl, HiLoVT, LH,
8547 DAG.getConstant(Mask, dl, HiLoVT));
8548 }
8549 }
8550
8551 SDValue Sum;
8552 // If BestChunkWidth is HBitWidth add low and high half. If there is a carry
8553 // out, add that to the final sum.
8554 if (BestChunkWidth == HBitWidth) {
8555 assert(!Alternate);
8556 // Shift LH:LL right if there were trailing zeros in the divisor.
8557 ShiftRight(LL, LH, TrailingZeros);
8558
8559 // Use uaddo_carry if we can, otherwise use a compare to detect overflow.
8560 EVT SetCCType =
8561 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), HiLoVT);
8563 SDVTList VTList = DAG.getVTList(HiLoVT, SetCCType);
8564 Sum = DAG.getNode(ISD::UADDO, dl, VTList, LL, LH);
8565 Sum = DAG.getNode(ISD::UADDO_CARRY, dl, VTList, Sum,
8566 DAG.getConstant(0, dl, HiLoVT), Sum.getValue(1));
8567 } else {
8568 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, LL, LH);
8569 SDValue Carry = DAG.getSetCC(dl, SetCCType, Sum, LL, ISD::SETULT);
8570 // If the boolean for the target is 0 or 1, we can add the setcc result
8571 // directly.
8572 if (getBooleanContents(HiLoVT) ==
8574 Carry = DAG.getZExtOrTrunc(Carry, dl, HiLoVT);
8575 else
8576 Carry = DAG.getSelect(dl, HiLoVT, Carry, DAG.getConstant(1, dl, HiLoVT),
8577 DAG.getConstant(0, dl, HiLoVT));
8578 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, Carry);
8579 }
8580 } else {
8581 // Otherwise split into multple chunks and add them together. We chose
8582 // BestChunkWidth so that the sum will not overflow.
8583 SDValue Mask = DAG.getConstant(
8584 APInt::getLowBitsSet(HBitWidth, BestChunkWidth), dl, HiLoVT);
8585
8586 for (unsigned I = 0; I < BitWidth - TrailingZeros; I += BestChunkWidth) {
8587 // If there were trailing zeros in the divisor, increase the shift amount.
8588 unsigned Shift = I + TrailingZeros;
8589 SDValue Chunk;
8590 if (Shift == 0)
8591 Chunk = LL;
8592 else if (Shift >= HBitWidth)
8593 Chunk = DAG.getNode(
8594 ISD::SRL, dl, HiLoVT, LH,
8595 DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, dl));
8596 else
8597 Chunk = GetFSHR(LL, LH, Shift);
8598 // If we're on the last chunk, we don't need an AND.
8599 if (I + BestChunkWidth < BitWidth - TrailingZeros)
8600 Chunk = DAG.getNode(ISD::AND, dl, HiLoVT, Chunk, Mask);
8601 if (!Sum) {
8602 Sum = Chunk;
8603 } else {
8604 // For Alternate, we need to subtract odd chunks.
8605 unsigned ChunkNum = I / BestChunkWidth;
8606 unsigned Opc = (Alternate && (ChunkNum % 2) != 0) ? ISD::SUB : ISD::ADD;
8607 Sum = DAG.getNode(Opc, dl, HiLoVT, Sum, Chunk);
8608 }
8609 }
8610
8611 // For Alternate, the sum may be negative, but we need a positive sum. We
8612 // can increase it by a multiple of the divisor to make it positive. For 3
8613 // chunks the largest negative value is -(2^BestChunkWidth - 1). For 4
8614 // chunks, it's 2*-(2^BestChunkWidth - 1). We know that 2^BestChunkWidth + 1
8615 // is a multiple of the divisor. Add that 1 or 2 times to make the sum
8616 // positive.
8617 if (Alternate) {
8618 unsigned NumChunks = divideCeil(BitWidth - TrailingZeros, BestChunkWidth);
8619 assert(NumChunks <= 4);
8620
8621 APInt Adjust = APInt::getOneBitSet(HBitWidth, BestChunkWidth);
8622 Adjust.setBit(0);
8623 // If there are 4 chunks, we need to adjust twice.
8624 if (NumChunks == 4)
8625 Adjust <<= 1;
8626 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum,
8627 DAG.getConstant(Adjust, dl, HiLoVT));
8628 }
8629 }
8630
8631 // Perform a HiLoVT urem on the Sum using truncated divisor.
8632 SDValue RemL =
8633 DAG.getNode(ISD::UREM, dl, HiLoVT, Sum,
8634 DAG.getConstant(Divisor.trunc(HBitWidth), dl, HiLoVT));
8635 SDValue RemH = DAG.getConstant(0, dl, HiLoVT);
8636
8637 if (Opcode != ISD::UREM) {
8638 // If we didn't shift LH/LR earlier, do it now.
8639 if (BestChunkWidth != HBitWidth)
8640 ShiftRight(LL, LH, TrailingZeros);
8641
8642 // Subtract the remainder from the shifted dividend.
8643 SDValue Dividend = DAG.getNode(ISD::BUILD_PAIR, dl, VT, LL, LH);
8644 SDValue Rem = DAG.getNode(ISD::BUILD_PAIR, dl, VT, RemL, RemH);
8645
8646 Dividend = DAG.getNode(ISD::SUB, dl, VT, Dividend, Rem);
8647
8648 // Multiply by the multiplicative inverse of the divisor modulo
8649 // (1 << BitWidth).
8650 APInt MulFactor = Divisor.multiplicativeInverse();
8651
8652 SDValue Quotient = DAG.getNode(ISD::MUL, dl, VT, Dividend,
8653 DAG.getConstant(MulFactor, dl, VT));
8654
8655 // Split the quotient into low and high parts.
8656 SDValue QuotL, QuotH;
8657 std::tie(QuotL, QuotH) = DAG.SplitScalar(Quotient, dl, HiLoVT, HiLoVT);
8658 Result.push_back(QuotL);
8659 Result.push_back(QuotH);
8660 }
8661
8662 if (Opcode != ISD::UDIV) {
8663 // If we shifted the input, shift the remainder left and add the bits we
8664 // shifted off the input.
8665 if (TrailingZeros) {
8666 if (TrailingZeros < HBitWidth) {
8667 // Shift RemH:RemL left by TrailingZeros.
8668 // RemH gets the high bits shifted out of RemL.
8669 RemH = DAG.getNode(
8670 ISD::SRL, dl, HiLoVT, RemL,
8671 DAG.getShiftAmountConstant(HBitWidth - TrailingZeros, HiLoVT, dl));
8672 RemL =
8673 DAG.getNode(ISD::SHL, dl, HiLoVT, RemL,
8674 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
8675 // OR in the partial remainder.
8676 RemL = DAG.getNode(ISD::OR, dl, HiLoVT, RemL, PartialRemL,
8678 } else if (TrailingZeros == HBitWidth) {
8679 // Shift left by exactly HBitWidth: RemH becomes RemL, RemL becomes
8680 // PartialRemL.
8681 RemH = RemL;
8682 RemL = PartialRemL;
8683 } else {
8684 // Shift left by more than HBitWidth.
8685 RemH = DAG.getNode(
8686 ISD::SHL, dl, HiLoVT, RemL,
8687 DAG.getShiftAmountConstant(TrailingZeros - HBitWidth, HiLoVT, dl));
8688 RemH = DAG.getNode(ISD::OR, dl, HiLoVT, RemH, PartialRemH,
8690 RemL = PartialRemL;
8691 }
8692 }
8693 Result.push_back(RemL);
8694 Result.push_back(RemH);
8695 }
8696
8697 return true;
8698}
8699
8700bool TargetLowering::expandUDIVREMByConstantViaUMulHiMagic(
8701 SDNode *N, const APInt &Divisor, SmallVectorImpl<SDValue> &Result,
8702 EVT HiLoVT, SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8703
8704 SDValue N0 = N->getOperand(0);
8705 EVT VT = N0->getValueType(0);
8706 SDLoc DL{N};
8707
8708 assert(!Divisor.isOne() && "Magic algorithm does not work for division by 1");
8709
8710 // This helper creates a MUL_LOHI of the pair (LL, LH) by a constant.
8711 auto MakeMUL_LOHIByConst = [&](unsigned Opc, SDValue LL, SDValue LH,
8712 const APInt &Const,
8713 SmallVectorImpl<SDValue> &Result) {
8714 SDValue LHS = DAG.getNode(ISD::BUILD_PAIR, DL, VT, LL, LH);
8715 SDValue RHS = DAG.getConstant(Const, DL, VT);
8716 auto [RL, RH] = DAG.SplitScalar(RHS, DL, HiLoVT, HiLoVT);
8717 return expandMUL_LOHI(Opc, VT, DL, LHS, RHS, Result, HiLoVT, DAG,
8719 LL, LH, RL, RH);
8720 };
8721
8722 // This helper creates an ADD/SUB of the pairs (LL, LH) and (RL, RH).
8723 auto MakeAddSubLong = [&](unsigned Opc, SDValue LL, SDValue LH, SDValue RL,
8724 SDValue RH) {
8725 SDValue AddSubNode =
8727 DAG.getVTList(HiLoVT, MVT::i1), LL, RL);
8728 SDValue OutL = AddSubNode.getValue(0);
8729 SDValue Overflow = AddSubNode.getValue(1);
8730 SDValue AddSubWithOverflow =
8732 DAG.getVTList(HiLoVT, MVT::i1), LH, RH, Overflow);
8733 SDValue OutH = AddSubWithOverflow.getValue(0);
8734 return std::make_pair(OutL, OutH);
8735 };
8736
8737 // This helper creates a SRL of the pair (LL, LH) by Shift.
8738 auto MakeSRLLong = [&](SDValue LL, SDValue LH, unsigned Shift) {
8739 unsigned HBitWidth = HiLoVT.getScalarSizeInBits();
8740 if (Shift < HBitWidth) {
8741 SDValue ShAmt = DAG.getShiftAmountConstant(Shift, HiLoVT, DL);
8742 SDValue ResL = DAG.getNode(ISD::FSHR, DL, HiLoVT, LH, LL, ShAmt);
8743 SDValue ResH = DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt);
8744 return std::make_pair(ResL, ResH);
8745 }
8746 SDValue Zero = DAG.getConstant(0, DL, HiLoVT);
8747 if (Shift == HBitWidth)
8748 return std::make_pair(LH, Zero);
8749 assert(Shift - HBitWidth < HBitWidth &&
8750 "We shouldn't generate an undefined shift");
8751 SDValue ShAmt = DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, DL);
8752 return std::make_pair(DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt), Zero);
8753 };
8754
8755 // Knowledge of leading zeros may help to reduce the multiplier.
8756 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
8757
8758 UnsignedDivisionByConstantInfo Magics = UnsignedDivisionByConstantInfo::get(
8759 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()));
8760
8761 assert(!LL == !LH && "Expected both input halves or no input halves!");
8762 if (!LL)
8763 std::tie(LL, LH) = DAG.SplitScalar(N0, DL, HiLoVT, HiLoVT);
8764 SDValue QL = LL;
8765 SDValue QH = LH;
8766 if (Magics.PreShift != 0)
8767 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PreShift);
8768
8769 SmallVector<SDValue, 4> UMulResult;
8770 if (!MakeMUL_LOHIByConst(ISD::UMUL_LOHI, QL, QH, Magics.Magic, UMulResult))
8771 return false;
8772
8773 QL = UMulResult[2];
8774 QH = UMulResult[3];
8775
8776 if (Magics.IsAdd) {
8777 auto [NPQL, NPQH] = MakeAddSubLong(ISD::SUB, LL, LH, QL, QH);
8778 std::tie(NPQL, NPQH) = MakeSRLLong(NPQL, NPQH, 1);
8779 std::tie(QL, QH) = MakeAddSubLong(ISD::ADD, NPQL, NPQH, QL, QH);
8780 }
8781
8782 if (Magics.PostShift != 0)
8783 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PostShift);
8784
8785 unsigned Opcode = N->getOpcode();
8786 if (Opcode != ISD::UREM) {
8787 Result.push_back(QL);
8788 Result.push_back(QH);
8789 }
8790
8791 if (Opcode != ISD::UDIV) {
8792 SmallVector<SDValue, 2> MulResult;
8793 if (!MakeMUL_LOHIByConst(ISD::MUL, QL, QH, Divisor, MulResult))
8794 return false;
8795
8796 assert(MulResult.size() == 2);
8797
8798 auto [RemL, RemH] =
8799 MakeAddSubLong(ISD::SUB, LL, LH, MulResult[0], MulResult[1]);
8800
8801 Result.push_back(RemL);
8802 Result.push_back(RemH);
8803 }
8804
8805 return true;
8806}
8807
8810 EVT HiLoVT, SelectionDAG &DAG,
8811 SDValue LL, SDValue LH) const {
8812 unsigned Opcode = N->getOpcode();
8813
8814 // TODO: Support signed division/remainder.
8815 if (Opcode == ISD::SREM || Opcode == ISD::SDIV || Opcode == ISD::SDIVREM)
8816 return false;
8817 assert(
8818 (Opcode == ISD::UREM || Opcode == ISD::UDIV || Opcode == ISD::UDIVREM) &&
8819 "Unexpected opcode");
8820
8821 auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(1));
8822 if (!CN)
8823 return false;
8824
8825 APInt Divisor = CN->getAPIntValue();
8826
8827 // The generated half-width UREM is normally optimized using high multiply.
8828 // If the wide UREM libcall is unavailable, a legal or custom half-width
8829 // UDIVREM can lower it instead.
8830 bool CanDecomposeUREMWithoutMulHi =
8831 Opcode == ISD::UREM &&
8832 getLibcallImpl(RTLIB::getUREM(N->getValueType(0))) ==
8833 RTLIB::Unsupported &&
8835 if (!CanDecomposeUREMWithoutMulHi &&
8838 return false;
8839
8840 // Prefer the smaller libcall when one is available.
8841 if (DAG.shouldOptForSize() && !CanDecomposeUREMWithoutMulHi)
8842 return false;
8843
8844 // Early out for 0 or 1 divisors.
8845 if (Divisor.ule(1))
8846 return false;
8847
8848 if (expandUDIVREMByConstantViaUREMDecomposition(N, Divisor, Result, HiLoVT,
8849 DAG, LL, LH))
8850 return true;
8851
8852 if (expandUDIVREMByConstantViaUMulHiMagic(N, Divisor, Result, HiLoVT, DAG, LL,
8853 LH))
8854 return true;
8855
8856 return false;
8857}
8858
8859// Check that (every element of) Z is undef or not an exact multiple of BW.
8860static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
8862 Z,
8863 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
8864 /*AllowUndefs=*/true, /*AllowTruncation=*/true);
8865}
8866
8868 SelectionDAG &DAG) const {
8869 EVT VT = Node->getValueType(0);
8870
8871 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
8875 return SDValue();
8876
8877 SDValue X = Node->getOperand(0);
8878 SDValue Y = Node->getOperand(1);
8879 SDValue Z = Node->getOperand(2);
8880
8881 unsigned BW = VT.getScalarSizeInBits();
8882 bool IsFSHL = Node->getOpcode() == ISD::FSHL;
8883 SDLoc DL(SDValue(Node, 0));
8884
8885 EVT ShVT = Z.getValueType();
8886
8887 // If a funnel shift in the other direction is more supported, use it.
8888 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
8889 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
8890 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
8891 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
8892 // fshl X, Y, Z -> fshr X, Y, -Z
8893 // fshr X, Y, Z -> fshl X, Y, -Z
8894 Z = DAG.getNegative(Z, DL, ShVT);
8895 } else {
8896 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
8897 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
8898 SDValue One = DAG.getConstant(1, DL, ShVT);
8899 if (IsFSHL) {
8900 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
8901 X = DAG.getNode(ISD::SRL, DL, VT, X, One);
8902 } else {
8903 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
8904 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
8905 }
8906 Z = DAG.getNOT(DL, Z, ShVT);
8907 }
8908 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
8909 }
8910
8911 SDValue ShX, ShY;
8912 SDValue ShAmt, InvShAmt;
8913 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
8914 // fshl: X << C | Y >> (BW - C)
8915 // fshr: X << (BW - C) | Y >> C
8916 // where C = Z % BW is not zero
8917 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
8918 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
8919 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
8920 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
8921 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
8922 } else {
8923 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
8924 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
8925 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
8926 if (isPowerOf2_32(BW)) {
8927 // Z % BW -> Z & (BW - 1)
8928 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
8929 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
8930 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
8931 } else {
8932 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
8933 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
8934 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
8935 }
8936
8937 SDValue One = DAG.getConstant(1, DL, ShVT);
8938 if (IsFSHL) {
8939 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
8940 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
8941 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
8942 } else {
8943 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
8944 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
8945 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
8946 }
8947 }
8948 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
8949}
8950
8951// TODO: Merge with expandFunnelShift.
8953 SelectionDAG &DAG) const {
8954 EVT VT = Node->getValueType(0);
8955 unsigned EltSizeInBits = VT.getScalarSizeInBits();
8956 bool IsLeft = Node->getOpcode() == ISD::ROTL;
8957 SDValue Op0 = Node->getOperand(0);
8958 SDValue Op1 = Node->getOperand(1);
8959 SDLoc DL(SDValue(Node, 0));
8960
8961 EVT ShVT = Op1.getValueType();
8962 SDValue Zero = DAG.getConstant(0, DL, ShVT);
8963
8964 // If a rotate in the other direction is more supported, use it.
8965 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
8966 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
8967 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
8968 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
8969 return DAG.getNode(RevRot, DL, VT, Op0, Sub);
8970 }
8971
8972 if (!AllowVectorOps && VT.isVector() &&
8978 return SDValue();
8979
8980 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
8981 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
8982 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
8983 SDValue ShVal;
8984 SDValue HsVal;
8985 if (isPowerOf2_32(EltSizeInBits)) {
8986 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
8987 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
8988 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
8989 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
8990 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
8991 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
8992 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
8993 } else {
8994 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
8995 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
8996 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
8997 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
8998 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
8999 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
9000 SDValue One = DAG.getConstant(1, DL, ShVT);
9001 HsVal =
9002 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
9003 }
9004 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
9005}
9006
9007/// Check if CLMUL on VT can eventually reach a type with legal CLMUL through
9008/// a chain of halving decompositions (halving element width) and/or vector
9009/// widening (doubling element count). This guides expansion strategy selection:
9010/// if true, the halving/widening path produces better code than bit-by-bit.
9011///
9012/// HalveDepth tracks halving steps only (each creates ~4x more operations).
9013/// Widening steps are cheap (O(1) pad/extract) and don't count.
9014/// Limiting halvings to 2 prevents exponential blowup:
9015/// 1 halving: ~4 sub-CLMULs (good, e.g. v8i16 -> v8i8)
9016/// 2 halvings: ~16 sub-CLMULs (acceptable, e.g. v4i32 -> v4i16 -> v8i8)
9017/// 3 halvings: ~64 sub-CLMULs (worse than bit-by-bit expansion)
9019 EVT VT, unsigned HalveDepth = 0,
9020 unsigned TotalDepth = 0) {
9021 if (HalveDepth > 2 || TotalDepth > 8 || !VT.isFixedLengthVector())
9022 return false;
9024 return true;
9025 if (!TLI.isTypeLegal(VT))
9026 return false;
9027
9028 unsigned BW = VT.getScalarSizeInBits();
9029
9030 // Halve: halve element width, same element count.
9031 // This is the expensive step -- each halving creates ~4x more operations.
9032 if (BW % 2 == 0) {
9033 EVT HalfEltVT = EVT::getIntegerVT(Ctx, BW / 2);
9034 EVT HalfVT = VT.changeVectorElementType(Ctx, HalfEltVT);
9035 if (TLI.isTypeLegal(HalfVT) &&
9036 canNarrowCLMULToLegal(TLI, Ctx, HalfVT, HalveDepth + 1, TotalDepth + 1))
9037 return true;
9038 }
9039
9040 // Widen: double element count (fixed-width vectors only).
9041 // This is cheap -- just INSERT_SUBVECTOR + EXTRACT_SUBVECTOR.
9042 EVT WideVT = VT.getDoubleNumVectorElementsVT(Ctx);
9043 if (TLI.isTypeLegal(WideVT) &&
9044 canNarrowCLMULToLegal(TLI, Ctx, WideVT, HalveDepth, TotalDepth + 1))
9045 return true;
9046
9047 return false;
9048}
9049
9051 SDLoc DL(Node);
9052 EVT VT = Node->getValueType(0);
9053 SDValue X = Node->getOperand(0);
9054 SDValue Y = Node->getOperand(1);
9055 unsigned BW = VT.getScalarSizeInBits();
9056 unsigned Opcode = Node->getOpcode();
9057 LLVMContext &Ctx = *DAG.getContext();
9058
9059 switch (Opcode) {
9060 case ISD::CLMUL: {
9061 // For vector types, try decomposition strategies that leverage legal
9062 // CLMUL on narrower or wider element types, avoiding the expensive
9063 // bit-by-bit expansion.
9064 if (VT.isVector()) {
9065 // Strategy 1: Halving decomposition to half-element-width CLMUL.
9066 // Applies ExpandIntRes_CLMUL's identity element-wise:
9067 // CLMUL(X, Y) = (Hi << HalfBW) | Lo
9068 // where:
9069 // Lo = CLMUL(XLo, YLo)
9070 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
9071 unsigned HalfBW = BW / 2;
9072 if (BW % 2 == 0) {
9073 EVT HalfEltVT = EVT::getIntegerVT(Ctx, HalfBW);
9074 EVT HalfVT =
9075 EVT::getVectorVT(Ctx, HalfEltVT, VT.getVectorElementCount());
9076 if (isTypeLegal(HalfVT) && canNarrowCLMULToLegal(*this, Ctx, HalfVT,
9077 /*HalveDepth=*/1)) {
9078 SDValue ShAmt = DAG.getShiftAmountConstant(HalfBW, VT, DL);
9079
9080 // Extract low and high halves of each element.
9081 SDValue XLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, X);
9082 SDValue XHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
9083 DAG.getNode(ISD::SRL, DL, VT, X, ShAmt));
9084 SDValue YLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, Y);
9085 SDValue YHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
9086 DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt));
9087
9088 // Lo = CLMUL(XLo, YLo)
9089 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YLo);
9090
9091 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
9092 SDValue LoH = DAG.getNode(ISD::CLMULH, DL, HalfVT, XLo, YLo);
9093 SDValue Cross1 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YHi);
9094 SDValue Cross2 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XHi, YLo);
9095 SDValue Cross = DAG.getNode(ISD::XOR, DL, HalfVT, Cross1, Cross2);
9096 SDValue Hi = DAG.getNode(ISD::XOR, DL, HalfVT, LoH, Cross);
9097
9098 // Reassemble: Result = ZExt(Lo) | (AnyExt(Hi) << HalfBW)
9099 SDValue LoExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo);
9100 SDValue HiExt = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Hi);
9101 SDValue HiShifted = DAG.getNode(ISD::SHL, DL, VT, HiExt, ShAmt);
9102 return DAG.getNode(ISD::OR, DL, VT, LoExt, HiShifted);
9103 }
9104 }
9105
9106 // Strategy 2: Promote to double-element-width CLMUL.
9107 // CLMUL(X, Y) = Trunc(CLMUL(AnyExt(X), AnyExt(Y)))
9108 {
9109 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9110 if (isTypeLegal(ExtVT) && isOperationLegalOrCustom(ISD::CLMUL, ExtVT)) {
9111 // If CLMUL on ExtVT is Custom (not Legal), the target may
9112 // scalarize it, costing O(NumElements) scalar ops. The bit-by-bit
9113 // fallback costs O(BW) vectorized iterations. Only widen when
9114 // element count is small enough that scalarization is cheaper.
9115 unsigned NumElts = VT.getVectorMinNumElements();
9116 if (isOperationLegal(ISD::CLMUL, ExtVT) || NumElts < BW) {
9117 SDValue XExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, X);
9118 SDValue YExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, Y);
9119 SDValue Mul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9120 return DAG.getNode(ISD::TRUNCATE, DL, VT, Mul);
9121 }
9122 }
9123 }
9124
9125 // Strategy 3: Widen element count (pad with undef, do CLMUL on wider
9126 // vector, extract lower result). CLMUL is element-wise, so upper
9127 // (undef) lanes don't affect the lower results.
9128 // e.g. v4i16 => pad to v8i16 => halve to v8i8 PMUL => extract v4i16.
9129 if (auto EC = VT.getVectorElementCount(); EC.isFixed()) {
9130 EVT WideVT = EVT::getVectorVT(Ctx, VT.getVectorElementType(), EC * 2);
9131 if (isTypeLegal(WideVT) && canNarrowCLMULToLegal(*this, Ctx, WideVT)) {
9132 SDValue Undef = DAG.getUNDEF(WideVT);
9133 SDValue XWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
9134 X, DAG.getVectorIdxConstant(0, DL));
9135 SDValue YWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
9136 Y, DAG.getVectorIdxConstant(0, DL));
9137 SDValue WideRes = DAG.getNode(ISD::CLMUL, DL, WideVT, XWide, YWide);
9138 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WideRes,
9139 DAG.getVectorIdxConstant(0, DL));
9140 }
9141 }
9142 }
9143
9144 // Special case: clmul(X, Y) where Y is a known constant (splat) that forms
9145 // a contiguous block of trailing ones whose length N is a power of two
9146 // (e.g. i8 0xFF, i8 0x0F, ...) or equal to the operand width. In this
9147 // special case, clmul(X, Y) is equivalent to a "parallel prefix XOR" or
9148 // "bitwise parity" operation on X.
9149 //
9150 // Note: This special currently dose NOT apply when the mask is neither a
9151 // power of two nor equal to the operand width because the loop inside
9152 // behaves as if the mask was bit-ceiled, and "undoing" the XOR with parts
9153 // of that CLMUL is a recursive problem (e.g. CLMUL with a 20-bit mask
9154 // requires correction XOR with CLMUL with 12-bit mask).
9155 if (auto *C = isConstOrConstSplat(Y, /*AllowUndefs=*/true)) {
9156 const APInt &YVal = C->getAPIntValue();
9157 unsigned N = YVal.countr_one();
9158 if (YVal.isAllOnes() || (YVal.isMask() && isPowerOf2_32(N))) {
9159 SDValue R = X;
9160 for (unsigned I = 1; I < N; I <<= 1) {
9161 SDValue ShAmt = DAG.getShiftAmountConstant(I, VT, DL);
9162 SDValue Shifted = DAG.getNode(ISD::SHL, DL, VT, R, ShAmt);
9163 R = DAG.getNode(ISD::XOR, DL, VT, R, Shifted);
9164 }
9165 return R;
9166 }
9167 }
9168
9169 // NOTE: If you change this expansion, please update the cost model
9170 // calculation in BasicTTIImpl::getTypeBasedIntrinsicInstrCost for
9171 // Intrinsic::clmul.
9172
9173 // Strategy 4: multiplication with holes.
9174 //
9175 // Uses "holes" (sequences of zeroes) to avoid carry spilling. When carries
9176 // do occur, they wind up in a "hole" and are subsequently masked out of the
9177 // result.
9178 //
9179 // https://www.bearssl.org/constanttime.html#ghash-for-gcm describes this
9180 // approach.
9181
9182 // Stride S handles operands up to S·2^S bits using S² multiplies.
9183 //
9184 // * BW <= 8 uses S = 2 (holes of 1 bit)
9185 // * BW <= 24 uses S = 3 (holes of 2 bits)
9186 // * BW <= 64 uses S = 4 (holes of 3 bits)
9187 // * BW <= 160 uses S = 5 (holes of 4 bits)
9188 // * BW <= 384 uses S = 6 (holes of 5 bits)
9189 //
9190 // We distribute the BW bits over S phases:
9191 //
9192 // phase 0 keeps bits: 0, S, 2S, ...
9193 // phase 1 keeps bits: 1, S + 1, 2S + 1, ...
9194 // ...
9195 //
9196 // Each phase has up to n = ceil(BW / S) bits set, and the holes are S-1
9197 // bits wide.
9198 //
9199 // Take BW = 4, S = 2, n = 2. The worst case is a fully populated phase (all
9200 // non-hole bits are set to 1) multiplied by itself, 0b0101 * 0b0101. Each
9201 // set bit of one operand shifts a copy of the other, and we add the copies:
9202 //
9203 // col: 4 3 2 1 0
9204 // 0b0101 << 0: 0 0 1 0 1
9205 // 0b0101 << 2: 1 0 1 0 0
9206 // ----------------- +
9207 // count: 1 0 2 0 1
9208 //
9209 // Counting the number of one-bits in each column gives a triangle: the
9210 // counts climb 1, 2, ..., n and back down (here 1, 2, 1 across the data
9211 // columns). So a column holds at most n one-bits, and that maximum n is
9212 // reached in only one column: the peak. Every other column holds at most n
9213 // - 1 one-bits.
9214 //
9215 // A stack of one-bits in a column turns into carries: column 2 above really
9216 // stores the value 1 + 1 = 2 = n. A column spans S bits, its kept bit
9217 // plus S-1 hole bits, and the count is written from the kept bit upward,
9218 // so any count <= 2^S - 1 stays within the column and never interferes with
9219 // the next data bit S positions up. Every non-peak column holds at most n -
9220 // 1, so they all fit as soon as n - 1 <= 2^S - 1.
9221 //
9222 // That leaves only the peak column. Because both operands set all data
9223 // bits, the triangle peaks at the top of the word at the highest data bit
9224 // still inside BW. Here the count reaches exactly n = 2^S and overflows.
9225 // But its carry lands at bit n*S >= BW, off the top, where it (and the
9226 // whole descending half of the triangle) is truncated.
9227 //
9228 // Hence the holes suffice exactly when n = ceil(BW / S) <= 2^S, i.e. BW <=
9229 // S*2^S.
9230 //
9231 // Here we find the smallest S that satisfies this inequality.
9232 unsigned S = 1;
9233 while (S < 32 && divideCeil(BW, S) > (1u << S))
9234 ++S;
9235
9236 // The "multiplication with holes" expansion emits S*S MULs, 3*S ANDs,
9237 // S*(S-1) XORs and S-1 ORs.
9238 unsigned HolesCost = S * S + 3 * S + S * (S - 1) + (S - 1);
9239
9240 // Estimate the cost of the naive algorithm.
9241 KnownBits KnownY = DAG.computeKnownBits(Y);
9242 unsigned NaiveCost = 0;
9243 for (unsigned I = 0; I < BW; ++I) {
9244 // The iteration folds away entirely and is free.
9245 if (KnownY.Zero[I])
9246 continue;
9247
9248 // On targets with a fast bit test instruction more instructions are used
9249 // to not need a (potentially expensive) multiplication. See also below.
9250 if (hasBitTest(Y, DAG.getShiftAmountConstant(I, VT, DL))) {
9251 // AND + SETCC + SHL + SELECT + XOR.
9252 NaiveCost += 5;
9253 } else {
9254 // AND + MUL + XOR.
9255 NaiveCost += 3;
9256 }
9257 }
9258
9259 // Only use multiplication with holes when it is cheaper, else use the naive
9260 // fallback below.
9261 if (HolesCost < NaiveCost &&
9263
9264 // Set a bit every S positions, e.g. for S = 4 this is equivalent to
9265 // 0b...00010001...0001.
9266 APInt MaskVal = APInt::getSplat(BW, APInt(S, 1));
9267
9268 // Create versions of X and Y that keep only the I-th bit of each S-bit
9269 // slice.
9270 SmallVector<SDValue, 4> M(S), Xp(S), Yp(S);
9271 for (unsigned I = 0; I < S; ++I) {
9272 M[I] = DAG.getConstant(MaskVal.shl(I), DL, VT);
9273 Xp[I] = DAG.getNode(ISD::AND, DL, VT, X, M[I]);
9274 Yp[I] = DAG.getNode(ISD::AND, DL, VT, Y, M[I]);
9275 }
9276
9277 // Codegens these expressions (S*S multiplications), e.g. for S=4:
9278 //
9279 // z0 = (x0 * y0) ^ (x1 * y3) ^ (x2 * y2) ^ (x3 * y1);
9280 // z1 = (x0 * y1) ^ (x1 * y0) ^ (x2 * y3) ^ (x3 * y2);
9281 // z2 = (x0 * y2) ^ (x1 * y1) ^ (x2 * y0) ^ (x3 * y3);
9282 // z3 = (x0 * y3) ^ (x1 * y2) ^ (x2 * y1) ^ (x3 * y0);
9283 SDValue Res = DAG.getConstant(0, DL, VT);
9284 for (unsigned I = 0; I < S; ++I) {
9285 SDValue Zi = DAG.getConstant(0, DL, VT);
9286 for (unsigned J = 0; J < S; ++J) {
9287 unsigned K = (I + S - J) % S;
9288 SDValue P = DAG.getNode(ISD::MUL, DL, VT, Xp[J], Yp[K]);
9289 Zi = DAG.getNode(ISD::XOR, DL, VT, Zi, P);
9290 }
9291
9292 // Keep only the bits belonging to this iteration, and bitwise or it all
9293 // together.
9294 Zi = DAG.getNode(ISD::AND, DL, VT, Zi, M[I]);
9295 Res = DAG.getNode(ISD::OR, DL, VT, Res, Zi, SDNodeFlags::Disjoint);
9296 }
9297 return Res;
9298 }
9299
9300 // Strategy 5: the naive fallback.
9301 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
9302
9303 SDValue Res = DAG.getConstant(0, DL, VT);
9304 for (unsigned I = 0; I < BW; ++I) {
9305 SDValue ShiftAmt = DAG.getShiftAmountConstant(I, VT, DL);
9306 SDValue Mask = DAG.getConstant(APInt::getOneBitSet(BW, I), DL, VT);
9307 SDValue YMasked = DAG.getNode(ISD::AND, DL, VT, Y, Mask);
9308
9309 // For targets with a fast bit test instruction (e.g., x86 BT) or without
9310 // multiply, use a shift-based expansion to avoid expensive MUL
9311 // instructions.
9312 SDValue Part;
9313 if (!hasBitTest(Y, ShiftAmt) &&
9316 Part = DAG.getNode(ISD::MUL, DL, VT, X, YMasked);
9317 } else {
9318 // Canonical bit test: (Y & (1 << I)) != 0
9319 SDValue Zero = DAG.getConstant(0, DL, VT);
9320 SDValue Cond = DAG.getSetCC(DL, SetCCVT, YMasked, Zero, ISD::SETEQ);
9321 SDValue XShifted = DAG.getNode(ISD::SHL, DL, VT, X, ShiftAmt);
9322 Part = DAG.getSelect(DL, VT, Cond, Zero, XShifted);
9323 }
9324 Res = DAG.getNode(ISD::XOR, DL, VT, Res, Part);
9325 }
9326 return Res;
9327 }
9328 case ISD::CLMULR:
9329 // If we have CLMUL/CLMULH, merge the shifted results to form CLMULR.
9332 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, VT, X, Y);
9333 SDValue Hi = DAG.getNode(ISD::CLMULH, DL, VT, X, Y);
9334 Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
9335 DAG.getShiftAmountConstant(BW - 1, VT, DL));
9336 Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
9337 DAG.getShiftAmountConstant(1, VT, DL));
9338 return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
9339 }
9340 [[fallthrough]];
9341 case ISD::CLMULH: {
9342 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9343 // Use bitreverse-based lowering (CLMULR/H = rev(CLMUL(rev,rev)) >> S)
9344 // when any of these hold:
9345 // (a) ZERO_EXTEND to ExtVT or SRL on ExtVT isn't legal.
9346 // (b) CLMUL is legal on VT but not on ExtVT (e.g. v8i8 on AArch64).
9347 // (c) CLMUL on ExtVT isn't legal, but CLMUL on VT can be efficiently
9348 // expanded via halving/widening to reach legal CLMUL. The bitreverse
9349 // path creates CLMUL(VT) which will be expanded efficiently. The
9350 // promote path would create CLMUL(ExtVT) => halving => CLMULH(VT),
9351 // causing a cycle.
9352 // Note: when CLMUL is legal on ExtVT, the zext => CLMUL(ExtVT) => shift
9353 // => trunc path is preferred over the bitreverse path, as it avoids the
9354 // cost of 3 bitreverse operations.
9359 canNarrowCLMULToLegal(*this, Ctx, VT)))) {
9360 SDValue XRev = DAG.getNode(ISD::BITREVERSE, DL, VT, X);
9361 SDValue YRev = DAG.getNode(ISD::BITREVERSE, DL, VT, Y);
9362 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, VT, XRev, YRev);
9363 SDValue Res = DAG.getNode(ISD::BITREVERSE, DL, VT, ClMul);
9364 if (Opcode == ISD::CLMULH)
9365 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
9366 DAG.getShiftAmountConstant(1, VT, DL));
9367 return Res;
9368 }
9369 SDValue XExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, X);
9370 SDValue YExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, Y);
9371 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9372 unsigned ShAmt = Opcode == ISD::CLMULR ? BW - 1 : BW;
9373 SDValue HiBits = DAG.getNode(ISD::SRL, DL, ExtVT, ClMul,
9374 DAG.getShiftAmountConstant(ShAmt, ExtVT, DL));
9375 return DAG.getNode(ISD::TRUNCATE, DL, VT, HiBits);
9376 }
9377 }
9378 llvm_unreachable("Expected CLMUL, CLMULR, or CLMULH");
9379}
9380
9382 SDLoc DL(Node);
9383 EVT VT = Node->getValueType(0);
9384 SDValue Val = Node->getOperand(0);
9385 SDValue Msk = Node->getOperand(1);
9386 unsigned BW = VT.getScalarSizeInBits();
9387
9388 // Just scalarize if scalar PEXT is legal
9390 return DAG.UnrollVectorOp(Node);
9391
9392 // Hacker's Delight §7-4: Compress, or Generalized Extract
9393 SDValue X = DAG.getNode(ISD::AND, DL, VT, Val, Msk);
9394 SDValue M = Msk;
9395 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9396 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, M, VT), One);
9397
9398 // Repeatedly compute which bits would shift to the right by an odd amount,
9399 // shift all such bits in parallel using a mask, and double the shift amount.
9400 for (unsigned I = 1; I < BW; I *= 2) {
9401 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9402 SDValue Mp =
9403 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9404 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, M);
9405 SDValue ShiftI = DAG.getShiftAmountConstant(I, VT, DL);
9406 SDValue MvS = DAG.getNode(ISD::SRL, DL, VT, Mv, ShiftI);
9407 M = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, M, Mv), MvS,
9409 SDValue T = DAG.getNode(ISD::AND, DL, VT, X, Mv);
9410 SDValue TS = DAG.getNode(ISD::SRL, DL, VT, T, ShiftI);
9411 X = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, X, T), TS,
9413 if (I * 2 < BW)
9414 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9415 }
9416
9417 return X;
9418}
9419
9421 SDLoc DL(Node);
9422 EVT VT = Node->getValueType(0);
9423 SDValue Val = Node->getOperand(0);
9424 SDValue Msk = Node->getOperand(1);
9425 unsigned BW = VT.getScalarSizeInBits();
9426
9427 // Just scalarize if scalar PDEP is legal
9429 return DAG.UnrollVectorOp(Node);
9430
9431 // Hacker's Delight §7-5: Expand, or Generalized Insert.
9432 unsigned LogBW = Log2_32_Ceil(BW);
9433 SmallVector<SDValue, 8> MvArray(LogBW);
9434 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9435 SDValue Mc = Msk;
9436 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, Msk, VT), One);
9437
9438 // First pass: compute move masks for each power of two that a bit moves by.
9439 for (unsigned S = 0; S < LogBW; ++S) {
9440 unsigned ShiftS = 1u << S;
9441 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9442 SDValue Mp =
9443 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9444 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, Mc);
9445 MvArray[S] = Mv;
9446 if (S + 1 < LogBW) {
9447 SDValue McXorMv = DAG.getNode(ISD::XOR, DL, VT, Mc, Mv);
9448 SDValue MvShifted = DAG.getNode(
9449 ISD::SRL, DL, VT, Mv, DAG.getShiftAmountConstant(ShiftS, VT, DL));
9450 Mc = DAG.getNode(ISD::OR, DL, VT, McXorMv, MvShifted,
9452 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9453 }
9454 }
9455
9456 // Second pass: move bits by 32, 16, 8, 4, 2, 1, using masks, in parallel.
9457 // Each pass handles half the shift amount of the previous pass.
9458 SDValue X = Val;
9459 for (int S = (int)LogBW - 1; S >= 0; --S) {
9460 SDValue ShiftSv = DAG.getShiftAmountConstant(1ull << S, VT, DL);
9461 SDValue T = DAG.getNode(ISD::SHL, DL, VT, X, ShiftSv);
9462 SDValue UnshiftedBits =
9463 DAG.getNode(ISD::AND, DL, VT, X, DAG.getNOT(DL, MvArray[S], VT));
9464 SDValue ShiftedBits = DAG.getNode(ISD::AND, DL, VT, T, MvArray[S]);
9465 X = DAG.getNode(ISD::OR, DL, VT, UnshiftedBits, ShiftedBits,
9467 }
9468
9469 return DAG.getNode(ISD::AND, DL, VT, X, Msk);
9470}
9471
9473 SelectionDAG &DAG) const {
9474 assert(Node->getNumOperands() == 3 && "Not a double-shift!");
9475 EVT VT = Node->getValueType(0);
9476 unsigned VTBits = VT.getScalarSizeInBits();
9477 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
9478
9479 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
9480 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
9481 SDValue ShOpLo = Node->getOperand(0);
9482 SDValue ShOpHi = Node->getOperand(1);
9483 SDValue ShAmt = Node->getOperand(2);
9484 EVT ShAmtVT = ShAmt.getValueType();
9485 EVT ShAmtCCVT =
9486 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
9487 SDLoc dl(Node);
9488
9489 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
9490 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
9491 // away during isel.
9492 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9493 DAG.getConstant(VTBits - 1, dl, ShAmtVT));
9494 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9495 DAG.getConstant(VTBits - 1, dl, ShAmtVT))
9496 : DAG.getConstant(0, dl, VT);
9497
9498 SDValue Tmp2, Tmp3;
9499 if (IsSHL) {
9500 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
9501 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9502 } else {
9503 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
9504 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9505 }
9506
9507 // If the shift amount is larger or equal than the width of a part we don't
9508 // use the result from the FSHL/FSHR. Insert a test and select the appropriate
9509 // values for large shift amounts.
9510 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9511 DAG.getConstant(VTBits, dl, ShAmtVT));
9512 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
9513 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
9514
9515 if (IsSHL) {
9516 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9517 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9518 } else {
9519 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9520 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9521 }
9522}
9523
9525 SelectionDAG &DAG) const {
9526 // This implements llvm.canonicalize.f* by multiplication with 1.0, as
9527 // suggested in
9528 // https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic.
9529 // It uses strict_fp operations even outside a strict_fp context in order
9530 // to guarantee that the canonicalization is not optimized away by later
9531 // passes. The result chain introduced by that is intentionally ignored
9532 // since no ordering requirement is intended here.
9533 EVT VT = Node->getValueType(0);
9534 SDLoc DL(Node);
9535 SDNodeFlags Flags = Node->getFlags();
9536 Flags.setNoFPExcept(true);
9537 SDValue One = DAG.getConstantFP(1.0, DL, VT);
9538 SDValue Mul =
9539 DAG.getNode(ISD::STRICT_FMUL, DL, {VT, MVT::Other},
9540 {DAG.getEntryNode(), Node->getOperand(0), One}, Flags);
9541 return Mul;
9542}
9543
9545 SelectionDAG &DAG) const {
9546 // Expand conversion from a native IEEE float type to an arbitrary FP format
9547 // returning the result as an integer using bit manipulation.
9548 EVT ResVT = Node->getValueType(0);
9549 SDLoc dl(Node);
9550
9551 SDValue FloatVal = Node->getOperand(0);
9552 const uint64_t SemEnum = Node->getConstantOperandVal(1);
9553 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
9554 const auto RoundMode =
9555 static_cast<RoundingMode>(Node->getConstantOperandVal(2));
9556 const bool Saturate = Node->getConstantOperandVal(3) != 0;
9557
9558 // Supported destination formats.
9559 switch (Sem) {
9566 break;
9567 default:
9568 DAG.getContext()->emitError("CONVERT_TO_ARBITRARY_FP: not implemented "
9569 "destination format (semantics enum " +
9570 Twine(SemEnum) + ")");
9571 return SDValue();
9572 }
9573
9574 // Supported rounding modes.
9575 switch (RoundMode) {
9581 break;
9582 default:
9583 DAG.getContext()->emitError(
9584 "CONVERT_TO_ARBITRARY_FP: unsupported rounding mode (enum " +
9585 Twine(static_cast<int>(RoundMode)) + ")");
9586 return SDValue();
9587 }
9588
9589 // Destination format parameters.
9590 const fltSemantics &DstSem = APFloatBase::EnumToSemantics(Sem);
9591 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
9592 const unsigned DstPrecision = APFloat::semanticsPrecision(DstSem);
9593 const unsigned DstMant = DstPrecision - 1;
9594 // Unsigned formats spend no bit on the sign.
9595 const bool DstHasSign = APFloat::semanticsHasSignedRepr(DstSem);
9596 const unsigned DstExpBits = DstBits - (DstHasSign ? 1 : 0) - DstMant;
9597 const int DstBias = 1 - APFloat::semanticsMinExponent(DstSem);
9598 const unsigned DstExpMax = (1U << DstExpBits) - 1;
9599 const uint64_t DstMantMask = (DstMant > 0) ? ((1ULL << DstMant) - 1) : 0;
9600 const fltNonfiniteBehavior DstNFBehavior = DstSem.nonFiniteBehavior;
9601 const fltNanEncoding DstNanEnc = DstSem.nanEncoding;
9602
9603 // Compute the maximum normal exponent for the destination format.
9604 const unsigned DstExpMaxNormal =
9605 DstNFBehavior == fltNonfiniteBehavior::IEEE754 ? DstExpMax - 1
9606 : DstExpMax;
9607
9608 // For NanOnly formats the max exponent field for finite values
9609 // is DstExpMax, but the encoding with exp = DstExpMax and
9610 // mant = all-ones is NaN. So DstExpMaxNormal = DstExpMax, but max
9611 // mantissa at that exponent is DstMantMask - 1 (if NanEnc == AllOnes) to
9612 // avoid the NaN encoding.
9613 uint64_t DstMaxMantAtMaxExp = DstMantMask;
9614 if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9615 DstNanEnc == fltNanEncoding::AllOnes)
9616 DstMaxMantAtMaxExp = DstMantMask - 1;
9617
9618 // Source format parameters.
9619 EVT SrcVT = FloatVal.getValueType();
9620 const fltSemantics &SrcSem = SrcVT.getScalarType().getFltSemantics();
9621 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
9622 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
9623 const unsigned SrcMant = SrcPrecision - 1;
9624 const uint64_t SrcMantMask = (1ULL << SrcMant) - 1;
9625
9626 // Work in the source integer type. Match the destination shape so the
9627 // expansion stays vector when ResVT is a vector.
9628 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), SrcBits);
9629 EVT IntVT = ResVT.changeElementType(*DAG.getContext(), IntScalarVT);
9630 EVT SetCCVT =
9631 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
9632 EVT FPSetCCVT =
9633 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
9634
9635 SDValue Zero = DAG.getConstant(0, dl, IntVT);
9636 SDValue One = DAG.getConstant(1, dl, IntVT);
9637
9638 // Bitcast source float to integer to extract the sign bit.
9639 SDValue Src = DAG.getNode(ISD::BITCAST, dl, IntVT, FloatVal);
9640 SDValue SignBit =
9641 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9642 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl));
9643
9644 // Classify the input.
9645 SDValue FPZero = DAG.getConstantFP(0.0, dl, SrcVT);
9646 SDValue FPInf = DAG.getConstantFP(APFloat::getInf(SrcSem), dl, SrcVT);
9647 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, SrcVT, FloatVal);
9648 SDValue IsNaN = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETUO);
9649 SDValue IsInf = DAG.getSetCC(dl, FPSetCCVT, AbsVal, FPInf, ISD::SETOEQ);
9650 SDValue IsZero = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOEQ);
9651
9652 // Split into a normalized fraction and unbiased exponent. FFREXP normalizes
9653 // source denormals automatically. The result is unspecified for Inf/NaN, but
9654 // those inputs are detected above and override the final result.
9655 EVT FrexpExpScalarVT =
9657 EVT FrexpExpVT = SrcVT.changeElementType(*DAG.getContext(), FrexpExpScalarVT);
9658 SDValue Frexp =
9659 DAG.getNode(ISD::FFREXP, dl, DAG.getVTList(SrcVT, FrexpExpVT), FloatVal);
9660 SDValue FrexpFrac = Frexp.getValue(0);
9661 SDValue FrexpExp = Frexp.getValue(1);
9662
9663 SDValue FrexpFracInt = DAG.getNode(ISD::BITCAST, dl, IntVT, FrexpFrac);
9664 SDValue EffSrcMant = DAG.getNode(ISD::AND, dl, IntVT, FrexpFracInt,
9665 DAG.getConstant(SrcMantMask, dl, IntVT));
9666
9667 SDValue FrexpExpExt = DAG.getSExtOrTrunc(FrexpExp, dl, IntVT);
9668 SDValue NewExp = DAG.getNode(ISD::ADD, dl, IntVT, FrexpExpExt,
9669 DAG.getConstant(DstBias - 1, dl, IntVT));
9670
9671 // Compute rounding increment given the round bit, sticky bits, and LSB
9672 // of the truncated mantissa.
9673 auto ComputeRoundUp = [&](SDValue RoundBit, SDValue StickyBits,
9674 SDValue LSB) -> SDValue {
9675 switch (RoundMode) {
9677 // Round up if round_bit && (sticky || lsb)
9678 SDValue StickyOrLSB = DAG.getNode(ISD::OR, dl, IntVT, StickyBits, LSB);
9679 return DAG.getNode(ISD::AND, dl, IntVT, RoundBit, StickyOrLSB);
9680 }
9682 return Zero;
9684 // Round up if positive and any truncated bits are set.
9685 SDValue AnyTruncBits =
9686 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9687 SDValue HasTruncBits =
9688 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9689 SDValue IsPositive = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETEQ);
9690 SDValue DoRound =
9691 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsPositive);
9692 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9693 }
9695 // Round up if negative and any truncated bits are set (to -Inf).
9696 SDValue AnyTruncBits =
9697 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9698 SDValue HasTruncBits =
9699 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9700 SDValue IsNegative = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETNE);
9701 SDValue DoRound =
9702 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsNegative);
9703 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9704 }
9706 return RoundBit;
9707 default:
9708 llvm_unreachable("unsupported rounding mode");
9709 }
9710 };
9711
9712 // Round mantissa from SrcMant bits to DstMant bits.
9713 SDValue TruncMant;
9714 SDValue RoundUp;
9715 if (SrcMant > DstMant) {
9716 const unsigned Shift = SrcMant - DstMant;
9717 SDValue ShiftConst = DAG.getShiftAmountConstant(Shift, IntVT, dl);
9718 TruncMant = DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, ShiftConst);
9719
9720 // Check bit at position Shift - 1 aka the round bit.
9721 SDValue RoundBit;
9722 if (Shift >= 1) {
9723 SDValue RoundBitShift = DAG.getShiftAmountConstant(Shift - 1, IntVT, dl);
9724 SDValue ShiftedMant =
9725 DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, RoundBitShift);
9726 RoundBit = DAG.getNode(ISD::AND, dl, IntVT, ShiftedMant, One);
9727 } else {
9728 RoundBit = Zero;
9729 }
9730
9731 // OR of all bits below the round bit to get sticky bits.
9732 SDValue StickyBits;
9733 if (Shift >= 2) {
9734 uint64_t StickyMask = maskTrailingOnes<uint64_t>(Shift - 1);
9735 StickyBits = DAG.getNode(ISD::AND, dl, IntVT, EffSrcMant,
9736 DAG.getConstant(StickyMask, dl, IntVT));
9737 StickyBits = DAG.getSetCC(dl, SetCCVT, StickyBits, Zero, ISD::SETNE);
9738 StickyBits = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, StickyBits);
9739 } else {
9740 StickyBits = Zero;
9741 }
9742
9743 // LSB of truncated mantissa.
9744 SDValue LSB = DAG.getNode(ISD::AND, dl, IntVT, TruncMant, One);
9745
9746 RoundUp = ComputeRoundUp(RoundBit, StickyBits, LSB);
9747 } else {
9748 // If DstMant >= SrcMant, then no rounding needed, just shift left.
9749 SDValue MantShift =
9750 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
9751 TruncMant = DAG.getNode(ISD::SHL, dl, IntVT, EffSrcMant, MantShift);
9752 RoundUp = Zero;
9753 }
9754
9755 // Apply rounding.
9756 SDValue RoundedMant = DAG.getNode(ISD::ADD, dl, IntVT, TruncMant, RoundUp);
9757
9758 // Handle mantissa overflow from rounding.
9759 // If rounded_mant > DstMantMask, carry into exponent.
9760 SDValue MantOverflow =
9761 DAG.getSetCC(dl, SetCCVT, RoundedMant,
9762 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9763 // On overflow: mant = 0, exp += 1.
9764 SDValue AdjMant = DAG.getSelect(dl, IntVT, MantOverflow, Zero, RoundedMant);
9765 SDValue AdjExp =
9766 DAG.getNode(ISD::ADD, dl, IntVT, NewExp,
9767 DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, MantOverflow));
9768
9769 // Precompute sign shifted to MSB of destination. Unsigned formats have no
9770 // sign bit to merge in.
9771 SDValue SignShifted =
9772 DstHasSign
9773 ? DAG.getNode(ISD::SHL, dl, IntVT, SignBit,
9774 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
9775 : Zero;
9776
9777 // Destination denormal conversion (when new_exp <= 0).
9778 // Shift the mantissa right by 1 - new_exp additional bits and set the
9779 // exponent field to 0.
9780 SDValue ExpIsNeg = DAG.getSetCC(dl, SetCCVT, AdjExp,
9781 DAG.getConstant(1, dl, IntVT), ISD::SETLT);
9782
9783 SDValue DenormResult;
9784 {
9785 // denorm_shift = 1 - NewExp.
9786 SDValue DenormShift = DAG.getNode(ISD::SUB, dl, IntVT, One, NewExp);
9787
9788 // full_src_mant = (1 << SrcMant) | EffSrcMant.
9789 SDValue ImplicitOne =
9790 DAG.getNode(ISD::SHL, dl, IntVT, One,
9791 DAG.getShiftAmountConstant(SrcMant, IntVT, dl));
9792 SDValue FullSrcMant =
9793 DAG.getNode(ISD::OR, dl, IntVT, EffSrcMant, ImplicitOne);
9794
9795 // Total right shift = DenormShift + (SrcMant - DstMant).
9796 int64_t MantDelta = static_cast<int64_t>(SrcMant) - DstMant;
9797 SDValue TotalShift =
9798 DAG.getNode(ISD::ADD, dl, IntVT, DenormShift,
9799 DAG.getSignedConstant(MantDelta, dl, IntVT));
9800
9801 // Clamp total shift to avoid UB, then truncate denorm mantissa.
9802 EVT ShiftVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
9803 SDValue MaxShift = DAG.getConstant(SrcBits - 1, dl, IntVT);
9804 SDValue ClampedShift =
9805 DAG.getNode(ISD::UMIN, dl, IntVT, TotalShift, MaxShift);
9806 SDValue DenormTruncMant =
9807 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant,
9808 DAG.getZExtOrTrunc(ClampedShift, dl, ShiftVT));
9809
9810 // Rounding for denorm path.
9811 SDValue DenormRoundUp;
9812 {
9813 // Round bit is at position TotalShift - 1 of FullSrcMant.
9814 // Clamp to at least 1 so the subtraction doesn't underflow and create
9815 // shift nodes with invalid shift amounts.
9816 SDValue SafeShift = DAG.getNode(ISD::UMAX, dl, IntVT, ClampedShift, One);
9817 SDValue RoundBitPos = DAG.getNode(ISD::SUB, dl, IntVT, SafeShift, One);
9818 SDValue RoundBitPosAmt = DAG.getZExtOrTrunc(RoundBitPos, dl, ShiftVT);
9819 SDValue DenormRoundBit = DAG.getNode(
9820 ISD::AND, dl, IntVT,
9821 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant, RoundBitPosAmt), One);
9822
9823 // Sticky: all bits below round bit.
9824 // sticky_mask = (1 << RoundBitPos) - 1
9825 SDValue StickyMask = DAG.getNode(
9826 ISD::SUB, dl, IntVT,
9827 DAG.getNode(ISD::SHL, dl, IntVT, One, RoundBitPosAmt), One);
9828 SDValue DenormStickyBits =
9829 DAG.getNode(ISD::AND, dl, IntVT, FullSrcMant, StickyMask);
9830 SDValue HasSticky = DAG.getNode(
9831 ISD::ZERO_EXTEND, dl, IntVT,
9832 DAG.getSetCC(dl, SetCCVT, DenormStickyBits, Zero, ISD::SETNE));
9833
9834 SDValue DenormLSB =
9835 DAG.getNode(ISD::AND, dl, IntVT, DenormTruncMant, One);
9836
9837 DenormRoundUp = ComputeRoundUp(DenormRoundBit, HasSticky, DenormLSB);
9838
9839 // Only apply rounding if TotalShift >= 1 (i.e., there are bits to round).
9840 SDValue ShiftGEOne =
9841 DAG.getSetCC(dl, SetCCVT, ClampedShift, One, ISD::SETUGE);
9842 DenormRoundUp = DAG.getSelect(dl, IntVT, ShiftGEOne, DenormRoundUp, Zero);
9843 }
9844
9845 SDValue DenormRoundedMant =
9846 DAG.getNode(ISD::ADD, dl, IntVT, DenormTruncMant, DenormRoundUp);
9847
9848 // If rounding caused overflow into the normal range, then we get the
9849 // smallest normal number.
9850 SDValue DenormMantOF =
9851 DAG.getSetCC(dl, SetCCVT, DenormRoundedMant,
9852 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9853 SDValue DenormFinalMant =
9854 DAG.getSelect(dl, IntVT, DenormMantOF, Zero, DenormRoundedMant);
9855 SDValue DenormFinalExp = DAG.getSelect(dl, IntVT, DenormMantOF, One, Zero);
9856
9857 // Assemble: sign | (exp << DstMant) | mant
9858 SDValue DenormExpShifted =
9859 DAG.getNode(ISD::SHL, dl, IntVT, DenormFinalExp,
9860 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
9861 DenormResult = DAG.getNode(
9862 ISD::OR, dl, IntVT,
9863 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
9864 DenormFinalMant);
9865 }
9866
9867 // Exponent overflow detection.
9868 SDValue ExpOF =
9869 DAG.getSetCC(dl, SetCCVT, AdjExp,
9870 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETGT);
9871
9872 // Also check if AdjExp == DstExpMaxNormal and mantissa overflow into
9873 // a value that exceeds the max allowed mantissa at that exponent.
9874 SDValue ExpAtMax =
9875 DAG.getSetCC(dl, SetCCVT, AdjExp,
9876 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETEQ);
9877 SDValue MantExceedsMax =
9878 DAG.getSetCC(dl, SetCCVT, AdjMant,
9879 DAG.getConstant(DstMaxMantAtMaxExp, dl, IntVT), ISD::SETGT);
9880 SDValue ExpMantOF =
9881 DAG.getNode(ISD::AND, dl, SetCCVT, ExpAtMax, MantExceedsMax);
9882 SDValue IsOverflow = DAG.getNode(ISD::OR, dl, SetCCVT, ExpOF, ExpMantOF);
9883
9884 // Build overflow result.
9886
9887 if (Saturate) {
9888 // Clamp to max finite value:
9889 // sign | (DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp
9890 uint64_t MaxFinite =
9891 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
9892 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9893 DAG.getConstant(MaxFinite, dl, IntVT));
9894 } else if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9895 // Produce infinity.
9896 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
9897 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9898 DAG.getConstant(InfBits, dl, IntVT));
9899 } else {
9900 // Emit poison if no Inf in format and not saturating.
9901 OverflowResult = DAG.getPOISON(IntVT);
9902 }
9903
9904 // Assemble normal result: sign | (AdjExp << DstMant) | AdjMant
9905 SDValue NormExpShifted =
9906 DAG.getNode(ISD::SHL, dl, IntVT, AdjExp,
9907 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
9908 SDValue NormResult = DAG.getNode(
9909 ISD::OR, dl, IntVT,
9910 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted), AdjMant);
9911
9912 // Build special-value results.
9913 SDValue NaNResult;
9914 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9915 // Produce canonical NaN.
9916 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
9917 NaNResult =
9918 DAG.getConstant(((uint64_t)DstExpMax << DstMant) | QNaNBit, dl, IntVT);
9919 } else if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9920 DstNanEnc == fltNanEncoding::AllOnes) {
9921 // E4M3FN-style: NaN is exp=all-ones, mant=all-ones.
9922 NaNResult = DAG.getConstant(((uint64_t)DstExpMax << DstMant) | DstMantMask,
9923 dl, IntVT);
9924 } else {
9925 // NaN -> poison for finite only values.
9926 NaNResult = DAG.getPOISON(IntVT);
9927 }
9928
9929 // Inf handling.
9930 SDValue InfResult;
9931 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9932 // Produce signed infinity.
9933 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
9934 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9935 DAG.getConstant(InfBits, dl, IntVT));
9936 } else if (Saturate) {
9937 // Inf saturates to max finite.
9938 uint64_t MaxFinite =
9939 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
9940 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9941 DAG.getConstant(MaxFinite, dl, IntVT));
9942 } else {
9943 // No Inf and not saturating -> poison.
9944 InfResult = DAG.getPOISON(IntVT);
9945 }
9946
9947 SDValue ZeroResult = SignShifted;
9948
9949 // Final selection in an order: NaN takes priority, then Inf, then Zero.
9950 SDValue FiniteResult =
9951 DAG.getSelect(dl, IntVT, ExpIsNeg, DenormResult, NormResult);
9952 FiniteResult =
9953 DAG.getSelect(dl, IntVT, IsOverflow, OverflowResult, FiniteResult);
9954
9955 SDValue Result = FiniteResult;
9956 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
9957 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
9958
9959 // Negative values are unrepresentable in an unsigned format: clamp to zero
9960 // when saturating, poison otherwise so no select is needed. -0.0 is handled
9961 // by IsZero above. Run before the NaN case so a negative NaN still yields
9962 // NaN.
9963 if (!DstHasSign && Saturate) {
9964 SDValue IsNegative =
9965 DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOLT);
9966 Result = DAG.getSelect(dl, IntVT, IsNegative, Zero, Result);
9967 }
9968
9969 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
9970
9971 // Truncate to destination integer type.
9972 return DAG.getZExtOrTrunc(Result, dl, ResVT);
9973}
9974
9975SDValue
9977 SelectionDAG &DAG) const {
9978 SDLoc dl(Node);
9979 EVT DstVT = Node->getValueType(0);
9980 EVT DstScalarVT = DstVT.getScalarType();
9981
9982 SDValue IntVal = Node->getOperand(0);
9983 const uint64_t SemEnum = Node->getConstantOperandVal(1);
9984 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
9985
9986 // Supported source formats.
9987 switch (Sem) {
9994 break;
9995 default:
9996 DAG.getContext()->emitError("CONVERT_FROM_ARBITRARY_FP: not implemented "
9997 "source format (semantics enum " +
9998 Twine(SemEnum) + ")");
9999 return SDValue();
10000 }
10001
10002 const fltSemantics &SrcSem = APFloatBase::EnumToSemantics(Sem);
10003 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
10004 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
10005 const unsigned SrcMant = SrcPrecision - 1;
10006 // Unsigned formats spend no bit on the sign.
10007 const bool SrcHasSign = APFloat::semanticsHasSignedRepr(SrcSem);
10008 const unsigned SrcExp = SrcBits - (SrcHasSign ? 1 : 0) - SrcMant;
10009 const int SrcBias = 1 - APFloat::semanticsMinExponent(SrcSem);
10010 const fltNonfiniteBehavior NFBehavior = SrcSem.nonFiniteBehavior;
10011
10012 // Destination format parameters.
10013 const fltSemantics &DstSem = DstScalarVT.getFltSemantics();
10014 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
10015 const unsigned DstMant = APFloat::semanticsPrecision(DstSem) - 1;
10016 const unsigned DstExpBits = DstBits - DstMant - 1;
10017 const int DstMinExp = APFloat::semanticsMinExponent(DstSem);
10018 const int DstBias = 1 - DstMinExp;
10019 const uint64_t DstExpAllOnes = (1ULL << DstExpBits) - 1;
10020
10021 // Work in an integer type matching the destination float width.
10022 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), DstBits);
10023 EVT IntVT = IntScalarVT;
10024 if (DstVT.isVector()) {
10025 IntVT = EVT::getVectorVT(*DAG.getContext(), IntScalarVT,
10026 DstVT.getVectorElementCount());
10027 } else if (!isTypeLegal(IntScalarVT)) {
10028 // Avoid generating illegal type as there is no other places that'll
10029 // legalize it. Vector types don't have this problem because they
10030 // are subject to LegalizeVectorOps and another type legalization phase
10031 // will follow.
10032 if (getTypeAction(*DAG.getContext(), IntScalarVT) != TypePromoteInteger) {
10033 // We only know how to handle situations where the legal type is wider.
10034 DAG.getContext()->emitError(
10035 "CONVERT_FROM_ARBITRARY_FP: the requested integer value type for its "
10036 "legalization is not supported");
10037 return SDValue();
10038 }
10039 IntVT = getTypeToTransformTo(*DAG.getContext(), IntScalarVT);
10040 }
10041
10042 SDValue Src = DAG.getZExtOrTrunc(IntVal, dl, IntVT);
10043
10044 EVT SetCCVT =
10045 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
10046
10047 SDValue Zero = DAG.getConstant(0, dl, IntVT);
10048 SDValue One = DAG.getConstant(1, dl, IntVT);
10049
10050 // Extract bit fields.
10051 const uint64_t MantMask = (SrcMant > 0) ? ((1ULL << SrcMant) - 1) : 0;
10052 const uint64_t ExpMask = (1ULL << SrcExp) - 1;
10053
10054 SDValue MantField = DAG.getNode(ISD::AND, dl, IntVT, Src,
10055 DAG.getConstant(MantMask, dl, IntVT));
10056
10057 SDValue ExpField =
10058 DAG.getNode(ISD::AND, dl, IntVT,
10059 DAG.getNode(ISD::SRL, dl, IntVT, Src,
10060 DAG.getShiftAmountConstant(SrcMant, IntVT, dl)),
10061 DAG.getConstant(ExpMask, dl, IntVT));
10062
10063 // An unsigned source has no sign bit; bit SrcBits - 1 is part of the
10064 // exponent.
10065 SDValue SignShifted =
10066 SrcHasSign
10067 ? DAG.getNode(
10068 ISD::SHL, dl, IntVT,
10069 DAG.getNode(ISD::SRL, dl, IntVT, Src,
10070 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl)),
10071 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
10072 : Zero;
10073
10074 // Classify the input.
10075 SDValue ExpAllOnes = DAG.getConstant(ExpMask, dl, IntVT);
10076 SDValue IsExpAllOnes =
10077 DAG.getSetCC(dl, SetCCVT, ExpField, ExpAllOnes, ISD::SETEQ);
10078 SDValue IsExpZero = DAG.getSetCC(dl, SetCCVT, ExpField, Zero, ISD::SETEQ);
10079 SDValue IsMantZero = DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETEQ);
10080 SDValue IsMantNonZero =
10081 DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETNE);
10082
10083 SDValue IsNaN;
10084 if (NFBehavior == fltNonfiniteBehavior::FiniteOnly) {
10085 IsNaN = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10086 } else if (NFBehavior == fltNonfiniteBehavior::IEEE754) {
10087 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantNonZero);
10088 } else {
10090 SDValue MantAllOnes = DAG.getConstant(MantMask, dl, IntVT);
10091 SDValue IsMantAllOnes =
10092 DAG.getSetCC(dl, SetCCVT, MantField, MantAllOnes, ISD::SETEQ);
10093 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantAllOnes);
10094 }
10095
10096 SDValue IsInf;
10097 if (NFBehavior == fltNonfiniteBehavior::IEEE754)
10098 IsInf = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantZero);
10099 else
10100 IsInf = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10101
10102 SDValue IsZero = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantZero);
10103 SDValue IsDenorm =
10104 DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantNonZero);
10105
10106 // Normal value conversion.
10107 const int BiasAdjust = DstBias - SrcBias;
10108 SDValue NormDstExp = DAG.getNode(
10109 ISD::ADD, dl, IntVT, ExpField,
10110 DAG.getConstant(APInt(IntVT.getScalarSizeInBits(), BiasAdjust, true), dl,
10111 IntVT));
10112
10113 SDValue NormDstMant;
10114 if (DstMant > SrcMant) {
10115 SDValue NormDstMantShift =
10116 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
10117 NormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, MantField, NormDstMantShift);
10118 } else {
10119 NormDstMant = MantField;
10120 }
10121
10122 SDValue DstMantShift = DAG.getShiftAmountConstant(DstMant, IntVT, dl);
10123 SDValue NormExpShifted =
10124 DAG.getNode(ISD::SHL, dl, IntVT, NormDstExp, DstMantShift);
10125 SDValue NormResult =
10126 DAG.getNode(ISD::OR, dl, IntVT,
10127 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted),
10128 NormDstMant);
10129
10130 // With identical exponent biases, denormal values remain denormal and the
10131 // normal conversion's mantissa shift is sufficient.
10132 SDValue DenormResult = NormResult;
10133 if (BiasAdjust != 0) {
10134 const unsigned IntVTBits = IntVT.getScalarSizeInBits();
10135 SDValue LeadingZeros =
10136 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, IntVT, MantField);
10137
10138 const int DenormExpConst =
10139 (int)IntVTBits + DstBias - SrcBias - (int)SrcMant;
10140 SDValue DenormDstExp = DAG.getNode(
10141 ISD::SUB, dl, IntVT,
10142 DAG.getConstant(APInt(IntVTBits, DenormExpConst, true), dl, IntVT),
10143 LeadingZeros);
10144
10145 SDValue MantMSB =
10146 DAG.getNode(ISD::SUB, dl, IntVT,
10147 DAG.getConstant(IntVTBits - 1, dl, IntVT), LeadingZeros);
10148
10149 SDValue LeadingOne = DAG.getNode(ISD::SHL, dl, IntVT, One, MantMSB);
10150 SDValue Frac = DAG.getNode(ISD::XOR, dl, IntVT, MantField, LeadingOne);
10151
10152 const unsigned ShiftSub = IntVTBits - 1 - DstMant;
10153 SDValue ShiftAmount = DAG.getNode(ISD::SUB, dl, IntVT, LeadingZeros,
10154 DAG.getConstant(ShiftSub, dl, IntVT));
10155
10156 SDValue DenormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, Frac, ShiftAmount);
10157
10158 SDValue DenormExpShifted =
10159 DAG.getNode(ISD::SHL, dl, IntVT, DenormDstExp, DstMantShift);
10160 DenormResult = DAG.getNode(
10161 ISD::OR, dl, IntVT,
10162 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
10163 DenormDstMant);
10164 }
10165
10166 SDValue FiniteResult =
10167 DAG.getSelect(dl, IntVT, IsDenorm, DenormResult, NormResult);
10168
10169 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
10170 SDValue NaNResult =
10171 DAG.getConstant((DstExpAllOnes << DstMant) | QNaNBit, dl, IntVT);
10172
10173 SDValue InfResult =
10174 DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10175 DAG.getConstant(DstExpAllOnes << DstMant, dl, IntVT));
10176
10177 // A source format may have a larger finite exponent range despite having
10178 // fewer bits, as with Float8E5M3FNU converted to half. Its overflowing finite
10179 // values become infinity. The NaN selection below still takes precedence.
10180 if (APFloat::semanticsMaxExponent(SrcSem) >
10182 SDValue IsOverflow =
10183 DAG.getSetCC(dl, SetCCVT, NormDstExp,
10184 DAG.getConstant(DstExpAllOnes, dl, IntVT), ISD::SETUGE);
10185 FiniteResult =
10186 DAG.getSelect(dl, IntVT, IsOverflow, InfResult, FiniteResult);
10187 }
10188
10189 SDValue ZeroResult = SignShifted;
10190
10191 SDValue Result = FiniteResult;
10192 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
10193 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
10194 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
10195
10196 if (!DstVT.bitsEq(IntVT)) {
10197 // Store to stack before loading it back.
10198 assert(!IntVT.isVector() && IntVT.bitsGT(DstVT));
10199 // IntScalarVT is the original type that has the same width as DstVT.
10200 Align Alignment = DAG.getReducedAlign(IntScalarVT, /*UseABI=*/false);
10201 SDValue StackPtr =
10202 DAG.CreateStackTemporary(IntScalarVT.getStoreSize(), Alignment);
10203 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
10205 MachinePointerInfo PtrInfo =
10206 MachinePointerInfo::getFixedStack(MF, FrameIndex);
10207 SDValue Store = DAG.getTruncStore(DAG.getEntryNode(), dl, Result, StackPtr,
10208 PtrInfo, IntScalarVT, Alignment);
10209
10210 SDValue Load = DAG.getLoad(DstVT, dl, Store, StackPtr, PtrInfo, Alignment);
10211 return DAG.getMergeValues({Load, Load.getValue(1)}, dl);
10212 }
10213
10214 return DAG.getNode(ISD::BITCAST, dl, DstVT, Result);
10215}
10216
10218 SelectionDAG &DAG) const {
10219 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10220 SDValue Src = Node->getOperand(OpNo);
10221 EVT SrcVT = Src.getValueType();
10222 EVT DstVT = Node->getValueType(0);
10223 SDLoc dl(SDValue(Node, 0));
10224
10225 // FIXME: Only f32 to i64 conversions are supported.
10226 if (SrcVT != MVT::f32 || DstVT != MVT::i64)
10227 return false;
10228
10229 if (Node->isStrictFPOpcode())
10230 // When a NaN is converted to an integer a trap is allowed. We can't
10231 // use this expansion here because it would eliminate that trap. Other
10232 // traps are also allowed and cannot be eliminated. See
10233 // IEEE 754-2008 sec 5.8.
10234 return false;
10235
10236 // Expand f32 -> i64 conversion
10237 // This algorithm comes from compiler-rt's implementation of fixsfdi:
10238 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
10239 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
10240 EVT IntVT = SrcVT.changeTypeToInteger();
10241 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
10242
10243 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
10244 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
10245 SDValue Bias = DAG.getConstant(127, dl, IntVT);
10246 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
10247 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
10248 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
10249
10250 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
10251
10252 SDValue ExponentBits = DAG.getNode(
10253 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
10254 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
10255 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
10256
10257 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
10258 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
10259 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
10260 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
10261
10262 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
10263 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
10264 DAG.getConstant(0x00800000, dl, IntVT));
10265
10266 R = DAG.getZExtOrTrunc(R, dl, DstVT);
10267
10268 R = DAG.getSelectCC(
10269 dl, Exponent, ExponentLoBit,
10270 DAG.getNode(ISD::SHL, dl, DstVT, R,
10271 DAG.getZExtOrTrunc(
10272 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
10273 dl, IntShVT)),
10274 DAG.getNode(ISD::SRL, dl, DstVT, R,
10275 DAG.getZExtOrTrunc(
10276 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
10277 dl, IntShVT)),
10278 ISD::SETGT);
10279
10280 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
10281 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
10282
10283 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
10284 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
10285 return true;
10286}
10287
10289 SDValue &Chain,
10290 SelectionDAG &DAG) const {
10291 SDLoc dl(SDValue(Node, 0));
10292 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10293 SDValue Src = Node->getOperand(OpNo);
10294
10295 EVT SrcVT = Src.getValueType();
10296 EVT DstVT = Node->getValueType(0);
10297 EVT SetCCVT =
10298 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
10299 EVT DstSetCCVT =
10300 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
10301
10302 // Only expand vector types if we have the appropriate vector bit operations.
10303 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
10305 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
10307 return false;
10308
10309 // If the maximum float value is smaller then the signed integer range,
10310 // the destination signmask can't be represented by the float, so we can
10311 // just use FP_TO_SINT directly.
10312 const fltSemantics &APFSem = SrcVT.getFltSemantics();
10313 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
10314 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
10316 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
10317 if (Node->isStrictFPOpcode()) {
10318 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10319 { Node->getOperand(0), Src });
10320 Chain = Result.getValue(1);
10321 } else
10322 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10323 return true;
10324 }
10325
10326 // Don't expand it if there isn't cheap fsub instruction.
10328 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
10329 return false;
10330
10331 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
10332 SDValue Sel;
10333
10334 if (Node->isStrictFPOpcode()) {
10335 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
10336 Node->getOperand(0), /*IsSignaling*/ true);
10337 Chain = Sel.getValue(1);
10338 } else {
10339 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
10340 }
10341
10342 bool Strict = Node->isStrictFPOpcode() ||
10343 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
10344
10345 if (Strict) {
10346 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
10347 // signmask then offset (the result of which should be fully representable).
10348 // Sel = Src < 0x8000000000000000
10349 // FltOfs = select Sel, 0, 0x8000000000000000
10350 // IntOfs = select Sel, 0, 0x8000000000000000
10351 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
10352
10353 // TODO: Should any fast-math-flags be set for the FSUB?
10354 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
10355 DAG.getConstantFP(0.0, dl, SrcVT), Cst);
10356 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10357 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
10358 DAG.getConstant(0, dl, DstVT),
10359 DAG.getConstant(SignMask, dl, DstVT));
10360 SDValue SInt;
10361 if (Node->isStrictFPOpcode()) {
10362 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
10363 { Chain, Src, FltOfs });
10364 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10365 { Val.getValue(1), Val });
10366 Chain = SInt.getValue(1);
10367 } else {
10368 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
10369 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
10370 }
10371 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
10372 } else {
10373 // Expand based on maximum range of FP_TO_SINT:
10374 // True = fp_to_sint(Src)
10375 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
10376 // Result = select (Src < 0x8000000000000000), True, False
10377
10378 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10379 // TODO: Should any fast-math-flags be set for the FSUB?
10380 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
10381 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
10382 False = DAG.getNode(ISD::XOR, dl, DstVT, False,
10383 DAG.getConstant(SignMask, dl, DstVT));
10384 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10385 Result = DAG.getSelect(dl, DstVT, Sel, True, False);
10386 }
10387 return true;
10388}
10389
10391 SDValue &Chain, SelectionDAG &DAG) const {
10392 // This transform is not correct for converting 0 when rounding mode is set
10393 // to round toward negative infinity which will produce -0.0. So disable
10394 // under strictfp.
10395 if (Node->isStrictFPOpcode())
10396 return false;
10397
10398 SDValue Src = Node->getOperand(0);
10399 EVT SrcVT = Src.getValueType();
10400 EVT DstVT = Node->getValueType(0);
10401
10402 // If the input is known to be non-negative and SINT_TO_FP is legal then use
10403 // it.
10404 if (Node->getFlags().hasNonNeg() &&
10406 Result =
10407 DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), DstVT, Node->getOperand(0));
10408 return true;
10409 }
10410
10411 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
10412 return false;
10413
10414 // Only expand vector types if we have the appropriate vector bit
10415 // operations.
10416 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
10421 return false;
10422
10423 SDLoc dl(SDValue(Node, 0));
10424
10425 // Implementation of unsigned i64 to f64 following the algorithm in
10426 // __floatundidf in compiler_rt. This implementation performs rounding
10427 // correctly in all rounding modes with the exception of converting 0
10428 // when rounding toward negative infinity. In that case the fsub will
10429 // produce -0.0. This will be added to +0.0 and produce -0.0 which is
10430 // incorrect.
10431 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
10432 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
10433 llvm::bit_cast<double>(UINT64_C(0x4530000000100000)), dl, DstVT);
10434 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
10435 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
10436 SDValue HiShift = DAG.getShiftAmountConstant(32, SrcVT, dl);
10437
10438 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
10439 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
10440 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
10441 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
10442 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
10443 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
10444 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
10445 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
10446 return true;
10447}
10448
10449SDValue
10451 SelectionDAG &DAG) const {
10452 unsigned Opcode = Node->getOpcode();
10453 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
10454 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
10455 "Wrong opcode");
10456
10457 if (Node->getFlags().hasNoNaNs()) {
10458 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
10459 EVT VT = Node->getValueType(0);
10460 if ((!isCondCodeLegal(Pred, VT.getSimpleVT()) ||
10462 VT.isVector())
10463 return SDValue();
10464 SDValue Op1 = Node->getOperand(0);
10465 SDValue Op2 = Node->getOperand(1);
10466 return DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred,
10467 Node->getFlags());
10468 }
10469
10470 return SDValue();
10471}
10472
10474 SelectionDAG &DAG) const {
10475 if (SDValue Expanded = expandVectorNaryOpBySplitting(Node, DAG))
10476 return Expanded;
10477
10478 EVT VT = Node->getValueType(0);
10479 if (VT.isScalableVector())
10481 "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
10482
10483 SDLoc dl(Node);
10484 unsigned NewOp =
10486
10487 if (isOperationLegalOrCustom(NewOp, VT)) {
10488 SDValue Quiet0 = Node->getOperand(0);
10489 SDValue Quiet1 = Node->getOperand(1);
10490
10491 if (!Node->getFlags().hasNoNaNs()) {
10492 // Insert canonicalizes if it's possible we need to quiet to get correct
10493 // sNaN behavior.
10494 if (!DAG.isKnownNeverSNaN(Quiet0)) {
10495 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
10496 Node->getFlags());
10497 }
10498 if (!DAG.isKnownNeverSNaN(Quiet1)) {
10499 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
10500 Node->getFlags());
10501 }
10502 }
10503
10504 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
10505 }
10506
10507 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
10508 // instead if there are no NaNs.
10509 if (Node->getFlags().hasNoNaNs() ||
10510 (DAG.isKnownNeverNaN(Node->getOperand(0)) &&
10511 DAG.isKnownNeverNaN(Node->getOperand(1)))) {
10512 unsigned IEEE2018Op =
10513 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
10514 if (isOperationLegalOrCustom(IEEE2018Op, VT))
10515 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
10516 Node->getOperand(1), Node->getFlags());
10517 }
10518
10520 return SelCC;
10521
10522 return SDValue();
10523}
10524
10526 const TargetLowering &TLI,
10527 const SDLoc &DL, SDValue Val,
10528 FPClassTest FPClass) {
10529 EVT VT = Val.getValueType();
10530 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10531 EVT IntVT = VT.changeTypeToInteger();
10532 EVT FloatVT = VT.changeElementType(*DAG.getContext(), MVT::f32);
10533 SDValue TestZero = DAG.getTargetConstant(FPClass, DL, MVT::i32);
10534 if (!TLI.isTypeLegal(IntVT) &&
10536 Val = DAG.getNode(ISD::FP_ROUND, DL, FloatVT, Val,
10537 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true));
10538 return DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, Val, TestZero);
10539}
10540
10542 SelectionDAG &DAG) const {
10543 if (SDValue Expanded = expandVectorNaryOpBySplitting(N, DAG))
10544 return Expanded;
10545
10546 SDLoc DL(N);
10547 SDValue LHS = N->getOperand(0);
10548 SDValue RHS = N->getOperand(1);
10549 unsigned Opc = N->getOpcode();
10550 EVT VT = N->getValueType(0);
10551 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10552 bool IsMax = Opc == ISD::FMAXIMUM;
10553 SDNodeFlags Flags = N->getFlags();
10554
10555 // First, implement comparison not propagating NaN. If no native fmin or fmax
10556 // available, use plain select with setcc instead.
10558 unsigned CompOpcIeee = IsMax ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
10559 unsigned CompOpc = IsMax ? ISD::FMAXNUM : ISD::FMINNUM;
10560
10561 // FIXME: We should probably define fminnum/fmaxnum variants with correct
10562 // signed zero behavior.
10563 bool MinMaxMustRespectOrderedZero = false;
10564
10565 if (isOperationLegalOrCustom(CompOpcIeee, VT)) {
10566 MinMax = DAG.getNode(CompOpcIeee, DL, VT, LHS, RHS, Flags);
10567 MinMaxMustRespectOrderedZero = true;
10568 } else if (isOperationLegalOrCustom(CompOpc, VT)) {
10569 MinMax = DAG.getNode(CompOpc, DL, VT, LHS, RHS, Flags);
10570 } else {
10572 return DAG.UnrollVectorOp(N);
10573
10574 // NaN (if exists) will be propagated later, so orderness doesn't matter.
10575 SDValue Compare =
10576 DAG.getSetCC(DL, CCVT, LHS, RHS, IsMax ? ISD::SETOGT : ISD::SETOLT);
10577 MinMax = DAG.getSelect(DL, VT, Compare, LHS, RHS, Flags);
10578 }
10579
10580 // Propagate any NaN of both operands
10581 if (!N->getFlags().hasNoNaNs() &&
10582 (!DAG.isKnownNeverNaN(RHS) || !DAG.isKnownNeverNaN(LHS))) {
10583 ConstantFP *FPNaN = ConstantFP::get(*DAG.getContext(),
10585 MinMax = DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETUO),
10586 DAG.getConstantFP(*FPNaN, DL, VT), MinMax, Flags);
10587 }
10588
10589 // fminimum/fmaximum requires -0.0 less than +0.0
10590 if (!MinMaxMustRespectOrderedZero && !N->getFlags().hasNoSignedZeros() &&
10591 !DAG.isKnownNeverLogicalZero(RHS) && !DAG.isKnownNeverLogicalZero(LHS)) {
10592 SDValue IsEqual = DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETOEQ);
10594 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10595 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, RHS, Flags);
10596 MinMax = DAG.getSelect(DL, VT, IsEqual, RetZero, MinMax, Flags);
10597 }
10598
10599 return MinMax;
10600}
10601
10603 SelectionDAG &DAG) const {
10604 SDLoc DL(Node);
10605 SDValue LHS = Node->getOperand(0);
10606 SDValue RHS = Node->getOperand(1);
10607 unsigned Opc = Node->getOpcode();
10608 EVT VT = Node->getValueType(0);
10609 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10610 bool IsMax = Opc == ISD::FMAXIMUMNUM;
10611 SDNodeFlags Flags = Node->getFlags();
10612
10613 unsigned NewOp =
10615
10616 if (isOperationLegalOrCustom(NewOp, VT)) {
10617 if (!Flags.hasNoNaNs()) {
10618 // Insert canonicalizes if it's possible we need to quiet to get correct
10619 // sNaN behavior.
10620 if (!DAG.isKnownNeverSNaN(LHS)) {
10621 LHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, LHS, Flags);
10622 }
10623 if (!DAG.isKnownNeverSNaN(RHS)) {
10624 RHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, RHS, Flags);
10625 }
10626 }
10627
10628 return DAG.getNode(NewOp, DL, VT, LHS, RHS, Flags);
10629 }
10630
10631 // We can use FMINIMUM/FMAXIMUM if there is no NaN, since it has
10632 // same behaviors for all of other cases: +0.0 vs -0.0 included.
10633 if (Flags.hasNoNaNs() ||
10634 (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS))) {
10635 unsigned IEEE2019Op =
10637 if (isOperationLegalOrCustom(IEEE2019Op, VT))
10638 return DAG.getNode(IEEE2019Op, DL, VT, LHS, RHS, Flags);
10639 }
10640
10641 // FMINNUM/FMAXMUM returns qNaN if either operand is sNaN, and it may return
10642 // either one for +0.0 vs -0.0.
10643 if ((Flags.hasNoNaNs() ||
10644 (DAG.isKnownNeverSNaN(LHS) && DAG.isKnownNeverSNaN(RHS))) &&
10645 (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10646 DAG.isKnownNeverLogicalZero(RHS))) {
10647 unsigned IEEE2008Op = Opc == ISD::FMINIMUMNUM ? ISD::FMINNUM : ISD::FMAXNUM;
10648 if (isOperationLegalOrCustom(IEEE2008Op, VT))
10649 return DAG.getNode(IEEE2008Op, DL, VT, LHS, RHS, Flags);
10650 }
10651
10652 if (VT.isVector() &&
10655 return DAG.UnrollVectorOp(Node);
10656
10657 // If only one operand is NaN, override it with another operand.
10658 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(LHS)) {
10659 LHS = DAG.getSelectCC(DL, LHS, LHS, RHS, LHS, ISD::SETUO);
10660 }
10661 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(RHS)) {
10662 RHS = DAG.getSelectCC(DL, RHS, RHS, LHS, RHS, ISD::SETUO);
10663 }
10664
10665 // Always prefer RHS if equal.
10666 SDValue MinMax =
10667 DAG.getSelectCC(DL, LHS, RHS, LHS, RHS, IsMax ? ISD::SETGT : ISD::SETLT);
10668
10669 // TODO: We need quiet sNaN if strictfp.
10670
10671 // Fixup signed zero behavior.
10672 if (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10673 DAG.isKnownNeverLogicalZero(RHS)) {
10674 return MinMax;
10675 }
10676 SDValue IsZero = DAG.getSetCC(DL, CCVT, MinMax,
10677 DAG.getConstantFP(0.0, DL, VT), ISD::SETEQ);
10679 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10680 // It's OK to select from LHS and MinMax, with only one ISD::IS_FPCLASS, as
10681 // we preferred RHS when generate MinMax, if the operands are equal.
10682 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, MinMax, Flags);
10683 return DAG.getSelect(DL, VT, IsZero, RetZero, MinMax, Flags);
10684}
10685
10686/// Returns a true value if if this FPClassTest can be performed with an ordered
10687/// fcmp to 0, and a false value if it's an unordered fcmp to 0. Returns
10688/// std::nullopt if it cannot be performed as a compare with 0.
10689static std::optional<bool> isFCmpEqualZero(FPClassTest Test,
10690 const fltSemantics &Semantics,
10691 const MachineFunction &MF) {
10692 FPClassTest OrderedMask = Test & ~fcNan;
10693 FPClassTest NanTest = Test & fcNan;
10694 bool IsOrdered = NanTest == fcNone;
10695 bool IsUnordered = NanTest == fcNan;
10696
10697 // Skip cases that are testing for only a qnan or snan.
10698 if (!IsOrdered && !IsUnordered)
10699 return std::nullopt;
10700
10701 if (OrderedMask == fcZero &&
10702 MF.getDenormalMode(Semantics).Input == DenormalMode::IEEE)
10703 return IsOrdered;
10704 if (OrderedMask == (fcZero | fcSubnormal) &&
10705 MF.getDenormalMode(Semantics).inputsAreZero())
10706 return IsOrdered;
10707 return std::nullopt;
10708}
10709
10711 const FPClassTest OrigTestMask,
10712 SDNodeFlags Flags, const SDLoc &DL,
10713 SelectionDAG &DAG) const {
10714 EVT OperandVT = Op.getValueType();
10715 assert(OperandVT.isFloatingPoint());
10716 FPClassTest Test = OrigTestMask;
10717
10718 // Degenerated cases.
10719 if (Test == fcNone)
10720 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT);
10721 if (Test == fcAllFlags)
10722 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT);
10723
10724 // PPC double double is a pair of doubles, of which the higher part determines
10725 // the value class.
10726 if (OperandVT == MVT::ppcf128) {
10727 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op,
10728 DAG.getConstant(1, DL, MVT::i32));
10729 OperandVT = MVT::f64;
10730 }
10731
10732 // Floating-point type properties.
10733 EVT ScalarFloatVT = OperandVT.getScalarType();
10734 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext());
10735 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics();
10736 bool IsF80 = (ScalarFloatVT == MVT::f80);
10737
10738 // Some checks can be implemented using float comparisons, if floating point
10739 // exceptions are ignored.
10740 if (Flags.hasNoFPExcept() &&
10742 FPClassTest FPTestMask = Test;
10743 bool IsInvertedFP = false;
10744
10745 if (FPClassTest InvertedFPCheck =
10746 invertFPClassTestIfSimpler(FPTestMask, true)) {
10747 FPTestMask = InvertedFPCheck;
10748 IsInvertedFP = true;
10749 }
10750
10751 ISD::CondCode OrderedCmpOpcode = IsInvertedFP ? ISD::SETUNE : ISD::SETOEQ;
10752 ISD::CondCode UnorderedCmpOpcode = IsInvertedFP ? ISD::SETONE : ISD::SETUEQ;
10753
10754 // See if we can fold an | fcNan into an unordered compare.
10755 FPClassTest OrderedFPTestMask = FPTestMask & ~fcNan;
10756
10757 // Can't fold the ordered check if we're only testing for snan or qnan
10758 // individually.
10759 if ((FPTestMask & fcNan) != fcNan)
10760 OrderedFPTestMask = FPTestMask;
10761
10762 const bool IsOrdered = FPTestMask == OrderedFPTestMask;
10763
10764 if (std::optional<bool> IsCmp0 =
10765 isFCmpEqualZero(FPTestMask, Semantics, DAG.getMachineFunction());
10766 IsCmp0 && (isCondCodeLegalOrCustom(
10767 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode,
10768 OperandVT.getScalarType().getSimpleVT()))) {
10769
10770 // If denormals could be implicitly treated as 0, this is not equivalent
10771 // to a compare with 0 since it will also be true for denormals.
10772 return DAG.getSetCC(DL, ResultVT, Op,
10773 DAG.getConstantFP(0.0, DL, OperandVT),
10774 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode);
10775 }
10776
10777 if (FPTestMask == fcNan &&
10779 OperandVT.getScalarType().getSimpleVT()))
10780 return DAG.getSetCC(DL, ResultVT, Op, Op,
10781 IsInvertedFP ? ISD::SETO : ISD::SETUO);
10782
10783 bool IsOrderedInf = FPTestMask == fcInf;
10784 if ((FPTestMask == fcInf || FPTestMask == (fcInf | fcNan)) &&
10785 isCondCodeLegalOrCustom(IsOrderedInf ? OrderedCmpOpcode
10786 : UnorderedCmpOpcode,
10787 OperandVT.getScalarType().getSimpleVT()) &&
10790 (OperandVT.isVector() &&
10792 // isinf(x) --> fabs(x) == inf
10793 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10794 SDValue Inf =
10795 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10796 return DAG.getSetCC(DL, ResultVT, Abs, Inf,
10797 IsOrderedInf ? OrderedCmpOpcode : UnorderedCmpOpcode);
10798 }
10799
10800 if ((OrderedFPTestMask == fcPosInf || OrderedFPTestMask == fcNegInf) &&
10801 isCondCodeLegalOrCustom(IsOrdered ? OrderedCmpOpcode
10802 : UnorderedCmpOpcode,
10803 OperandVT.getSimpleVT())) {
10804 // isposinf(x) --> x == inf
10805 // isneginf(x) --> x == -inf
10806 // isposinf(x) || nan --> x u== inf
10807 // isneginf(x) || nan --> x u== -inf
10808
10809 SDValue Inf = DAG.getConstantFP(
10810 APFloat::getInf(Semantics, OrderedFPTestMask == fcNegInf), DL,
10811 OperandVT);
10812 return DAG.getSetCC(DL, ResultVT, Op, Inf,
10813 IsOrdered ? OrderedCmpOpcode : UnorderedCmpOpcode);
10814 }
10815
10816 if (OrderedFPTestMask == (fcSubnormal | fcZero) && !IsOrdered) {
10817 // TODO: Could handle ordered case, but it produces worse code for
10818 // x86. Maybe handle ordered if fabs is free?
10819
10820 ISD::CondCode OrderedOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10821 ISD::CondCode UnorderedOp = IsInvertedFP ? ISD::SETOGE : ISD::SETULT;
10822
10823 if (isCondCodeLegalOrCustom(IsOrdered ? OrderedOp : UnorderedOp,
10824 OperandVT.getScalarType().getSimpleVT())) {
10825 // (issubnormal(x) || iszero(x)) --> fabs(x) < smallest_normal
10826
10827 // TODO: Maybe only makes sense if fabs is free. Integer test of
10828 // exponent bits seems better for x86.
10829 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10830 SDValue SmallestNormal = DAG.getConstantFP(
10831 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
10832 return DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal,
10833 IsOrdered ? OrderedOp : UnorderedOp);
10834 }
10835 }
10836
10837 if (FPTestMask == fcNormal) {
10838 // TODO: Handle unordered
10839 ISD::CondCode IsFiniteOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10840 ISD::CondCode IsNormalOp = IsInvertedFP ? ISD::SETOLT : ISD::SETUGE;
10841
10842 if (isCondCodeLegalOrCustom(IsFiniteOp,
10843 OperandVT.getScalarType().getSimpleVT()) &&
10844 isCondCodeLegalOrCustom(IsNormalOp,
10845 OperandVT.getScalarType().getSimpleVT()) &&
10846 isFAbsFree(OperandVT)) {
10847 // isnormal(x) --> fabs(x) < infinity && !(fabs(x) < smallest_normal)
10848 SDValue Inf =
10849 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10850 SDValue SmallestNormal = DAG.getConstantFP(
10851 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
10852
10853 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10854 SDValue IsFinite = DAG.getSetCC(DL, ResultVT, Abs, Inf, IsFiniteOp);
10855 SDValue IsNormal =
10856 DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal, IsNormalOp);
10857 unsigned LogicOp = IsInvertedFP ? ISD::OR : ISD::AND;
10858 return DAG.getNode(LogicOp, DL, ResultVT, IsFinite, IsNormal);
10859 }
10860 }
10861 }
10862
10863 // Some checks may be represented as inversion of simpler check, for example
10864 // "inf|normal|subnormal|zero" => !"nan".
10865 bool IsInverted = false;
10866
10867 if (FPClassTest InvertedCheck = invertFPClassTestIfSimpler(Test, false)) {
10868 Test = InvertedCheck;
10869 IsInverted = true;
10870 }
10871
10872 // In the general case use integer operations.
10873 unsigned BitSize = OperandVT.getScalarSizeInBits();
10874 EVT IntVT = OperandVT.changeElementType(
10875 *DAG.getContext(), EVT::getIntegerVT(*DAG.getContext(), BitSize));
10876 SDValue OpAsInt = DAG.getBitcast(IntVT, Op);
10877
10878 // Various masks.
10879 APInt SignBit = APInt::getSignMask(BitSize);
10880 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign.
10881 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit.
10882 const unsigned ExplicitIntBitInF80 = 63;
10883 APInt ExpMask = Inf;
10884 if (IsF80)
10885 ExpMask.clearBit(ExplicitIntBitInF80);
10886 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf;
10887 APInt QNaNBitMask =
10888 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1);
10889 APInt InversionMask = APInt::getAllOnes(ResultVT.getScalarSizeInBits());
10890
10891 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT);
10892 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT);
10893 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT);
10894 SDValue ZeroV = DAG.getConstant(0, DL, IntVT);
10895 SDValue InfV = DAG.getConstant(Inf, DL, IntVT);
10896 SDValue ResultInversionMask = DAG.getConstant(InversionMask, DL, ResultVT);
10897
10898 SDValue Res;
10899 const auto appendResult = [&](SDValue PartialRes) {
10900 if (PartialRes) {
10901 if (Res)
10902 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes);
10903 else
10904 Res = PartialRes;
10905 }
10906 };
10907
10908 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set.
10909 const auto getIntBitIsSet = [&]() -> SDValue {
10910 if (!IntBitIsSetV) {
10911 APInt IntBitMask(BitSize, 0);
10912 IntBitMask.setBit(ExplicitIntBitInF80);
10913 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT);
10914 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV);
10915 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE);
10916 }
10917 return IntBitIsSetV;
10918 };
10919
10920 // Split the value into sign bit and absolute value.
10921 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV);
10922 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt,
10923 DAG.getConstant(0, DL, IntVT), ISD::SETLT);
10924
10925 // Tests that involve more than one class should be processed first.
10926 SDValue PartialRes;
10927
10928 if (IsF80)
10929 ; // Detect finite numbers of f80 by checking individual classes because
10930 // they have different settings of the explicit integer bit.
10931 else if ((Test & fcFinite) == fcFinite) {
10932 // finite(V) ==> (a << 1) < (inf << 1)
10933 //
10934 // See https://github.com/llvm/llvm-project/issues/169270, this is slightly
10935 // shorter than the `finite(V) ==> abs(V) < exp_mask` formula used before.
10936
10938 "finite check requires IEEE-like FP");
10939
10940 SDValue One = DAG.getShiftAmountConstant(1, IntVT, DL);
10941 SDValue TwiceOp = DAG.getNode(ISD::SHL, DL, IntVT, OpAsInt, One);
10942 SDValue TwiceInf = DAG.getNode(ISD::SHL, DL, IntVT, ExpMaskV, One);
10943
10944 PartialRes = DAG.getSetCC(DL, ResultVT, TwiceOp, TwiceInf, ISD::SETULT);
10945 Test &= ~fcFinite;
10946 } else if ((Test & fcFinite) == fcPosFinite) {
10947 // finite(V) && V > 0 ==> V < exp_mask
10948 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT);
10949 Test &= ~fcPosFinite;
10950 } else if ((Test & fcFinite) == fcNegFinite) {
10951 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1
10952 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
10953 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
10954 Test &= ~fcNegFinite;
10955 }
10956 appendResult(PartialRes);
10957
10958 if (FPClassTest PartialCheck = Test & (fcZero | fcSubnormal)) {
10959 // fcZero | fcSubnormal => test all exponent bits are 0
10960 // TODO: Handle sign bit specific cases
10961 if (PartialCheck == (fcZero | fcSubnormal)) {
10962 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ExpMaskV);
10963 SDValue ExpIsZero =
10964 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
10965 appendResult(ExpIsZero);
10966 Test &= ~PartialCheck & fcAllFlags;
10967 }
10968 }
10969
10970 // Check for individual classes.
10971
10972 if (unsigned PartialCheck = Test & fcZero) {
10973 if (PartialCheck == fcPosZero)
10974 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ);
10975 else if (PartialCheck == fcZero)
10976 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ);
10977 else // ISD::fcNegZero
10978 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ);
10979 appendResult(PartialRes);
10980 }
10981
10982 if (unsigned PartialCheck = Test & fcSubnormal) {
10983 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set)
10984 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set)
10985 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV;
10986 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT);
10987 SDValue VMinusOneV =
10988 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT));
10989 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT);
10990 if (PartialCheck == fcNegSubnormal)
10991 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
10992 appendResult(PartialRes);
10993 }
10994
10995 if (unsigned PartialCheck = Test & fcInf) {
10996 if (PartialCheck == fcPosInf)
10997 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ);
10998 else if (PartialCheck == fcInf)
10999 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ);
11000 else { // ISD::fcNegInf
11001 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt();
11002 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT);
11003 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ);
11004 }
11005 appendResult(PartialRes);
11006 }
11007
11008 if (unsigned PartialCheck = Test & fcNan) {
11009 APInt InfWithQnanBit = Inf | QNaNBitMask;
11010 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT);
11011 if (PartialCheck == fcNan) {
11012 // isnan(V) ==> abs(V) > int(inf)
11013 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
11014 if (IsF80) {
11015 // Recognize unsupported values as NaNs for compatibility with glibc.
11016 // In them (exp(V)==0) == int_bit.
11017 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV);
11018 SDValue ExpIsZero =
11019 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
11020 SDValue IsPseudo =
11021 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ);
11022 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo);
11023 }
11024 } else if (PartialCheck == fcQNan) {
11025 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit)
11026 PartialRes =
11027 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE);
11028 } else { // ISD::fcSNan
11029 // issignaling(V) ==> abs(V) > unsigned(Inf) &&
11030 // abs(V) < (unsigned(Inf) | quiet_bit)
11031 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
11032 SDValue IsNotQnan =
11033 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT);
11034 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan);
11035 }
11036 appendResult(PartialRes);
11037 }
11038
11039 if (unsigned PartialCheck = Test & fcNormal) {
11040 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1))
11041 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1));
11042 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT);
11043 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV);
11044 APInt ExpLimit = ExpMask - ExpLSB;
11045 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT);
11046 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT);
11047 if (PartialCheck == fcNegNormal)
11048 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
11049 else if (PartialCheck == fcPosNormal) {
11050 SDValue PosSignV =
11051 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInversionMask);
11052 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV);
11053 }
11054 if (IsF80)
11055 PartialRes =
11056 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet());
11057 appendResult(PartialRes);
11058 }
11059
11060 if (!Res)
11061 return DAG.getConstant(IsInverted, DL, ResultVT);
11062 if (IsInverted)
11063 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInversionMask);
11064 return Res;
11065}
11066
11067// Only expand vector types if we have the appropriate vector bit operations.
11068static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) {
11069 assert(VT.isVector() && "Expected vector type");
11070 unsigned Len = VT.getScalarSizeInBits();
11071 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
11074 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
11076}
11077
11079 SDLoc dl(Node);
11080 EVT VT = Node->getValueType(0);
11081 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11082 SDValue Op = Node->getOperand(0);
11083 unsigned Len = VT.getScalarSizeInBits();
11084
11085 // Compute effective bit width from known bits, allowing us to shift the
11086 // active bits down if necessary to fit into smaller specialized expansions.
11088 unsigned LZ = Known.countMinLeadingZeros();
11089 unsigned TZ = Known.countMinTrailingZeros();
11090 unsigned ShiftedActiveBits = Known.getBitWidth() - (LZ + TZ);
11091
11092 // Round up to 8-bit boundary for byte-oriented SWAR algorithm
11093 unsigned EffectiveLen = Len;
11094 if (ShiftedActiveBits > 0 && ShiftedActiveBits < Len)
11095 EffectiveLen = std::min(alignTo(ShiftedActiveBits, 8), Len);
11096
11097 assert(VT.isInteger() && "CTPOP not implemented for this type.");
11098
11099 // TODO: Add support for irregular type lengths.
11100 if (!(Len <= 128 && Len % 8 == 0))
11101 return SDValue();
11102
11103 // Only expand vector types if we have the appropriate vector bit operations.
11104 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
11105 return SDValue();
11106
11107 // If the active bits are not at the low end, shift them down
11108 if (EffectiveLen < Len && TZ > 0) {
11109 Op = DAG.getNode(ISD::SRL, dl, VT, Op,
11110 DAG.getShiftAmountConstant(TZ, VT, dl));
11111 }
11112
11113 // This is the "best" algorithm from
11114 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
11115 SDValue Mask55 =
11116 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
11117 SDValue Mask33 =
11118 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
11119 SDValue Mask0F =
11120 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
11121
11122 // v = v - ((v >> 1) & 0x55555555...)
11123 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
11124 DAG.getNode(ISD::AND, dl, VT,
11125 DAG.getNode(ISD::SRL, dl, VT, Op,
11126 DAG.getConstant(1, dl, ShVT)),
11127 Mask55));
11128 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
11129 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
11130 DAG.getNode(ISD::AND, dl, VT,
11131 DAG.getNode(ISD::SRL, dl, VT, Op,
11132 DAG.getConstant(2, dl, ShVT)),
11133 Mask33));
11134 // v = (v + (v >> 4)) & 0x0F0F0F0F...
11135 Op = DAG.getNode(ISD::AND, dl, VT,
11136 DAG.getNode(ISD::ADD, dl, VT, Op,
11137 DAG.getNode(ISD::SRL, dl, VT, Op,
11138 DAG.getConstant(4, dl, ShVT))),
11139 Mask0F);
11140
11141 if (EffectiveLen <= 8)
11142 return Op;
11143
11144 // Avoid the multiply if we only have 2 bytes to add.
11145 // TODO: Only doing this for scalars because vectors weren't as obviously
11146 // improved.
11147 if (EffectiveLen == 16 && !VT.isVector()) {
11148 // v = (v + (v >> 8)) & 0x00FF;
11149 return DAG.getNode(ISD::AND, dl, VT,
11150 DAG.getNode(ISD::ADD, dl, VT, Op,
11151 DAG.getNode(ISD::SRL, dl, VT, Op,
11152 DAG.getConstant(8, dl, ShVT))),
11153 DAG.getConstant(0xFF, dl, VT));
11154 }
11155
11156 // v = (v * 0x01010101...) >> (Len - 8)
11157 SDValue V;
11160 SDValue Mask01 =
11161 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
11162 V = DAG.getNode(ISD::MUL, dl, VT, Op, Mask01);
11163 } else {
11164 V = Op;
11165 for (unsigned Shift = 8; Shift < EffectiveLen; Shift *= 2) {
11166 SDValue ShiftC = DAG.getShiftAmountConstant(Shift, VT, dl);
11167 V = DAG.getNode(ISD::ADD, dl, VT, V,
11168 DAG.getNode(ISD::SHL, dl, VT, V, ShiftC));
11169 }
11170 }
11171 return DAG.getNode(ISD::SRL, dl, VT, V, DAG.getConstant(Len - 8, dl, ShVT));
11172}
11173
11175 SDLoc dl(Node);
11176 EVT VT = Node->getValueType(0);
11177 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11178 SDValue Op = Node->getOperand(0);
11179 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11180
11181 // If the non-ZERO_POISON version is supported we can use that instead.
11182 if (Node->getOpcode() == ISD::CTLZ_ZERO_POISON &&
11184 return DAG.getNode(ISD::CTLZ, dl, VT, Op);
11185
11186 // If the ZERO_POISON version is supported use that and handle the zero case.
11188 EVT SetCCVT =
11189 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11190 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Op);
11191 SDValue Zero = DAG.getConstant(0, dl, VT);
11192 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11193 return DAG.getSelect(dl, VT, SrcIsZero,
11194 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
11195 }
11196
11197 // Only expand vector types if we have the appropriate vector bit operations.
11198 // This includes the operations needed to expand CTPOP if it isn't supported.
11199 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11201 !canExpandVectorCTPOP(*this, VT)) ||
11204 return SDValue();
11205
11206 // for now, we do this:
11207 // x = x | (x >> 1);
11208 // x = x | (x >> 2);
11209 // ...
11210 // x = x | (x >>16);
11211 // x = x | (x >>32); // for 64-bit input
11212 // return popcount(~x);
11213 //
11214 // Ref: "Hacker's Delight" by Henry Warren
11215 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) {
11216 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
11217 Op = DAG.getNode(ISD::OR, dl, VT, Op,
11218 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
11219 }
11220 Op = DAG.getNOT(dl, Op, VT);
11221 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
11222}
11223
11225 SDLoc dl(Node);
11226 EVT VT = Node->getValueType(0);
11227 SDValue Op = DAG.getFreeze(Node->getOperand(0));
11228 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11229
11230 // CTLS(x) = CTLZ(OR(SHL(XOR(x, SRA(x, BW-1)), 1), 1))
11231 // This transforms the sign bits into leading zeros that can be counted.
11232 SDValue ShiftAmt = DAG.getShiftAmountConstant(NumBitsPerElt - 1, VT, dl);
11233 SDValue SignBit = DAG.getNode(ISD::SRA, dl, VT, Op, ShiftAmt);
11234 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, SignBit);
11235 SDValue Shl =
11236 DAG.getNode(ISD::SHL, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11237 SDValue Or = DAG.getNode(ISD::OR, dl, VT, Shl, DAG.getConstant(1, dl, VT));
11238 return DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Or);
11239}
11240
11242 const SDLoc &DL, EVT VT, SDValue Op,
11243 unsigned BitWidth) const {
11244 if (BitWidth != 32 && BitWidth != 64)
11245 return SDValue();
11246
11247 const DataLayout &TD = DAG.getDataLayout();
11249 return SDValue();
11250
11251 APInt DeBruijn = BitWidth == 32 ? APInt(32, 0x077CB531U)
11252 : APInt(64, 0x0218A392CD3D5DBFULL);
11253 MachinePointerInfo PtrInfo =
11255 unsigned ShiftAmt = BitWidth - Log2_32(BitWidth);
11256 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11257 SDValue Lookup = DAG.getNode(
11258 ISD::SRL, DL, VT,
11259 DAG.getNode(ISD::MUL, DL, VT, DAG.getNode(ISD::AND, DL, VT, Op, Neg),
11260 DAG.getConstant(DeBruijn, DL, VT)),
11261 DAG.getShiftAmountConstant(ShiftAmt, VT, DL));
11263
11265 for (unsigned i = 0; i < BitWidth; i++) {
11266 APInt Shl = DeBruijn.shl(i);
11267 APInt Lshr = Shl.lshr(ShiftAmt);
11268 Table[Lshr.getZExtValue()] = i;
11269 }
11270
11271 // Create a ConstantArray in Constant Pool
11272 auto *CA = ConstantDataArray::get(*DAG.getContext(), Table);
11273 SDValue CPIdx = DAG.getConstantPool(CA, getPointerTy(TD),
11274 TD.getPrefTypeAlign(CA->getType()));
11275 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getEntryNode(),
11276 DAG.getMemBasePlusOffset(CPIdx, Lookup, DL),
11277 PtrInfo, MVT::i8);
11278 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON)
11279 return ExtLoad;
11280
11281 EVT SetCCVT =
11282 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11283 SDValue Zero = DAG.getConstant(0, DL, VT);
11284 SDValue SrcIsZero = DAG.getSetCC(DL, SetCCVT, Op, Zero, ISD::SETEQ);
11285 return DAG.getSelect(DL, VT, SrcIsZero,
11286 DAG.getConstant(BitWidth, DL, VT), ExtLoad);
11287}
11288
11290 SDLoc dl(Node);
11291 EVT VT = Node->getValueType(0);
11292 SDValue Op = Node->getOperand(0);
11293 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11294
11295 // If the non-ZERO_POISON version is supported we can use that instead.
11296 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON &&
11298 return DAG.getNode(ISD::CTTZ, dl, VT, Op);
11299
11300 // If the ZERO_POISON version is supported use that and handle the zero case.
11302 EVT SetCCVT =
11303 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11304 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_POISON, dl, VT, Op);
11305 SDValue Zero = DAG.getConstant(0, dl, VT);
11306 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11307 return DAG.getSelect(dl, VT, SrcIsZero,
11308 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
11309 }
11310
11311 // Only expand vector types if we have the appropriate vector bit operations.
11312 // This includes the operations needed to expand CTPOP if it isn't supported.
11313 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11316 !canExpandVectorCTPOP(*this, VT)) ||
11320 return SDValue();
11321
11322 // Emit Table Lookup if ISD::CTPOP used in the fallback path below is going
11323 // to be expanded or converted to a libcall.
11326 if (SDValue V = CTTZTableLookup(Node, DAG, dl, VT, Op, NumBitsPerElt))
11327 return V;
11328
11329 bool UseCTLZ =
11331
11332 // When only ctlz is available and the operand is nonzero we can use:
11333 // { return nlz(x & -x) ^ 31; }
11334 // which is more efficient than:
11335 // { return 32 - nlz(~x & (x - 1)); }.
11336 if (UseCTLZ && Node->getOpcode() == ISD::CTTZ_ZERO_POISON) {
11337 SDValue LowestBit =
11338 DAG.getNode(ISD::AND, dl, VT, Op, DAG.getNegative(Op, dl, VT));
11339 return DAG.getNode(ISD::XOR, dl, VT,
11340 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, LowestBit),
11341 DAG.getConstant(NumBitsPerElt - 1, dl, VT));
11342 }
11343
11344 // If ctpop is available, we use:
11345 // { return popcount(~x & (x-1)); }
11346 // If the target has ctlz but not ctpop, we use:
11347 // { return 32 - nlz(~x & (x-1)); }
11348 // Ref: "Hacker's Delight" by Henry Warren
11349 SDValue Tmp = DAG.getNode(
11350 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
11351 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
11352
11353 if (UseCTLZ)
11354 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
11355 DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
11356
11357 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
11358}
11359
11361 SelectionDAG &DAG) const {
11362 // %cond = to_bool_vec %source
11363 // %splat = splat /*val=*/VL
11364 // %tz = step_vector
11365 // %v = select %cond, /*true=*/tz, /*false=*/%splat
11366 // %r = vp.reduce.umin %v
11367 SDLoc DL(N);
11368 SDValue Source = N->getOperand(0);
11369 SDValue Mask = N->getOperand(1);
11370 SDValue EVL = N->getOperand(2);
11371 EVT SrcVT = Source.getValueType();
11372 EVT ResVT = N->getValueType(0);
11373 EVT ResVecVT =
11374 EVT::getVectorVT(*DAG.getContext(), ResVT, SrcVT.getVectorElementCount());
11375
11376 // Convert to boolean vector.
11377 if (SrcVT.getScalarType() != MVT::i1) {
11378 SDValue AllZero = DAG.getConstant(0, DL, SrcVT);
11379 SrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
11380 SrcVT.getVectorElementCount());
11381 Source = DAG.getSetCC(DL, SrcVT, Source, AllZero, ISD::SETNE);
11382 }
11383
11384 SDValue ExtEVL = DAG.getZExtOrTrunc(EVL, DL, ResVT);
11385 SDValue Splat = DAG.getSplat(ResVecVT, DL, ExtEVL);
11386 SDValue StepVec = DAG.getStepVector(DL, ResVecVT);
11387 SDValue Select = DAG.getSelect(DL, ResVecVT, Source, StepVec, Splat);
11388 return DAG.getNode(ISD::VP_REDUCE_UMIN, DL, ResVT, ExtEVL, Select, Mask, EVL);
11389}
11390
11391/// Returns a type-legalized version of \p Mask as the first item in the
11392/// pair. The second item contains a type-legalized step vector that's
11393/// guaranteed to fit the number of elements in \p Mask.
11394/// If the stepvector would require splitting, returns an empty SDValue
11395/// as the second item to signal that the operation should be split instead.
11396static std::pair<SDValue, SDValue>
11398 SelectionDAG &DAG) {
11399 EVT MaskVT = Mask.getValueType();
11400 EVT BoolVT = MaskVT.getScalarType();
11401
11402 // Find a suitable type for a stepvector.
11403 // If zero is poison, we can assume the upper limit of the result is VF-1.
11404 ConstantRange VScaleRange(1, /*isFullSet=*/true); // Fixed length default.
11405 if (MaskVT.isScalableVector())
11406 VScaleRange = getVScaleRange(&DAG.getMachineFunction().getFunction(), 64);
11407 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11408 uint64_t EltWidth = TLI.getBitWidthForCttzElements(
11409 EVT(TLI.getVectorIdxTy(DAG.getDataLayout())),
11410 MaskVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
11411 // If the step vector element type is smaller than the mask element type,
11412 // use the mask type directly to avoid widening issues.
11413 EltWidth = std::max(EltWidth, BoolVT.getFixedSizeInBits());
11414 EVT StepVT = MVT::getIntegerVT(EltWidth);
11415 EVT StepVecVT = MaskVT.changeVectorElementType(*DAG.getContext(), StepVT);
11416
11417 // If promotion or widening is required to make the type legal, do it here.
11418 // Promotion of integers within LegalizeVectorOps is looking for types of
11419 // the same size but with a smaller number of larger elements, not the usual
11420 // larger size with the same number of larger elements.
11422 TLI.getTypeAction(*DAG.getContext(), StepVecVT);
11423 SDValue StepVec;
11424 if (TypeAction == TargetLowering::TypePromoteInteger) {
11425 StepVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11426 StepVec = DAG.getStepVector(DL, StepVecVT);
11427 } else if (TypeAction == TargetLowering::TypeWidenVector) {
11428 // For widening, the element count changes. Create a step vector with only
11429 // the original elements valid and zeros for padding. Also widen the mask.
11430 EVT WideVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11431 unsigned WideNumElts = WideVecVT.getVectorNumElements();
11432
11433 // Build widened step vector: <0, 1, ..., OrigNumElts-1, poison, poison, ..>
11434 SDValue OrigStepVec = DAG.getStepVector(DL, StepVecVT);
11435 SDValue UndefStep = DAG.getPOISON(WideVecVT);
11436 StepVec = DAG.getInsertSubvector(DL, UndefStep, OrigStepVec, 0);
11437
11438 // Widen mask: pad with zeros.
11439 EVT WideMaskVT = EVT::getVectorVT(*DAG.getContext(), BoolVT, WideNumElts);
11440 SDValue ZeroMask = DAG.getConstant(0, DL, WideMaskVT);
11441 Mask = DAG.getInsertSubvector(DL, ZeroMask, Mask, 0);
11442 } else if (TypeAction == TargetLowering::TypeSplitVector) {
11443 // The stepvector type would require splitting. Signal to the caller
11444 // that the operation should be split instead of expanded.
11445 return {Mask, SDValue()};
11446 } else {
11447 StepVec = DAG.getStepVector(DL, StepVecVT);
11448 }
11449
11450 return {Mask, StepVec};
11451}
11452
11454 SelectionDAG &DAG) const {
11455 SDLoc DL(N);
11456 auto [Mask, StepVec] = getLegalMaskAndStepVector(
11457 N->getOperand(0), /*ZeroIsPoison=*/true, DL, DAG);
11458
11459 // If StepVec is empty, the stepvector would require splitting.
11460 // Split the operation instead and let it be recursively legalized.
11461 if (!StepVec) {
11462 EVT MaskVT = N->getOperand(0).getValueType();
11463 EVT ResVT = N->getValueType(0);
11464
11465 // Split the mask
11466 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(MaskVT);
11467 auto [MaskLo, MaskHi] = DAG.SplitVector(N->getOperand(0), DL);
11468
11469 // Create split VECTOR_FIND_LAST_ACTIVE operations
11470 SDValue LoResult =
11471 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskLo);
11472 SDValue HiResult =
11473 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskHi);
11474
11475 // Check if any lane is active in the high mask.
11476 SDValue AnyHiActive = DAG.getNode(ISD::VECREDUCE_OR, DL, MVT::i1, MaskHi);
11478 AnyHiActive, DL,
11479 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i1),
11480 MVT::i1);
11481
11482 // Adjust HiResult by adding the number of elements in Lo
11483 SDValue LoNumElts =
11484 DAG.getElementCount(DL, ResVT, LoVT.getVectorElementCount());
11485 SDValue AdjustedHiResult =
11486 DAG.getNode(ISD::ADD, DL, ResVT, HiResult, LoNumElts);
11487
11488 // Return: AnyHiActive ? AdjustedHiResult : LoResult;
11489 return DAG.getNode(ISD::SELECT, DL, ResVT, Cond, AdjustedHiResult,
11490 LoResult);
11491 }
11492
11493 EVT StepVecVT = StepVec.getValueType();
11494 EVT StepVT = StepVec.getValueType().getVectorElementType();
11495
11496 // Zero out lanes with inactive elements, then find the highest remaining
11497 // value from the stepvector.
11498 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
11499 SDValue ActiveElts = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
11500 SDValue HighestIdx = DAG.getNode(ISD::VECREDUCE_UMAX, DL, StepVT, ActiveElts);
11501 return DAG.getZExtOrTrunc(HighestIdx, DL, N->getValueType(0));
11502}
11503
11505 SelectionDAG &DAG) const {
11506 SDLoc DL(N);
11507 EVT VT = N->getValueType(0);
11508 SDValue SourceValue = N->getOperand(0);
11509 SDValue SinkValue = N->getOperand(1);
11510 SDValue EltSizeInBytes = N->getOperand(2);
11511
11512 // Note: The lane offset is scalable if the mask is scalable.
11513 ElementCount LaneOffsetEC =
11514 ElementCount::get(N->getConstantOperandVal(3), VT.isScalableVT());
11515
11516 EVT AddrVT = SourceValue->getValueType(0);
11517 bool IsReadAfterWrite = N->getOpcode() == ISD::LOOP_DEPENDENCE_RAW_MASK;
11518
11519 EVT CmpVT =
11520 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), AddrVT);
11521
11522 // Unsigned compare: Source >= Sink.
11523 SDValue SourceAheadOfOrEqualToSink =
11524 DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETUGE);
11525
11526 // Take the difference between the pointers and divided by the element size,
11527 // to see how many lanes separate them.
11528 SDValue Diff = DAG.getNode(ISD::SUB, DL, AddrVT, SinkValue, SourceValue);
11529
11530 // RAW_MASK: Diff = Source >= Sink ? (Source - Sink) : (Sink - Source)
11531 if (IsReadAfterWrite)
11532 Diff = DAG.getSelect(DL, AddrVT, SourceAheadOfOrEqualToSink,
11533 DAG.getNegative(Diff, DL, AddrVT), Diff);
11534
11535 Diff = DAG.getNode(ISD::SDIV, DL, AddrVT, Diff, EltSizeInBytes);
11536
11537 // The pointers do not alias if:
11538 // - Source >= Sink (WAR_MASK)
11539 // - Source == Sink (RAW_MASK)
11540 SDValue NoAlias = SourceAheadOfOrEqualToSink;
11541 if (IsReadAfterWrite)
11542 NoAlias = DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETEQ);
11543
11544 // The pointers do not alias if:
11545 // Lane + LaneOffset < Diff (WAR/RAW_MASK)
11546 SDValue LaneOffset = DAG.getElementCount(DL, AddrVT, LaneOffsetEC);
11547 SDValue MaskN = DAG.getSelect(
11548 DL, AddrVT, NoAlias,
11550 AddrVT),
11551 Diff);
11552
11553 return DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, VT, LaneOffset, MaskN);
11554}
11555
11557 bool IsNegative) const {
11558 SDLoc dl(N);
11559 EVT VT = N->getValueType(0);
11560 SDValue Op = N->getOperand(0);
11561
11562 // If expanding ABS_MIN_POISON, fall back to ABS if the target supports it.
11563 if (N->getOpcode() == ISD::ABS_MIN_POISON &&
11565 SDValue AbsVal = DAG.getNode(ISD::ABS, dl, VT, Op);
11566 if (IsNegative)
11567 return DAG.getNegative(AbsVal, dl, VT);
11568 return AbsVal;
11569 }
11570
11571 // abs(x) -> smax(x,sub(0,x))
11572 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11574 SDValue Zero = DAG.getConstant(0, dl, VT);
11575 Op = DAG.getFreeze(Op);
11576 return DAG.getNode(ISD::SMAX, dl, VT, Op,
11577 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11578 }
11579
11580 // abs(x) -> umin(x,sub(0,x))
11581 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11583 SDValue Zero = DAG.getConstant(0, dl, VT);
11584 Op = DAG.getFreeze(Op);
11585 return DAG.getNode(ISD::UMIN, dl, VT, Op,
11586 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11587 }
11588
11589 // 0 - abs(x) -> smin(x, sub(0,x))
11590 if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
11592 SDValue Zero = DAG.getConstant(0, dl, VT);
11593 Op = DAG.getFreeze(Op);
11594 return DAG.getNode(ISD::SMIN, dl, VT, Op,
11595 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11596 }
11597
11598 // Only expand vector types if we have the appropriate vector operations.
11599 if (VT.isVector() &&
11601 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
11602 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
11604 return SDValue();
11605
11606 Op = DAG.getFreeze(Op);
11607 SDValue Shift = DAG.getNode(
11608 ISD::SRA, dl, VT, Op,
11609 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11610 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
11611
11612 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
11613 if (!IsNegative)
11614 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
11615
11616 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
11617 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
11618}
11619
11621 SDLoc dl(N);
11622 EVT VT = N->getValueType(0);
11623 SDValue LHS = N->getOperand(0);
11624 SDValue RHS = N->getOperand(1);
11625 bool IsSigned = N->getOpcode() == ISD::ABDS;
11626
11627 // abds(lhs, rhs) -> sub(smax(lhs,rhs), smin(lhs,rhs))
11628 // abdu(lhs, rhs) -> sub(umax(lhs,rhs), umin(lhs,rhs))
11629 unsigned MaxOpc = IsSigned ? ISD::SMAX : ISD::UMAX;
11630 unsigned MinOpc = IsSigned ? ISD::SMIN : ISD::UMIN;
11631 if (isOperationLegal(MaxOpc, VT) && isOperationLegal(MinOpc, VT)) {
11632 LHS = DAG.getFreeze(LHS);
11633 RHS = DAG.getFreeze(RHS);
11634 SDValue Max = DAG.getNode(MaxOpc, dl, VT, LHS, RHS);
11635 SDValue Min = DAG.getNode(MinOpc, dl, VT, LHS, RHS);
11636 return DAG.getNode(ISD::SUB, dl, VT, Max, Min);
11637 }
11638
11639 // abdu(lhs, rhs) -> or(usubsat(lhs,rhs), usubsat(rhs,lhs))
11640 if (!IsSigned && isOperationLegal(ISD::USUBSAT, VT)) {
11641 LHS = DAG.getFreeze(LHS);
11642 RHS = DAG.getFreeze(RHS);
11643 return DAG.getNode(ISD::OR, dl, VT,
11644 DAG.getNode(ISD::USUBSAT, dl, VT, LHS, RHS),
11645 DAG.getNode(ISD::USUBSAT, dl, VT, RHS, LHS));
11646 }
11647
11648 // If the subtract doesn't overflow then just use abs(sub())
11649 bool IsNonNegative = DAG.SignBitIsZero(LHS) && DAG.SignBitIsZero(RHS);
11650
11651 if (DAG.willNotOverflowSub(IsSigned || IsNonNegative, LHS, RHS))
11652 return DAG.getNode(ISD::ABS, dl, VT,
11653 DAG.getNode(ISD::SUB, dl, VT, LHS, RHS));
11654
11655 if (DAG.willNotOverflowSub(IsSigned || IsNonNegative, RHS, LHS))
11656 return DAG.getNode(ISD::ABS, dl, VT,
11657 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11658
11659 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11661 LHS = DAG.getFreeze(LHS);
11662 RHS = DAG.getFreeze(RHS);
11663 SDValue Cmp = DAG.getSetCC(dl, CCVT, LHS, RHS, CC);
11664
11665 // Branchless expansion iff cmp result is allbits:
11666 // abds(lhs, rhs) -> sub(sgt(lhs, rhs), xor(sgt(lhs, rhs), sub(lhs, rhs)))
11667 // abdu(lhs, rhs) -> sub(ugt(lhs, rhs), xor(ugt(lhs, rhs), sub(lhs, rhs)))
11668 if (CCVT == VT && getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
11669 SDValue Diff = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
11670 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Diff, Cmp);
11671 return DAG.getNode(ISD::SUB, dl, VT, Cmp, Xor);
11672 }
11673
11674 // Similar to the branchless expansion, if we don't prefer selects, use the
11675 // (sign-extended) usubo overflow flag if the (scalar) type is illegal as this
11676 // is more likely to legalize cleanly: abdu(lhs, rhs) -> sub(xor(sub(lhs,
11677 // rhs), uof(lhs, rhs)), uof(lhs, rhs))
11678 if (!IsSigned && VT.isScalarInteger() && !isTypeLegal(VT) &&
11680 SDValue USubO =
11681 DAG.getNode(ISD::USUBO, dl, DAG.getVTList(VT, MVT::i1), {LHS, RHS});
11682 SDValue Cmp = DAG.getNode(ISD::SIGN_EXTEND, dl, VT, USubO.getValue(1));
11683 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, USubO.getValue(0), Cmp);
11684 return DAG.getNode(ISD::SUB, dl, VT, Xor, Cmp);
11685 }
11686
11687 // FIXME: Should really try to split the vector in case it's legal on a
11688 // subvector.
11690 return DAG.UnrollVectorOp(N);
11691
11692 // abds(lhs, rhs) -> select(sgt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11693 // abdu(lhs, rhs) -> select(ugt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11694 return DAG.getSelect(dl, VT, Cmp, DAG.getNode(ISD::SUB, dl, VT, LHS, RHS),
11695 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11696}
11697
11699 SDLoc dl(N);
11700 EVT VT = N->getValueType(0);
11701 SDValue LHS = N->getOperand(0);
11702 SDValue RHS = N->getOperand(1);
11703
11704 unsigned Opc = N->getOpcode();
11705 bool IsFloor = Opc == ISD::AVGFLOORS || Opc == ISD::AVGFLOORU;
11706 bool IsSigned = Opc == ISD::AVGCEILS || Opc == ISD::AVGFLOORS;
11707 unsigned SumOpc = IsFloor ? ISD::ADD : ISD::SUB;
11708 unsigned SignOpc = IsFloor ? ISD::AND : ISD::OR;
11709 unsigned ShiftOpc = IsSigned ? ISD::SRA : ISD::SRL;
11710 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
11712 Opc == ISD::AVGFLOORU || Opc == ISD::AVGCEILU) &&
11713 "Unknown AVG node");
11714
11715 // If the operands are already extended, we can add+shift.
11716 bool IsExt =
11717 (IsSigned && DAG.ComputeNumSignBits(LHS) >= 2 &&
11718 DAG.ComputeNumSignBits(RHS) >= 2) ||
11719 (!IsSigned && DAG.computeKnownBits(LHS).countMinLeadingZeros() >= 1 &&
11720 DAG.computeKnownBits(RHS).countMinLeadingZeros() >= 1);
11721 if (IsExt) {
11722 SDValue Sum = DAG.getNode(ISD::ADD, dl, VT, LHS, RHS);
11723 if (!IsFloor)
11724 Sum = DAG.getNode(ISD::ADD, dl, VT, Sum, DAG.getConstant(1, dl, VT));
11725 return DAG.getNode(ShiftOpc, dl, VT, Sum,
11726 DAG.getShiftAmountConstant(1, VT, dl));
11727 }
11728
11729 // For scalars, see if we can efficiently extend/truncate to use add+shift.
11730 if (VT.isScalarInteger()) {
11731 EVT ExtVT = VT.widenIntegerElementType(*DAG.getContext());
11732 if (isTypeLegal(ExtVT) && isTruncateFree(ExtVT, VT)) {
11733 LHS = DAG.getNode(ExtOpc, dl, ExtVT, LHS);
11734 RHS = DAG.getNode(ExtOpc, dl, ExtVT, RHS);
11735 SDValue Avg = DAG.getNode(ISD::ADD, dl, ExtVT, LHS, RHS);
11736 if (!IsFloor)
11737 Avg = DAG.getNode(ISD::ADD, dl, ExtVT, Avg,
11738 DAG.getConstant(1, dl, ExtVT));
11739 // Just use SRL as we will be truncating away the extended sign bits.
11740 Avg = DAG.getNode(ISD::SRL, dl, ExtVT, Avg,
11741 DAG.getShiftAmountConstant(1, ExtVT, dl));
11742 return DAG.getNode(ISD::TRUNCATE, dl, VT, Avg);
11743 }
11744 }
11745
11746 // avgflooru(lhs, rhs) -> or(lshr(add(lhs, rhs),1),shl(overflow, typesize-1))
11747 if (Opc == ISD::AVGFLOORU && VT.isScalarInteger() && !isTypeLegal(VT) &&
11750 SDValue UAddWithOverflow =
11751 DAG.getNode(ISD::UADDO, dl, DAG.getVTList(VT, MVT::i1), {RHS, LHS});
11752
11753 SDValue Sum = UAddWithOverflow.getValue(0);
11754 SDValue Overflow = UAddWithOverflow.getValue(1);
11755
11756 // Right shift the sum by 1
11757 SDValue LShrVal = DAG.getNode(ISD::SRL, dl, VT, Sum,
11758 DAG.getShiftAmountConstant(1, VT, dl));
11759
11760 SDValue ZeroExtOverflow = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Overflow);
11761 SDValue OverflowShl = DAG.getNode(
11762 ISD::SHL, dl, VT, ZeroExtOverflow,
11763 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11764
11765 return DAG.getNode(ISD::OR, dl, VT, LShrVal, OverflowShl);
11766 }
11767
11768 // avgceils(lhs, rhs) -> sub(or(lhs,rhs),ashr(xor(lhs,rhs),1))
11769 // avgceilu(lhs, rhs) -> sub(or(lhs,rhs),lshr(xor(lhs,rhs),1))
11770 // avgfloors(lhs, rhs) -> add(and(lhs,rhs),ashr(xor(lhs,rhs),1))
11771 // avgflooru(lhs, rhs) -> add(and(lhs,rhs),lshr(xor(lhs,rhs),1))
11772 LHS = DAG.getFreeze(LHS);
11773 RHS = DAG.getFreeze(RHS);
11774 SDValue Sign = DAG.getNode(SignOpc, dl, VT, LHS, RHS);
11775 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
11776 SDValue Shift =
11777 DAG.getNode(ShiftOpc, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11778 return DAG.getNode(SumOpc, dl, VT, Sign, Shift);
11779}
11780
11782 SDLoc dl(N);
11783 EVT VT = N->getValueType(0);
11784 SDValue Op = N->getOperand(0);
11785
11786 if (!VT.isSimple())
11787 return SDValue();
11788
11789 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11790 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
11791 switch (VT.getSimpleVT().getScalarType().SimpleTy) {
11792 default:
11793 return SDValue();
11794 case MVT::i16:
11795 // Use a rotate by 8. This can be further expanded if necessary.
11796 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11797 case MVT::i32:
11798 // This is meant for ARM specifically, which has ROTR but no ROTL.
11799 // t = x ^ rotr(x, 16)
11800 // t = bic(t, 0x00ff0000)
11801 // t = lshr(t, 8)
11802 // x = t ^ rotr(x, 8)
11804 SDValue Rotr16 =
11805 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(16, dl, SHVT));
11806 SDValue Tmp = DAG.getNode(ISD::XOR, dl, VT, Op, Rotr16);
11807 Tmp = DAG.getNode(ISD::AND, dl, VT, Tmp,
11808 DAG.getConstant(0xFF00FFFF, dl, VT));
11809 Tmp = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(8, dl, SHVT));
11810 SDValue Rotr8 =
11811 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11812 return DAG.getNode(ISD::XOR, dl, VT, Tmp, Rotr8);
11813 }
11814 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11815 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Op,
11816 DAG.getConstant(0xFF00, dl, VT));
11817 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT));
11818 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11819 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
11820 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11821 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
11822 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
11823 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
11824 case MVT::i64:
11825 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
11826 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Op,
11827 DAG.getConstant(255ULL<<8, dl, VT));
11828 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT));
11829 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Op,
11830 DAG.getConstant(255ULL<<16, dl, VT));
11831 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT));
11832 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Op,
11833 DAG.getConstant(255ULL<<24, dl, VT));
11834 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT));
11835 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11836 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
11837 DAG.getConstant(255ULL<<24, dl, VT));
11838 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11839 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
11840 DAG.getConstant(255ULL<<16, dl, VT));
11841 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
11842 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
11843 DAG.getConstant(255ULL<<8, dl, VT));
11844 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
11845 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
11846 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
11847 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
11848 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
11849 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
11850 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
11851 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
11852 }
11853}
11854
11856 SDLoc dl(N);
11857 EVT VT = N->getValueType(0);
11858 SDValue Op = N->getOperand(0);
11859 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11860 unsigned Sz = VT.getScalarSizeInBits();
11861
11862 SDValue Tmp, Tmp2, Tmp3;
11863
11864 // If we can, perform BSWAP first and then the mask+swap the i4, then i2
11865 // and finally the i1 pairs.
11866 // TODO: We can easily support i4/i2 legal types if any target ever does.
11867 if (Sz >= 8 && isPowerOf2_32(Sz)) {
11868 // Create the masks - repeating the pattern every byte.
11869 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
11870 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
11871 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
11872
11873 // BSWAP if the type is wider than a single byte.
11874 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
11875
11876 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
11877 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
11878 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
11879 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
11880 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
11881 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11882
11883 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
11884 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
11885 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
11886 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
11887 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
11888 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11889
11890 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
11891 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
11892 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
11893 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
11894 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
11895 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11896 return Tmp;
11897 }
11898
11899 Tmp = DAG.getConstant(0, dl, VT);
11900 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
11901 if (I < J)
11902 Tmp2 =
11903 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
11904 else
11905 Tmp2 =
11906 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
11907
11908 APInt Shift = APInt::getOneBitSet(Sz, J);
11909 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
11910 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
11911 }
11912
11913 return Tmp;
11914}
11915
11916std::pair<SDValue, SDValue>
11918 SelectionDAG &DAG) const {
11919 SDLoc SL(LD);
11920 SDValue Chain = LD->getChain();
11921 SDValue BasePTR = LD->getBasePtr();
11922 EVT SrcVT = LD->getMemoryVT();
11923 EVT DstVT = LD->getValueType(0);
11924 ISD::LoadExtType ExtType = LD->getExtensionType();
11925
11926 if (SrcVT.isScalableVector())
11927 report_fatal_error("Cannot scalarize scalable vector loads");
11928
11929 unsigned NumElem = SrcVT.getVectorNumElements();
11930
11931 EVT SrcEltVT = SrcVT.getScalarType();
11932 EVT DstEltVT = DstVT.getScalarType();
11933
11934 // A vector must always be stored in memory as-is, i.e. without any padding
11935 // between the elements, since various code depend on it, e.g. in the
11936 // handling of a bitcast of a vector type to int, which may be done with a
11937 // vector store followed by an integer load. A vector that does not have
11938 // elements that are byte-sized must therefore be stored as an integer
11939 // built out of the extracted vector elements.
11940 if (!SrcEltVT.isByteSized()) {
11941 unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
11942 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
11943
11944 unsigned NumSrcBits = SrcVT.getSizeInBits();
11945 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
11946
11947 unsigned SrcEltBits = SrcEltVT.getSizeInBits();
11948 SDValue SrcEltBitMask = DAG.getConstant(
11949 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
11950
11951 // Load the whole vector and avoid masking off the top bits as it makes
11952 // the codegen worse.
11953 SDValue Load = DAG.getExtLoad(
11954 ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, LD->getPointerInfo(),
11955 SrcIntVT, LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
11956 LD->getMMOMetadataForSubAccess());
11957
11959 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11960 unsigned ShiftIntoIdx =
11961 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
11962 SDValue ShiftAmount = DAG.getShiftAmountConstant(
11963 ShiftIntoIdx * SrcEltVT.getSizeInBits(), LoadVT, SL);
11964 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
11965 SDValue Elt =
11966 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
11967 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
11968
11969 if (ExtType != ISD::NON_EXTLOAD) {
11970 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
11971 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
11972 }
11973
11974 Vals.push_back(Scalar);
11975 }
11976
11977 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
11978 return std::make_pair(Value, Load.getValue(1));
11979 }
11980
11981 unsigned Stride = SrcEltVT.getSizeInBits() / 8;
11982 assert(SrcEltVT.isByteSized());
11983
11985 SmallVector<SDValue, 8> LoadChains;
11986
11987 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11988 SDValue ScalarLoad = DAG.getExtLoad(
11989 ExtType, SL, DstEltVT, Chain, BasePTR,
11990 LD->getPointerInfo().getWithOffset(Idx * Stride), SrcEltVT,
11991 LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
11992 LD->getMMOMetadataForSubAccess());
11993
11994 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::getFixed(Stride));
11995
11996 Vals.push_back(ScalarLoad.getValue(0));
11997 LoadChains.push_back(ScalarLoad.getValue(1));
11998 }
11999
12000 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
12001 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
12002
12003 return std::make_pair(Value, NewChain);
12004}
12005
12007 SelectionDAG &DAG) const {
12008 SDLoc SL(ST);
12009
12010 SDValue Chain = ST->getChain();
12011 SDValue BasePtr = ST->getBasePtr();
12012 SDValue Value = ST->getValue();
12013 EVT StVT = ST->getMemoryVT();
12014
12015 if (StVT.isScalableVector())
12016 report_fatal_error("Cannot scalarize scalable vector stores");
12017
12018 // The type of the data we want to save
12019 EVT RegVT = Value.getValueType();
12020 EVT RegSclVT = RegVT.getScalarType();
12021
12022 // The type of data as saved in memory.
12023 EVT MemSclVT = StVT.getScalarType();
12024
12025 unsigned NumElem = StVT.getVectorNumElements();
12026
12027 // A vector must always be stored in memory as-is, i.e. without any padding
12028 // between the elements, since various code depend on it, e.g. in the
12029 // handling of a bitcast of a vector type to int, which may be done with a
12030 // vector store followed by an integer load. A vector that does not have
12031 // elements that are byte-sized must therefore be stored as an integer
12032 // built out of the extracted vector elements.
12033 if (!MemSclVT.isByteSized()) {
12034 unsigned NumBits = StVT.getSizeInBits();
12035 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
12036
12037 SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
12038
12039 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12040 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
12041 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
12042 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
12043 unsigned ShiftIntoIdx =
12044 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
12045 SDValue ShiftAmount =
12046 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
12047 SDValue ShiftedElt =
12048 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
12049 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
12050 }
12051
12052 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
12053 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12054 ST->getMMOMetadataForSubAccess());
12055 }
12056
12057 // Store Stride in bytes
12058 unsigned Stride = MemSclVT.getSizeInBits() / 8;
12059 assert(Stride && "Zero stride!");
12060 // Extract each of the elements from the original vector and save them into
12061 // memory individually.
12063 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12064 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
12065
12066 SDValue Ptr =
12067 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Idx * Stride));
12068
12069 // This scalar TruncStore may be illegal, but we legalize it later.
12071 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
12072 MemSclVT, ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12073 ST->getMMOMetadataForSubAccess());
12074
12075 Stores.push_back(Store);
12076 }
12077
12078 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
12079}
12080
12081std::pair<SDValue, SDValue>
12083 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
12084 "unaligned indexed loads not implemented!");
12085 SDValue Chain = LD->getChain();
12086 SDValue Ptr = LD->getBasePtr();
12087 EVT VT = LD->getValueType(0);
12088 EVT LoadedVT = LD->getMemoryVT();
12089 SDLoc dl(LD);
12090 auto &MF = DAG.getMachineFunction();
12091
12092 if (VT.isFloatingPoint() || VT.isVector()) {
12093 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
12094 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
12095 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
12096 LoadedVT.isVector()) {
12097 // Scalarize the load and let the individual components be handled.
12098 return scalarizeVectorLoad(LD, DAG);
12099 }
12100
12101 // Expand to a (misaligned) integer load of the same size,
12102 // then bitconvert to floating point or vector.
12103 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
12104 LD->getMemOperand());
12105 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
12106 if (LoadedVT != VT)
12107 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
12108 ISD::ANY_EXTEND, dl, VT, Result);
12109
12110 return std::make_pair(Result, newLoad.getValue(1));
12111 }
12112
12113 // Copy the value to a (aligned) stack slot using (unaligned) integer
12114 // loads and stores, then do a (aligned) load from the stack slot.
12115 MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
12116 unsigned LoadedBytes = LoadedVT.getStoreSize();
12117 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12118 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
12119
12120 // Make sure the stack slot is also aligned for the register type.
12121 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
12122 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
12124 SDValue StackPtr = StackBase;
12125 unsigned Offset = 0;
12126
12127 EVT PtrVT = Ptr.getValueType();
12128 EVT StackPtrVT = StackPtr.getValueType();
12129
12130 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12131 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12132
12133 // Do all but one copies using the full register width.
12134 for (unsigned i = 1; i < NumRegs; i++) {
12135 // Load one integer register's worth from the original location.
12136 SDValue Load = DAG.getLoad(
12137 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
12138 LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12139 LD->getMMOMetadataForSubAccess());
12140 // Follow the load with a store to the stack slot. Remember the store.
12141 Stores.push_back(DAG.getStore(
12142 Load.getValue(1), dl, Load, StackPtr,
12143 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
12144 // Increment the pointers.
12145 Offset += RegBytes;
12146
12147 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12148 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12149 }
12150
12151 // The last copy may be partial. Do an extending load.
12152 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
12153 8 * (LoadedBytes - Offset));
12154 SDValue Load = DAG.getExtLoad(
12155 ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
12156 LD->getPointerInfo().getWithOffset(Offset), MemVT, LD->getBaseAlign(),
12157 LD->getMemOperand()->getFlags(), LD->getMMOMetadataForSubAccess());
12158 // Follow the load with a store to the stack slot. Remember the store.
12159 // On big-endian machines this requires a truncating store to ensure
12160 // that the bits end up in the right place.
12161 Stores.push_back(DAG.getTruncStore(
12162 Load.getValue(1), dl, Load, StackPtr,
12163 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
12164
12165 // The order of the stores doesn't matter - say it with a TokenFactor.
12166 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12167
12168 // Finally, perform the original load only redirected to the stack slot.
12169 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
12170 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
12171 LoadedVT);
12172
12173 // Callers expect a MERGE_VALUES node.
12174 return std::make_pair(Load, TF);
12175 }
12176
12177 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
12178 "Unaligned load of unsupported type.");
12179
12180 // Compute the new VT that is half the size of the old one. This is an
12181 // integer MVT.
12182 unsigned NumBits = LoadedVT.getSizeInBits();
12183 EVT NewLoadedVT;
12184 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
12185 NumBits >>= 1;
12186
12187 Align Alignment = LD->getBaseAlign();
12188 unsigned IncrementSize = NumBits / 8;
12189 ISD::LoadExtType HiExtType = LD->getExtensionType();
12190
12191 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
12192 if (HiExtType == ISD::NON_EXTLOAD)
12193 HiExtType = ISD::ZEXTLOAD;
12194
12195 // Load the value in two parts
12196 SDValue Lo, Hi;
12197 if (DAG.getDataLayout().isLittleEndian()) {
12198 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12199 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12200 LD->getMMOMetadataForSubAccess());
12201
12202 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12203 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
12204 LD->getPointerInfo().getWithOffset(IncrementSize),
12205 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12206 LD->getMMOMetadataForSubAccess());
12207 } else {
12208 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12209 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12210 LD->getMMOMetadataForSubAccess());
12211
12212 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12213 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
12214 LD->getPointerInfo().getWithOffset(IncrementSize),
12215 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12216 LD->getMMOMetadataForSubAccess());
12217 }
12218
12219 // aggregate the two parts
12220 SDValue ShiftAmount = DAG.getShiftAmountConstant(NumBits, VT, dl);
12221 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
12222 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
12223
12224 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
12225 Hi.getValue(1));
12226
12227 return std::make_pair(Result, TF);
12228}
12229
12231 SelectionDAG &DAG) const {
12232 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
12233 "unaligned indexed stores not implemented!");
12234 SDValue Chain = ST->getChain();
12235 SDValue Ptr = ST->getBasePtr();
12236 SDValue Val = ST->getValue();
12237 EVT VT = Val.getValueType();
12238 Align Alignment = ST->getBaseAlign();
12239 auto &MF = DAG.getMachineFunction();
12240 EVT StoreMemVT = ST->getMemoryVT();
12241
12242 SDLoc dl(ST);
12243 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
12244 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12245 if (isTypeLegal(intVT)) {
12246 if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
12247 StoreMemVT.isVector()) {
12248 // Scalarize the store and let the individual components be handled.
12249 SDValue Result = scalarizeVectorStore(ST, DAG);
12250 return Result;
12251 }
12252 // Expand to a bitconvert of the value to the integer type of the
12253 // same size, then a (misaligned) int store.
12254 // FIXME: Does not handle truncating floating point stores!
12255 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
12256 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
12257 Alignment, ST->getMemOperand()->getFlags(),
12258 ST->getMMOMetadataForSubAccess());
12259 return Result;
12260 }
12261 // Do a (aligned) store to a stack slot, then copy from the stack slot
12262 // to the final destination using (unaligned) integer loads and stores.
12263 MVT RegVT = getRegisterType(
12264 *DAG.getContext(),
12265 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
12266 EVT PtrVT = Ptr.getValueType();
12267 unsigned StoredBytes = StoreMemVT.getStoreSize();
12268 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12269 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
12270
12271 // Make sure the stack slot is also aligned for the register type.
12272 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
12273 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
12274
12275 // Perform the original store, only redirected to the stack slot.
12277 Chain, dl, Val, StackPtr,
12278 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
12279
12280 EVT StackPtrVT = StackPtr.getValueType();
12281
12282 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12283 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12285 unsigned Offset = 0;
12286
12287 // Do all but one copies using the full register width.
12288 for (unsigned i = 1; i < NumRegs; i++) {
12289 // Load one integer register's worth from the stack slot.
12290 SDValue Load = DAG.getLoad(
12291 RegVT, dl, Store, StackPtr,
12292 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
12293 // Store it to the final location. Remember the store.
12294 Stores.push_back(DAG.getStore(
12295 Load.getValue(1), dl, Load, Ptr,
12296 ST->getPointerInfo().getWithOffset(Offset), ST->getBaseAlign(),
12297 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess()));
12298 // Increment the pointers.
12299 Offset += RegBytes;
12300 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12301 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12302 }
12303
12304 // The last store may be partial. Do a truncating store. On big-endian
12305 // machines this requires an extending load from the stack slot to ensure
12306 // that the bits are in the right place.
12307 EVT LoadMemVT =
12308 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
12309
12310 // Load from the stack slot.
12311 SDValue Load = DAG.getExtLoad(
12312 ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
12313 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
12314
12315 Stores.push_back(
12316 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
12317 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
12318 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12319 ST->getMMOMetadataForSubAccess()));
12320 // The order of the stores doesn't matter - say it with a TokenFactor.
12321 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12322 return Result;
12323 }
12324
12325 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
12326 "Unaligned store of unknown type.");
12327 // Get the half-size VT
12328 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
12329 unsigned NumBits = NewStoredVT.getFixedSizeInBits();
12330 unsigned IncrementSize = NumBits / 8;
12331
12332 // Divide the stored value in two parts.
12333 SDValue ShiftAmount =
12334 DAG.getShiftAmountConstant(NumBits, Val.getValueType(), dl);
12335 SDValue Lo = Val;
12336 // If Val is a constant, replace the upper bits with 0. The SRL will constant
12337 // fold and not use the upper bits. A smaller constant may be easier to
12338 // materialize.
12339 if (auto *C = dyn_cast<ConstantSDNode>(Lo); C && !C->isOpaque())
12340 Lo = DAG.getNode(
12341 ISD::AND, dl, VT, Lo,
12342 DAG.getConstant(APInt::getLowBitsSet(VT.getSizeInBits(), NumBits), dl,
12343 VT));
12344 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
12345
12346 // Store the two parts
12347 SDValue Store1, Store2;
12348 Store1 = DAG.getTruncStore(
12349 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Lo : Hi, Ptr,
12350 ST->getPointerInfo(), NewStoredVT, Alignment,
12351 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess());
12352
12353 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12354 Store2 = DAG.getTruncStore(
12355 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
12356 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
12357 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess());
12358
12359 SDValue Result =
12360 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
12361 return Result;
12362}
12363
12364SDValue
12366 const SDLoc &DL, EVT DataVT,
12367 SelectionDAG &DAG,
12368 bool IsCompressedMemory) const {
12370 EVT AddrVT = Addr.getValueType();
12371 EVT MaskVT = Mask.getValueType();
12372 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
12373 "Incompatible types of Data and Mask");
12374 if (IsCompressedMemory) {
12375 // Incrementing the pointer according to number of '1's in the mask.
12376 if (DataVT.isScalableVector()) {
12377 EVT MaskExtVT = MaskVT.changeElementType(*DAG.getContext(), MVT::i32);
12378 SDValue MaskExt = DAG.getNode(ISD::ZERO_EXTEND, DL, MaskExtVT, Mask);
12379 Increment = DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i32, MaskExt);
12380 } else {
12381 EVT MaskIntVT =
12382 EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
12383 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
12384 if (MaskIntVT.getSizeInBits() < 32) {
12385 MaskInIntReg =
12386 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
12387 MaskIntVT = MVT::i32;
12388 }
12389 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
12390 }
12391 // Scale is an element size in bytes.
12392 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
12393 AddrVT);
12394 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
12395 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
12396 } else
12397 Increment = DAG.getTypeSize(DL, AddrVT, DataVT.getStoreSize());
12398
12399 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
12400}
12401
12403 EVT VecVT, const SDLoc &dl,
12404 ElementCount SubEC) {
12405 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
12406 "Cannot index a scalable vector within a fixed-width vector");
12407
12408 unsigned NElts = VecVT.getVectorMinNumElements();
12409 unsigned NumSubElts = SubEC.getKnownMinValue();
12410 EVT IdxVT = Idx.getValueType();
12411
12412 if (VecVT.isScalableVector() && !SubEC.isScalable()) {
12413 // If this is a constant index and we know the value plus the number of the
12414 // elements in the subvector minus one is less than the minimum number of
12415 // elements then it's safe to return Idx.
12416 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx))
12417 if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts)
12418 return Idx;
12419 SDValue VS =
12420 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts));
12421 unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT;
12422 SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS,
12423 DAG.getConstant(NumSubElts, dl, IdxVT));
12424 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub);
12425 }
12426 if (isPowerOf2_32(NElts) && NumSubElts == 1) {
12428 return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
12429 DAG.getConstant(Imm, dl, IdxVT));
12430 }
12431 unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0;
12432 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
12433 DAG.getConstant(MaxIndex, dl, IdxVT));
12434}
12435
12436SDValue
12438 EVT VecVT, SDValue Index,
12439 const SDNodeFlags PtrArithFlags) const {
12441 DAG, VecPtr, VecVT,
12443 Index, PtrArithFlags);
12444}
12445
12446SDValue
12448 EVT VecVT, EVT SubVecVT, SDValue Index,
12449 const SDNodeFlags PtrArithFlags) const {
12450 SDLoc dl(Index);
12451 // Make sure the index type is big enough to compute in.
12452 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
12453
12454 EVT EltVT = VecVT.getVectorElementType();
12455
12456 // Calculate the element offset and add it to the pointer.
12457 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
12458 assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
12459 "Converting bits to bytes lost precision");
12460 assert(SubVecVT.getVectorElementType() == EltVT &&
12461 "Sub-vector must be a vector with matching element type");
12462
12463 // An out-of-range index only makes the vector operation return poison, but
12464 // a load/store through the pointer computed below would be immediate UB, so
12465 // freeze the index before clamping it into range.
12466 if (!DAG.isGuaranteedNotToBePoison(Index))
12467 Index = DAG.getFreeze(Index);
12468
12469 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
12470 SubVecVT.getVectorElementCount());
12471
12472 EVT IdxVT = Index.getValueType();
12473 if (SubVecVT.isScalableVector())
12474 Index =
12475 DAG.getNode(ISD::MUL, dl, IdxVT, Index,
12476 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1)));
12477
12478 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
12479 DAG.getConstant(EltSize, dl, IdxVT));
12480 return DAG.getMemBasePlusOffset(VecPtr, Index, dl, PtrArithFlags);
12481}
12482
12483//===----------------------------------------------------------------------===//
12484// Implementation of Emulated TLS Model
12485//===----------------------------------------------------------------------===//
12486
12488 SelectionDAG &DAG) const {
12489 // Access to address of TLS varialbe xyz is lowered to a function call:
12490 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
12491 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12492 PointerType *VoidPtrType = PointerType::get(*DAG.getContext(), 0);
12493 SDLoc dl(GA);
12494
12495 ArgListTy Args;
12496 const GlobalValue *GV =
12498 SmallString<32> NameString("__emutls_v.");
12499 NameString += GV->getName();
12500 StringRef EmuTlsVarName(NameString);
12501 const GlobalVariable *EmuTlsVar =
12502 GV->getParent()->getNamedGlobal(EmuTlsVarName);
12503 assert(EmuTlsVar && "Cannot find EmuTlsVar ");
12504 Args.emplace_back(DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT), VoidPtrType);
12505
12506 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
12507
12509 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
12510 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
12511 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12512
12513 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12514 // At last for X86 targets, maybe good for other targets too?
12516 MFI.setAdjustsStack(true); // Is this only for X86 target?
12517 MFI.setHasCalls(true);
12518
12519 assert((GA->getOffset() == 0) &&
12520 "Emulated TLS must have zero offset in GlobalAddressSDNode");
12521 return CallResult.first;
12522}
12523
12525 SelectionDAG &DAG) const {
12526 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
12527 if (!isCtlzFast())
12528 return SDValue();
12529 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12530 SDLoc dl(Op);
12531 if (isNullConstant(Op.getOperand(1)) && CC == ISD::SETEQ) {
12532 EVT VT = Op.getOperand(0).getValueType();
12533 SDValue Zext = Op.getOperand(0);
12534 if (VT.bitsLT(MVT::i32)) {
12535 VT = MVT::i32;
12536 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
12537 }
12538 unsigned Log2b = Log2_32(VT.getSizeInBits());
12539 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
12540 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
12541 DAG.getConstant(Log2b, dl, MVT::i32));
12542 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
12543 }
12544 return SDValue();
12545}
12546
12548 SDValue Op0 = Node->getOperand(0);
12549 SDValue Op1 = Node->getOperand(1);
12550 EVT VT = Op0.getValueType();
12551 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12552 unsigned Opcode = Node->getOpcode();
12553 SDLoc DL(Node);
12554
12555 // If both sign bits are zero, flip UMIN/UMAX <-> SMIN/SMAX if legal.
12556 unsigned AltOpcode = ISD::getOppositeSignednessMinMaxOpcode(Opcode);
12557 if (isOperationLegal(AltOpcode, VT) && DAG.SignBitIsZero(Op0) &&
12558 DAG.SignBitIsZero(Op1))
12559 return DAG.getNode(AltOpcode, DL, VT, Op0, Op1);
12560
12561 // umax(x,1) --> sub(x,cmpeq(x,0)) iff cmp result is allbits
12562 if (Opcode == ISD::UMAX && llvm::isOneOrOneSplat(Op1, true) && BoolVT == VT &&
12564 Op0 = DAG.getFreeze(Op0);
12565 SDValue Zero = DAG.getConstant(0, DL, VT);
12566 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12567 DAG.getSetCC(DL, VT, Op0, Zero, ISD::SETEQ));
12568 }
12569
12570 // umin(x,y) -> sub(x,usubsat(x,y))
12571 // TODO: Missing freeze(Op0)?
12572 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
12574 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12575 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
12576 }
12577
12578 // umax(x,y) -> add(x,usubsat(y,x))
12579 // TODO: Missing freeze(Op0)?
12580 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
12582 return DAG.getNode(ISD::ADD, DL, VT, Op0,
12583 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
12584 }
12585
12586 // FIXME: Should really try to split the vector in case it's legal on a
12587 // subvector.
12589 return DAG.UnrollVectorOp(Node);
12590
12591 // Attempt to find an existing SETCC node that we can reuse.
12592 // TODO: Do we need a generic doesSETCCNodeExist?
12593 // TODO: Missing freeze(Op0)/freeze(Op1)?
12594 auto buildMinMax = [&](ISD::CondCode PrefCC, ISD::CondCode AltCC,
12595 ISD::CondCode PrefCommuteCC,
12596 ISD::CondCode AltCommuteCC) {
12597 SDVTList BoolVTList = DAG.getVTList(BoolVT);
12598 for (ISD::CondCode CC : {PrefCC, AltCC}) {
12599 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12600 {Op0, Op1, DAG.getCondCode(CC)})) {
12601 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12602 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12603 }
12604 }
12605 for (ISD::CondCode CC : {PrefCommuteCC, AltCommuteCC}) {
12606 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12607 {Op0, Op1, DAG.getCondCode(CC)})) {
12608 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12609 return DAG.getSelect(DL, VT, Cond, Op1, Op0);
12610 }
12611 }
12612 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, PrefCC);
12613 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12614 };
12615
12616 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
12617 // -> Y = (A < B) ? B : A
12618 // -> Y = (A >= B) ? A : B
12619 // -> Y = (A <= B) ? B : A
12620 switch (Opcode) {
12621 case ISD::SMAX:
12622 return buildMinMax(ISD::SETGT, ISD::SETGE, ISD::SETLT, ISD::SETLE);
12623 case ISD::SMIN:
12624 return buildMinMax(ISD::SETLT, ISD::SETLE, ISD::SETGT, ISD::SETGE);
12625 case ISD::UMAX:
12626 return buildMinMax(ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE);
12627 case ISD::UMIN:
12628 return buildMinMax(ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE);
12629 }
12630
12631 llvm_unreachable("How did we get here?");
12632}
12633
12635 unsigned Opcode = Node->getOpcode();
12636 SDValue LHS = Node->getOperand(0);
12637 SDValue RHS = Node->getOperand(1);
12638 EVT VT = LHS.getValueType();
12639 SDLoc dl(Node);
12640
12641 assert(VT == RHS.getValueType() && "Expected operands to be the same type");
12642 assert(VT.isInteger() && "Expected operands to be integers");
12643
12644 // usub.sat(a, b) -> umax(a, b) - b
12645 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
12646 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
12647 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
12648 }
12649
12650 // usub.sat(a, 1) -> sub(a, zext(a != 0))
12651 // Prefer this on targets without legal/cost-effective overflow-carry nodes.
12652 if (Opcode == ISD::USUBSAT && isOneOrOneSplat(RHS) &&
12654 LHS = DAG.getFreeze(LHS);
12655 SDValue Zero = DAG.getConstant(0, dl, VT);
12656 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12657 SDValue IsNonZero = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETNE);
12658 SDValue Subtrahend = DAG.getBoolExtOrTrunc(IsNonZero, dl, VT, BoolVT);
12659 Subtrahend =
12660 DAG.getNode(ISD::AND, dl, VT, Subtrahend, DAG.getConstant(1, dl, VT));
12661 return DAG.getNode(ISD::SUB, dl, VT, LHS, Subtrahend);
12662 }
12663
12664 // uadd.sat(a, b) -> umin(a, ~b) + b
12665 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
12666 SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
12667 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
12668 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
12669 }
12670
12671 unsigned OverflowOp;
12672 switch (Opcode) {
12673 case ISD::SADDSAT:
12674 OverflowOp = ISD::SADDO;
12675 break;
12676 case ISD::UADDSAT:
12677 OverflowOp = ISD::UADDO;
12678 break;
12679 case ISD::SSUBSAT:
12680 OverflowOp = ISD::SSUBO;
12681 break;
12682 case ISD::USUBSAT:
12683 OverflowOp = ISD::USUBO;
12684 break;
12685 default:
12686 llvm_unreachable("Expected method to receive signed or unsigned saturation "
12687 "addition or subtraction node.");
12688 }
12689
12690 // FIXME: Should really try to split the vector in case it's legal on a
12691 // subvector.
12693 return DAG.UnrollVectorOp(Node);
12694
12695 unsigned BitWidth = LHS.getScalarValueSizeInBits();
12696 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12697 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12698 SDValue SumDiff = Result.getValue(0);
12699 SDValue Overflow = Result.getValue(1);
12700 SDValue Zero = DAG.getConstant(0, dl, VT);
12701 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
12702
12703 if (Opcode == ISD::UADDSAT) {
12705 // (LHS + RHS) | OverflowMask
12706 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12707 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
12708 }
12709 // Overflow ? 0xffff.... : (LHS + RHS)
12710 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
12711 }
12712
12713 if (Opcode == ISD::USUBSAT) {
12715 // (LHS - RHS) & ~OverflowMask
12716 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12717 SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
12718 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
12719 }
12720 // Overflow ? 0 : (LHS - RHS)
12721 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
12722 }
12723
12724 assert((Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) &&
12725 "Expected signed saturating add/sub opcode");
12726
12727 const APInt MinVal = APInt::getSignedMinValue(BitWidth);
12728 const APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
12729
12730 KnownBits KnownLHS = DAG.computeKnownBits(LHS);
12731 KnownBits KnownRHS = DAG.computeKnownBits(RHS);
12732
12733 // If either of the operand signs are known, then they are guaranteed to
12734 // only saturate in one direction. If non-negative they will saturate
12735 // towards SIGNED_MAX, if negative they will saturate towards SIGNED_MIN.
12736 //
12737 // In the case of ISD::SSUBSAT, 'x - y' is equivalent to 'x + (-y)', so the
12738 // sign of 'y' has to be flipped.
12739
12740 bool LHSIsNonNegative = KnownLHS.isNonNegative();
12741 bool RHSIsNonNegative =
12742 Opcode == ISD::SADDSAT ? KnownRHS.isNonNegative() : KnownRHS.isNegative();
12743 if (LHSIsNonNegative || RHSIsNonNegative) {
12744 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12745 return DAG.getSelect(dl, VT, Overflow, SatMax, SumDiff);
12746 }
12747
12748 bool LHSIsNegative = KnownLHS.isNegative();
12749 bool RHSIsNegative =
12750 Opcode == ISD::SADDSAT ? KnownRHS.isNegative() : KnownRHS.isNonNegative();
12751 if (LHSIsNegative || RHSIsNegative) {
12752 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12753 return DAG.getSelect(dl, VT, Overflow, SatMin, SumDiff);
12754 }
12755
12756 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
12757 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12758 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
12759 DAG.getConstant(BitWidth - 1, dl, VT));
12760 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
12761 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
12762}
12763
12765 unsigned Opcode = Node->getOpcode();
12766 SDValue LHS = Node->getOperand(0);
12767 SDValue RHS = Node->getOperand(1);
12768 EVT VT = LHS.getValueType();
12769 EVT ResVT = Node->getValueType(0);
12770 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12771 SDLoc dl(Node);
12772
12773 auto LTPredicate = (Opcode == ISD::UCMP ? ISD::SETULT : ISD::SETLT);
12774 auto GTPredicate = (Opcode == ISD::UCMP ? ISD::SETUGT : ISD::SETGT);
12775 SDValue IsLT = DAG.getSetCC(dl, BoolVT, LHS, RHS, LTPredicate);
12776 SDValue IsGT = DAG.getSetCC(dl, BoolVT, LHS, RHS, GTPredicate);
12777
12778 // We can't perform arithmetic on i1 values. Extending them would
12779 // probably result in worse codegen, so let's just use two selects instead.
12780 // Some targets are also just better off using selects rather than subtraction
12781 // because one of the conditions can be merged with one of the selects.
12782 // And finally, if we don't know the contents of high bits of a boolean value
12783 // we can't perform any arithmetic either.
12785 BoolVT.getScalarSizeInBits() == 1 ||
12787 SDValue SelectZeroOrOne =
12788 DAG.getSelect(dl, ResVT, IsGT, DAG.getConstant(1, dl, ResVT),
12789 DAG.getConstant(0, dl, ResVT));
12790 return DAG.getSelect(dl, ResVT, IsLT, DAG.getAllOnesConstant(dl, ResVT),
12791 SelectZeroOrOne);
12792 }
12793
12795 std::swap(IsGT, IsLT);
12796 return DAG.getSExtOrTrunc(DAG.getNode(ISD::SUB, dl, BoolVT, IsGT, IsLT), dl,
12797 ResVT);
12798}
12799
12801 unsigned Opcode = Node->getOpcode();
12802 bool IsSigned = Opcode == ISD::SSHLSAT;
12803 SDValue LHS = Node->getOperand(0);
12804 SDValue RHS = Node->getOperand(1);
12805 EVT VT = LHS.getValueType();
12806 SDLoc dl(Node);
12807
12808 assert((Node->getOpcode() == ISD::SSHLSAT ||
12809 Node->getOpcode() == ISD::USHLSAT) &&
12810 "Expected a SHLSAT opcode");
12811 assert(VT.isInteger() && "Expected operands to be integers");
12812
12814 return DAG.UnrollVectorOp(Node);
12815
12816 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
12817
12818 unsigned BW = VT.getScalarSizeInBits();
12819 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12820 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
12821 SDValue Orig =
12822 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
12823
12824 SDValue SatVal;
12825 if (IsSigned) {
12826 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
12827 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
12828 SDValue Cond =
12829 DAG.getSetCC(dl, BoolVT, LHS, DAG.getConstant(0, dl, VT), ISD::SETLT);
12830 SatVal = DAG.getSelect(dl, VT, Cond, SatMin, SatMax);
12831 } else {
12832 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
12833 }
12834 SDValue Cond = DAG.getSetCC(dl, BoolVT, LHS, Orig, ISD::SETNE);
12835 return DAG.getSelect(dl, VT, Cond, SatVal, Result);
12836}
12837
12839 bool Signed, SDValue &Lo, SDValue &Hi,
12840 SDValue LHS, SDValue RHS,
12841 SDValue HiLHS, SDValue HiRHS) const {
12842 EVT VT = LHS.getValueType();
12843 assert(RHS.getValueType() == VT && "Mismatching operand types");
12844
12845 assert((HiLHS && HiRHS) || (!HiLHS && !HiRHS));
12846 assert((!Signed || !HiLHS) &&
12847 "Signed flag should only be set when HiLHS and RiRHS are null");
12848
12849 // We'll expand the multiplication by brute force because we have no other
12850 // options. This is a trivially-generalized version of the code from
12851 // Hacker's Delight (itself derived from Knuth's Algorithm M from section
12852 // 4.3.1). If Signed is set, we can use arithmetic right shifts to propagate
12853 // sign bits while calculating the Hi half.
12854 unsigned Bits = VT.getScalarSizeInBits();
12855 unsigned HalfBits = Bits / 2;
12856 SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(Bits, HalfBits), dl, VT);
12857 SDValue LL = DAG.getNode(ISD::AND, dl, VT, LHS, Mask);
12858 SDValue RL = DAG.getNode(ISD::AND, dl, VT, RHS, Mask);
12859
12860 SDValue T = DAG.getNode(ISD::MUL, dl, VT, LL, RL);
12861 SDValue TL = DAG.getNode(ISD::AND, dl, VT, T, Mask);
12862
12863 SDValue Shift = DAG.getShiftAmountConstant(HalfBits, VT, dl);
12864 // This is always an unsigned shift.
12865 SDValue TH = DAG.getNode(ISD::SRL, dl, VT, T, Shift);
12866
12867 unsigned ShiftOpc = Signed ? ISD::SRA : ISD::SRL;
12868 SDValue LH = DAG.getNode(ShiftOpc, dl, VT, LHS, Shift);
12869 SDValue RH = DAG.getNode(ShiftOpc, dl, VT, RHS, Shift);
12870
12871 SDValue U =
12872 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RL), TH);
12873 SDValue UL = DAG.getNode(ISD::AND, dl, VT, U, Mask);
12874 SDValue UH = DAG.getNode(ShiftOpc, dl, VT, U, Shift);
12875
12876 SDValue V =
12877 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LL, RH), UL);
12878 SDValue VH = DAG.getNode(ShiftOpc, dl, VT, V, Shift);
12879
12880 Lo = DAG.getNode(ISD::ADD, dl, VT, TL,
12881 DAG.getNode(ISD::SHL, dl, VT, V, Shift));
12882
12883 Hi = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RH),
12884 DAG.getNode(ISD::ADD, dl, VT, UH, VH));
12885
12886 // If HiLHS and HiRHS are set, multiply them by the opposite low part and add
12887 // the products to Hi.
12888 if (HiLHS) {
12889 SDValue RHLL = DAG.getNode(ISD::MUL, dl, VT, HiRHS, LHS);
12890 SDValue RLLH = DAG.getNode(ISD::MUL, dl, VT, RHS, HiLHS);
12891 Hi = DAG.getNode(ISD::ADD, dl, VT, Hi,
12892 DAG.getNode(ISD::ADD, dl, VT, RHLL, RLLH));
12893 }
12894}
12895
12897 bool Signed, const SDValue LHS,
12898 const SDValue RHS, SDValue &Lo,
12899 SDValue &Hi) const {
12900 EVT VT = LHS.getValueType();
12901 assert(RHS.getValueType() == VT && "Mismatching operand types");
12902 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
12903 // We can fall back to a libcall with an illegal type for the MUL if we
12904 // have a libcall big enough.
12905 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
12906 if (WideVT == MVT::i16)
12907 LC = RTLIB::MUL_I16;
12908 else if (WideVT == MVT::i32)
12909 LC = RTLIB::MUL_I32;
12910 else if (WideVT == MVT::i64)
12911 LC = RTLIB::MUL_I64;
12912 else if (WideVT == MVT::i128)
12913 LC = RTLIB::MUL_I128;
12914
12915 RTLIB::LibcallImpl LibcallImpl = getLibcallImpl(LC);
12916 if (LibcallImpl == RTLIB::Unsupported) {
12917 forceExpandMultiply(DAG, dl, Signed, Lo, Hi, LHS, RHS);
12918 return;
12919 }
12920
12921 // The libcall takes and returns WideVT values as packed VT halves. This only
12922 // works if VT is legal and WideVT isn't. Otherwise, emit a wide multiply and
12923 // let it legalise normally, possibly into a wider libcall.
12924 if (isTypeLegal(WideVT) || !isTypeLegal(VT)) {
12925 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT,
12926 DAG.getExtOrTrunc(Signed, LHS, dl, WideVT),
12927 DAG.getExtOrTrunc(Signed, RHS, dl, WideVT));
12928 SDValue Shift =
12929 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
12930 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
12931 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT,
12932 DAG.getNode(ISD::SRL, dl, WideVT, Mul, Shift));
12933 return;
12934 }
12935
12936 SDValue HiLHS, HiRHS;
12937 if (Signed) {
12938 // The high part is obtained by SRA'ing all but one of the bits of low
12939 // part.
12940 unsigned LoSize = VT.getFixedSizeInBits();
12941 SDValue Shift = DAG.getShiftAmountConstant(LoSize - 1, VT, dl);
12942 HiLHS = DAG.getNode(ISD::SRA, dl, VT, LHS, Shift);
12943 HiRHS = DAG.getNode(ISD::SRA, dl, VT, RHS, Shift);
12944 } else {
12945 HiLHS = DAG.getConstant(0, dl, VT);
12946 HiRHS = DAG.getConstant(0, dl, VT);
12947 }
12948
12949 // Attempt a libcall.
12950 SDValue Ret;
12952 CallOptions.setIsSigned(Signed);
12953 CallOptions.setIsPostTypeLegalization(true);
12955 // Halves of WideVT are packed into registers in different order
12956 // depending on platform endianness. This is usually handled by
12957 // the C calling convention, but we can't defer to it in
12958 // the legalizer.
12959 SDValue Args[] = {LHS, HiLHS, RHS, HiRHS};
12960 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
12961 } else {
12962 SDValue Args[] = {HiLHS, LHS, HiRHS, RHS};
12963 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
12964 }
12966 "Ret value is a collection of constituent nodes holding result.");
12967 if (DAG.getDataLayout().isLittleEndian()) {
12968 // Same as above.
12969 Lo = Ret.getOperand(0);
12970 Hi = Ret.getOperand(1);
12971 } else {
12972 Lo = Ret.getOperand(1);
12973 Hi = Ret.getOperand(0);
12974 }
12975}
12976
12977SDValue
12979 assert((Node->getOpcode() == ISD::SMULFIX ||
12980 Node->getOpcode() == ISD::UMULFIX ||
12981 Node->getOpcode() == ISD::SMULFIXSAT ||
12982 Node->getOpcode() == ISD::UMULFIXSAT) &&
12983 "Expected a fixed point multiplication opcode");
12984
12985 SDLoc dl(Node);
12986 SDValue LHS = Node->getOperand(0);
12987 SDValue RHS = Node->getOperand(1);
12988 EVT VT = LHS.getValueType();
12989 unsigned Scale = Node->getConstantOperandVal(2);
12990 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
12991 Node->getOpcode() == ISD::UMULFIXSAT);
12992 bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
12993 Node->getOpcode() == ISD::SMULFIXSAT);
12994 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12995 unsigned VTSize = VT.getScalarSizeInBits();
12996
12997 if (!Scale) {
12998 // [us]mul.fix(a, b, 0) -> mul(a, b)
12999 if (!Saturating) {
13001 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13002 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
13003 SDValue Result =
13004 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
13005 SDValue Product = Result.getValue(0);
13006 SDValue Overflow = Result.getValue(1);
13007 SDValue Zero = DAG.getConstant(0, dl, VT);
13008
13009 APInt MinVal = APInt::getSignedMinValue(VTSize);
13010 APInt MaxVal = APInt::getSignedMaxValue(VTSize);
13011 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
13012 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
13013 // Xor the inputs, if resulting sign bit is 0 the product will be
13014 // positive, else negative.
13015 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
13016 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
13017 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
13018 return DAG.getSelect(dl, VT, Overflow, Result, Product);
13019 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
13020 SDValue Result =
13021 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
13022 SDValue Product = Result.getValue(0);
13023 SDValue Overflow = Result.getValue(1);
13024
13025 APInt MaxVal = APInt::getMaxValue(VTSize);
13026 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
13027 return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
13028 }
13029 }
13030
13031 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
13032 "Expected scale to be less than the number of bits if signed or at "
13033 "most the number of bits if unsigned.");
13034 assert(LHS.getValueType() == RHS.getValueType() &&
13035 "Expected both operands to be the same type");
13036
13037 // Select the saturated value when Cond0 <CC> Cond1, keeping it vectorized:
13038 // SELECT_CC is scalarized for vector types, so build SETCC + VSELECT there.
13039 auto getSaturatingSelect = [&](SDValue Cond0, SDValue Cond1, SDValue Sat,
13040 SDValue Val, ISD::CondCode CC) {
13041 if (VT.isVector())
13042 return DAG.getSelect(dl, VT, DAG.getSetCC(dl, BoolVT, Cond0, Cond1, CC),
13043 Sat, Val);
13044 return DAG.getSelectCC(dl, Cond0, Cond1, Sat, Val, CC);
13045 };
13046
13047 // Get the upper and lower bits of the result.
13048 SDValue Lo, Hi;
13049 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
13050 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
13051 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13052 if (isOperationLegalOrCustom(LoHiOp, VT)) {
13053 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
13054 Lo = Result.getValue(0);
13055 Hi = Result.getValue(1);
13056 } else if (isOperationLegalOrCustom(HiOp, VT)) {
13057 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13058 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
13059 } else if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
13060 // Try for a multiplication using a wider type.
13061 unsigned Ext = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13062 SDValue LHSExt = DAG.getNode(Ext, dl, WideVT, LHS);
13063 SDValue RHSExt = DAG.getNode(Ext, dl, WideVT, RHS);
13064 SDValue Res = DAG.getNode(ISD::MUL, dl, WideVT, LHSExt, RHSExt);
13065 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
13066 SDValue Shifted =
13067 DAG.getNode(ISD::SRA, dl, WideVT, Res,
13068 DAG.getShiftAmountConstant(VTSize, WideVT, dl));
13069 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT, Shifted);
13070 } else if (VT.isVector()) {
13071 return SDValue();
13072 } else {
13073 forceExpandWideMUL(DAG, dl, Signed, LHS, RHS, Lo, Hi);
13074 }
13075
13076 if (Scale == VTSize)
13077 // Result is just the top half since we'd be shifting by the width of the
13078 // operand. Overflow impossible so this works for both UMULFIX and
13079 // UMULFIXSAT.
13080 return Hi;
13081
13082 // The result will need to be shifted right by the scale since both operands
13083 // are scaled. The result is given to us in 2 halves, so we only want part of
13084 // both in the result.
13085 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
13086 DAG.getShiftAmountConstant(Scale, VT, dl));
13087 if (!Saturating)
13088 return Result;
13089
13090 if (!Signed) {
13091 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
13092 // widened multiplication) aren't all zeroes.
13093
13094 // Saturate to max if ((Hi >> Scale) != 0),
13095 // which is the same as if (Hi > ((1 << Scale) - 1))
13096 APInt MaxVal = APInt::getMaxValue(VTSize);
13097 SDValue LowMask =
13098 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), dl, VT);
13099 return getSaturatingSelect(Hi, LowMask, DAG.getConstant(MaxVal, dl, VT),
13100 Result, ISD::SETUGT);
13101 }
13102
13103 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
13104 // widened multiplication) aren't all ones or all zeroes.
13105
13106 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
13107 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
13108
13109 if (Scale == 0) {
13110 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
13111 DAG.getShiftAmountConstant(VTSize - 1, VT, dl));
13112 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
13113 // Saturated to SatMin if wide product is negative, and SatMax if wide
13114 // product is positive ...
13115 SDValue Zero = DAG.getConstant(0, dl, VT);
13116 SDValue ResultIfOverflow =
13117 getSaturatingSelect(Hi, Zero, SatMin, SatMax, ISD::SETLT);
13118 // ... but only if we overflowed.
13119 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
13120 }
13121
13122 // We handled Scale==0 above so all the bits to examine is in Hi.
13123
13124 // Saturate to max if ((Hi >> (Scale - 1)) > 0),
13125 // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
13126 SDValue LowMask =
13127 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), dl, VT);
13128 // Saturate to min if (Hi >> (Scale - 1)) < -1),
13129 // which is the same as if (HI < (-1 << (Scale - 1))
13130 SDValue HighMask = DAG.getConstant(
13131 APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), dl, VT);
13132 Result = getSaturatingSelect(Hi, LowMask, SatMax, Result, ISD::SETGT);
13133 Result = getSaturatingSelect(Hi, HighMask, SatMin, Result, ISD::SETLT);
13134 return Result;
13135}
13136
13137SDValue
13139 SDValue LHS, SDValue RHS,
13140 unsigned Scale, SelectionDAG &DAG) const {
13141 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
13142 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
13143 "Expected a fixed point division opcode");
13144
13145 EVT VT = LHS.getValueType();
13146 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
13147 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
13148 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13149
13150 // If there is enough room in the type to upscale the LHS or downscale the
13151 // RHS before the division, we can perform it in this type without having to
13152 // resize. For signed operations, the LHS headroom is the number of
13153 // redundant sign bits, and for unsigned ones it is the number of zeroes.
13154 // The headroom for the RHS is the number of trailing zeroes.
13155 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
13157 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
13158
13159 // For signed saturating operations, we need to be able to detect true integer
13160 // division overflow; that is, when you have MIN / -EPS. However, this
13161 // is undefined behavior and if we emit divisions that could take such
13162 // values it may cause undesired behavior (arithmetic exceptions on x86, for
13163 // example).
13164 // Avoid this by requiring an extra bit so that we never get this case.
13165 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
13166 // signed saturating division, we need to emit a whopping 32-bit division.
13167 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
13168 return SDValue();
13169
13170 unsigned LHSShift = std::min(LHSLead, Scale);
13171 unsigned RHSShift = Scale - LHSShift;
13172
13173 // At this point, we know that if we shift the LHS up by LHSShift and the
13174 // RHS down by RHSShift, we can emit a regular division with a final scaling
13175 // factor of Scale.
13176
13177 if (LHSShift)
13178 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
13179 DAG.getShiftAmountConstant(LHSShift, VT, dl));
13180 if (RHSShift)
13181 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
13182 DAG.getShiftAmountConstant(RHSShift, VT, dl));
13183
13184 SDValue Quot;
13185 if (Signed) {
13186 // For signed operations, if the resulting quotient is negative and the
13187 // remainder is nonzero, subtract 1 from the quotient to round towards
13188 // negative infinity.
13189 SDValue Rem;
13190 // FIXME: Ideally we would always produce an SDIVREM here, but if the
13191 // type isn't legal, SDIVREM cannot be expanded. There is no reason why
13192 // we couldn't just form a libcall, but the type legalizer doesn't do it.
13193 if (isTypeLegal(VT) &&
13195 Quot = DAG.getNode(ISD::SDIVREM, dl,
13196 DAG.getVTList(VT, VT),
13197 LHS, RHS);
13198 Rem = Quot.getValue(1);
13199 Quot = Quot.getValue(0);
13200 } else {
13201 Quot = DAG.getNode(ISD::SDIV, dl, VT,
13202 LHS, RHS);
13203 Rem = DAG.getNode(ISD::SREM, dl, VT,
13204 LHS, RHS);
13205 }
13206 SDValue Zero = DAG.getConstant(0, dl, VT);
13207 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
13208 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
13209 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
13210 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
13211 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
13212 DAG.getConstant(1, dl, VT));
13213 Quot = DAG.getSelect(dl, VT,
13214 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
13215 Sub1, Quot);
13216 } else
13217 Quot = DAG.getNode(ISD::UDIV, dl, VT,
13218 LHS, RHS);
13219
13220 return Quot;
13221}
13222
13224 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13225 SDLoc dl(Node);
13226 SDValue LHS = Node->getOperand(0);
13227 SDValue RHS = Node->getOperand(1);
13228 bool IsAdd = Node->getOpcode() == ISD::UADDO;
13229
13230 // If UADDO_CARRY/SUBO_CARRY is legal, use that instead.
13231 unsigned OpcCarry = IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
13232 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
13233 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
13234 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
13235 { LHS, RHS, CarryIn });
13236 Result = SDValue(NodeCarry.getNode(), 0);
13237 Overflow = SDValue(NodeCarry.getNode(), 1);
13238 return;
13239 }
13240
13241 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13242 LHS.getValueType(), LHS, RHS);
13243
13244 EVT ResultType = Node->getValueType(1);
13245 EVT SetCCType = getSetCCResultType(
13246 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13247 SDValue SetCC;
13248 if (IsAdd && isOneConstant(RHS)) {
13249 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces
13250 // the live range of X. We assume comparing with 0 is cheap.
13251 // The general case (X + C) < C is not necessarily beneficial. Although we
13252 // reduce the live range of X, we may introduce the materialization of
13253 // constant C.
13254 SetCC =
13255 DAG.getSetCC(dl, SetCCType, Result,
13256 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ);
13257 } else if (IsAdd && isAllOnesConstant(RHS)) {
13258 // Special case: uaddo X, -1 overflows if X != 0.
13259 SetCC =
13260 DAG.getSetCC(dl, SetCCType, LHS,
13261 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETNE);
13262 } else {
13263 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
13264 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
13265 }
13266 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13267}
13268
13270 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13271 SDLoc dl(Node);
13272 SDValue LHS = Node->getOperand(0);
13273 SDValue RHS = Node->getOperand(1);
13274 bool IsAdd = Node->getOpcode() == ISD::SADDO;
13275
13276 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13277 LHS.getValueType(), LHS, RHS);
13278
13279 EVT ResultType = Node->getValueType(1);
13280 EVT OType = getSetCCResultType(
13281 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13282
13283 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
13284 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
13285 if (isOperationLegal(OpcSat, LHS.getValueType())) {
13286 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
13287 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
13288 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13289 return;
13290 }
13291
13292 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
13293
13294 if (IsAdd) {
13295 // For an addition, the result should be less than one of the operands (LHS)
13296 // if and only if the other operand (RHS) is negative, otherwise there will
13297 // be overflow.
13298 SDValue ResultLowerThanLHS =
13299 DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
13300 SDValue RHSNegative = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETLT);
13301 Overflow = DAG.getBoolExtOrTrunc(
13302 DAG.getNode(ISD::XOR, dl, OType, RHSNegative, ResultLowerThanLHS), dl,
13303 ResultType, ResultType);
13304 } else {
13305 // For subtraction, overflow occurs when the signed comparison of operands
13306 // doesn't match the sign of the result.
13307 SDValue LHSLessThanRHS = DAG.getSetCC(dl, OType, LHS, RHS, ISD::SETLT);
13308 SDValue ResultNegative = DAG.getSetCC(dl, OType, Result, Zero, ISD::SETLT);
13309 Overflow = DAG.getBoolExtOrTrunc(
13310 DAG.getNode(ISD::XOR, dl, OType, LHSLessThanRHS, ResultNegative), dl,
13311 ResultType, ResultType);
13312 }
13313}
13314
13316 SDValue &Overflow, SelectionDAG &DAG) const {
13317 SDLoc dl(Node);
13318 EVT VT = Node->getValueType(0);
13319 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13320 SDValue LHS = Node->getOperand(0);
13321 SDValue RHS = Node->getOperand(1);
13322 bool isSigned = Node->getOpcode() == ISD::SMULO;
13323
13324 // For power-of-two multiplications we can use a simpler shift expansion.
13325 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
13326 const APInt &C = RHSC->getAPIntValue();
13327 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
13328 if (C.isPowerOf2()) {
13329 // smulo(x, signed_min) is same as umulo(x, signed_min).
13330 bool UseArithShift = isSigned && !C.isMinSignedValue();
13331 SDValue ShiftAmt = DAG.getShiftAmountConstant(C.logBase2(), VT, dl);
13332 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
13333 Overflow = DAG.getSetCC(dl, SetCCVT,
13334 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
13335 dl, VT, Result, ShiftAmt),
13336 LHS, ISD::SETNE);
13337 return true;
13338 }
13339 }
13340
13341 SDValue BottomHalf;
13342 SDValue TopHalf;
13343 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13344
13345 static const unsigned Ops[2][3] =
13348 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
13349 BottomHalf = DAG.getNode(Ops[isSigned][0], dl, DAG.getVTList(VT, VT), LHS,
13350 RHS);
13351 TopHalf = BottomHalf.getValue(1);
13352 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
13353 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13354 TopHalf = DAG.getNode(Ops[isSigned][1], dl, VT, LHS, RHS);
13355 } else if (isTypeLegal(WideVT)) {
13356 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
13357 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
13358 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
13359 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
13360 SDValue ShiftAmt =
13361 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
13362 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
13363 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
13364 } else {
13365 if (VT.isVector())
13366 return false;
13367
13368 forceExpandWideMUL(DAG, dl, isSigned, LHS, RHS, BottomHalf, TopHalf);
13369 }
13370
13371 Result = BottomHalf;
13372 if (isSigned) {
13373 SDValue ShiftAmt = DAG.getShiftAmountConstant(
13374 VT.getScalarSizeInBits() - 1, BottomHalf.getValueType(), dl);
13375 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
13376 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
13377 } else {
13378 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
13379 DAG.getConstant(0, dl, VT), ISD::SETNE);
13380 }
13381
13382 // Truncate the result if SetCC returns a larger type than needed.
13383 EVT RType = Node->getValueType(1);
13384 if (RType.bitsLT(Overflow.getValueType()))
13385 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
13386
13387 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
13388 "Unexpected result type for S/UMULO legalization");
13389 return true;
13390}
13391
13393 SDLoc dl(Node);
13394 EVT VT = Node->getValueType(0);
13395 SDValue LHS = Node->getOperand(0);
13396 SDValue RHS = Node->getOperand(1);
13397 bool IsSigned = Node->getOpcode() == ISD::MULHS;
13398
13399 // Use MUL_LOHI if legal/custom for the original type.
13400 unsigned LoHiOp = IsSigned ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
13401 if (isOperationLegalOrCustom(LoHiOp, VT))
13402 return DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS).getValue(1);
13403
13404 // Use a wide multiply if available.
13405 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13406 if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
13407 unsigned BW = VT.getScalarSizeInBits();
13408 LHS = DAG.getExtOrTrunc(IsSigned, LHS, dl, WideVT);
13409 RHS = DAG.getExtOrTrunc(IsSigned, RHS, dl, WideVT);
13410 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13411 DAG.getNode(ISD::SRL, dl, WideVT,
13412 DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS),
13413 DAG.getShiftAmountConstant(BW, WideVT, dl)));
13414 }
13415
13416 // Let fixed-length vectors be scalarised by the caller.
13417 // Expand everything else with a wide multiply.
13418 if (!VT.isFixedLengthVector()) {
13419 SDValue Lo, Hi;
13420 forceExpandWideMUL(DAG, dl, IsSigned, LHS, RHS, Lo, Hi);
13421 return Hi;
13422 }
13423
13424 return SDValue();
13425}
13426
13428 SDLoc dl(Node);
13429 ISD::NodeType BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13430 SDValue Op = Node->getOperand(0);
13431 SDNodeFlags Flags = Node->getFlags();
13432 EVT VT = Op.getValueType();
13433
13434 // Try to use a shuffle reduction for power of two vectors.
13435 if (VT.isPow2VectorType()) {
13436 // See if the reduction opcode is safe to use with widened types.
13437 bool WidenSrc = false;
13438 switch (Node->getOpcode()) {
13441 case ISD::VECREDUCE_ADD:
13442 case ISD::VECREDUCE_MUL:
13443 case ISD::VECREDUCE_AND:
13444 case ISD::VECREDUCE_OR:
13445 case ISD::VECREDUCE_XOR:
13450 WidenSrc = VT.isFixedLengthVector();
13451 break;
13452 }
13453
13455 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
13456 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) {
13457 if (WidenSrc && Op.getOpcode() != ISD::BUILD_VECTOR) {
13458 // Attempt to widen the source vectors to a legal op.
13459 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), HalfVT);
13460 if (WideVT.isVector() &&
13461 WideVT.getScalarType() == HalfVT.getScalarType() &&
13462 WideVT.getVectorNumElements() >= HalfVT.getVectorNumElements() &&
13463 isOperationLegalOrCustom(BaseOpcode, WideVT)) {
13464 SDValue Lo, Hi;
13465 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13466 Lo = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Lo, 0);
13467 Hi = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Hi, 0);
13468 Op = DAG.getNode(BaseOpcode, dl, WideVT, Lo, Hi, Flags);
13469 Op = DAG.getExtractSubvector(dl, HalfVT, Op, 0);
13470 VT = HalfVT;
13471 continue;
13472 }
13473 }
13474 break;
13475 }
13476
13477 SDValue Lo, Hi;
13478 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13479 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi, Flags);
13480 VT = HalfVT;
13481
13482 // Stop if splitting is enough to make the reduction legal.
13483 if (isOperationLegalOrCustom(Node->getOpcode(), HalfVT))
13484 return DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Op,
13485 Flags);
13486 }
13487 }
13488
13489 if (VT.isScalableVector())
13491 "Expanding reductions for scalable vectors is undefined.");
13492
13493 EVT EltVT = VT.getVectorElementType();
13494 unsigned NumElts = VT.getVectorNumElements();
13495
13497 DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
13498
13499 SDValue Res = Ops[0];
13500 for (unsigned i = 1; i < NumElts; i++)
13501 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13502
13503 // Result type may be wider than element type.
13504 if (EltVT != Node->getValueType(0))
13505 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
13506 return Res;
13507}
13508
13510 SDLoc dl(Node);
13511 SDValue AccOp = Node->getOperand(0);
13512 SDValue VecOp = Node->getOperand(1);
13513 SDNodeFlags Flags = Node->getFlags();
13514
13515 EVT VT = VecOp.getValueType();
13516 EVT EltVT = VT.getVectorElementType();
13517
13518 if (VT.isScalableVector())
13520 "Expanding reductions for scalable vectors is undefined.");
13521
13522 unsigned NumElts = VT.getVectorNumElements();
13523
13525 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
13526
13527 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13528
13529 SDValue Res = AccOp;
13530 for (unsigned i = 0; i < NumElts; i++)
13531 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13532
13533 return Res;
13534}
13535
13537 SelectionDAG &DAG) const {
13538 EVT VT = Node->getValueType(0);
13539 SDLoc dl(Node);
13540 bool isSigned = Node->getOpcode() == ISD::SREM;
13541 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
13542 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
13543 SDValue Dividend = Node->getOperand(0);
13544 SDValue Divisor = Node->getOperand(1);
13545 if (isOperationLegalOrCustom(DivRemOpc, VT)) {
13546 SDVTList VTs = DAG.getVTList(VT, VT);
13547 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
13548 return true;
13549 }
13550 if (isOperationLegalOrCustom(DivOpc, VT)) {
13551 // X % Y -> X-X/Y*Y
13552 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
13553 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
13554 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13555 return true;
13556 }
13557 return false;
13558}
13559
13561 SelectionDAG &DAG) const {
13562 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
13563 SDLoc dl(SDValue(Node, 0));
13564 SDValue Src = Node->getOperand(0);
13565
13566 // DstVT is the result type, while SatVT is the size to which we saturate
13567 EVT SrcVT = Src.getValueType();
13568 EVT DstVT = Node->getValueType(0);
13569
13570 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
13571 unsigned SatWidth = SatVT.getScalarSizeInBits();
13572 unsigned DstWidth = DstVT.getScalarSizeInBits();
13573 assert(SatWidth <= DstWidth &&
13574 "Expected saturation width smaller than result width");
13575
13576 // Determine minimum and maximum integer values and their corresponding
13577 // floating-point values.
13578 APInt MinInt, MaxInt;
13579 if (IsSigned) {
13580 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
13581 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
13582 } else {
13583 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
13584 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
13585 }
13586
13587 // We cannot risk emitting FP_TO_XINT nodes with a source VT of [b]f16, as
13588 // libcall emission cannot handle this. Large result types will fail.
13589 if (SrcVT == MVT::f16 || SrcVT == MVT::bf16) {
13590 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
13591 SrcVT = Src.getValueType();
13592 }
13593
13594 const fltSemantics &Sem = SrcVT.getFltSemantics();
13595 APFloat MinFloat(Sem);
13596 APFloat MaxFloat(Sem);
13597
13598 APFloat::opStatus MinStatus =
13599 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
13600 APFloat::opStatus MaxStatus =
13601 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
13602 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
13603 !(MaxStatus & APFloat::opStatus::opInexact);
13604
13605 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
13606 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
13607
13608 // If the integer bounds are exactly representable as floats and min/max are
13609 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
13610 // of comparisons and selects.
13611 auto EmitMinMax = [&](unsigned MinOpcode, unsigned MaxOpcode,
13612 bool MayPropagateNaN) {
13613 bool MinMaxLegal = isOperationLegalOrCustom(MinOpcode, SrcVT) &&
13614 isOperationLegalOrCustom(MaxOpcode, SrcVT);
13615 if (!MinMaxLegal)
13616 return SDValue();
13617
13618 SDValue Clamped = Src;
13619
13620 // Clamp Src by MinFloat from below. If !MayPropagateNaN and Src is NaN
13621 // then the result is MinFloat.
13622 Clamped = DAG.getNode(MaxOpcode, dl, SrcVT, Clamped, MinFloatNode);
13623 // Clamp by MaxFloat from above. If !MayPropagateNaN then NaN cannot occur.
13624 Clamped = DAG.getNode(MinOpcode, dl, SrcVT, Clamped, MaxFloatNode);
13625 // Convert clamped value to integer.
13626 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
13627 dl, DstVT, Clamped);
13628
13629 // If !MayPropagateNan and the conversion is unsigned case we're done,
13630 // because we mapped NaN to MinFloat, which will cast to zero.
13631 if (!MayPropagateNaN && !IsSigned)
13632 return FpToInt;
13633
13634 // Otherwise, select 0 if Src is NaN.
13635 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13636 EVT SetCCVT =
13637 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13638 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13639 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, FpToInt);
13640 };
13641 if (AreExactFloatBounds) {
13642 if (SDValue Res = EmitMinMax(ISD::FMINIMUMNUM, ISD::FMAXIMUMNUM,
13643 /*MayPropagateNaN=*/false))
13644 return Res;
13645 // These may propagate NaN for sNaN operands.
13646 if (SDValue Res =
13647 EmitMinMax(ISD::FMINNUM, ISD::FMAXNUM, /*MayPropagateNaN=*/true))
13648 return Res;
13649 // These always propagate NaN.
13650 if (SDValue Res =
13651 EmitMinMax(ISD::FMINIMUM, ISD::FMAXIMUM, /*MayPropagateNaN=*/true))
13652 return Res;
13653 }
13654
13655 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
13656 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
13657
13658 // Result of direct conversion. The assumption here is that the operation is
13659 // non-trapping and it's fine to apply it to an out-of-range value if we
13660 // select it away later.
13661 SDValue FpToInt =
13662 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
13663
13664 SDValue Select = FpToInt;
13665
13666 EVT SetCCVT =
13667 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13668
13669 // If Src ULT MinFloat, select MinInt. In particular, this also selects
13670 // MinInt if Src is NaN.
13671 SDValue ULT = DAG.getSetCC(dl, SetCCVT, Src, MinFloatNode, ISD::SETULT);
13672 Select = DAG.getSelect(dl, DstVT, ULT, MinIntNode, Select);
13673 // If Src OGT MaxFloat, select MaxInt.
13674 SDValue OGT = DAG.getSetCC(dl, SetCCVT, Src, MaxFloatNode, ISD::SETOGT);
13675 Select = DAG.getSelect(dl, DstVT, OGT, MaxIntNode, Select);
13676
13677 // In the unsigned case we are done, because we mapped NaN to MinInt, which
13678 // is already zero.
13679 if (!IsSigned)
13680 return Select;
13681
13682 // Otherwise, select 0 if Src is NaN.
13683 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13684 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13685 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, Select);
13686}
13687
13689 const SDLoc &dl,
13690 SelectionDAG &DAG) const {
13691 EVT OperandVT = Op.getValueType();
13692 if (OperandVT.getScalarType() == ResultVT.getScalarType())
13693 return Op;
13694 EVT ResultIntVT = ResultVT.changeTypeToInteger();
13695 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13696 // can induce double-rounding which may alter the results. We can
13697 // correct for this using a trick explained in: Boldo, Sylvie, and
13698 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13699 // World Congress. 2005.
13700 SDValue Narrow = DAG.getFPExtendOrRound(Op, dl, ResultVT);
13701 SDValue NarrowAsWide = DAG.getFPExtendOrRound(Narrow, dl, OperandVT);
13702
13703 // We can keep the narrow value as-is if narrowing was exact (no
13704 // rounding error), the wide value was NaN (the narrow value is also
13705 // NaN and should be preserved) or if we rounded to the odd value.
13706 SDValue NarrowBits = DAG.getNode(ISD::BITCAST, dl, ResultIntVT, Narrow);
13707 SDValue One = DAG.getConstant(1, dl, ResultIntVT);
13708 SDValue NegativeOne = DAG.getAllOnesConstant(dl, ResultIntVT);
13709 SDValue And = DAG.getNode(ISD::AND, dl, ResultIntVT, NarrowBits, One);
13710 EVT ResultIntVTCCVT = getSetCCResultType(
13711 DAG.getDataLayout(), *DAG.getContext(), And.getValueType());
13712 SDValue Zero = DAG.getConstant(0, dl, ResultIntVT);
13713 // The result is already odd so we don't need to do anything.
13714 SDValue AlreadyOdd = DAG.getSetCC(dl, ResultIntVTCCVT, And, Zero, ISD::SETNE);
13715
13716 EVT WideSetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
13717 Op.getValueType());
13718 // We keep results which are exact, odd or NaN.
13719 SDValue KeepNarrow =
13720 DAG.getSetCC(dl, WideSetCCVT, Op, NarrowAsWide, ISD::SETUEQ);
13721 KeepNarrow = DAG.getNode(ISD::OR, dl, WideSetCCVT, KeepNarrow, AlreadyOdd);
13722 // We morally performed a round-down if AbsNarrow is smaller than
13723 // AbsWide.
13724 SDValue AbsWide = DAG.getNode(ISD::FABS, dl, OperandVT, Op);
13725 SDValue AbsNarrowAsWide = DAG.getNode(ISD::FABS, dl, OperandVT, NarrowAsWide);
13726 SDValue NarrowIsRd =
13727 DAG.getSetCC(dl, WideSetCCVT, AbsWide, AbsNarrowAsWide, ISD::SETOGT);
13728 // If the narrow value is odd or exact, pick it.
13729 // Otherwise, narrow is even and corresponds to either the rounded-up
13730 // or rounded-down value. If narrow is the rounded-down value, we want
13731 // the rounded-up value as it will be odd.
13732 SDValue Adjust = DAG.getSelect(dl, ResultIntVT, NarrowIsRd, One, NegativeOne);
13733 SDValue Adjusted = DAG.getNode(ISD::ADD, dl, ResultIntVT, NarrowBits, Adjust);
13734 Op = DAG.getSelect(dl, ResultIntVT, KeepNarrow, NarrowBits, Adjusted);
13735 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Op);
13736}
13737
13739 assert(Node->getOpcode() == ISD::FP_ROUND && "Unexpected opcode!");
13740 SDValue Op = Node->getOperand(0);
13741 EVT VT = Node->getValueType(0);
13742 SDLoc dl(Node);
13743 if (VT.getScalarType() == MVT::bf16) {
13744 if (Node->getConstantOperandVal(1) == 1) {
13745 return DAG.getNode(ISD::FP_TO_BF16, dl, VT, Node->getOperand(0));
13746 }
13747 EVT OperandVT = Op.getValueType();
13748 SDValue IsNaN = DAG.getSetCC(
13749 dl,
13750 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), OperandVT),
13751 Op, Op, ISD::SETUO);
13752
13753 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13754 // can induce double-rounding which may alter the results. We can
13755 // correct for this using a trick explained in: Boldo, Sylvie, and
13756 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13757 // World Congress. 2005.
13758 EVT F32 = VT.changeElementType(*DAG.getContext(), MVT::f32);
13759 EVT I32 = F32.changeTypeToInteger();
13760 Op = expandRoundInexactToOdd(F32, Op, dl, DAG);
13761 Op = DAG.getNode(ISD::BITCAST, dl, I32, Op);
13762
13763 // Conversions should set NaN's quiet bit. This also prevents NaNs from
13764 // turning into infinities.
13765 SDValue NaN =
13766 DAG.getNode(ISD::OR, dl, I32, Op, DAG.getConstant(0x400000, dl, I32));
13767
13768 // Factor in the contribution of the low 16 bits.
13769 SDValue One = DAG.getConstant(1, dl, I32);
13770 SDValue Lsb = DAG.getNode(ISD::SRL, dl, I32, Op,
13771 DAG.getShiftAmountConstant(16, I32, dl));
13772 Lsb = DAG.getNode(ISD::AND, dl, I32, Lsb, One);
13773 SDValue RoundingBias =
13774 DAG.getNode(ISD::ADD, dl, I32, Lsb, DAG.getConstant(0x7fff, dl, I32));
13775 SDValue Add = DAG.getNode(ISD::ADD, dl, I32, Op, RoundingBias);
13776
13777 // Don't round if we had a NaN, we don't want to turn 0x7fffffff into
13778 // 0x80000000.
13779 Op = DAG.getSelect(dl, I32, IsNaN, NaN, Add);
13780
13781 // Now that we have rounded, shift the bits into position.
13782 Op = DAG.getNode(ISD::SRL, dl, I32, Op,
13783 DAG.getShiftAmountConstant(16, I32, dl));
13784 EVT I16 = I32.changeElementType(*DAG.getContext(), MVT::i16);
13785 Op = DAG.getNode(ISD::TRUNCATE, dl, I16, Op);
13786 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13787 }
13788 return SDValue();
13789}
13790
13793 SelectionDAG &DAG) const {
13794 assert(Node->getOpcode() == ISD::VECTOR_INTERLEAVE && "Unexpected opcode");
13795 EVT VT = Node->getValueType(0);
13796 unsigned Factor = Node->getNumOperands();
13797 SDLoc DL(Node);
13798
13799 if (Factor > 2 && Factor % 2 == 0) {
13800 SmallVector<EVT> HalfVTs(Factor / 2, VT);
13801 SmallVector<SDValue, 8> LOps, ROps;
13802 // Interleave so we have 2 factors per result:
13803 // a0a1 b0b1 c0c1 d0d1 -> [a0c0 b0d0] [a1c1 b1d1]
13804 for (unsigned I = 0; I < Factor / 2; I++) {
13805 SDValue Interleave =
13806 DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, {VT, VT},
13807 {Node->getOperand(I), Node->getOperand(I + Factor / 2)});
13808 LOps.push_back(Interleave.getValue(0));
13809 ROps.push_back(Interleave.getValue(1));
13810 }
13811 // Interleave at Factor/2:
13812 // [a0c0 b0d0] [a1c1 b1d1] -> a0b0 c0d0 a1b1 c1d1
13813 SDValue L = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, HalfVTs, LOps);
13814 SDValue R = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, HalfVTs, ROps);
13815 for (unsigned I = 0; I < Factor / 2; I++)
13816 Results.push_back(L.getValue(I));
13817 for (unsigned I = 0; I < Factor / 2; I++)
13818 Results.push_back(R.getValue(I));
13819 return;
13820 }
13821
13822 if (!VT.isFixedLengthVector())
13823 return;
13824
13825 unsigned NumElts = VT.getVectorNumElements();
13826 EVT EltVT = VT.getVectorElementType();
13827
13828 // A factor of two needs only same-width, two-input shuffles.
13829 if (Factor == 2) {
13830 SmallVector<int, 8> Mask = createInterleaveMask(NumElts, Factor);
13831 for (unsigned I = 0; I != Factor; ++I)
13832 Results.push_back(DAG.getVectorShuffle(
13833 VT, DL, Node->getOperand(0), Node->getOperand(1),
13834 ArrayRef<int>(Mask).slice(I * NumElts, NumElts)));
13835 return;
13836 }
13837
13838 SmallVector<SDValue> InterleavedElts;
13839 InterleavedElts.reserve(Factor * NumElts);
13840 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
13841 for (unsigned OperandIdx = 0; OperandIdx != Factor; ++OperandIdx)
13842 InterleavedElts.push_back(DAG.getExtractVectorElt(
13843 DL, EltVT, Node->getOperand(OperandIdx), EltIdx));
13844
13845 for (unsigned ResultIdx = 0; ResultIdx != Factor; ++ResultIdx)
13846 Results.push_back(DAG.getBuildVector(
13847 VT, DL, ArrayRef(InterleavedElts).slice(ResultIdx * NumElts, NumElts)));
13848}
13849
13852 SelectionDAG &DAG) const {
13853 assert(Node->getOpcode() == ISD::VECTOR_DEINTERLEAVE && "Unexpected opcode");
13854 EVT VT = Node->getValueType(0);
13855 unsigned Factor = Node->getNumOperands();
13856 SDLoc DL(Node);
13857
13858 if (Factor > 2 && Factor % 2 == 0) {
13860 SmallVector<EVT> HalfVTs(Factor / 2, VT);
13861 // Deinterleave at Factor/2 so each result contains two factors interleaved:
13862 // a0b0 c0d0 a1b1 c1d1 -> [a0c0 b0d0] [a1c1 b1d1]
13863 SDValue L = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, HalfVTs,
13864 ArrayRef(Ops).take_front(Factor / 2));
13865 SDValue R = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, HalfVTs,
13866 ArrayRef(Ops).take_back(Factor / 2));
13867 Results.resize(Factor);
13868 // Deinterleave the 2 factors out:
13869 // [a0c0 a1c1] [b0d0 b1d1] -> a0a1 b0b1 c0c1 d0d1
13870 for (unsigned I = 0; I < Factor / 2; ++I) {
13872 {L.getValue(I), R.getValue(I)});
13873 Results[I] = Deinterleave.getValue(0);
13874 Results[I + Factor / 2] = Deinterleave.getValue(1);
13875 }
13876 return;
13877 }
13878
13879 if (!VT.isFixedLengthVector())
13880 return;
13881
13882 unsigned NumElts = VT.getVectorNumElements();
13883 EVT EltVT = VT.getVectorElementType();
13884
13885 // A factor of two needs only same-width, two-input shuffles.
13886 if (Factor == 2) {
13887 for (unsigned I = 0; I != Factor; ++I)
13888 Results.push_back(
13889 DAG.getVectorShuffle(VT, DL, Node->getOperand(0), Node->getOperand(1),
13890 createStrideMask(I, Factor, NumElts)));
13891 return;
13892 }
13893
13894 SmallVector<SDValue> ConcatElts;
13895 ConcatElts.reserve(Factor * NumElts);
13896 for (unsigned OperandIdx = 0; OperandIdx != Factor; ++OperandIdx)
13897 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
13898 ConcatElts.push_back(DAG.getExtractVectorElt(
13899 DL, EltVT, Node->getOperand(OperandIdx), EltIdx));
13900
13901 SmallVector<SDValue> DeinterleavedElts;
13902 DeinterleavedElts.reserve(Factor * NumElts);
13903 for (unsigned ResultIdx = 0; ResultIdx != Factor; ++ResultIdx) {
13904 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
13905 DeinterleavedElts.push_back(ConcatElts[ResultIdx + EltIdx * Factor]);
13906 Results.push_back(DAG.getBuildVector(
13907 VT, DL,
13908 ArrayRef(DeinterleavedElts).slice(ResultIdx * NumElts, NumElts)));
13909 }
13910}
13911
13913 SelectionDAG &DAG) const {
13914 assert((Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT ||
13915 Node->getOpcode() == ISD::VECTOR_SPLICE_RIGHT) &&
13916 "Unexpected opcode!");
13917 assert((Node->getValueType(0).isScalableVector() ||
13918 !isa<ConstantSDNode>(Node->getOperand(2))) &&
13919 "Fixed length vector types with constant offsets expected to use "
13920 "SHUFFLE_VECTOR!");
13921
13922 EVT VT = Node->getValueType(0);
13923 SDValue V1 = Node->getOperand(0);
13924 SDValue V2 = Node->getOperand(1);
13925 SDValue Offset = Node->getOperand(2);
13926 SDLoc DL(Node);
13927
13928 // Expand through memory thusly:
13929 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
13930 // Store V1, Ptr
13931 // Store V2, Ptr + sizeof(V1)
13932 // if (VECTOR_SPLICE_LEFT)
13933 // Ptr = Ptr + (Offset * sizeof(VT.Elt))
13934 // else
13935 // Ptr = Ptr + sizeof(V1) - (Offset * size(VT.Elt))
13936 // Res = Load Ptr
13937
13938 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
13939
13941 VT.getVectorElementCount() * 2);
13942 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
13943 EVT PtrVT = StackPtr.getValueType();
13944 auto &MF = DAG.getMachineFunction();
13945 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
13946 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
13947
13948 // Store the lo part of CONCAT_VECTORS(V1, V2)
13949 SDValue StoreV1 =
13950 DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo, Alignment);
13951 // Store the hi part of CONCAT_VECTORS(V1, V2)
13952 SDValue VTBytes = DAG.getTypeSize(DL, PtrVT, VT.getStoreSize());
13953 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, VTBytes);
13954 SDValue StoreV2 =
13955 DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo, Alignment);
13956
13957 // NOTE: TrailingBytes must be clamped so as not to read outside of V1:V2.
13958 SDValue EltByteSize =
13959 DAG.getTypeSize(DL, PtrVT, VT.getVectorElementType().getStoreSize());
13960 Offset = DAG.getZExtOrTrunc(Offset, DL, PtrVT);
13961 SDValue TrailingBytes = DAG.getNode(ISD::MUL, DL, PtrVT, Offset, EltByteSize);
13962
13963 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VTBytes);
13964
13965 if (Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT)
13966 StackPtr = DAG.getMemBasePlusOffset(StackPtr, TrailingBytes, DL);
13967 else
13968 StackPtr = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
13969
13970 // Load the spliced result
13971 return DAG.getLoad(VT, DL, StoreV2, StackPtr,
13973}
13974
13976 SelectionDAG &DAG) const {
13977 SDLoc DL(Node);
13978 SDValue Vec = Node->getOperand(0);
13979 SDValue Mask = Node->getOperand(1);
13980 SDValue Passthru = Node->getOperand(2);
13981
13982 EVT VecVT = Vec.getValueType();
13983 EVT ScalarVT = VecVT.getScalarType();
13984 EVT MaskVT = Mask.getValueType();
13985 EVT MaskScalarVT = MaskVT.getScalarType();
13986
13987 // Needs to be handled by targets that have scalable vector types.
13988 if (VecVT.isScalableVector())
13989 report_fatal_error("Cannot expand masked_compress for scalable vectors.");
13990
13991 Align Alignment = DAG.getReducedAlign(VecVT, /*UseABI=*/false);
13992 SDValue StackPtr = DAG.CreateStackTemporary(VecVT.getStoreSize(), Alignment);
13993 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
13994 MachinePointerInfo PtrInfo =
13996
13997 MVT PositionVT = getVectorIdxTy(DAG.getDataLayout());
13998 SDValue Chain = DAG.getEntryNode();
13999 SDValue OutPos = DAG.getConstant(0, DL, PositionVT);
14000
14001 bool HasPassthru = !Passthru.isUndef();
14002
14003 // If we have a passthru vector, store it on the stack, overwrite the matching
14004 // positions and then re-write the last element that was potentially
14005 // overwritten even though mask[i] = false.
14006 if (HasPassthru)
14007 Chain = DAG.getStore(Chain, DL, Passthru, StackPtr, PtrInfo, Alignment);
14008
14009 SDValue LastWriteVal;
14010 APInt PassthruSplatVal;
14011 bool IsSplatPassthru =
14012 ISD::isConstantSplatVector(Passthru.getNode(), PassthruSplatVal);
14013
14014 if (IsSplatPassthru) {
14015 // As we do not know which position we wrote to last, we cannot simply
14016 // access that index from the passthru vector. So we first check if passthru
14017 // is a splat vector, to use any element ...
14018 LastWriteVal = DAG.getConstant(PassthruSplatVal, DL, ScalarVT);
14019 } else if (HasPassthru) {
14020 // ... if it is not a splat vector, we need to get the passthru value at
14021 // position = popcount(mask) and re-load it from the stack before it is
14022 // overwritten in the loop below.
14023 EVT PopcountVT = ScalarVT.changeTypeToInteger();
14024 SDValue Popcount = DAG.getNode(
14026 MaskVT.changeVectorElementType(*DAG.getContext(), MVT::i1), Mask);
14027 Popcount = DAG.getNode(
14029 MaskVT.changeVectorElementType(*DAG.getContext(), PopcountVT),
14030 Popcount);
14031 Popcount = DAG.getNode(ISD::VECREDUCE_ADD, DL, PopcountVT, Popcount);
14032 SDValue LastElmtPtr =
14033 getVectorElementPointer(DAG, StackPtr, VecVT, Popcount);
14034 LastWriteVal = DAG.getLoad(
14035 ScalarVT, DL, Chain, LastElmtPtr,
14037 Chain = LastWriteVal.getValue(1);
14038 }
14039
14040 unsigned NumElms = VecVT.getVectorNumElements();
14041 for (unsigned I = 0; I < NumElms; I++) {
14042 SDValue ValI = DAG.getExtractVectorElt(DL, ScalarVT, Vec, I);
14043 SDValue OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
14044 Chain = DAG.getStore(
14045 Chain, DL, ValI, OutPtr,
14047
14048 // Get the mask value and add it to the current output position. This
14049 // either increments by 1 if MaskI is true or adds 0 otherwise.
14050 // Freeze in case we have poison/undef mask entries.
14051 SDValue MaskI = DAG.getExtractVectorElt(DL, MaskScalarVT, Mask, I);
14052 MaskI = DAG.getFreeze(MaskI);
14053 MaskI = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, MaskI);
14054 MaskI = DAG.getNode(ISD::ZERO_EXTEND, DL, PositionVT, MaskI);
14055 OutPos = DAG.getNode(ISD::ADD, DL, PositionVT, OutPos, MaskI);
14056
14057 if (HasPassthru && I == NumElms - 1) {
14058 SDValue EndOfVector =
14059 DAG.getConstant(VecVT.getVectorNumElements() - 1, DL, PositionVT);
14060 SDValue AllLanesSelected =
14061 DAG.getSetCC(DL, MVT::i1, OutPos, EndOfVector, ISD::CondCode::SETUGT);
14062 OutPos = DAG.getNode(ISD::UMIN, DL, PositionVT, OutPos, EndOfVector);
14063 OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
14064
14065 // Re-write the last ValI if all lanes were selected. Otherwise,
14066 // overwrite the last write it with the passthru value.
14067 LastWriteVal = DAG.getSelect(DL, ScalarVT, AllLanesSelected, ValI,
14068 LastWriteVal, SDNodeFlags::Unpredictable);
14069 Chain = DAG.getStore(
14070 Chain, DL, LastWriteVal, OutPtr,
14072 }
14073 }
14074
14075 return DAG.getLoad(VecVT, DL, Chain, StackPtr, PtrInfo, Alignment);
14076}
14077
14079 SDLoc DL(Node);
14080 EVT VT = Node->getValueType(0);
14081 SDValue Op = Node->getOperand(0);
14082 ElementCount EC = Op.getValueType().getVectorElementCount();
14083
14084 bool ZeroIsPoison = Node->getOpcode() == ISD::CTTZ_ELTS_ZERO_POISON;
14085 auto [Mask, StepVec] = getLegalMaskAndStepVector(Op, ZeroIsPoison, DL, DAG);
14086
14087 // No legal step vector: split mask in half and recombine results.
14088 // LoNumElts uses the non-poison CTTZ_ELTS so its result is well-defined
14089 // (== LoNumElts when no active lane), allowing the SETNE comparison.
14090 // Result: (ResLo != LoNumElts) ? ResLo : (LoNumElts + ResHi)
14091 if (!StepVec) {
14092 EVT ResVT = Node->getValueType(0);
14093 auto [MaskLo, MaskHi] = DAG.SplitVector(Op, DL);
14094 SDValue LoNumElts = DAG.getElementCount(
14095 DL, ResVT, MaskLo.getValueType().getVectorElementCount());
14096 SDValue ResLo = DAG.getNode(ISD::CTTZ_ELTS, DL, ResVT, MaskLo);
14097 SDValue ResHi = DAG.getNode(Node->getOpcode(), DL, ResVT, MaskHi);
14098 SDValue ResLoNotNumElts = DAG.getSetCC(
14099 DL, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ResVT),
14100 ResLo, LoNumElts, ISD::SETNE);
14101 // Per LangRef, ResVT must be wide enough to hold the total element count,
14102 // so the sum cannot wrap as an unsigned add. NSW is not guaranteed since
14103 // the count is only required to fit unsigned.
14104 SDValue Sum = DAG.getNode(ISD::ADD, DL, ResVT, LoNumElts, ResHi,
14106 return DAG.getSelect(DL, ResVT, ResLoNotNumElts, ResLo, Sum);
14107 }
14108
14109 EVT StepVecVT = StepVec.getValueType();
14110 EVT StepVT = StepVecVT.getVectorElementType();
14111
14112 // Promote the scalar result type early to avoid redundant zexts.
14114 StepVT = getTypeToTransformTo(*DAG.getContext(), StepVT);
14115
14116 SDValue VL = DAG.getElementCount(DL, StepVT, EC);
14117 SDValue SplatVL = DAG.getSplat(StepVecVT, DL, VL);
14118 StepVec = DAG.getNode(ISD::SUB, DL, StepVecVT, SplatVL, StepVec);
14119 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
14120 SDValue Select = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
14122 StepVecVT.getVectorElementType(), Select);
14123 SDValue Sub = DAG.getNode(ISD::SUB, DL, StepVT, VL,
14124 DAG.getZExtOrTrunc(Max, DL, StepVT));
14125
14126 return DAG.getZExtOrTrunc(Sub, DL, VT);
14127}
14128
14130 SDLoc DL(N);
14131 SDValue Source = N->getOperand(0);
14132 SDValue Needle = N->getOperand(1);
14133 SDValue Mask = N->getOperand(2);
14134 EVT SourceVT = Source.getValueType();
14135 EVT NeedleVT = Needle.getValueType();
14136 EVT ResVT = N->getValueType(0);
14137 EVT CmpVT =
14138 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SourceVT);
14139
14140 assert(NeedleVT.isFixedLengthVector() && "Needle must be a fixed vector");
14141
14142 SDValue Ret = DAG.getConstant(0, DL, CmpVT);
14143 EVT NeedleEltVT = NeedleVT.getVectorElementType();
14144 for (unsigned I = 0, E = NeedleVT.getVectorNumElements(); I != E; ++I) {
14145 SDValue Splat;
14146 if (NeedleVT == SourceVT) {
14147 // Prefer a shuffle over scalar extracts + splat for fixed vectors.
14148 Splat = DAG.getVectorShuffle(
14149 SourceVT, DL, Needle, DAG.getUNDEF(SourceVT),
14151 } else {
14152 SDValue NeedleElt = DAG.getExtractVectorElt(DL, NeedleEltVT, Needle, I);
14153 Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, SourceVT, NeedleElt);
14154 }
14155 SDValue Cmp = DAG.getSetCC(DL, CmpVT, Source, Splat, ISD::SETEQ);
14156 Ret = DAG.getNode(ISD::OR, DL, CmpVT, Ret, Cmp);
14157 }
14158
14159 EVT UseVT = ResVT;
14160 // If the result is immediately truncated, only extend to that type (to avoid
14161 // unnecessary sign/zero extends).
14162 if (N->hasOneUse() && N->user_begin()->getOpcode() == ISD::TRUNCATE)
14163 UseVT = N->user_begin()->getValueType(0);
14164
14165 Mask = DAG.getBoolExtOrTrunc(Mask, DL, UseVT, Mask.getValueType());
14166 Ret = DAG.getBoolExtOrTrunc(Ret, DL, UseVT, Ret.getValueType());
14167
14168 Ret = DAG.getNode(ISD::AND, DL, UseVT, Ret, Mask);
14169 if (UseVT != ResVT)
14170 Ret = DAG.getNode(ISD::ANY_EXTEND, DL, ResVT, Ret);
14171 return Ret;
14172}
14173
14175 SelectionDAG &DAG) const {
14176 SDLoc DL(N);
14177 SDValue Acc = N->getOperand(0);
14178 SDValue MulLHS = N->getOperand(1);
14179 SDValue MulRHS = N->getOperand(2);
14180 EVT AccVT = Acc.getValueType();
14181 EVT MulOpVT = MulLHS.getValueType();
14182
14183 EVT ExtMulOpVT =
14185 MulOpVT.getVectorElementCount());
14186
14187 unsigned ExtOpcLHS, ExtOpcRHS;
14188 switch (N->getOpcode()) {
14189 default:
14190 llvm_unreachable("Unexpected opcode");
14192 ExtOpcLHS = ExtOpcRHS = ISD::ZERO_EXTEND;
14193 break;
14195 ExtOpcLHS = ExtOpcRHS = ISD::SIGN_EXTEND;
14196 break;
14198 ExtOpcLHS = ISD::SIGN_EXTEND;
14199 ExtOpcRHS = ISD::ZERO_EXTEND;
14200 break;
14202 ExtOpcLHS = ExtOpcRHS = ISD::FP_EXTEND;
14203 break;
14204 }
14205
14206 // A wide partial reduction is built from a ladder of narrower ones, a rung
14207 // at a time, each halving the element count and doubling the width.
14208 unsigned Opc = N->getOpcode();
14209 ElementCount MulEC = MulOpVT.getVectorElementCount();
14210 ElementCount AccEC = AccVT.getVectorElementCount();
14211 unsigned CountRatio =
14212 MulEC.hasKnownScalarFactor(AccEC) ? MulEC.getKnownScalarFactor(AccEC) : 0;
14213 unsigned WidthRatio =
14214 AccVT.getScalarSizeInBits() / MulOpVT.getScalarSizeInBits();
14215 if (Opc != ISD::PARTIAL_REDUCE_FMLA && CountRatio > 2 && WidthRatio >= 2) {
14216 LLVMContext &Ctx = *DAG.getContext();
14217 EVT ProdVT = MulOpVT.widenIntegerVectorElementType(Ctx);
14218
14219 // A pure reduction peels one rung and re-enters.
14220 if (llvm::isOneOrOneSplat(MulRHS)) {
14221 EVT RungVT = ProdVT.getHalfNumVectorElementsVT(Ctx);
14222 return DAG.getNode(Opc, DL, AccVT, Acc,
14223 DAG.getNode(Opc, DL, RungVT,
14224 DAG.getConstant(0, DL, RungVT), MulLHS,
14225 MulRHS),
14226 DAG.getConstant(1, DL, RungVT));
14227 }
14228
14229 // A multiply widens the products by one rung, which legalizes back into a
14230 // widening multiply per half, and the ladder re-enters as a plain sum.
14231 SDValue Prod = DAG.getNode(ISD::MUL, DL, ProdVT,
14232 DAG.getNode(ExtOpcLHS, DL, ProdVT, MulLHS),
14233 DAG.getNode(ExtOpcRHS, DL, ProdVT, MulRHS));
14234 auto [Lo, Hi] = DAG.SplitVector(Prod, DL);
14235 SDValue One = DAG.getConstant(1, DL, Lo.getValueType());
14236
14237 // The halves meet at the narrowest rung, so the accumulator is added once.
14238 EVT MidVT = Lo.getValueType()
14239 .widenIntegerVectorElementType(Ctx)
14240 .getHalfNumVectorElementsVT(Ctx);
14242 return DAG.getNode(Opc, DL, AccVT,
14243 DAG.getNode(Opc, DL, AccVT, Acc, Lo, One), Hi, One);
14244 SDValue Mid =
14245 DAG.getNode(Opc, DL, MidVT, DAG.getConstant(0, DL, MidVT), Lo, One);
14246 Mid = DAG.getNode(Opc, DL, MidVT, Mid, Hi, One);
14247 return DAG.getNode(Opc, DL, AccVT, Acc, Mid, DAG.getConstant(1, DL, MidVT));
14248 }
14249
14250 if (ExtMulOpVT != MulOpVT) {
14251 MulLHS = DAG.getNode(ExtOpcLHS, DL, ExtMulOpVT, MulLHS);
14252 MulRHS = DAG.getNode(ExtOpcRHS, DL, ExtMulOpVT, MulRHS);
14253 }
14254 SDValue Input = MulLHS;
14255 if (N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA) {
14256 if (!llvm::isOneOrOneSplatFP(MulRHS))
14257 Input = DAG.getNode(ISD::FMUL, DL, ExtMulOpVT, MulLHS, MulRHS);
14258 } else if (!llvm::isOneOrOneSplat(MulRHS)) {
14259 Input = DAG.getNode(ISD::MUL, DL, ExtMulOpVT, MulLHS, MulRHS);
14260 }
14261
14262 unsigned Stride = AccVT.getVectorMinNumElements();
14263 unsigned ScaleFactor = MulOpVT.getVectorMinNumElements() / Stride;
14264
14265 // Collect all of the subvectors
14266 std::deque<SDValue> Subvectors = {Acc};
14267 for (unsigned I = 0; I < ScaleFactor; I++)
14268 Subvectors.push_back(DAG.getExtractSubvector(DL, AccVT, Input, I * Stride));
14269
14270 unsigned FlatNode =
14271 N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA ? ISD::FADD : ISD::ADD;
14272
14273 // Flatten the subvector tree
14274 while (Subvectors.size() > 1) {
14275 Subvectors.push_back(
14276 DAG.getNode(FlatNode, DL, AccVT, {Subvectors[0], Subvectors[1]}));
14277 Subvectors.pop_front();
14278 Subvectors.pop_front();
14279 }
14280
14281 assert(Subvectors.size() == 1 &&
14282 "There should only be one subvector after tree flattening");
14283
14284 return Subvectors[0];
14285}
14286
14287/// Given a store node \p StoreNode, return true if it is safe to fold that node
14288/// into \p FPNode, which expands to a library call with output pointers.
14290 SDNode *FPNode) {
14292 SmallVector<const SDNode *, 8> DeferredNodes;
14294
14295 // Skip FPNode use by StoreNode (that's the use we want to fold into FPNode).
14296 for (SDValue Op : StoreNode->ops())
14297 if (Op.getNode() != FPNode)
14298 Worklist.push_back(Op.getNode());
14299
14301 while (!Worklist.empty()) {
14302 const SDNode *Node = Worklist.pop_back_val();
14303 auto [_, Inserted] = Visited.insert(Node);
14304 if (!Inserted)
14305 continue;
14306
14307 if (MaxSteps > 0 && Visited.size() >= MaxSteps)
14308 return false;
14309
14310 // Reached the FPNode (would result in a cycle).
14311 // OR Reached CALLSEQ_START (would result in nested call sequences).
14312 if (Node == FPNode || Node->getOpcode() == ISD::CALLSEQ_START)
14313 return false;
14314
14315 if (Node->getOpcode() == ISD::CALLSEQ_END) {
14316 // Defer looking into call sequences (so we can check we're outside one).
14317 // We still need to look through these for the predecessor check.
14318 DeferredNodes.push_back(Node);
14319 continue;
14320 }
14321
14322 for (SDValue Op : Node->ops())
14323 Worklist.push_back(Op.getNode());
14324 }
14325
14326 // True if we're outside a call sequence and don't have the FPNode as a
14327 // predecessor. No cycles or nested call sequences possible.
14328 return !SDNode::hasPredecessorHelper(FPNode, Visited, DeferredNodes,
14329 MaxSteps);
14330}
14331
14333 SelectionDAG &DAG, RTLIB::Libcall LC, SDNode *Node,
14335 std::optional<unsigned> CallRetResNo) const {
14336 if (LC == RTLIB::UNKNOWN_LIBCALL)
14337 return false;
14338
14339 RTLIB::LibcallImpl LibcallImpl =
14341 if (LibcallImpl == RTLIB::Unsupported)
14342 return false;
14343
14344 LLVMContext &Ctx = *DAG.getContext();
14345 EVT VT = Node->getValueType(0);
14346 unsigned NumResults = Node->getNumValues();
14347
14348 // Find users of the node that store the results (and share input chains). The
14349 // destination pointers can be used instead of creating stack allocations.
14350 SDValue StoresInChain;
14351 SmallVector<StoreSDNode *, 2> ResultStores(NumResults);
14352 for (SDNode *User : Node->users()) {
14354 continue;
14355 auto *ST = cast<StoreSDNode>(User);
14356 SDValue StoreValue = ST->getValue();
14357 unsigned ResNo = StoreValue.getResNo();
14358 // Ensure the store corresponds to an output pointer.
14359 if (CallRetResNo == ResNo)
14360 continue;
14361 // Ensure the store to the default address space and not atomic or volatile.
14362 if (!ST->isSimple() || ST->getAddressSpace() != 0)
14363 continue;
14364 // Ensure all store chains are the same (so they don't alias).
14365 if (StoresInChain && ST->getChain() != StoresInChain)
14366 continue;
14367 // Ensure the store is properly aligned.
14368 Type *StoreType = StoreValue.getValueType().getTypeForEVT(Ctx);
14369 if (ST->getAlign() <
14370 DAG.getDataLayout().getABITypeAlign(StoreType->getScalarType()))
14371 continue;
14372 // Avoid:
14373 // 1. Creating cyclic dependencies.
14374 // 2. Expanding the node to a call within a call sequence.
14376 continue;
14377 ResultStores[ResNo] = ST;
14378 StoresInChain = ST->getChain();
14379 }
14380
14381 ArgListTy Args;
14382
14383 // Pass the arguments.
14384 for (const SDValue &Op : Node->op_values()) {
14385 EVT ArgVT = Op.getValueType();
14386 Type *ArgTy = ArgVT.getTypeForEVT(Ctx);
14387 Args.emplace_back(Op, ArgTy);
14388 }
14389
14390 // Pass the output pointers.
14391 SmallVector<SDValue, 2> ResultPtrs(NumResults);
14393 for (auto [ResNo, ST] : llvm::enumerate(ResultStores)) {
14394 if (ResNo == CallRetResNo)
14395 continue;
14396 EVT ResVT = Node->getValueType(ResNo);
14397 SDValue ResultPtr = ST ? ST->getBasePtr() : DAG.CreateStackTemporary(ResVT);
14398 ResultPtrs[ResNo] = ResultPtr;
14399 Args.emplace_back(ResultPtr, PointerTy);
14400 }
14401
14402 SDLoc DL(Node);
14403
14405 // Pass the vector mask (if required).
14406 EVT MaskVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
14407 SDValue Mask = DAG.getBoolConstant(true, DL, MaskVT, VT);
14408 Args.emplace_back(Mask, MaskVT.getTypeForEVT(Ctx));
14409 }
14410
14411 Type *RetType = CallRetResNo.has_value()
14412 ? Node->getValueType(*CallRetResNo).getTypeForEVT(Ctx)
14413 : Type::getVoidTy(Ctx);
14414 SDValue InChain = StoresInChain ? StoresInChain : DAG.getEntryNode();
14415 SDValue Callee =
14416 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
14418 CLI.setDebugLoc(DL).setChain(InChain).setLibCallee(
14419 getLibcallImplCallingConv(LibcallImpl), RetType, Callee, std::move(Args));
14420
14421 auto [Call, CallChain] = LowerCallTo(CLI);
14422
14423 for (auto [ResNo, ResultPtr] : llvm::enumerate(ResultPtrs)) {
14424 if (ResNo == CallRetResNo) {
14425 Results.push_back(Call);
14426 continue;
14427 }
14428 MachinePointerInfo PtrInfo;
14429 SDValue LoadResult = DAG.getLoad(Node->getValueType(ResNo), DL, CallChain,
14430 ResultPtr, PtrInfo);
14431 SDValue OutChain = LoadResult.getValue(1);
14432
14433 if (StoreSDNode *ST = ResultStores[ResNo]) {
14434 // Replace store with the library call.
14435 DAG.ReplaceAllUsesOfValueWith(SDValue(ST, 0), OutChain);
14436 PtrInfo = ST->getPointerInfo();
14437 } else {
14439 DAG.getMachineFunction(),
14440 cast<FrameIndexSDNode>(ResultPtr)->getIndex());
14441 }
14442
14443 Results.push_back(LoadResult);
14444 }
14445
14446 return true;
14447}
14448
14450 SDValue &LHS, SDValue &RHS,
14451 SDValue &CC, bool &NeedInvert,
14452 const SDLoc &dl, SDValue &Chain,
14453 bool IsSignaling) const {
14454 MVT OpVT = LHS.getSimpleValueType();
14455 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
14456 NeedInvert = false;
14457 switch (getCondCodeAction(CCCode, OpVT)) {
14458 default:
14459 llvm_unreachable("Unknown condition code action!");
14461 // Nothing to do.
14462 break;
14465 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14466 std::swap(LHS, RHS);
14467 CC = DAG.getCondCode(InvCC);
14468 return true;
14469 }
14470 // Swapping operands didn't work. Try inverting the condition.
14471 bool NeedSwap = false;
14472 InvCC = getSetCCInverse(CCCode, OpVT);
14473 if (!isCondCodeLegalOrCustom(InvCC, OpVT)) {
14474 // If inverting the condition is not enough, try swapping operands
14475 // on top of it.
14476 InvCC = ISD::getSetCCSwappedOperands(InvCC);
14477 NeedSwap = true;
14478 }
14479 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14480 CC = DAG.getCondCode(InvCC);
14481 NeedInvert = true;
14482 if (NeedSwap)
14483 std::swap(LHS, RHS);
14484 return true;
14485 }
14486
14487 // Special case: expand i1 comparisons using logical operations.
14488 if (OpVT == MVT::i1) {
14489 SDValue Ret;
14490 switch (CCCode) {
14491 default:
14492 llvm_unreachable("Unknown integer setcc!");
14493 case ISD::SETEQ: // X == Y --> ~(X ^ Y)
14494 Ret = DAG.getNOT(dl, DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS),
14495 MVT::i1);
14496 break;
14497 case ISD::SETNE: // X != Y --> (X ^ Y)
14498 Ret = DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS);
14499 break;
14500 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
14501 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
14502 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, RHS,
14503 DAG.getNOT(dl, LHS, MVT::i1));
14504 break;
14505 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
14506 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
14507 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, LHS,
14508 DAG.getNOT(dl, RHS, MVT::i1));
14509 break;
14510 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
14511 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
14512 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, RHS,
14513 DAG.getNOT(dl, LHS, MVT::i1));
14514 break;
14515 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
14516 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
14517 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, LHS,
14518 DAG.getNOT(dl, RHS, MVT::i1));
14519 break;
14520 }
14521
14522 LHS = DAG.getZExtOrTrunc(Ret, dl, VT);
14523 RHS = SDValue();
14524 CC = SDValue();
14525 return true;
14526 }
14527
14529 unsigned Opc = 0;
14530 switch (CCCode) {
14531 default:
14532 llvm_unreachable("Don't know how to expand this condition!");
14533 case ISD::SETUO:
14534 if (isCondCodeLegal(ISD::SETUNE, OpVT)) {
14535 CC1 = ISD::SETUNE;
14536 CC2 = ISD::SETUNE;
14537 Opc = ISD::OR;
14538 break;
14539 }
14541 "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
14542 NeedInvert = true;
14543 [[fallthrough]];
14544 case ISD::SETO:
14546 "If SETO is expanded, SETOEQ must be legal!");
14547 CC1 = ISD::SETOEQ;
14548 CC2 = ISD::SETOEQ;
14549 Opc = ISD::AND;
14550 break;
14551 case ISD::SETONE:
14552 case ISD::SETUEQ:
14553 // If the SETUO or SETO CC isn't legal, we might be able to use
14554 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
14555 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
14556 // the operands.
14557 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14558 if (!isCondCodeLegal(CC2, OpVT) && (isCondCodeLegal(ISD::SETOGT, OpVT) ||
14559 isCondCodeLegal(ISD::SETOLT, OpVT))) {
14560 CC1 = ISD::SETOGT;
14561 CC2 = ISD::SETOLT;
14562 Opc = ISD::OR;
14563 NeedInvert = ((unsigned)CCCode & 0x8U);
14564 break;
14565 }
14566 [[fallthrough]];
14567 case ISD::SETOEQ:
14568 case ISD::SETOGT:
14569 case ISD::SETOGE:
14570 case ISD::SETOLT:
14571 case ISD::SETOLE:
14572 case ISD::SETUNE:
14573 case ISD::SETUGT:
14574 case ISD::SETUGE:
14575 case ISD::SETULT:
14576 case ISD::SETULE:
14577 // If we are floating point, assign and break, otherwise fall through.
14578 if (!OpVT.isInteger()) {
14579 // We can use the 4th bit to tell if we are the unordered
14580 // or ordered version of the opcode.
14581 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14582 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
14583 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
14584 break;
14585 }
14586 // Fallthrough if we are unsigned integer.
14587 [[fallthrough]];
14588 case ISD::SETLE:
14589 case ISD::SETGT:
14590 case ISD::SETGE:
14591 case ISD::SETLT:
14592 case ISD::SETNE:
14593 case ISD::SETEQ:
14594 // If all combinations of inverting the condition and swapping operands
14595 // didn't work then we have no means to expand the condition.
14596 llvm_unreachable("Don't know how to expand this condition!");
14597 }
14598
14599 SDValue SetCC1, SetCC2;
14600 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
14601 // If we aren't the ordered or unorder operation,
14602 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
14603 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
14604 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
14605 } else {
14606 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
14607 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
14608 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
14609 }
14610 if (Chain)
14611 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
14612 SetCC2.getValue(1));
14613 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
14614 RHS = SDValue();
14615 CC = SDValue();
14616 return true;
14617 }
14618 }
14619 return false;
14620}
14621
14623 SelectionDAG &DAG) const {
14624 EVT VT = Node->getValueType(0);
14625 // Despite its documentation, GetSplitDestVTs will assert if VT cannot be
14626 // split into two equal parts.
14627 if (!VT.isVector() || !VT.getVectorElementCount().isKnownMultipleOf(2))
14628 return SDValue();
14629
14630 // Restrict expansion to cases where both parts can be concatenated.
14631 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
14632 if (LoVT != HiVT || !isTypeLegal(LoVT))
14633 return SDValue();
14634
14635 SDLoc DL(Node);
14636 unsigned Opcode = Node->getOpcode();
14637
14638 // Don't expand if the result is likely to be unrolled anyway.
14639 if (!isOperationLegalOrCustomOrPromote(Opcode, LoVT))
14640 return SDValue();
14641
14642 SmallVector<SDValue, 4> LoOps, HiOps;
14643 for (const SDValue &V : Node->op_values()) {
14644 if (!V.getValueType().isVector()) {
14645 // Scalar operands pass through to both halves unchanged.
14646 LoOps.push_back(V);
14647 HiOps.push_back(V);
14648 continue;
14649 }
14650 auto [Lo, Hi] = DAG.SplitVector(V, DL, LoVT, HiVT);
14651 LoOps.push_back(Lo);
14652 HiOps.push_back(Hi);
14653 }
14654
14655 SDValue SplitOpLo = DAG.getNode(Opcode, DL, LoVT, LoOps, Node->getFlags());
14656 SDValue SplitOpHi = DAG.getNode(Opcode, DL, HiVT, HiOps, Node->getFlags());
14657 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SplitOpLo, SplitOpHi);
14658}
14659
14661 const SDLoc &DL,
14662 EVT InVecVT, SDValue EltNo,
14663 LoadSDNode *OriginalLoad,
14664 SelectionDAG &DAG) const {
14665 assert(OriginalLoad->isSimple());
14666
14667 EVT VecEltVT = InVecVT.getVectorElementType();
14668
14669 // If the vector element type is not a multiple of a byte then we are unable
14670 // to correctly compute an address to load only the extracted element as a
14671 // scalar.
14672 if (!VecEltVT.isByteSized())
14673 return SDValue();
14674
14675 ISD::LoadExtType ExtTy =
14676 ResultVT.bitsGT(VecEltVT) ? ISD::EXTLOAD : ISD::NON_EXTLOAD;
14677 if (!isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14678 return SDValue();
14679
14680 std::optional<unsigned> ByteOffset;
14681 Align Alignment = OriginalLoad->getAlign();
14683 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14684 int Elt = ConstEltNo->getZExtValue();
14685 ByteOffset = VecEltVT.getSizeInBits() * Elt / 8;
14686 MPI = OriginalLoad->getPointerInfo().getWithOffset(*ByteOffset);
14687 Alignment = commonAlignment(Alignment, *ByteOffset);
14688 } else {
14689 // Discard the pointer info except the address space because the memory
14690 // operand can't represent this new access since the offset is variable.
14691 MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace());
14692 Alignment = commonAlignment(Alignment, VecEltVT.getSizeInBits() / 8);
14693 }
14694
14695 if (!shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT, ByteOffset))
14696 return SDValue();
14697
14698 unsigned IsFast = 0;
14699 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VecEltVT,
14700 OriginalLoad->getAddressSpace(), Alignment,
14701 OriginalLoad->getMemOperand()->getFlags(), &IsFast) ||
14702 !IsFast)
14703 return SDValue();
14704
14705 // The original DAG loaded the entire vector from memory, so arithmetic
14706 // within it must be inbounds.
14708 DAG, OriginalLoad->getBasePtr(), InVecVT, EltNo);
14709
14710 // We are replacing a vector load with a scalar load. The new load must have
14711 // identical memory op ordering to the original.
14712 SDValue Load;
14713 if (ResultVT.bitsGT(VecEltVT)) {
14714 // If the result type of vextract is wider than the load, then issue an
14715 // extending load instead.
14716 ISD::LoadExtType ExtType =
14717 isLoadLegal(ResultVT, VecEltVT, Alignment,
14718 OriginalLoad->getAddressSpace(), ISD::ZEXTLOAD, false)
14720 : ISD::EXTLOAD;
14721 Load = DAG.getExtLoad(ExtType, DL, ResultVT, OriginalLoad->getChain(),
14722 NewPtr, MPI, VecEltVT, Alignment,
14723 OriginalLoad->getMemOperand()->getFlags(),
14724 OriginalLoad->getMMOMetadataForSubAccess());
14725 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14726 } else {
14727 // The result type is narrower or the same width as the vector element
14728 Load = DAG.getLoad(VecEltVT, DL, OriginalLoad->getChain(), NewPtr, MPI,
14729 Alignment, OriginalLoad->getMemOperand()->getFlags(),
14730 OriginalLoad->getMMOMetadataForSubAccess());
14731 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14732 if (ResultVT.bitsLT(VecEltVT))
14733 Load = DAG.getNode(ISD::TRUNCATE, DL, ResultVT, Load);
14734 else
14735 Load = DAG.getBitcast(ResultVT, Load);
14736 }
14737
14738 return Load;
14739}
14740
14741// Set type id for call site info and metadata 'call_target'.
14742// We are filtering for:
14743// a) The call-graph-section use case that wants to know about indirect
14744// calls, or
14745// b) We want to annotate indirect calls.
14747 const CallBase *CB, MachineFunction &MF,
14748 MachineFunction::CallSiteInfo &CSInfo) const {
14749 if (CB && CB->isIndirectCall() &&
14752 CSInfo = MachineFunction::CallSiteInfo(*CB);
14753}
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
constexpr LLT F32
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
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 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
const SmallVectorImpl< MachineOperand > & Cond
Contains matchers for matching SelectionDAG nodes and values.
This file contains some templates that are useful if you are working with the STL at all.
static cl::opt< unsigned > MaxSteps("has-predecessor-max-steps", cl::Hidden, cl::init(8192), cl::desc("DAG combiner limit number of steps when searching DAG " "for predecessor nodes"))
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static std::pair< SDValue, SDValue > getLegalMaskAndStepVector(SDValue Mask, bool ZeroIsPoison, SDLoc DL, SelectionDAG &DAG)
Returns a type-legalized version of Mask as the first item in the pair.
static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, const SDLoc &dl, SelectionDAG &DAG)
static bool lowerImmediateIfPossible(TargetLowering::ConstraintPair &P, SDValue Op, SelectionDAG *DAG, const TargetLowering &TLI)
If we have an immediate, see if we can lower it.
#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 clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx, EVT VecVT, const SDLoc &dl, ElementCount SubEC)
static unsigned getConstraintPiority(TargetLowering::ConstraintType CT)
Return a number indicating our preference for chosing a type of constraint over another,...
static std::optional< bool > isFCmpEqualZero(FPClassTest Test, const fltSemantics &Semantics, const MachineFunction &MF)
Returns a true value if if this FPClassTest can be performed with an ordered fcmp to 0,...
static bool canFoldStoreIntoLibCallOutputPointers(StoreSDNode *StoreNode, SDNode *FPNode)
Given a store node StoreNode, return true if it is safe to fold that node into FPNode,...
static void turnVectorIntoSplatVector(MutableArrayRef< SDValue > Values, std::function< bool(SDValue)> Predicate, SDValue AlternativeReplacement=SDValue())
If all values in Values that don't match the predicate are same 'splat' value, then replace all value...
static 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
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
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
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition APInt.h:1253
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
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
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 isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:401
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:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:305
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:311
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:71
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,...
LLVM_ABI MCRegister getLiveInPhysReg(Register VReg) const
getLiveInPhysReg - If VReg is a live-in virtual register, return the corresponding live-in physical r...
unsigned getAddressSpace() const
Return the address space for the associated pointer.
Align getAlign() const
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
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 setAttributes(const CallBase *Call, unsigned ArgIdx)
ArgListEntry(Value *Val, SDValue Node, Type *Ty)
Type * Ty
Same as OrigTy, or partially legalized for soft float libcalls.
bool isOperationExpand(unsigned Op, EVT VT) const
Return true if the specified operation is illegal on this target or unlikely to be made legal with cu...
unsigned getBitWidthForCttzElements(EVT RetVT, ElementCount EC, bool ZeroIsPoison, const ConstantRange *VScaleRange) const
Return the minimum number of bits required to hold the maximum possible number of trailing zero vecto...
virtual 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 isCtpopFast(EVT VT) const
Return true if ctpop instruction is fast.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
bool isPaddedAtMostSignificantBitsWhenStored(EVT VT) const
Indicates if any padding is guaranteed to go at the most significant bits when storing the type to me...
LegalizeTypeAction
This enum indicates whether a types are legal for a target, and if not, what action should be used to...
virtual bool hasBitTest(SDValue X, SDValue Y) const
Return true if the target has a bit-test instruction: (X & (1 << Y)) ==/!= 0 This knowledge can be us...
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 isFPImmLegal(const APFloat &, EVT, bool ForCodeSize=false) const
Returns true if the target can instruction select the specified FP immediate natively.
virtual bool shouldTransformSignedTruncationCheck(EVT XVT, unsigned KeptBits) const
Should we tranform the IR-optimal check for whether given truncation down into KeptBits would be trun...
bool isLegalRC(const TargetRegisterInfo &TRI, const TargetRegisterClass &RC) const
Return true if the value types that can be represented by the specified register class are all legal.
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
Determine if the target supports unaligned memory accesses.
bool isOperationCustom(unsigned Op, EVT VT) const
Return true if the operation uses custom lowering, regardless of whether the type is legal or not.
EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL) const
Returns the type for the shift amount of a shift opcode.
virtual bool shouldExtendTypeInLibCall(EVT Type) const
Returns true if arguments should be extended in lib calls.
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
virtual bool shouldAvoidTransformToShift(EVT VT, unsigned Amount) const
Return true if creating a shift of the type by the given amount is not profitable.
virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const
Return true if an fpext operation is free (for instance, because single-precision floating-point numb...
virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const
Return the ValueType of the result of SETCC operations.
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
BooleanContent getBooleanContents(bool isVec, bool isFloat) const
For targets without i1 registers, this gives the nature of the high-bits of boolean values held in ty...
bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal for a comparison of the specified types on this ...
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
TargetLoweringBase(const TargetMachine &TM, const TargetSubtargetInfo &STI)
NOTE: The TargetMachine owns TLOF.
virtual unsigned getCustomCtpopCost(EVT VT, ISD::CondCode Cond) const
Return the maximum number of "x & (x - 1)" operations that can be done instead of deferring to a cust...
virtual bool shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, unsigned OldShiftOpcode, unsigned NewShiftOpcode, SelectionDAG &DAG) const
Given the pattern (X & (C l>>/<< Y)) ==/!= 0 return true if it should be transformed into: ((X <</l>>...
BooleanContent
Enum that describes how the target represents true/false values.
virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const
Return true if integer divide is usually cheaper than a sequence of several shifts,...
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
virtual bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const
Return true if the target supports a memory access of this type for the given address space and align...
virtual bool hasAndNotCompare(SDValue Y) const
Return true if the target should transform: (X & Y) == Y ---> (~X & Y) == 0 (X & Y) !...
virtual bool isNarrowingProfitable(SDNode *N, EVT SrcVT, EVT DestVT) const
Return true if it's profitable to narrow operations of type SrcVT to DestVT.
virtual bool isBinOp(unsigned Opcode) const
Return true if the node is a math/logic binary operator.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Get the libcall impl routine name for the specified libcall.
virtual bool isCtlzFast() const
Return true if ctlz instruction is fast.
virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT, bool IsSigned) const
Return true if it is more correct/profitable to use strict FP_TO_INT conversion operations - canonica...
NegatibleCost
Enum that specifies when a float negation is beneficial.
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
virtual bool shouldSignExtendTypeInLibCall(Type *Ty, bool IsSigned) const
Returns true if arguments should be sign-extended in lib calls.
std::vector< ArgListEntry > ArgListTy
virtual EVT getOptimalMemOpType(LLVMContext &Context, const MemOp &Op, const AttributeList &) const
Returns the target specific optimal type for load and store operations as a result of memset,...
virtual EVT getAsmOperandValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
bool isCondCodeLegalOrCustom(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal or custom for a comparison of the specified type...
bool isLoadLegal(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return true if the specified load with extension is legal on this target.
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 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.
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:339
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:716
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
constexpr bool isKnownMultipleOf(ScalarTy RHS) const
This function tells the caller whether the element count is known at compile time to be a multiple of...
Definition TypeSize.h:180
constexpr 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:265
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:230
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:273
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp: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:837
@ 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
@ 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:797
@ 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:871
@ 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:898
@ 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:757
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:928
@ 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:788
@ 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:806
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:862
@ 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:814
@ 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:779
@ 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 - Perform floating-point minimumNumber or maximumNumber on two values,...
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:868
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:829
@ FMINNUM
FMINNUM/FMAXNUM - Perform floating-point minimum maximum on two values, following IEEE-754 definition...
@ SSHLSAT
RESULT = [US]SHLSAT(LHS, RHS) - Perform saturation left shift.
Definition ISDOpcodes.h: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:917
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:906
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:737
@ 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.
Definition ISDOpcodes.h:996
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:823
@ 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:793
@ 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 - NaN-propagating minimum/maximum that also treat -0.0 as less than 0....
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:944
@ 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:749
@ 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:805
@ 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:977
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:939
@ 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:963
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:874
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:851
@ 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 - minimumnum/maximumnum that is same with FMINNUM_IEEE and FMAXNUM_IEEE besid...
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:732
@ 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:761
@ 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)
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
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:1558
@ 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:541
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:1540
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:1727
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
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:418
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
EVT changeTypeToInteger() const
Return the type converted to an equivalently sized integer or vector with integer element type.
Definition ValueTypes.h:129
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:307
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
ElementCount getVectorElementCount() const
Definition ValueTypes.h:373
EVT getDoubleNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:494
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
bool isByteSized() const
Return true if the bit size is a multiple of 8.
Definition ValueTypes.h:266
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:382
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
EVT getHalfSizedIntegerVT(LLVMContext &Context) const
Finds the smallest simple value type that is greater than or equal to half the width of this EVT.
Definition ValueTypes.h:453
bool isPow2VectorType() const
Returns true if the given vector is a power of 2.
Definition ValueTypes.h:501
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:435
EVT changeVectorElementType(LLVMContext &Context, EVT EltVT) const
Return a VT for a vector type whose attributes match ourselves with the exception of the element type...
Definition ValueTypes.h:98
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:404
EVT widenIntegerVectorElementType(LLVMContext &Context) const
Return a VT for an integer vector type with the size of the elements doubled.
Definition ValueTypes.h:475
EVT changeVectorElementCount(LLVMContext &Context, ElementCount EC) const
Return a VT for a vector type whose attributes match ourselves with the exception of the element coun...
Definition ValueTypes.h:109
bool isScalableVT() const
Return true if the type is a scalable type.
Definition ValueTypes.h:210
bool isFixedLengthVector() const
Definition ValueTypes.h:199
LLVM_ABI std::string getEVTString() const
This function returns value type as a string, e.g. "i32".
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
bool bitsEq(EVT VT) const
Return true if this has the same number of bits as VT.
Definition ValueTypes.h:279
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
EVT widenIntegerElementType(LLVMContext &Context) const
Return a VT for an integer element type with doubled bit width.
Definition ValueTypes.h:467
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:187
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
EVT changeElementType(LLVMContext &Context, EVT EltVT) const
Return a VT for a type whose attributes match ourselves with the exception of the element type that i...
Definition ValueTypes.h:121
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:165
LLVM_ABI const fltSemantics & getFltSemantics() const
Returns an APFloat semantics tag appropriate for the value type.
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Definition ValueTypes.h:331
EVT getHalfNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:484
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
KnownBits trunc(unsigned BitWidth) const
Return known bits for a truncation of the value we're tracking.
Definition KnownBits.h:165
KnownBits byteSwap() const
Definition KnownBits.h:559
static LLVM_ABI std::optional< bool > sge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGE result.
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
KnownBits reverseBits() const
Definition KnownBits.h:563
KnownBits concat(const KnownBits &Lo) const
Concatenate the bits from Lo onto the bottom of *this.
Definition KnownBits.h:247
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI std::optional< bool > ugt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGT result.
static LLVM_ABI std::optional< bool > slt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SLT result.
static LLVM_ABI KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition KnownBits.cpp:61
static LLVM_ABI std::optional< bool > ult(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_ULT result.
static LLVM_ABI std::optional< bool > ule(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_ULE result.
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
static LLVM_ABI std::optional< bool > sle(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SLE result.
static LLVM_ABI std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
unsigned countMinPopulation() const
Returns the number of bits known to be one.
Definition KnownBits.h:300
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
Matching combinators.
This class contains a discriminated union of information about pointers in memory operands,...
LLVM_ABI unsigned getAddrSpace() const
Return the LLVM IR address space number that this pointer points into.
static LLVM_ABI MachinePointerInfo getConstantPool(MachineFunction &MF)
Return a MachinePointerInfo record that refers to the constant pool.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getUnknownStack(MachineFunction &MF)
Stack memory without other information.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
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