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>
40using namespace llvm;
41using namespace llvm::SDPatternMatch;
42
43/// NOTE: The TargetMachine owns TLOF.
47
48// Define the virtual destructor out-of-line for build efficiency.
50
51const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
52 return nullptr;
53}
54
58
59/// Check whether a given call node is in tail position within its function. If
60/// so, it sets Chain to the input chain of the tail call.
62 SDValue &Chain) const {
64
65 // First, check if tail calls have been disabled in this function.
66 if (F.getFnAttribute("disable-tail-calls").getValueAsBool())
67 return false;
68
69 // Conservatively require the attributes of the call to match those of
70 // the return. Ignore following attributes because they don't affect the
71 // call sequence.
72 AttrBuilder CallerAttrs(F.getContext(), F.getAttributes().getRetAttrs());
73 for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable,
74 Attribute::DereferenceableOrNull, Attribute::NoAlias,
75 Attribute::NonNull, Attribute::NoUndef,
76 Attribute::Range, Attribute::NoFPClass})
77 CallerAttrs.removeAttribute(Attr);
78
79 if (CallerAttrs.hasAttributes())
80 return false;
81
82 // It's not safe to eliminate the sign / zero extension of the return value.
83 if (CallerAttrs.contains(Attribute::ZExt) ||
84 CallerAttrs.contains(Attribute::SExt))
85 return false;
86
87 // Check if the only use is a function return node.
88 return isUsedByReturnOnly(Node, Chain);
89}
90
92 const uint32_t *CallerPreservedMask,
93 const SmallVectorImpl<CCValAssign> &ArgLocs,
94 const SmallVectorImpl<SDValue> &OutVals) const {
95 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
96 const CCValAssign &ArgLoc = ArgLocs[I];
97 if (!ArgLoc.isRegLoc())
98 continue;
99 MCRegister Reg = ArgLoc.getLocReg();
100 // Only look at callee saved registers.
101 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
102 continue;
103 // Check that we pass the value used for the caller.
104 // (We look for a CopyFromReg reading a virtual register that is used
105 // for the function live-in value of register Reg)
106 SDValue Value = OutVals[I];
107 if (Value->getOpcode() == ISD::AssertZext)
108 Value = Value.getOperand(0);
109 if (Value->getOpcode() != ISD::CopyFromReg)
110 return false;
111 Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
112 if (MRI.getLiveInPhysReg(ArgReg) != Reg)
113 return false;
114 }
115 return true;
116}
117
118/// Set CallLoweringInfo attribute flags based on a call instruction
119/// and called function attributes.
121 unsigned ArgIdx) {
122 IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt);
123 IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt);
124 IsNoExt = Call->paramHasAttr(ArgIdx, Attribute::NoExt);
125 IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg);
126 IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet);
127 IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest);
128 IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal);
129 IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated);
130 IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca);
131 IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned);
132 IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf);
133 IsSwiftAsync = Call->paramHasAttr(ArgIdx, Attribute::SwiftAsync);
134 IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError);
135 Alignment = Call->getParamStackAlign(ArgIdx);
136 IndirectType = nullptr;
138 "multiple ABI attributes?");
139 if (IsByVal) {
140 IndirectType = Call->getParamByValType(ArgIdx);
141 if (!Alignment)
142 Alignment = Call->getParamAlign(ArgIdx);
143 }
144 if (IsPreallocated)
145 IndirectType = Call->getParamPreallocatedType(ArgIdx);
146 if (IsInAlloca)
147 IndirectType = Call->getParamInAllocaType(ArgIdx);
148 if (IsSRet)
149 IndirectType = Call->getParamStructRetType(ArgIdx);
150}
151
152/// Generate a libcall taking the given operands as arguments and returning a
153/// result of type RetVT.
154std::pair<SDValue, SDValue>
155TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl,
157 MakeLibCallOptions CallOptions, const SDLoc &dl,
158 SDValue InChain) const {
159 if (LibcallImpl == RTLIB::Unsupported)
160 reportFatalInternalError("unsupported library call operation");
161
162 if (!InChain)
163 InChain = DAG.getEntryNode();
164
166 Args.reserve(Ops.size());
167
168 ArrayRef<Type *> OpsTypeOverrides = CallOptions.OpsTypeOverrides;
169 for (unsigned i = 0; i < Ops.size(); ++i) {
170 SDValue NewOp = Ops[i];
171 Type *Ty = i < OpsTypeOverrides.size() && OpsTypeOverrides[i]
172 ? OpsTypeOverrides[i]
173 : NewOp.getValueType().getTypeForEVT(*DAG.getContext());
174 TargetLowering::ArgListEntry Entry(NewOp, Ty);
175 if (CallOptions.IsSoften)
176 Entry.OrigTy =
177 CallOptions.OpsVTBeforeSoften[i].getTypeForEVT(*DAG.getContext());
178
179 Entry.IsSExt =
180 shouldSignExtendTypeInLibCall(Entry.Ty, CallOptions.IsSigned);
181 Entry.IsZExt = !Entry.IsSExt;
182
183 if (CallOptions.IsSoften &&
185 Entry.IsSExt = Entry.IsZExt = false;
186 }
187 Args.push_back(Entry);
188 }
189
190 SDValue Callee =
191 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
192
193 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
194 Type *OrigRetTy = RetTy;
196 bool signExtend = shouldSignExtendTypeInLibCall(RetTy, CallOptions.IsSigned);
197 bool zeroExtend = !signExtend;
198
199 if (CallOptions.IsSoften) {
200 OrigRetTy = CallOptions.RetVTBeforeSoften.getTypeForEVT(*DAG.getContext());
202 signExtend = zeroExtend = false;
203 }
204
205 CLI.setDebugLoc(dl)
206 .setChain(InChain)
207 .setLibCallee(getLibcallImplCallingConv(LibcallImpl), RetTy, OrigRetTy,
208 Callee, std::move(Args))
209 .setNoReturn(CallOptions.DoesNotReturn)
212 .setSExtResult(signExtend)
213 .setZExtResult(zeroExtend);
214 return LowerCallTo(CLI);
215}
216
218 LLVMContext &Context, std::vector<EVT> &MemOps, unsigned Limit,
219 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
220 const AttributeList &FuncAttributes, EVT *LargestVT) const {
221 EVT VT = getOptimalMemOpType(Context, Op, FuncAttributes);
222
223 if (VT == MVT::Other) {
224 // Use the largest integer type whose alignment constraints are satisfied.
225 VT = MVT::LAST_INTEGER_VALUETYPE;
226 if (Op.isFixedDstAlign()) {
227 bool LoadsFromSrc = Op.isMemcpyOrMemmove() && !Op.isMemcpyStrSrc();
228 while (VT != MVT::i8) {
229 unsigned VTSize = VT.getSizeInBits() / 8;
230 bool DstOk =
231 Op.getDstAlign() >= VTSize ||
232 allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign());
233 bool SrcOk =
234 !LoadsFromSrc || Op.getSrcAlign() >= VTSize ||
235 allowsMisalignedMemoryAccesses(VT, SrcAS, Op.getSrcAlign());
236 if (DstOk && SrcOk)
237 break;
239 }
240 }
241 assert(VT.isInteger());
242
243 // Find the largest legal integer type.
244 MVT LVT = MVT::LAST_INTEGER_VALUETYPE;
245 while (!isTypeLegal(LVT))
246 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
247 assert(LVT.isInteger());
248
249 // If the type we've chosen is larger than the largest legal integer type
250 // then use the largest legal type.
251 if (VT.bitsGT(LVT))
252 VT = LVT;
253 }
254
255 unsigned NumMemOps = 0;
256 uint64_t Size = Op.size();
257 while (Size) {
258 unsigned VTSize = VT.getSizeInBits() / 8;
259 while (VTSize > Size) {
260 // For now, only use non-vector load / store's for the left-over pieces.
261 EVT NewVT = VT;
262 unsigned NewVTSize;
263
264 bool Found = false;
265 if (VT.isVector() || VT.isFloatingPoint()) {
266 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
269 Found = true;
270 else if (NewVT == MVT::i64 &&
272 isSafeMemOpType(MVT::f64)) {
273 // i64 is usually not legal on 32-bit targets, but f64 may be.
274 NewVT = MVT::f64;
275 Found = true;
276 }
277 }
278
279 if (!Found) {
280 do {
281 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
282 if (NewVT == MVT::i8)
283 break;
284 } while (!isSafeMemOpType(NewVT.getSimpleVT()));
285 }
286 NewVTSize = NewVT.getSizeInBits() / 8;
287
288 // If the new VT cannot cover all of the remaining bits, then consider
289 // issuing a (or a pair of) unaligned and overlapping load / store.
290 unsigned Fast;
291 if (NumMemOps && !Op.isVolatile() && NewVTSize < Size &&
293 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
295 Fast)
296 VTSize = Size;
297 else {
298 VT = NewVT;
299 VTSize = NewVTSize;
300 }
301 }
302
303 if (++NumMemOps > Limit)
304 return false;
305
306 MemOps.push_back(VT);
307 Size -= VTSize;
308 }
309
310 return true;
311}
312
313/// Soften the operands of a comparison. This code is shared among BR_CC,
314/// SELECT_CC, and SETCC handlers.
316 SDValue &NewLHS, SDValue &NewRHS,
317 ISD::CondCode &CCCode,
318 const SDLoc &dl, const SDValue OldLHS,
319 const SDValue OldRHS) const {
320 SDValue Chain;
321 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS,
322 OldRHS, Chain);
323}
324
325/// Select the libcall and the condition code to test its result against 0 for
326/// an ordered floating-point compare. \p BoolLC is the boolean helper (result
327/// is 0/1). \p TriStateLC is the per-predicate three-way helper and \p
328/// GenericLC the generic single-symbol three-way helper (both return -1/0/1,
329/// tested against 0 with \p TriStateCC). The boolean form is preferred, then
330/// the per-predicate three-way, then the generic three-way.
331static std::pair<RTLIB::Libcall, ISD::CondCode>
332selectFPCmpLibcall(const LibcallLoweringInfo &Libcalls, RTLIB::Libcall BoolLC,
333 RTLIB::Libcall TriStateLC, RTLIB::Libcall GenericLC,
334 ISD::CondCode TriStateCC) {
335 if (Libcalls.getLibcallImpl(BoolLC) != RTLIB::Unsupported)
336 return {BoolLC, ISD::SETNE};
337 if (Libcalls.getLibcallImpl(TriStateLC) != RTLIB::Unsupported)
338 return {TriStateLC, TriStateCC};
339 return {GenericLC, TriStateCC};
340}
341
343 SDValue &NewLHS, SDValue &NewRHS,
344 ISD::CondCode &CCCode,
345 const SDLoc &dl, const SDValue OldLHS,
346 const SDValue OldRHS,
347 SDValue &Chain,
348 bool IsSignaling) const {
349 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc
350 // not supporting it. We can update this code when libgcc provides such
351 // functions.
352
353 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
354 && "Unsupported setcc type!");
355
356 // Expand into one or more soft-fp libcall(s).
357 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
359 bool ShouldInvertCC = false;
360
361 // Expand a compare libcall family name (e.g. OEQ, FCMP3_PRED_OEQ) to the
362 // RTLIB::Libcall for VT.
363#define FP_CMP_LIBCALL(BASE) \
364 RTLIB::getFPLibCall(VT, RTLIB::BASE##_F32, RTLIB::BASE##_F64, \
365 RTLIB::UNKNOWN_LIBCALL, RTLIB::BASE##_F128, \
366 RTLIB::BASE##_PPCF128)
367
368 switch (CCCode) {
369 case ISD::SETEQ:
370 case ISD::SETOEQ:
371 std::tie(LC1, CC1) = selectFPCmpLibcall(
372 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ), FP_CMP_LIBCALL(FCMP3_PRED_OEQ),
373 FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
374 break;
375 case ISD::SETNE:
376 case ISD::SETUNE:
377 std::tie(LC1, CC1) = selectFPCmpLibcall(
378 DAG.getLibcalls(), FP_CMP_LIBCALL(UNE), FP_CMP_LIBCALL(FCMP3_PRED_UNE),
379 FP_CMP_LIBCALL(FCMP3), ISD::SETNE);
380 // Some ABIs (e.g. AEABI) provide neither a not-equal nor a three-way
381 // compare; obtain not-equal (UNE = !OEQ) by inverting ordered-equal.
382 if (DAG.getLibcalls().getLibcallImpl(LC1) == RTLIB::Unsupported) {
383 std::tie(LC1, CC1) = selectFPCmpLibcall(
384 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ),
385 FP_CMP_LIBCALL(FCMP3_PRED_OEQ), FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
386 ShouldInvertCC = true;
387 }
388 break;
389 case ISD::SETGE:
390 case ISD::SETOGE:
391 std::tie(LC1, CC1) = selectFPCmpLibcall(
392 DAG.getLibcalls(), FP_CMP_LIBCALL(OGE), FP_CMP_LIBCALL(FCMP3_PRED_OGE),
393 FP_CMP_LIBCALL(FCMP3), ISD::SETGE);
394 break;
395 case ISD::SETLT:
396 case ISD::SETOLT:
397 std::tie(LC1, CC1) = selectFPCmpLibcall(
398 DAG.getLibcalls(), FP_CMP_LIBCALL(OLT), FP_CMP_LIBCALL(FCMP3_PRED_OLT),
399 FP_CMP_LIBCALL(FCMP3), ISD::SETLT);
400 break;
401 case ISD::SETLE:
402 case ISD::SETOLE:
403 std::tie(LC1, CC1) = selectFPCmpLibcall(
404 DAG.getLibcalls(), FP_CMP_LIBCALL(OLE), FP_CMP_LIBCALL(FCMP3_PRED_OLE),
405 FP_CMP_LIBCALL(FCMP3), ISD::SETLE);
406 break;
407 case ISD::SETGT:
408 case ISD::SETOGT:
409 std::tie(LC1, CC1) = selectFPCmpLibcall(
410 DAG.getLibcalls(), FP_CMP_LIBCALL(OGT), FP_CMP_LIBCALL(FCMP3_PRED_OGT),
411 FP_CMP_LIBCALL(FCMP3), ISD::SETGT);
412 break;
413 case ISD::SETO:
414 ShouldInvertCC = true;
415 [[fallthrough]];
416 case ISD::SETUO:
417 // Unordered is a boolean everywhere (__unordXf2 returns 0/1).
418 LC1 = FP_CMP_LIBCALL(UO);
419 CC1 = ISD::SETNE;
420 break;
421 case ISD::SETONE:
422 // SETONE = O && UNE
423 ShouldInvertCC = true;
424 [[fallthrough]];
425 case ISD::SETUEQ:
426 LC1 = FP_CMP_LIBCALL(UO);
427 CC1 = ISD::SETNE;
428 std::tie(LC2, CC2) = selectFPCmpLibcall(
429 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ), FP_CMP_LIBCALL(FCMP3_PRED_OEQ),
430 FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
431 break;
432 default:
433 // Invert CC for unordered comparisons, handled by the ordered inverse.
434 ShouldInvertCC = true;
435 switch (CCCode) {
436 case ISD::SETULT:
437 std::tie(LC1, CC1) = selectFPCmpLibcall(
438 DAG.getLibcalls(), FP_CMP_LIBCALL(OGE),
439 FP_CMP_LIBCALL(FCMP3_PRED_OGE), FP_CMP_LIBCALL(FCMP3), ISD::SETGE);
440 break;
441 case ISD::SETULE:
442 std::tie(LC1, CC1) = selectFPCmpLibcall(
443 DAG.getLibcalls(), FP_CMP_LIBCALL(OGT),
444 FP_CMP_LIBCALL(FCMP3_PRED_OGT), FP_CMP_LIBCALL(FCMP3), ISD::SETGT);
445 break;
446 case ISD::SETUGT:
447 std::tie(LC1, CC1) = selectFPCmpLibcall(
448 DAG.getLibcalls(), FP_CMP_LIBCALL(OLE),
449 FP_CMP_LIBCALL(FCMP3_PRED_OLE), FP_CMP_LIBCALL(FCMP3), ISD::SETLE);
450 break;
451 case ISD::SETUGE:
452 std::tie(LC1, CC1) = selectFPCmpLibcall(
453 DAG.getLibcalls(), FP_CMP_LIBCALL(OLT),
454 FP_CMP_LIBCALL(FCMP3_PRED_OLT), FP_CMP_LIBCALL(FCMP3), ISD::SETLT);
455 break;
456 default:
457 llvm_unreachable("Do not know how to soften this setcc!");
458 }
459 }
460
461#undef FP_CMP_LIBCALL
462
463 // Use the target specific return value for comparison lib calls.
465 SDValue Ops[2] = {NewLHS, NewRHS};
467 EVT OpsVT[2] = { OldLHS.getValueType(),
468 OldRHS.getValueType() };
469 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT);
470 auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain);
471 NewLHS = Call.first;
472 NewRHS = DAG.getConstant(0, dl, RetVT);
473
474 if (DAG.getLibcalls().getLibcallImpl(LC1) == RTLIB::Unsupported) {
476 "no libcall available to soften floating-point compare");
477 }
478
479 CCCode = CC1;
480 if (ShouldInvertCC) {
481 assert(RetVT.isInteger());
482 CCCode = getSetCCInverse(CCCode, RetVT);
483 }
484
485 if (LC2 == RTLIB::UNKNOWN_LIBCALL) {
486 // Update Chain.
487 Chain = Call.second;
488 } else {
489 if (DAG.getLibcalls().getLibcallImpl(LC2) == RTLIB::Unsupported) {
491 "no libcall available to soften floating-point compare");
492 }
493
494 assert(CCCode == (ShouldInvertCC ? ISD::SETEQ : ISD::SETNE) &&
495 "unordered call should be simple boolean");
496
497 EVT SetCCVT =
498 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT);
500 NewLHS = DAG.getNode(ISD::AssertZext, dl, RetVT, Call.first,
501 DAG.getValueType(MVT::i1));
502 }
503
504 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode);
505 auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain);
506 CCCode = CC2;
507 if (ShouldInvertCC)
508 CCCode = getSetCCInverse(CCCode, RetVT);
509 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode);
510 if (Chain)
511 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second,
512 Call2.second);
513 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl,
514 Tmp.getValueType(), Tmp, NewLHS);
515 NewRHS = SDValue();
516 }
517}
518
519/// Return the entry encoding for a jump table in the current function. The
520/// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
522 // In non-pic modes, just use the address of a block.
525
526 // Otherwise, use a label difference.
528}
529
534
535/// This returns the relocation base for the given PIC jumptable, the same as
536/// getPICJumpTableRelocBase, but as an MCExpr.
537const MCExpr *
539 unsigned JTI,MCContext &Ctx) const{
540 // The normal PIC reloc base is the label at the start of the jump table.
541 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
542}
543
545 SDValue Addr, int JTI,
546 SelectionDAG &DAG) const {
547 SDValue Chain = Value;
548 // Jump table debug info is only needed if CodeView is enabled.
550 Chain = DAG.getJumpTableDebugInfo(JTI, Chain, dl);
551 }
552 return DAG.getNode(ISD::BRIND, dl, MVT::Other, Chain, Addr);
553}
554
555bool
557 const TargetMachine &TM = getTargetMachine();
558 const GlobalValue *GV = GA->getGlobal();
559
560 // If the address is not even local to this DSO we will have to load it from
561 // a got and then add the offset.
562 if (!TM.shouldAssumeDSOLocal(GV))
563 return false;
564
565 // If the code is position independent we will have to add a base register.
567 return false;
568
569 // Otherwise we can do it.
570 return true;
571}
572
573//===----------------------------------------------------------------------===//
574// Optimization Methods
575//===----------------------------------------------------------------------===//
576
577/// If the specified instruction has a constant integer operand and there are
578/// bits set in that constant that are not demanded, then clear those bits and
579/// return true.
581 const APInt &DemandedBits,
582 const APInt &DemandedElts,
583 TargetLoweringOpt &TLO) const {
584 SDLoc DL(Op);
585 unsigned Opcode = Op.getOpcode();
586
587 // Early-out if we've ended up calling an undemanded node, leave this to
588 // constant folding.
589 if (DemandedBits.isZero() || DemandedElts.isZero())
590 return false;
591
592 // Do target-specific constant optimization.
593 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
594 return TLO.New.getNode();
595
596 // FIXME: ISD::SELECT, ISD::SELECT_CC
597 switch (Opcode) {
598 default:
599 break;
600 case ISD::XOR:
601 case ISD::AND:
602 case ISD::OR: {
603 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
604 if (!Op1C || Op1C->isOpaque())
605 return false;
606
607 // If this is a 'not' op, don't touch it because that's a canonical form.
608 const APInt &C = Op1C->getAPIntValue();
609 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C))
610 return false;
611
612 if (!C.isSubsetOf(DemandedBits)) {
613 EVT VT = Op.getValueType();
614 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT);
615 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC,
616 Op->getFlags());
617 return TLO.CombineTo(Op, NewOp);
618 }
619
620 break;
621 }
622 }
623
624 return false;
625}
626
628 const APInt &DemandedBits,
629 TargetLoweringOpt &TLO) const {
630 EVT VT = Op.getValueType();
631 APInt DemandedElts = VT.isVector()
633 : APInt(1, 1);
634 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO);
635}
636
637/// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
638/// This uses isTruncateFree/isZExtFree and ANY_EXTEND for the widening cast,
639/// but it could be generalized for targets with other types of implicit
640/// widening casts.
642 const APInt &DemandedBits,
643 TargetLoweringOpt &TLO) const {
644 assert(Op.getNumOperands() == 2 &&
645 "ShrinkDemandedOp only supports binary operators!");
646 assert(Op.getNode()->getNumValues() == 1 &&
647 "ShrinkDemandedOp only supports nodes with one result!");
648
649 EVT VT = Op.getValueType();
650 SelectionDAG &DAG = TLO.DAG;
651 SDLoc dl(Op);
652
653 // Early return, as this function cannot handle vector types.
654 if (VT.isVector())
655 return false;
656
657 assert(Op.getOperand(0).getValueType().getScalarSizeInBits() == BitWidth &&
658 Op.getOperand(1).getValueType().getScalarSizeInBits() == BitWidth &&
659 "ShrinkDemandedOp only supports operands that have the same size!");
660
661 // Don't do this if the node has another user, which may require the
662 // full value.
663 if (!Op.getNode()->hasOneUse())
664 return false;
665
666 // Search for the smallest integer type with free casts to and from
667 // Op's type. For expedience, just check power-of-2 integer types.
668 unsigned DemandedSize = DemandedBits.getActiveBits();
669 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize);
670 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
671 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
672 if (isTruncateFree(Op, SmallVT) && isZExtFree(SmallVT, VT)) {
673 // We found a type with free casts.
674
675 // If the operation has the 'disjoint' flag, then the
676 // operands on the new node are also disjoint.
677 SDNodeFlags Flags(Op->getFlags().hasDisjoint() ? SDNodeFlags::Disjoint
679 unsigned Opcode = Op.getOpcode();
680 if (Opcode == ISD::PTRADD) {
681 // It isn't a ptradd anymore if it doesn't operate on the entire
682 // pointer.
683 Opcode = ISD::ADD;
684 }
685 SDValue X = DAG.getNode(
686 Opcode, dl, SmallVT,
687 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
688 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)), Flags);
689 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
690 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, VT, X);
691 return TLO.CombineTo(Op, Z);
692 }
693 }
694 return false;
695}
696
698 DAGCombinerInfo &DCI) const {
699 SelectionDAG &DAG = DCI.DAG;
700 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
701 !DCI.isBeforeLegalizeOps());
703
704 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
705 if (Simplified) {
706 DCI.AddToWorklist(Op.getNode());
708 }
709 return Simplified;
710}
711
713 const APInt &DemandedElts,
714 DAGCombinerInfo &DCI) const {
715 SelectionDAG &DAG = DCI.DAG;
716 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
717 !DCI.isBeforeLegalizeOps());
719
720 bool Simplified =
721 SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO);
722 if (Simplified) {
723 DCI.AddToWorklist(Op.getNode());
725 }
726 return Simplified;
727}
728
732 unsigned Depth,
733 bool AssumeSingleUse) const {
734 EVT VT = Op.getValueType();
735
736 // Since the number of lanes in a scalable vector is unknown at compile time,
737 // we track one bit which is implicitly broadcast to all lanes. This means
738 // that all lanes in a scalable vector are considered demanded.
739 APInt DemandedElts = VT.isFixedLengthVector()
741 : APInt(1, 1);
742 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
743 AssumeSingleUse);
744}
745
746// TODO: Under what circumstances can we create nodes? Constant folding?
748 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
749 SelectionDAG &DAG, unsigned Depth) const {
750 EVT VT = Op.getValueType();
751
752 // Limit search depth.
754 return SDValue();
755
756 // Ignore UNDEFs.
757 if (Op.isUndef())
758 return SDValue();
759
760 // Not demanding any bits/elts from Op.
761 if (DemandedBits == 0 || DemandedElts == 0)
762 return DAG.getUNDEF(VT);
763
764 bool IsLE = DAG.getDataLayout().isLittleEndian();
765 unsigned NumElts = DemandedElts.getBitWidth();
766 unsigned BitWidth = DemandedBits.getBitWidth();
767 KnownBits LHSKnown, RHSKnown;
768 switch (Op.getOpcode()) {
769 case ISD::BITCAST: {
770 if (VT.isScalableVector())
771 return SDValue();
772
773 SDValue Src = peekThroughBitcasts(Op.getOperand(0));
774 EVT SrcVT = Src.getValueType();
775 EVT DstVT = Op.getValueType();
776 if (SrcVT == DstVT)
777 return Src;
778
779 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
780 unsigned NumDstEltBits = DstVT.getScalarSizeInBits();
781 if (NumSrcEltBits == NumDstEltBits)
783 Src, DemandedBits, DemandedElts, DAG, Depth + 1))
784 return DAG.getBitcast(DstVT, V);
785
786 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) {
787 unsigned Scale = NumDstEltBits / NumSrcEltBits;
788 unsigned NumSrcElts = SrcVT.getVectorNumElements();
789 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
790 for (unsigned i = 0; i != Scale; ++i) {
791 unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
792 unsigned BitOffset = EltOffset * NumSrcEltBits;
793 DemandedSrcBits |= DemandedBits.extractBits(NumSrcEltBits, BitOffset);
794 }
795 // Recursive calls below may turn not demanded elements into poison, so we
796 // need to demand all smaller source elements that maps to a demanded
797 // destination element.
798 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
799
801 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
802 return DAG.getBitcast(DstVT, V);
803 }
804
805 // TODO - bigendian once we have test coverage.
806 if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) {
807 unsigned Scale = NumSrcEltBits / NumDstEltBits;
808 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
809 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
810 APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
811 for (unsigned i = 0; i != NumElts; ++i)
812 if (DemandedElts[i]) {
813 unsigned Offset = (i % Scale) * NumDstEltBits;
814 DemandedSrcBits.insertBits(DemandedBits, Offset);
815 DemandedSrcElts.setBit(i / Scale);
816 }
817
819 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
820 return DAG.getBitcast(DstVT, V);
821 }
822
823 break;
824 }
825 case ISD::AND: {
826 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
827 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
828
829 // If all of the demanded bits are known 1 on one side, return the other.
830 // These bits cannot contribute to the result of the 'and' in this
831 // context.
832 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
833 return Op.getOperand(0);
834 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
835 return Op.getOperand(1);
836 break;
837 }
838 case ISD::OR: {
839 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
840 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
841
842 // If all of the demanded bits are known zero on one side, return the
843 // other. These bits cannot contribute to the result of the 'or' in this
844 // context.
845 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
846 return Op.getOperand(0);
847 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
848 return Op.getOperand(1);
849 break;
850 }
851 case ISD::XOR: {
852 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
853 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
854
855 // If all of the demanded bits are known zero on one side, return the
856 // other.
857 if (DemandedBits.isSubsetOf(RHSKnown.Zero))
858 return Op.getOperand(0);
859 if (DemandedBits.isSubsetOf(LHSKnown.Zero))
860 return Op.getOperand(1);
861 break;
862 }
863 case ISD::ADD:
864 case ISD::MUL:
865 case ISD::SMIN:
866 case ISD::SMAX:
867 case ISD::UMIN:
868 case ISD::UMAX: {
869 if (DAG.isIdentityElement(Op.getOpcode(), Op->getFlags(), Op.getOperand(1),
870 DemandedElts, 1, Depth + 1))
871 return Op.getOperand(0);
872
873 if (DAG.isIdentityElement(Op.getOpcode(), Op->getFlags(), Op.getOperand(0),
874 DemandedElts, 0, Depth + 1))
875 return Op.getOperand(1);
876 break;
877 }
878 case ISD::SHL: {
879 // If we are only demanding sign bits then we can use the shift source
880 // directly.
881 if (std::optional<unsigned> MaxSA =
882 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
883 SDValue Op0 = Op.getOperand(0);
884 unsigned ShAmt = *MaxSA;
885 unsigned NumSignBits =
886 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
887 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
888 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
889 return Op0;
890 }
891 break;
892 }
893 case ISD::SRL: {
894 // If we are only demanding sign bits then we can use the shift source
895 // directly.
896 if (std::optional<unsigned> MaxSA =
897 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
898 SDValue Op0 = Op.getOperand(0);
899 unsigned ShAmt = *MaxSA;
900 // Must already be signbits in DemandedBits bounds, and can't demand any
901 // shifted in zeroes.
902 if (DemandedBits.countl_zero() >= ShAmt) {
903 unsigned NumSignBits =
904 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
905 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits))
906 return Op0;
907 }
908 }
909 break;
910 }
911 case ISD::SETCC: {
912 SDValue Op0 = Op.getOperand(0);
913 SDValue Op1 = Op.getOperand(1);
914 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
915 // If (1) we only need the sign-bit, (2) the setcc operands are the same
916 // width as the setcc result, and (3) the result of a setcc conforms to 0 or
917 // -1, we may be able to bypass the setcc.
918 if (DemandedBits.isSignMask() &&
922 // If we're testing X < 0, then this compare isn't needed - just use X!
923 // FIXME: We're limiting to integer types here, but this should also work
924 // if we don't care about FP signed-zero. The use of SETLT with FP means
925 // that we don't care about NaNs.
926 if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
928 return Op0;
929 }
930 break;
931 }
933 // If none of the extended bits are demanded, eliminate the sextinreg.
934 SDValue Op0 = Op.getOperand(0);
935 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
936 unsigned ExBits = ExVT.getScalarSizeInBits();
937 if (DemandedBits.getActiveBits() <= ExBits &&
939 return Op0;
940 // If the input is already sign extended, just drop the extension.
941 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
942 if (NumSignBits >= (BitWidth - ExBits + 1))
943 return Op0;
944 break;
945 }
949 if (VT.isScalableVector())
950 return SDValue();
951
952 // If we only want the lowest element and none of extended bits, then we can
953 // return the bitcasted source vector.
954 SDValue Src = Op.getOperand(0);
955 EVT SrcVT = Src.getValueType();
956 EVT DstVT = Op.getValueType();
957 if (IsLE && DemandedElts == 1 &&
958 DstVT.getSizeInBits() == SrcVT.getSizeInBits() &&
959 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) {
960 return DAG.getBitcast(DstVT, Src);
961 }
962 break;
963 }
965 if (VT.isScalableVector())
966 return SDValue();
967
968 // If we don't demand the inserted element, return the base vector.
969 SDValue Vec = Op.getOperand(0);
970 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
971 EVT VecVT = Vec.getValueType();
972 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
973 !DemandedElts[CIdx->getZExtValue()])
974 return Vec;
975 break;
976 }
978 if (VT.isScalableVector())
979 return SDValue();
980
981 SDValue Vec = Op.getOperand(0);
982 SDValue Sub = Op.getOperand(1);
983 uint64_t Idx = Op.getConstantOperandVal(2);
984 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
985 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
986 // If we don't demand the inserted subvector, return the base vector.
987 if (DemandedSubElts == 0)
988 return Vec;
989 break;
990 }
991 case ISD::VECTOR_SHUFFLE: {
993 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
994
995 // If all the demanded elts are from one operand and are inline,
996 // then we can use the operand directly.
997 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true;
998 for (unsigned i = 0; i != NumElts; ++i) {
999 int M = ShuffleMask[i];
1000 if (M < 0 || !DemandedElts[i])
1001 continue;
1002 AllUndef = false;
1003 IdentityLHS &= (M == (int)i);
1004 IdentityRHS &= ((M - NumElts) == i);
1005 }
1006
1007 if (AllUndef)
1008 return DAG.getUNDEF(Op.getValueType());
1009 if (IdentityLHS)
1010 return Op.getOperand(0);
1011 if (IdentityRHS)
1012 return Op.getOperand(1);
1013 break;
1014 }
1015 default:
1016 // TODO: Probably okay to remove after audit; here to reduce change size
1017 // in initial enablement patch for scalable vectors
1018 if (VT.isScalableVector())
1019 return SDValue();
1020
1021 if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
1023 Op, DemandedBits, DemandedElts, DAG, Depth))
1024 return V;
1025 break;
1026 }
1027 return SDValue();
1028}
1029
1032 unsigned Depth) const {
1033 EVT VT = Op.getValueType();
1034 // Since the number of lanes in a scalable vector is unknown at compile time,
1035 // we track one bit which is implicitly broadcast to all lanes. This means
1036 // that all lanes in a scalable vector are considered demanded.
1037 APInt DemandedElts = VT.isFixedLengthVector()
1039 : APInt(1, 1);
1040 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
1041 Depth);
1042}
1043
1045 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG,
1046 unsigned Depth) const {
1047 APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits());
1048 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
1049 Depth);
1050}
1051
1052// Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1).
1053// or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1).
1056 const TargetLowering &TLI,
1057 const APInt &DemandedBits,
1058 const APInt &DemandedElts, unsigned Depth) {
1059 assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) &&
1060 "SRL or SRA node is required here!");
1061 // Is the right shift using an immediate value of 1?
1062 ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
1063 if (!N1C || !N1C->isOne())
1064 return SDValue();
1065
1066 // We are looking for an avgfloor
1067 // add(ext, ext)
1068 // or one of these as a avgceil
1069 // add(add(ext, ext), 1)
1070 // add(add(ext, 1), ext)
1071 // add(ext, add(ext, 1))
1072 SDValue Add = Op.getOperand(0);
1073 if (Add.getOpcode() != ISD::ADD)
1074 return SDValue();
1075
1076 SDValue ExtOpA = Add.getOperand(0);
1077 SDValue ExtOpB = Add.getOperand(1);
1078 SDValue Add2;
1079 auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3, SDValue A) {
1080 ConstantSDNode *ConstOp;
1081 if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) &&
1082 ConstOp->isOne()) {
1083 ExtOpA = Op1;
1084 ExtOpB = Op3;
1085 Add2 = A;
1086 return true;
1087 }
1088 if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) &&
1089 ConstOp->isOne()) {
1090 ExtOpA = Op1;
1091 ExtOpB = Op2;
1092 Add2 = A;
1093 return true;
1094 }
1095 return false;
1096 };
1097 bool IsCeil =
1098 (ExtOpA.getOpcode() == ISD::ADD &&
1099 MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB, ExtOpA)) ||
1100 (ExtOpB.getOpcode() == ISD::ADD &&
1101 MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA, ExtOpB));
1102
1103 // If the shift is signed (sra):
1104 // - Needs >= 2 sign bit for both operands.
1105 // - Needs >= 2 zero bits.
1106 // If the shift is unsigned (srl):
1107 // - Needs >= 1 zero bit for both operands.
1108 // - Needs 1 demanded bit zero and >= 2 sign bits.
1109 SelectionDAG &DAG = TLO.DAG;
1110 unsigned ShiftOpc = Op.getOpcode();
1111 bool IsSigned = false;
1112 unsigned KnownBits;
1113 unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth);
1114 unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth);
1115 unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1;
1116 unsigned NumZeroA =
1117 DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros();
1118 unsigned NumZeroB =
1119 DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros();
1120 unsigned NumZero = std::min(NumZeroA, NumZeroB);
1121
1122 switch (ShiftOpc) {
1123 default:
1124 llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG");
1125 case ISD::SRA: {
1126 if (NumZero >= 2 && NumSigned < NumZero) {
1127 IsSigned = false;
1128 KnownBits = NumZero;
1129 break;
1130 }
1131 if (NumSigned >= 1) {
1132 IsSigned = true;
1133 KnownBits = NumSigned;
1134 break;
1135 }
1136 return SDValue();
1137 }
1138 case ISD::SRL: {
1139 if (NumZero >= 1 && NumSigned < NumZero) {
1140 IsSigned = false;
1141 KnownBits = NumZero;
1142 break;
1143 }
1144 if (NumSigned >= 1 && DemandedBits.isSignBitClear()) {
1145 IsSigned = true;
1146 KnownBits = NumSigned;
1147 break;
1148 }
1149 return SDValue();
1150 }
1151 }
1152
1153 unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU)
1154 : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU);
1155
1156 // Find the smallest power-2 type that is legal for this vector size and
1157 // operation, given the original type size and the number of known sign/zero
1158 // bits.
1159 EVT VT = Op.getValueType();
1160 unsigned MinWidth =
1161 std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8);
1162 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), llvm::bit_ceil(MinWidth));
1164 return SDValue();
1165 if (VT.isVector())
1166 NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount());
1167 if (TLO.LegalTypes() && !TLI.isOperationLegal(AVGOpc, NVT)) {
1168 // If we could not transform, and (both) adds are nuw/nsw, we can use the
1169 // larger type size to do the transform.
1170 if (TLO.LegalOperations() && !TLI.isOperationLegal(AVGOpc, VT))
1171 return SDValue();
1172 if (DAG.willNotOverflowAdd(IsSigned, Add.getOperand(0),
1173 Add.getOperand(1)) &&
1174 (!Add2 || DAG.willNotOverflowAdd(IsSigned, Add2.getOperand(0),
1175 Add2.getOperand(1))))
1176 NVT = VT;
1177 else
1178 return SDValue();
1179 }
1180
1181 // Don't create a AVGFLOOR node with a scalar constant unless its legal as
1182 // this is likely to stop other folds (reassociation, value tracking etc.)
1183 if (!IsCeil && !TLI.isOperationLegal(AVGOpc, NVT) &&
1184 (isa<ConstantSDNode>(ExtOpA) || isa<ConstantSDNode>(ExtOpB)))
1185 return SDValue();
1186
1187 SDLoc DL(Op);
1188 SDValue ResultAVG =
1189 DAG.getNode(AVGOpc, DL, NVT, DAG.getExtOrTrunc(IsSigned, ExtOpA, DL, NVT),
1190 DAG.getExtOrTrunc(IsSigned, ExtOpB, DL, NVT));
1191 return DAG.getExtOrTrunc(IsSigned, ResultAVG, DL, VT);
1192}
1193
1194/// Look at Op. At this point, we know that only the OriginalDemandedBits of the
1195/// result of Op are ever used downstream. If we can use this information to
1196/// simplify Op, create a new simplified DAG node and return true, returning the
1197/// original and new nodes in Old and New. Otherwise, analyze the expression and
1198/// return a mask of Known bits for the expression (used to simplify the
1199/// caller). The Known bits may only be accurate for those bits in the
1200/// OriginalDemandedBits and OriginalDemandedElts.
1202 SDValue Op, const APInt &OriginalDemandedBits,
1203 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
1204 unsigned Depth, bool AssumeSingleUse) const {
1205 unsigned BitWidth = OriginalDemandedBits.getBitWidth();
1206 assert(Op.getScalarValueSizeInBits() == BitWidth &&
1207 "Mask size mismatches value type size!");
1208
1209 // Don't know anything.
1211
1212 EVT VT = Op.getValueType();
1213 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
1214 unsigned NumElts = OriginalDemandedElts.getBitWidth();
1215 assert((!VT.isFixedLengthVector() || NumElts == VT.getVectorNumElements()) &&
1216 "Unexpected vector size");
1217
1218 APInt DemandedBits = OriginalDemandedBits;
1219 APInt DemandedElts = OriginalDemandedElts;
1220 SDLoc dl(Op);
1221
1222 // Undef operand.
1223 if (Op.isUndef())
1224 return false;
1225
1226 // We can't simplify target constants.
1227 if (Op.getOpcode() == ISD::TargetConstant)
1228 return false;
1229
1230 if (Op.getOpcode() == ISD::Constant) {
1231 // We know all of the bits for a constant!
1232 Known = KnownBits::makeConstant(Op->getAsAPIntVal());
1233 return false;
1234 }
1235
1236 if (Op.getOpcode() == ISD::ConstantFP) {
1237 // We know all of the bits for a floating point constant!
1239 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt());
1240 return false;
1241 }
1242
1243 // Other users may use these bits.
1244 bool HasMultiUse = false;
1245 if (!AssumeSingleUse && !Op.getNode()->hasOneUse()) {
1247 // Limit search depth.
1248 return false;
1249 }
1250 // Allow multiple uses, just set the DemandedBits/Elts to all bits.
1252 DemandedElts = APInt::getAllOnes(NumElts);
1253 HasMultiUse = true;
1254 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
1255 // Not demanding any bits/elts from Op.
1256 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1257 } else if (Depth >= SelectionDAG::MaxRecursionDepth) {
1258 // Limit search depth.
1259 return false;
1260 }
1261
1262 KnownBits Known2;
1263 switch (Op.getOpcode()) {
1264 case ISD::SCALAR_TO_VECTOR: {
1265 if (VT.isScalableVector())
1266 return false;
1267 if (!DemandedElts[0])
1268 return TLO.CombineTo(Op, TLO.DAG.getPOISON(VT));
1269
1270 KnownBits SrcKnown;
1271 SDValue Src = Op.getOperand(0);
1272 unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
1273 APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth);
1274 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
1275 return true;
1276
1277 // Upper elements are poison, so only get the knownbits if we just demand
1278 // the bottom element.
1279 if (DemandedElts == 1)
1280 Known = SrcKnown.anyextOrTrunc(BitWidth);
1281 break;
1282 }
1283 case ISD::BUILD_VECTOR:
1284 // Collect the known bits that are shared by every demanded element.
1285 // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
1286 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1287 return false; // Don't fall through, will infinitely loop.
1288 case ISD::SPLAT_VECTOR: {
1289 SDValue Scl = Op.getOperand(0);
1290 APInt DemandedSclBits = DemandedBits.zextOrTrunc(Scl.getValueSizeInBits());
1291 KnownBits KnownScl;
1292 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1293 return true;
1294
1295 // Implicitly truncate the bits to match the official semantics of
1296 // SPLAT_VECTOR.
1297 Known = KnownScl.trunc(BitWidth);
1298 break;
1299 }
1300 case ISD::FREEZE: {
1301 SDValue N0 = Op.getOperand(0);
1303 N0, DemandedElts, UndefPoisonKind::UndefOrPoison, Depth + 1))
1304 return TLO.CombineTo(Op, N0);
1305 break;
1306 }
1307 case ISD::LOAD: {
1308 auto *LD = cast<LoadSDNode>(Op);
1309 if (getTargetConstantFromLoad(LD)) {
1310 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1311 return false; // Don't fall through, will infinitely loop.
1312 }
1313 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
1314 // If this is a ZEXTLoad and we are looking at the loaded value.
1315 EVT MemVT = LD->getMemoryVT();
1316 unsigned MemBits = MemVT.getScalarSizeInBits();
1317 Known.Zero.setBitsFrom(MemBits);
1318 return false; // Don't fall through, will infinitely loop.
1319 }
1320 break;
1321 }
1323 if (VT.isScalableVector())
1324 return false;
1325 SDValue Vec = Op.getOperand(0);
1326 SDValue Scl = Op.getOperand(1);
1327 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1328 EVT VecVT = Vec.getValueType();
1329
1330 // If index isn't constant, assume we need all vector elements AND the
1331 // inserted element.
1332 APInt DemandedVecElts(DemandedElts);
1333 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
1334 unsigned Idx = CIdx->getZExtValue();
1335 DemandedVecElts.clearBit(Idx);
1336
1337 // Inserted element is not required.
1338 if (!DemandedElts[Idx])
1339 return TLO.CombineTo(Op, Vec);
1340 }
1341
1342 KnownBits KnownScl;
1343 unsigned NumSclBits = Scl.getScalarValueSizeInBits();
1344 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
1345 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1346 return true;
1347
1348 Known = KnownScl.anyextOrTrunc(BitWidth);
1349
1350 KnownBits KnownVec;
1351 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
1352 Depth + 1))
1353 return true;
1354
1355 if (!!DemandedVecElts)
1356 Known = Known.intersectWith(KnownVec);
1357
1358 return false;
1359 }
1360 case ISD::INSERT_SUBVECTOR: {
1361 if (VT.isScalableVector())
1362 return false;
1363 // Demand any elements from the subvector and the remainder from the src its
1364 // inserted into.
1365 SDValue Src = Op.getOperand(0);
1366 SDValue Sub = Op.getOperand(1);
1367 uint64_t Idx = Op.getConstantOperandVal(2);
1368 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1369 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1370 APInt DemandedSrcElts = DemandedElts;
1371 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
1372
1373 KnownBits KnownSub, KnownSrc;
1374 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO,
1375 Depth + 1))
1376 return true;
1377 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO,
1378 Depth + 1))
1379 return true;
1380
1381 Known.setAllConflict();
1382 if (!!DemandedSubElts)
1383 Known = Known.intersectWith(KnownSub);
1384 if (!!DemandedSrcElts)
1385 Known = Known.intersectWith(KnownSrc);
1386
1387 // Attempt to avoid multi-use src if we don't need anything from it.
1388 if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() ||
1389 !DemandedSrcElts.isAllOnes()) {
1391 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1);
1393 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1394 if (NewSub || NewSrc) {
1395 NewSub = NewSub ? NewSub : Sub;
1396 NewSrc = NewSrc ? NewSrc : Src;
1397 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub,
1398 Op.getOperand(2));
1399 return TLO.CombineTo(Op, NewOp);
1400 }
1401 }
1402 break;
1403 }
1405 if (VT.isScalableVector())
1406 return false;
1407 // Offset the demanded elts by the subvector index.
1408 SDValue Src = Op.getOperand(0);
1409 if (Src.getValueType().isScalableVector())
1410 break;
1411 uint64_t Idx = Op.getConstantOperandVal(1);
1412 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1413 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
1414
1415 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO,
1416 Depth + 1))
1417 return true;
1418
1419 // Attempt to avoid multi-use src if we don't need anything from it.
1420 if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
1422 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1423 if (DemandedSrc) {
1424 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc,
1425 Op.getOperand(1));
1426 return TLO.CombineTo(Op, NewOp);
1427 }
1428 }
1429 break;
1430 }
1431 case ISD::CONCAT_VECTORS: {
1432 if (VT.isScalableVector())
1433 return false;
1434 Known.setAllConflict();
1435 EVT SubVT = Op.getOperand(0).getValueType();
1436 unsigned NumSubVecs = Op.getNumOperands();
1437 unsigned NumSubElts = SubVT.getVectorNumElements();
1438 for (unsigned i = 0; i != NumSubVecs; ++i) {
1439 APInt DemandedSubElts =
1440 DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1441 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
1442 Known2, TLO, Depth + 1))
1443 return true;
1444 // Known bits are shared by every demanded subvector element.
1445 if (!!DemandedSubElts)
1446 Known = Known.intersectWith(Known2);
1447 }
1448 break;
1449 }
1450 case ISD::VECTOR_SHUFFLE: {
1451 assert(!VT.isScalableVector());
1452 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1453
1454 // Collect demanded elements from shuffle operands..
1455 APInt DemandedLHS, DemandedRHS;
1456 if (!getShuffleDemandedElts(NumElts, ShuffleMask, DemandedElts, DemandedLHS,
1457 DemandedRHS))
1458 break;
1459
1460 if (!!DemandedLHS || !!DemandedRHS) {
1461 SDValue Op0 = Op.getOperand(0);
1462 SDValue Op1 = Op.getOperand(1);
1463
1464 Known.setAllConflict();
1465 if (!!DemandedLHS) {
1466 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO,
1467 Depth + 1))
1468 return true;
1469 Known = Known.intersectWith(Known2);
1470 }
1471 if (!!DemandedRHS) {
1472 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO,
1473 Depth + 1))
1474 return true;
1475 Known = Known.intersectWith(Known2);
1476 }
1477
1478 // Attempt to avoid multi-use ops if we don't need anything from them.
1480 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1);
1482 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1);
1483 if (DemandedOp0 || DemandedOp1) {
1484 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1485 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1486 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask);
1487 return TLO.CombineTo(Op, NewOp);
1488 }
1489 }
1490 break;
1491 }
1492 case ISD::AND: {
1493 SDValue Op0 = Op.getOperand(0);
1494 SDValue Op1 = Op.getOperand(1);
1495
1496 // If the RHS is a constant, check to see if the LHS would be zero without
1497 // using the bits from the RHS. Below, we use knowledge about the RHS to
1498 // simplify the LHS, here we're using information from the LHS to simplify
1499 // the RHS.
1500 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1, DemandedElts)) {
1501 // Do not increment Depth here; that can cause an infinite loop.
1502 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
1503 // If the LHS already has zeros where RHSC does, this 'and' is dead.
1504 if ((LHSKnown.Zero & DemandedBits) ==
1505 (~RHSC->getAPIntValue() & DemandedBits))
1506 return TLO.CombineTo(Op, Op0);
1507
1508 // If any of the set bits in the RHS are known zero on the LHS, shrink
1509 // the constant.
1510 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits,
1511 DemandedElts, TLO))
1512 return true;
1513
1514 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
1515 // constant, but if this 'and' is only clearing bits that were just set by
1516 // the xor, then this 'and' can be eliminated by shrinking the mask of
1517 // the xor. For example, for a 32-bit X:
1518 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
1519 if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
1520 LHSKnown.One == ~RHSC->getAPIntValue()) {
1521 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
1522 return TLO.CombineTo(Op, Xor);
1523 }
1524 }
1525
1526 // (X +/- Y) & Y --> ~X & Y when Y is a power of 2 (or zero).
1527 SDValue X, Y;
1528 if (sd_match(Op,
1529 m_And(m_Value(Y),
1531 m_Sub(m_Value(X), m_Deferred(Y)))))) &&
1532 TLO.DAG.isKnownToBeAPowerOfTwo(Y, DemandedElts, /*OrZero=*/true)) {
1533 return TLO.CombineTo(
1534 Op, TLO.DAG.getNode(ISD::AND, dl, VT, TLO.DAG.getNOT(dl, X, VT), Y));
1535 }
1536
1537 // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I)
1538 // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits).
1539 if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR && !VT.isScalableVector() &&
1540 (Op0.getOperand(0).isUndef() ||
1542 Op0->hasOneUse()) {
1543 unsigned NumSubElts =
1545 unsigned SubIdx = Op0.getConstantOperandVal(2);
1546 APInt DemandedSub =
1547 APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts);
1548 KnownBits KnownSubMask =
1549 TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1);
1550 if (DemandedBits.isSubsetOf(KnownSubMask.One)) {
1551 SDValue NewAnd =
1552 TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1);
1553 SDValue NewInsert =
1554 TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd,
1555 Op0.getOperand(1), Op0.getOperand(2));
1556 return TLO.CombineTo(Op, NewInsert);
1557 }
1558 }
1559
1560 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1561 Depth + 1))
1562 return true;
1563 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
1564 Known2, TLO, Depth + 1))
1565 return true;
1566
1567 // If all of the demanded bits are known one on one side, return the other.
1568 // These bits cannot contribute to the result of the 'and'.
1569 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One))
1570 return TLO.CombineTo(Op, Op0);
1571 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
1572 return TLO.CombineTo(Op, Op1);
1573 // If all of the demanded bits in the inputs are known zeros, return zero.
1574 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1575 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
1576 // If the RHS is a constant, see if we can simplify it.
1577 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts,
1578 TLO))
1579 return true;
1580 // If the operation can be done in a smaller type, do so.
1582 return true;
1583
1584 // Attempt to avoid multi-use ops if we don't need anything from them.
1585 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1587 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1589 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1590 if (DemandedOp0 || DemandedOp1) {
1591 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1592 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1593 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1594 return TLO.CombineTo(Op, NewOp);
1595 }
1596 }
1597
1598 Known &= Known2;
1599 break;
1600 }
1601 case ISD::OR: {
1602 SDValue Op0 = Op.getOperand(0);
1603 SDValue Op1 = Op.getOperand(1);
1604 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1605 Depth + 1)) {
1606 Op->dropFlags(SDNodeFlags::Disjoint);
1607 return true;
1608 }
1609
1610 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
1611 Known2, TLO, Depth + 1)) {
1612 Op->dropFlags(SDNodeFlags::Disjoint);
1613 return true;
1614 }
1615
1616 // If all of the demanded bits are known zero on one side, return the other.
1617 // These bits cannot contribute to the result of the 'or'.
1618 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero))
1619 return TLO.CombineTo(Op, Op0);
1620 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
1621 return TLO.CombineTo(Op, Op1);
1622 // If the RHS is a constant, see if we can simplify it.
1623 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1624 return true;
1625 // If the operation can be done in a smaller type, do so.
1627 return true;
1628
1629 // Attempt to avoid multi-use ops if we don't need anything from them.
1630 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1632 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1634 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1635 if (DemandedOp0 || DemandedOp1) {
1636 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1637 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1638 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1639 return TLO.CombineTo(Op, NewOp);
1640 }
1641 }
1642
1643 // (or (and X, C1), (and (or X, Y), C2)) -> (or (and X, C1|C2), (and Y, C2))
1644 // TODO: Use SimplifyMultipleUseDemandedBits to peek through masks.
1645 SDValue X, Y, C1, C2;
1648 m_Value(C2)))))) {
1649 if (SDValue C12 =
1650 TLO.DAG.FoldConstantArithmetic(ISD::OR, dl, VT, {C1, C2})) {
1651 SDValue MaskX = TLO.DAG.getNode(ISD::AND, dl, VT, X, C12);
1652 SDValue MaskY = TLO.DAG.getNode(ISD::AND, dl, VT, Y, C2);
1653 return TLO.CombineTo(Op,
1654 TLO.DAG.getNode(ISD::OR, dl, VT, MaskX, MaskY));
1655 }
1656 }
1657
1658 Known |= Known2;
1659 break;
1660 }
1661 case ISD::XOR: {
1662 SDValue Op0 = Op.getOperand(0);
1663 SDValue Op1 = Op.getOperand(1);
1664
1665 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1666 Depth + 1))
1667 return true;
1668 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1669 Depth + 1))
1670 return true;
1671
1672 // If all of the demanded bits are known zero on one side, return the other.
1673 // These bits cannot contribute to the result of the 'xor'.
1674 if (DemandedBits.isSubsetOf(Known.Zero))
1675 return TLO.CombineTo(Op, Op0);
1676 if (DemandedBits.isSubsetOf(Known2.Zero))
1677 return TLO.CombineTo(Op, Op1);
1678 // If the operation can be done in a smaller type, do so.
1680 return true;
1681
1682 // If all of the unknown bits are known to be zero on one side or the other
1683 // turn this into an *inclusive* or.
1684 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1685 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1686 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1687
1688 ConstantSDNode *C = isConstOrConstSplat(Op1, DemandedElts);
1689 if (C) {
1690 // If one side is a constant, and all of the set bits in the constant are
1691 // also known set on the other side, turn this into an AND, as we know
1692 // the bits will be cleared.
1693 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1694 // NB: it is okay if more bits are known than are requested
1695 if (C->getAPIntValue() == Known2.One) {
1696 SDValue ANDC =
1697 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1698 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1699 }
1700
1701 // If the RHS is a constant, see if we can change it. Don't alter a -1
1702 // constant because that's a 'not' op, and that is better for combining
1703 // and codegen.
1704 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) {
1705 // We're flipping all demanded bits. Flip the undemanded bits too.
1706 SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1707 return TLO.CombineTo(Op, New);
1708 }
1709
1710 unsigned Op0Opcode = Op0.getOpcode();
1711 if ((Op0Opcode == ISD::SRL || Op0Opcode == ISD::SHL) && Op0.hasOneUse()) {
1712 if (ConstantSDNode *ShiftC =
1713 isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) {
1714 // Don't crash on an oversized shift. We can not guarantee that a
1715 // bogus shift has been simplified to undef.
1716 if (ShiftC->getAPIntValue().ult(BitWidth)) {
1717 uint64_t ShiftAmt = ShiftC->getZExtValue();
1719 Ones = Op0Opcode == ISD::SHL ? Ones.shl(ShiftAmt)
1720 : Ones.lshr(ShiftAmt);
1721 if ((DemandedBits & C->getAPIntValue()) == (DemandedBits & Ones) &&
1723 // If the xor constant is a demanded mask, do a 'not' before the
1724 // shift:
1725 // xor (X << ShiftC), XorC --> (not X) << ShiftC
1726 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC
1727 SDValue Not = TLO.DAG.getNOT(dl, Op0.getOperand(0), VT);
1728 return TLO.CombineTo(Op, TLO.DAG.getNode(Op0Opcode, dl, VT, Not,
1729 Op0.getOperand(1)));
1730 }
1731 }
1732 }
1733 }
1734 }
1735
1736 // If we can't turn this into a 'not', try to shrink the constant.
1737 if (!C || !C->isAllOnes())
1738 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1739 return true;
1740
1741 // Attempt to avoid multi-use ops if we don't need anything from them.
1742 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1744 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1746 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1747 if (DemandedOp0 || DemandedOp1) {
1748 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1749 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1750 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1751 return TLO.CombineTo(Op, NewOp);
1752 }
1753 }
1754
1755 Known ^= Known2;
1756 break;
1757 }
1758 case ISD::SELECT:
1759 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1760 Known, TLO, Depth + 1))
1761 return true;
1762 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1763 Known2, TLO, Depth + 1))
1764 return true;
1765
1766 // If the operands are constants, see if we can simplify them.
1767 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1768 return true;
1769
1770 // Only known if known in both the LHS and RHS.
1771 Known = Known.intersectWith(Known2);
1772 break;
1773 case ISD::VSELECT:
1774 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1775 Known, TLO, Depth + 1))
1776 return true;
1777 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1778 Known2, TLO, Depth + 1))
1779 return true;
1780
1781 // Only known if known in both the LHS and RHS.
1782 Known = Known.intersectWith(Known2);
1783 break;
1784 case ISD::SELECT_CC:
1785 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, DemandedElts,
1786 Known, TLO, Depth + 1))
1787 return true;
1788 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1789 Known2, TLO, Depth + 1))
1790 return true;
1791
1792 // If the operands are constants, see if we can simplify them.
1793 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1794 return true;
1795
1796 // Only known if known in both the LHS and RHS.
1797 Known = Known.intersectWith(Known2);
1798 break;
1799 case ISD::SETCC: {
1800 SDValue Op0 = Op.getOperand(0);
1801 SDValue Op1 = Op.getOperand(1);
1802 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1803 // If we're testing X < 0, X >= 0, X <= -1 or X > -1
1804 // (X is of integer type) then we only need the sign mask of the previous
1805 // result
1806 if (Op1.getValueType().isInteger() &&
1807 (((CC == ISD::SETLT || CC == ISD::SETGE) && isNullOrNullSplat(Op1)) ||
1808 ((CC == ISD::SETLE || CC == ISD::SETGT) &&
1809 isAllOnesOrAllOnesSplat(Op1)))) {
1810 KnownBits KnownOp0;
1813 DemandedElts, KnownOp0, TLO, Depth + 1))
1814 return true;
1815 // If (1) we only need the sign-bit, (2) the setcc operands are the same
1816 // width as the setcc result, and (3) the result of a setcc conforms to 0
1817 // or -1, we may be able to bypass the setcc.
1818 if (DemandedBits.isSignMask() &&
1822 // If we remove a >= 0 or > -1 (for integers), we need to introduce a
1823 // NOT Operation
1824 if (CC == ISD::SETGE || CC == ISD::SETGT) {
1825 SDLoc DL(Op);
1826 EVT VT = Op0.getValueType();
1827 SDValue NotOp0 = TLO.DAG.getNOT(DL, Op0, VT);
1828 return TLO.CombineTo(Op, NotOp0);
1829 }
1830 return TLO.CombineTo(Op, Op0);
1831 }
1832 }
1833 if (getBooleanContents(Op0.getValueType()) ==
1835 BitWidth > 1)
1836 Known.Zero.setBitsFrom(1);
1837 break;
1838 }
1839 case ISD::SHL: {
1840 SDValue Op0 = Op.getOperand(0);
1841 SDValue Op1 = Op.getOperand(1);
1842 EVT ShiftVT = Op1.getValueType();
1843
1844 if (std::optional<unsigned> KnownSA =
1845 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
1846 unsigned ShAmt = *KnownSA;
1847 if (ShAmt == 0)
1848 return TLO.CombineTo(Op, Op0);
1849
1850 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1851 // single shift. We can do this if the bottom bits (which are shifted
1852 // out) are never demanded.
1853 // TODO - support non-uniform vector amounts.
1854 if (Op0.getOpcode() == ISD::SRL) {
1855 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) {
1856 if (std::optional<unsigned> InnerSA =
1857 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
1858 unsigned C1 = *InnerSA;
1859 unsigned Opc = ISD::SHL;
1860 int Diff = ShAmt - C1;
1861 if (Diff < 0) {
1862 Diff = -Diff;
1863 Opc = ISD::SRL;
1864 }
1865 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1866 return TLO.CombineTo(
1867 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1868 }
1869 }
1870 }
1871
1872 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1873 // are not demanded. This will likely allow the anyext to be folded away.
1874 // TODO - support non-uniform vector amounts.
1875 if (Op0.getOpcode() == ISD::ANY_EXTEND) {
1876 SDValue InnerOp = Op0.getOperand(0);
1877 EVT InnerVT = InnerOp.getValueType();
1878 unsigned InnerBits = InnerVT.getScalarSizeInBits();
1879 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
1880 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
1881 SDValue NarrowShl = TLO.DAG.getNode(
1882 ISD::SHL, dl, InnerVT, InnerOp,
1883 TLO.DAG.getShiftAmountConstant(ShAmt, InnerVT, dl));
1884 return TLO.CombineTo(
1885 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
1886 }
1887
1888 // Repeat the SHL optimization above in cases where an extension
1889 // intervenes: (shl (anyext (shr x, c1)), c2) to
1890 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
1891 // aren't demanded (as above) and that the shifted upper c1 bits of
1892 // x aren't demanded.
1893 // TODO - support non-uniform vector amounts.
1894 if (InnerOp.getOpcode() == ISD::SRL && Op0.hasOneUse() &&
1895 InnerOp.hasOneUse()) {
1896 if (std::optional<unsigned> SA2 = TLO.DAG.getValidShiftAmount(
1897 InnerOp, DemandedElts, Depth + 2)) {
1898 unsigned InnerShAmt = *SA2;
1899 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
1900 DemandedBits.getActiveBits() <=
1901 (InnerBits - InnerShAmt + ShAmt) &&
1902 DemandedBits.countr_zero() >= ShAmt) {
1903 SDValue NewSA =
1904 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT);
1905 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
1906 InnerOp.getOperand(0));
1907 return TLO.CombineTo(
1908 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
1909 }
1910 }
1911 }
1912 }
1913
1914 APInt InDemandedMask = DemandedBits.lshr(ShAmt);
1915 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1916 Depth + 1)) {
1917 // Disable the nsw and nuw flags. We can no longer guarantee that we
1918 // won't wrap after simplification.
1919 Op->dropFlags(SDNodeFlags::NoWrap);
1920 return true;
1921 }
1922 Known <<= ShAmt;
1923 // low bits known zero.
1924 Known.Zero.setLowBits(ShAmt);
1925
1926 // Attempt to avoid multi-use ops if we don't need anything from them.
1927 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
1929 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
1930 if (DemandedOp0) {
1931 SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1);
1932 return TLO.CombineTo(Op, NewOp);
1933 }
1934 }
1935
1936 // TODO: Can we merge this fold with the one below?
1937 // Try shrinking the operation as long as the shift amount will still be
1938 // in range.
1939 if (ShAmt < DemandedBits.getActiveBits() && !VT.isVector() &&
1940 Op.getNode()->hasOneUse()) {
1941 // Search for the smallest integer type with free casts to and from
1942 // Op's type. For expedience, just check power-of-2 integer types.
1943 unsigned DemandedSize = DemandedBits.getActiveBits();
1944 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize);
1945 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
1946 EVT SmallVT = EVT::getIntegerVT(*TLO.DAG.getContext(), SmallVTBits);
1947 if (isNarrowingProfitable(Op.getNode(), VT, SmallVT) &&
1948 isTypeDesirableForOp(ISD::SHL, SmallVT) &&
1949 isTruncateFree(VT, SmallVT) && isZExtFree(SmallVT, VT) &&
1950 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, SmallVT))) {
1951 assert(DemandedSize <= SmallVTBits &&
1952 "Narrowed below demanded bits?");
1953 // We found a type with free casts.
1954 SDValue NarrowShl = TLO.DAG.getNode(
1955 ISD::SHL, dl, SmallVT,
1956 TLO.DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
1957 TLO.DAG.getShiftAmountConstant(ShAmt, SmallVT, dl));
1958 return TLO.CombineTo(
1959 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
1960 }
1961 }
1962 }
1963
1964 // Narrow shift to lower half - similar to ShrinkDemandedOp.
1965 // (shl i64:x, K) -> (i64 zero_extend (shl (i32 (trunc i64:x)), K))
1966 // Only do this if we demand the upper half so the knownbits are correct.
1967 unsigned HalfWidth = BitWidth / 2;
1968 if ((BitWidth % 2) == 0 && !VT.isVector() && ShAmt < HalfWidth &&
1969 DemandedBits.countLeadingOnes() >= HalfWidth) {
1970 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), HalfWidth);
1971 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) &&
1972 isTypeDesirableForOp(ISD::SHL, HalfVT) &&
1973 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
1974 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, HalfVT))) {
1975 // If we're demanding the upper bits at all, we must ensure
1976 // that the upper bits of the shift result are known to be zero,
1977 // which is equivalent to the narrow shift being NUW.
1978 if (bool IsNUW = (Known.countMinLeadingZeros() >= HalfWidth)) {
1979 bool IsNSW = Known.countMinSignBits() > HalfWidth;
1980 SDNodeFlags Flags;
1981 Flags.setNoSignedWrap(IsNSW);
1982 Flags.setNoUnsignedWrap(IsNUW);
1983 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
1984 SDValue NewShiftAmt =
1985 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl);
1986 SDValue NewShift = TLO.DAG.getNode(ISD::SHL, dl, HalfVT, NewOp,
1987 NewShiftAmt, Flags);
1988 SDValue NewExt =
1989 TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift);
1990 return TLO.CombineTo(Op, NewExt);
1991 }
1992 }
1993 }
1994 } else {
1995 // This is a variable shift, so we can't shift the demand mask by a known
1996 // amount. But if we are not demanding high bits, then we are not
1997 // demanding those bits from the pre-shifted operand either.
1998 if (unsigned CTLZ = DemandedBits.countl_zero()) {
1999 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
2000 if (SimplifyDemandedBits(Op0, DemandedFromOp, DemandedElts, Known, TLO,
2001 Depth + 1)) {
2002 // Disable the nsw and nuw flags. We can no longer guarantee that we
2003 // won't wrap after simplification.
2004 Op->dropFlags(SDNodeFlags::NoWrap);
2005 return true;
2006 }
2007 Known.resetAll();
2008 }
2009 }
2010
2011 // If we are only demanding sign bits then we can use the shift source
2012 // directly.
2013 if (std::optional<unsigned> MaxSA =
2014 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
2015 unsigned ShAmt = *MaxSA;
2016 unsigned NumSignBits =
2017 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
2018 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
2019 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
2020 return TLO.CombineTo(Op, Op0);
2021 }
2022 break;
2023 }
2024 case ISD::SRL: {
2025 SDValue Op0 = Op.getOperand(0);
2026 SDValue Op1 = Op.getOperand(1);
2027 EVT ShiftVT = Op1.getValueType();
2028
2029 if (std::optional<unsigned> KnownSA =
2030 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2031 unsigned ShAmt = *KnownSA;
2032 if (ShAmt == 0)
2033 return TLO.CombineTo(Op, Op0);
2034
2035 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
2036 // single shift. We can do this if the top bits (which are shifted out)
2037 // are never demanded.
2038 // TODO - support non-uniform vector amounts.
2039 if (Op0.getOpcode() == ISD::SHL) {
2040 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
2041 if (std::optional<unsigned> InnerSA =
2042 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2043 unsigned C1 = *InnerSA;
2044 unsigned Opc = ISD::SRL;
2045 int Diff = ShAmt - C1;
2046 if (Diff < 0) {
2047 Diff = -Diff;
2048 Opc = ISD::SHL;
2049 }
2050 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
2051 return TLO.CombineTo(
2052 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
2053 }
2054 }
2055 }
2056
2057 // If this is (srl (sra X, C1), ShAmt), see if we can combine this into a
2058 // single sra. We can do this if the top bits are never demanded.
2059 if (Op0.getOpcode() == ISD::SRA && Op0.hasOneUse()) {
2060 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
2061 if (std::optional<unsigned> InnerSA =
2062 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2063 unsigned C1 = *InnerSA;
2064 // Clamp the combined shift amount if it exceeds the bit width.
2065 unsigned Combined = std::min(C1 + ShAmt, BitWidth - 1);
2066 SDValue NewSA = TLO.DAG.getConstant(Combined, dl, ShiftVT);
2067 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRA, dl, VT,
2068 Op0.getOperand(0), NewSA));
2069 }
2070 }
2071 }
2072
2073 APInt InDemandedMask = (DemandedBits << ShAmt);
2074
2075 // If the shift is exact, then it does demand the low bits (and knows that
2076 // they are zero).
2077 if (Op->getFlags().hasExact())
2078 InDemandedMask.setLowBits(ShAmt);
2079
2080 // Narrow shift to lower half - similar to ShrinkDemandedOp.
2081 // (srl i64:x, K) -> (i64 zero_extend (srl (i32 (trunc i64:x)), K))
2082 if ((BitWidth % 2) == 0 && !VT.isVector()) {
2084 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), BitWidth / 2);
2085 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) &&
2086 isTypeDesirableForOp(ISD::SRL, HalfVT) &&
2087 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
2088 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, HalfVT)) &&
2089 ((InDemandedMask.countLeadingZeros() >= (BitWidth / 2)) ||
2090 TLO.DAG.MaskedValueIsZero(Op0, HiBits))) {
2091 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
2092 SDValue NewShiftAmt =
2093 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl);
2094 SDValue NewShift =
2095 TLO.DAG.getNode(ISD::SRL, dl, HalfVT, NewOp, NewShiftAmt);
2096 return TLO.CombineTo(
2097 Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift));
2098 }
2099 }
2100
2101 // Compute the new bits that are at the top now.
2102 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2103 Depth + 1))
2104 return true;
2105 Known >>= ShAmt;
2106 // High bits known zero.
2107 Known.Zero.setHighBits(ShAmt);
2108
2109 // Attempt to avoid multi-use ops if we don't need anything from them.
2110 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2112 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2113 if (DemandedOp0) {
2114 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, DemandedOp0, Op1);
2115 return TLO.CombineTo(Op, NewOp);
2116 }
2117 }
2118 } else {
2119 // Use generic knownbits computation as it has support for non-uniform
2120 // shift amounts.
2121 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2122 }
2123
2124 // If we are only demanding sign bits then we can use the shift source
2125 // directly.
2126 if (std::optional<unsigned> MaxSA =
2127 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
2128 unsigned ShAmt = *MaxSA;
2129 // Must already be signbits in DemandedBits bounds, and can't demand any
2130 // shifted in zeroes.
2131 if (DemandedBits.countl_zero() >= ShAmt) {
2132 unsigned NumSignBits =
2133 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
2134 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits))
2135 return TLO.CombineTo(Op, Op0);
2136 }
2137 }
2138
2139 // Try to match AVG patterns (after shift simplification).
2140 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits,
2141 DemandedElts, Depth + 1))
2142 return TLO.CombineTo(Op, AVG);
2143
2144 break;
2145 }
2146 case ISD::SRA: {
2147 SDValue Op0 = Op.getOperand(0);
2148 SDValue Op1 = Op.getOperand(1);
2149 EVT ShiftVT = Op1.getValueType();
2150
2151 // If we only want bits that already match the signbit then we don't need
2152 // to shift.
2153 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countr_zero();
2154 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >=
2155 NumHiDemandedBits)
2156 return TLO.CombineTo(Op, Op0);
2157
2158 // If this is an arithmetic shift right and only the low-bit is set, we can
2159 // always convert this into a logical shr, even if the shift amount is
2160 // variable. The low bit of the shift cannot be an input sign bit unless
2161 // the shift amount is >= the size of the datatype, which is undefined.
2162 if (DemandedBits.isOne())
2163 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2164
2165 if (std::optional<unsigned> KnownSA =
2166 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2167 unsigned ShAmt = *KnownSA;
2168 if (ShAmt == 0)
2169 return TLO.CombineTo(Op, Op0);
2170
2171 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target
2172 // supports sext_inreg.
2173 if (Op0.getOpcode() == ISD::SHL) {
2174 if (std::optional<unsigned> InnerSA =
2175 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2176 unsigned LowBits = BitWidth - ShAmt;
2177 EVT ExtVT = VT.changeElementType(
2178 *TLO.DAG.getContext(),
2179 EVT::getIntegerVT(*TLO.DAG.getContext(), LowBits));
2180
2181 if (*InnerSA == ShAmt) {
2182 if (!TLO.LegalOperations() ||
2184 return TLO.CombineTo(
2185 Op, TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
2186 Op0.getOperand(0),
2187 TLO.DAG.getValueType(ExtVT)));
2188
2189 // Even if we can't convert to sext_inreg, we might be able to
2190 // remove this shift pair if the input is already sign extended.
2191 unsigned NumSignBits =
2192 TLO.DAG.ComputeNumSignBits(Op0.getOperand(0), DemandedElts);
2193 if (NumSignBits > ShAmt)
2194 return TLO.CombineTo(Op, Op0.getOperand(0));
2195 }
2196 }
2197 }
2198
2199 APInt InDemandedMask = (DemandedBits << ShAmt);
2200
2201 // If the shift is exact, then it does demand the low bits (and knows that
2202 // they are zero).
2203 if (Op->getFlags().hasExact())
2204 InDemandedMask.setLowBits(ShAmt);
2205
2206 // If any of the demanded bits are produced by the sign extension, we also
2207 // demand the input sign bit.
2208 if (DemandedBits.countl_zero() < ShAmt)
2209 InDemandedMask.setSignBit();
2210
2211 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2212 Depth + 1))
2213 return true;
2214 Known >>= ShAmt;
2215
2216 // If the input sign bit is known to be zero, or if none of the top bits
2217 // are demanded, turn this into an unsigned shift right.
2218 if (Known.Zero[BitWidth - ShAmt - 1] ||
2219 DemandedBits.countl_zero() >= ShAmt) {
2220 SDNodeFlags Flags;
2221 Flags.setExact(Op->getFlags().hasExact());
2222 return TLO.CombineTo(
2223 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
2224 }
2225
2226 int Log2 = DemandedBits.exactLogBase2();
2227 if (Log2 >= 0) {
2228 // The bit must come from the sign.
2229 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT);
2230 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
2231 }
2232
2233 if (Known.One[BitWidth - ShAmt - 1])
2234 // New bits are known one.
2235 Known.One.setHighBits(ShAmt);
2236
2237 // Attempt to avoid multi-use ops if we don't need anything from them.
2238 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2240 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2241 if (DemandedOp0) {
2242 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1);
2243 return TLO.CombineTo(Op, NewOp);
2244 }
2245 }
2246 }
2247
2248 // Try to match AVG patterns (after shift simplification).
2249 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits,
2250 DemandedElts, Depth + 1))
2251 return TLO.CombineTo(Op, AVG);
2252
2253 break;
2254 }
2255 case ISD::FSHL:
2256 case ISD::FSHR: {
2257 SDValue Op0 = Op.getOperand(0);
2258 SDValue Op1 = Op.getOperand(1);
2259 SDValue Op2 = Op.getOperand(2);
2260 bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
2261
2262 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
2263 unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2264
2265 // For fshl, 0-shift returns the 1st arg.
2266 // For fshr, 0-shift returns the 2nd arg.
2267 if (Amt == 0) {
2268 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
2269 Known, TLO, Depth + 1))
2270 return true;
2271 break;
2272 }
2273
2274 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
2275 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
2276 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
2277 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
2278 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2279 Depth + 1))
2280 return true;
2281 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
2282 Depth + 1))
2283 return true;
2284
2285 Known2 <<= (IsFSHL ? Amt : (BitWidth - Amt));
2286 Known >>= (IsFSHL ? (BitWidth - Amt) : Amt);
2287 Known = Known.unionWith(Known2);
2288
2289 // Attempt to avoid multi-use ops if we don't need anything from them.
2290 if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() ||
2291 !DemandedElts.isAllOnes()) {
2293 Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1);
2295 Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1);
2296 if (DemandedOp0 || DemandedOp1) {
2297 DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0;
2298 DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1;
2299 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0,
2300 DemandedOp1, Op2);
2301 return TLO.CombineTo(Op, NewOp);
2302 }
2303 }
2304 }
2305
2306 if (isPowerOf2_32(BitWidth)) {
2307 // Fold FSHR(Op0,Op1,Op2) -> SRL(Op1,Op2)
2308 // iff we're guaranteed not to use Op0.
2309 // TODO: Add FSHL equivalent?
2310 if (!IsFSHL && !DemandedBits.isAllOnes() &&
2311 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT))) {
2312 KnownBits KnownAmt =
2313 TLO.DAG.computeKnownBits(Op2, DemandedElts, Depth + 1);
2314 unsigned MaxShiftAmt =
2315 KnownAmt.getMaxValue().getLimitedValue(BitWidth - 1);
2316 // Check we don't demand any shifted bits outside Op1.
2317 if (DemandedBits.countl_zero() >= MaxShiftAmt) {
2318 EVT AmtVT = Op2.getValueType();
2319 SDValue NewAmt =
2320 TLO.DAG.getNode(ISD::AND, dl, AmtVT, Op2,
2321 TLO.DAG.getConstant(BitWidth - 1, dl, AmtVT));
2322 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, Op1, NewAmt);
2323 return TLO.CombineTo(Op, NewOp);
2324 }
2325 }
2326
2327 // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2328 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1);
2329 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, Known2, TLO,
2330 Depth + 1))
2331 return true;
2332 }
2333 break;
2334 }
2335 case ISD::ROTL:
2336 case ISD::ROTR: {
2337 SDValue Op0 = Op.getOperand(0);
2338 SDValue Op1 = Op.getOperand(1);
2339 bool IsROTL = (Op.getOpcode() == ISD::ROTL);
2340
2341 // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
2342 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1))
2343 return TLO.CombineTo(Op, Op0);
2344
2345 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
2346 unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2347 unsigned RevAmt = BitWidth - Amt;
2348
2349 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt))
2350 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt)
2351 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt);
2352 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2353 Depth + 1))
2354 return true;
2355
2356 // rot*(x, 0) --> x
2357 if (Amt == 0)
2358 return TLO.CombineTo(Op, Op0);
2359
2360 // See if we don't demand either half of the rotated bits.
2361 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) &&
2362 DemandedBits.countr_zero() >= (IsROTL ? Amt : RevAmt)) {
2363 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType());
2364 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1));
2365 }
2366 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) &&
2367 DemandedBits.countl_zero() >= (IsROTL ? RevAmt : Amt)) {
2368 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType());
2369 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2370 }
2371 }
2372
2373 // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2374 if (isPowerOf2_32(BitWidth)) {
2375 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1);
2376 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO,
2377 Depth + 1))
2378 return true;
2379 }
2380 break;
2381 }
2382 case ISD::SMIN:
2383 case ISD::SMAX:
2384 case ISD::UMIN:
2385 case ISD::UMAX: {
2386 unsigned Opc = Op.getOpcode();
2387 SDValue Op0 = Op.getOperand(0);
2388 SDValue Op1 = Op.getOperand(1);
2389
2390 // If we're only demanding signbits, then we can simplify to OR/AND node.
2391 unsigned BitOp =
2392 (Opc == ISD::SMIN || Opc == ISD::UMAX) ? ISD::OR : ISD::AND;
2393 unsigned NumSignBits =
2394 std::min(TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1),
2395 TLO.DAG.ComputeNumSignBits(Op1, DemandedElts, Depth + 1));
2396 unsigned NumDemandedUpperBits = BitWidth - DemandedBits.countr_zero();
2397 if (NumSignBits >= NumDemandedUpperBits)
2398 return TLO.CombineTo(Op, TLO.DAG.getNode(BitOp, SDLoc(Op), VT, Op0, Op1));
2399
2400 // Check if one arg is always less/greater than (or equal) to the other arg.
2401 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
2402 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
2403 switch (Opc) {
2404 case ISD::SMIN:
2405 if (std::optional<bool> IsSLE = KnownBits::sle(Known0, Known1))
2406 return TLO.CombineTo(Op, *IsSLE ? Op0 : Op1);
2407 if (std::optional<bool> IsSLT = KnownBits::slt(Known0, Known1))
2408 return TLO.CombineTo(Op, *IsSLT ? Op0 : Op1);
2409 Known = KnownBits::smin(Known0, Known1);
2410 break;
2411 case ISD::SMAX:
2412 if (std::optional<bool> IsSGE = KnownBits::sge(Known0, Known1))
2413 return TLO.CombineTo(Op, *IsSGE ? Op0 : Op1);
2414 if (std::optional<bool> IsSGT = KnownBits::sgt(Known0, Known1))
2415 return TLO.CombineTo(Op, *IsSGT ? Op0 : Op1);
2416 Known = KnownBits::smax(Known0, Known1);
2417 break;
2418 case ISD::UMIN:
2419 if (std::optional<bool> IsULE = KnownBits::ule(Known0, Known1))
2420 return TLO.CombineTo(Op, *IsULE ? Op0 : Op1);
2421 if (std::optional<bool> IsULT = KnownBits::ult(Known0, Known1))
2422 return TLO.CombineTo(Op, *IsULT ? Op0 : Op1);
2423 Known = KnownBits::umin(Known0, Known1);
2424 break;
2425 case ISD::UMAX:
2426 if (std::optional<bool> IsUGE = KnownBits::uge(Known0, Known1))
2427 return TLO.CombineTo(Op, *IsUGE ? Op0 : Op1);
2428 if (std::optional<bool> IsUGT = KnownBits::ugt(Known0, Known1))
2429 return TLO.CombineTo(Op, *IsUGT ? Op0 : Op1);
2430 Known = KnownBits::umax(Known0, Known1);
2431 break;
2432 }
2433 break;
2434 }
2435 case ISD::BITREVERSE: {
2436 SDValue Src = Op.getOperand(0);
2437 APInt DemandedSrcBits = DemandedBits.reverseBits();
2438 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2439 Depth + 1))
2440 return true;
2441 Known = Known2.reverseBits();
2442 break;
2443 }
2444 case ISD::BSWAP: {
2445 SDValue Src = Op.getOperand(0);
2446
2447 // If the only bits demanded come from one byte of the bswap result,
2448 // just shift the input byte into position to eliminate the bswap.
2449 unsigned NLZ = DemandedBits.countl_zero();
2450 unsigned NTZ = DemandedBits.countr_zero();
2451
2452 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
2453 // we need all the bits down to bit 8. Likewise, round NLZ. If we
2454 // have 14 leading zeros, round to 8.
2455 NLZ = alignDown(NLZ, 8);
2456 NTZ = alignDown(NTZ, 8);
2457 // If we need exactly one byte, we can do this transformation.
2458 if (BitWidth - NLZ - NTZ == 8) {
2459 // Replace this with either a left or right shift to get the byte into
2460 // the right place.
2461 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL;
2462 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) {
2463 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ;
2464 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
2465 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt);
2466 return TLO.CombineTo(Op, NewOp);
2467 }
2468 }
2469
2470 APInt DemandedSrcBits = DemandedBits.byteSwap();
2471 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2472 Depth + 1))
2473 return true;
2474 Known = Known2.byteSwap();
2475 break;
2476 }
2477 case ISD::CTPOP: {
2478 // If only 1 bit is demanded, replace with PARITY as long as we're before
2479 // op legalization.
2480 // FIXME: Limit to scalars for now.
2481 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector())
2482 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT,
2483 Op.getOperand(0)));
2484
2485 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2486 break;
2487 }
2488 case ISD::PDEP: {
2489 SDValue Op0 = Op.getOperand(0);
2490 SDValue Op1 = Op.getOperand(1);
2491
2492 unsigned DemandedBitsLZ = DemandedBits.countl_zero();
2493 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2494
2495 // If the demanded bits has leading zeroes, we don't demand those from the
2496 // mask.
2497 if (SimplifyDemandedBits(Op1, LoMask, Known, TLO, Depth + 1))
2498 return true;
2499
2500 // The number of possible 1s in the mask determines the number of LSBs of
2501 // operand 0 used. Undemanded bits from the mask don't matter so filter
2502 // them before counting.
2503 KnownBits Known2;
2504 uint64_t Count = (~Known.Zero & LoMask).popcount();
2505 APInt DemandedMask(APInt::getLowBitsSet(BitWidth, Count));
2506 if (SimplifyDemandedBits(Op0, DemandedMask, Known2, TLO, Depth + 1))
2507 return true;
2508
2509 // Zeroes are retained from the mask, but not ones.
2510 Known.One.clearAllBits();
2511 // The result will have at least as many trailing zeros as the non-mask
2512 // operand since bits can only map to the same or higher bit position.
2513 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
2514 break;
2515 }
2517 SDValue Op0 = Op.getOperand(0);
2518 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2519 unsigned ExVTBits = ExVT.getScalarSizeInBits();
2520
2521 // If we only care about the highest bit, don't bother shifting right.
2522 if (DemandedBits.isSignMask()) {
2523 unsigned MinSignedBits =
2524 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1);
2525 bool AlreadySignExtended = ExVTBits >= MinSignedBits;
2526 // However if the input is already sign extended we expect the sign
2527 // extension to be dropped altogether later and do not simplify.
2528 if (!AlreadySignExtended) {
2529 // Compute the correct shift amount type, which must be getShiftAmountTy
2530 // for scalar types after legalization.
2531 SDValue ShiftAmt =
2532 TLO.DAG.getShiftAmountConstant(BitWidth - ExVTBits, VT, dl);
2533 return TLO.CombineTo(Op,
2534 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
2535 }
2536 }
2537
2538 // If none of the extended bits are demanded, eliminate the sextinreg.
2539 if (DemandedBits.getActiveBits() <= ExVTBits)
2540 return TLO.CombineTo(Op, Op0);
2541
2542 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
2543
2544 // Since the sign extended bits are demanded, we know that the sign
2545 // bit is demanded.
2546 InputDemandedBits.setBit(ExVTBits - 1);
2547
2548 if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO,
2549 Depth + 1))
2550 return true;
2551
2552 // If the sign bit of the input is known set or clear, then we know the
2553 // top bits of the result.
2554
2555 // If the input sign bit is known zero, convert this into a zero extension.
2556 if (Known.Zero[ExVTBits - 1])
2557 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT));
2558
2559 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
2560 if (Known.One[ExVTBits - 1]) { // Input sign bit known set
2561 Known.One.setBitsFrom(ExVTBits);
2562 Known.Zero &= Mask;
2563 } else { // Input sign bit unknown
2564 Known.Zero &= Mask;
2565 Known.One &= Mask;
2566 }
2567 break;
2568 }
2569 case ISD::BUILD_PAIR: {
2570 EVT HalfVT = Op.getOperand(0).getValueType();
2571 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
2572
2573 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
2574 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
2575
2576 KnownBits KnownLo, KnownHi;
2577
2578 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
2579 return true;
2580
2581 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
2582 return true;
2583
2584 Known = KnownHi.concat(KnownLo);
2585 break;
2586 }
2588 if (VT.isScalableVector())
2589 return false;
2590 [[fallthrough]];
2591 case ISD::ZERO_EXTEND: {
2592 SDValue Src = Op.getOperand(0);
2593 EVT SrcVT = Src.getValueType();
2594 unsigned InBits = SrcVT.getScalarSizeInBits();
2595 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2596 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
2597
2598 // If none of the top bits are demanded, convert this into an any_extend.
2599 if (DemandedBits.getActiveBits() <= InBits) {
2600 // If we only need the non-extended bits of the bottom element
2601 // then we can just bitcast to the result.
2602 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2603 VT.getSizeInBits() == SrcVT.getSizeInBits())
2604 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2605
2606 unsigned Opc =
2608 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2609 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2610 }
2611
2612 APInt InDemandedBits = DemandedBits.trunc(InBits);
2613 APInt InDemandedElts = DemandedElts.zext(InElts);
2614 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2615 Depth + 1)) {
2616 Op->dropFlags(SDNodeFlags::NonNeg);
2617 return true;
2618 }
2619 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2620 Known = Known.zext(BitWidth);
2621
2622 // Attempt to avoid multi-use ops if we don't need anything from them.
2624 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2625 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2626 break;
2627 }
2629 if (VT.isScalableVector())
2630 return false;
2631 [[fallthrough]];
2632 case ISD::SIGN_EXTEND: {
2633 SDValue Src = Op.getOperand(0);
2634 EVT SrcVT = Src.getValueType();
2635 unsigned InBits = SrcVT.getScalarSizeInBits();
2636 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2637 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
2638
2639 APInt InDemandedElts = DemandedElts.zext(InElts);
2640 APInt InDemandedBits = DemandedBits.trunc(InBits);
2641
2642 // Since some of the sign extended bits are demanded, we know that the sign
2643 // bit is demanded.
2644 InDemandedBits.setBit(InBits - 1);
2645
2646 // If none of the top bits are demanded, convert this into an any_extend.
2647 if (DemandedBits.getActiveBits() <= InBits) {
2648 // If we only need the non-extended bits of the bottom element
2649 // then we can just bitcast to the result.
2650 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2651 VT.getSizeInBits() == SrcVT.getSizeInBits())
2652 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2653
2654 // Don't lose an all signbits 0/-1 splat on targets with 0/-1 booleans.
2656 TLO.DAG.ComputeNumSignBits(Src, InDemandedElts, Depth + 1) !=
2657 InBits) {
2658 unsigned Opc =
2660 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2661 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2662 }
2663 }
2664
2665 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2666 Depth + 1))
2667 return true;
2668 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2669
2670 // If the sign bit is known one, the top bits match.
2671 Known = Known.sext(BitWidth);
2672
2673 // If the sign bit is known zero, convert this to a zero extend.
2674 if (Known.isNonNegative()) {
2675 unsigned Opc =
2677 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) {
2678 SDNodeFlags Flags;
2679 if (!IsVecInReg)
2680 Flags |= SDNodeFlags::NonNeg;
2681 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src, Flags));
2682 }
2683 }
2684
2685 // Attempt to avoid multi-use ops if we don't need anything from them.
2687 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2688 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2689 break;
2690 }
2692 if (VT.isScalableVector())
2693 return false;
2694 [[fallthrough]];
2695 case ISD::ANY_EXTEND: {
2696 SDValue Src = Op.getOperand(0);
2697 EVT SrcVT = Src.getValueType();
2698 unsigned InBits = SrcVT.getScalarSizeInBits();
2699 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2700 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
2701
2702 // If we only need the bottom element then we can just bitcast.
2703 // TODO: Handle ANY_EXTEND?
2704 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2705 VT.getSizeInBits() == SrcVT.getSizeInBits())
2706 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2707
2708 APInt InDemandedBits = DemandedBits.trunc(InBits);
2709 APInt InDemandedElts = DemandedElts.zext(InElts);
2710 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2711 Depth + 1))
2712 return true;
2713 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2714 Known = Known.anyext(BitWidth);
2715
2716 // Attempt to avoid multi-use ops if we don't need anything from them.
2718 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2719 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2720 break;
2721 }
2722 case ISD::TRUNCATE: {
2723 SDValue Src = Op.getOperand(0);
2724
2725 // Simplify the input, using demanded bit information, and compute the known
2726 // zero/one bits live out.
2727 unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
2728 APInt TruncMask = DemandedBits.zext(OperandBitWidth);
2729 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO,
2730 Depth + 1)) {
2731 // Disable the nsw and nuw flags. We can no longer guarantee that we
2732 // won't wrap after simplification.
2733 Op->dropFlags(SDNodeFlags::NoWrap);
2734 return true;
2735 }
2736 Known = Known.trunc(BitWidth);
2737
2738 // Attempt to avoid multi-use ops if we don't need anything from them.
2740 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1))
2741 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc));
2742
2743 // If the input is only used by this truncate, see if we can shrink it based
2744 // on the known demanded bits.
2745 switch (Src.getOpcode()) {
2746 default:
2747 break;
2748 case ISD::SRL:
2749 // Shrink SRL by a constant if none of the high bits shifted in are
2750 // demanded.
2751 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
2752 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
2753 // undesirable.
2754 break;
2755
2756 if (Src.getNode()->hasOneUse()) {
2757 if (isTruncateFree(Src, VT) &&
2758 !isTruncateFree(Src.getValueType(), VT)) {
2759 // If truncate is only free at trunc(srl), do not turn it into
2760 // srl(trunc). The check is done by first check the truncate is free
2761 // at Src's opcode(srl), then check the truncate is not done by
2762 // referencing sub-register. In test, if both trunc(srl) and
2763 // srl(trunc)'s trunc are free, srl(trunc) performs better. If only
2764 // trunc(srl)'s trunc is free, trunc(srl) is better.
2765 break;
2766 }
2767
2768 std::optional<unsigned> ShAmtC =
2769 TLO.DAG.getValidShiftAmount(Src, DemandedElts, Depth + 2);
2770 if (!ShAmtC || *ShAmtC >= BitWidth)
2771 break;
2772 unsigned ShVal = *ShAmtC;
2773
2774 APInt HighBits =
2775 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
2776 HighBits.lshrInPlace(ShVal);
2777 HighBits = HighBits.trunc(BitWidth);
2778 if (!(HighBits & DemandedBits)) {
2779 // None of the shifted in bits are needed. Add a truncate of the
2780 // shift input, then shift it.
2781 SDValue NewShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl);
2782 SDValue NewTrunc =
2783 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
2784 return TLO.CombineTo(
2785 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt));
2786 }
2787 }
2788 break;
2789 }
2790
2791 break;
2792 }
2793 case ISD::AssertZext: {
2794 // AssertZext demands all of the high bits, plus any of the low bits
2795 // demanded by its users.
2796 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2798 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
2799 TLO, Depth + 1))
2800 return true;
2801
2802 Known.Zero |= ~InMask;
2803 Known.One &= (~Known.Zero);
2804 break;
2805 }
2807 SDValue Src = Op.getOperand(0);
2808 SDValue Idx = Op.getOperand(1);
2809 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount();
2810 unsigned EltBitWidth = Src.getScalarValueSizeInBits();
2811
2812 if (SrcEltCnt.isScalable())
2813 return false;
2814
2815 // Demand the bits from every vector element without a constant index.
2816 unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2817 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
2818 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
2819 if (CIdx->getAPIntValue().ult(NumSrcElts))
2820 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
2821
2822 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2823 // anything about the extended bits.
2824 APInt DemandedSrcBits = DemandedBits;
2825 if (BitWidth > EltBitWidth)
2826 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
2827
2828 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
2829 Depth + 1))
2830 return true;
2831
2832 // Attempt to avoid multi-use ops if we don't need anything from them.
2833 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
2834 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
2835 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
2836 SDValue NewOp =
2837 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx);
2838 return TLO.CombineTo(Op, NewOp);
2839 }
2840 }
2841
2842 Known = Known2;
2843 if (BitWidth > EltBitWidth)
2844 Known = Known.anyext(BitWidth);
2845 break;
2846 }
2847 case ISD::BITCAST: {
2848 if (VT.isScalableVector())
2849 return false;
2850 SDValue Src = Op.getOperand(0);
2851 EVT SrcVT = Src.getValueType();
2852 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
2853
2854 // If this is an FP->Int bitcast and if the sign bit is the only
2855 // thing demanded, turn this into a FGETSIGN.
2856 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
2857 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
2858 SrcVT.isFloatingPoint()) {
2860 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
2861 // place. We expect the SHL to be eliminated by other optimizations.
2862 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, VT, Src);
2863 unsigned ShVal = Op.getValueSizeInBits() - 1;
2864 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl);
2865 return TLO.CombineTo(Op,
2866 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
2867 }
2868 }
2869
2870 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
2871 // Demand the elt/bit if any of the original elts/bits are demanded.
2872 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) {
2873 unsigned Scale = BitWidth / NumSrcEltBits;
2874 unsigned NumSrcElts = SrcVT.getVectorNumElements();
2875 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2876 for (unsigned i = 0; i != Scale; ++i) {
2877 unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
2878 unsigned BitOffset = EltOffset * NumSrcEltBits;
2879 DemandedSrcBits |= DemandedBits.extractBits(NumSrcEltBits, BitOffset);
2880 }
2881 // Recursive calls below may turn not demanded elements into poison, so we
2882 // need to demand all smaller source elements that maps to a demanded
2883 // destination element.
2884 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2885
2886 APInt KnownSrcUndef, KnownSrcZero;
2887 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2888 KnownSrcZero, TLO, Depth + 1))
2889 return true;
2890
2891 KnownBits KnownSrcBits;
2892 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2893 KnownSrcBits, TLO, Depth + 1))
2894 return true;
2895 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) {
2896 // TODO - bigendian once we have test coverage.
2897 unsigned Scale = NumSrcEltBits / BitWidth;
2898 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2899 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2900 APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
2901 for (unsigned i = 0; i != NumElts; ++i)
2902 if (DemandedElts[i]) {
2903 unsigned Offset = (i % Scale) * BitWidth;
2904 DemandedSrcBits.insertBits(DemandedBits, Offset);
2905 DemandedSrcElts.setBit(i / Scale);
2906 }
2907
2908 if (SrcVT.isVector()) {
2909 APInt KnownSrcUndef, KnownSrcZero;
2910 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2911 KnownSrcZero, TLO, Depth + 1))
2912 return true;
2913 }
2914
2915 KnownBits KnownSrcBits;
2916 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2917 KnownSrcBits, TLO, Depth + 1))
2918 return true;
2919
2920 // Attempt to avoid multi-use ops if we don't need anything from them.
2921 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
2922 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
2923 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
2924 SDValue NewOp = TLO.DAG.getBitcast(VT, DemandedSrc);
2925 return TLO.CombineTo(Op, NewOp);
2926 }
2927 }
2928 }
2929
2930 // If this is a bitcast, let computeKnownBits handle it. Only do this on a
2931 // recursive call where Known may be useful to the caller.
2932 if (Depth > 0) {
2933 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2934 return false;
2935 }
2936 break;
2937 }
2938 case ISD::MUL:
2939 if (DemandedBits.isPowerOf2()) {
2940 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
2941 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
2942 // odd (has LSB set), then the left-shifted low bit of X is the answer.
2943 unsigned CTZ = DemandedBits.countr_zero();
2944 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
2945 if (C && C->getAPIntValue().countr_zero() == CTZ) {
2946 SDValue AmtC = TLO.DAG.getShiftAmountConstant(CTZ, VT, dl);
2947 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC);
2948 return TLO.CombineTo(Op, Shl);
2949 }
2950 }
2951 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
2952 // X * X is odd iff X is odd.
2953 // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
2954 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) {
2955 SDValue One = TLO.DAG.getConstant(1, dl, VT);
2956 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One);
2957 return TLO.CombineTo(Op, And1);
2958 }
2959 [[fallthrough]];
2960 case ISD::PTRADD:
2961 if (Op.getOperand(0).getValueType() != Op.getOperand(1).getValueType())
2962 break;
2963 // PTRADD behaves like ADD if pointers are represented as integers.
2964 [[fallthrough]];
2965 case ISD::ADD:
2966 case ISD::SUB: {
2967 // Add, Sub, and Mul don't demand any bits in positions beyond that
2968 // of the highest bit demanded of them.
2969 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
2970 SDNodeFlags Flags = Op.getNode()->getFlags();
2971 unsigned DemandedBitsLZ = DemandedBits.countl_zero();
2972 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2973 KnownBits KnownOp0, KnownOp1;
2974 auto GetDemandedBitsLHSMask = [&](APInt Demanded,
2975 const KnownBits &KnownRHS) {
2976 if (Op.getOpcode() == ISD::MUL)
2977 Demanded.clearHighBits(KnownRHS.countMinTrailingZeros());
2978 return Demanded;
2979 };
2980 if (SimplifyDemandedBits(Op1, LoMask, DemandedElts, KnownOp1, TLO,
2981 Depth + 1) ||
2982 SimplifyDemandedBits(Op0, GetDemandedBitsLHSMask(LoMask, KnownOp1),
2983 DemandedElts, KnownOp0, TLO, Depth + 1) ||
2984 // See if the operation should be performed at a smaller bit width.
2986 // Disable the nsw and nuw flags. We can no longer guarantee that we
2987 // won't wrap after simplification.
2988 Op->dropFlags(SDNodeFlags::NoWrap);
2989 return true;
2990 }
2991
2992 // neg x with only low bit demanded is simply x.
2993 if (Op.getOpcode() == ISD::SUB && DemandedBits.isOne() &&
2994 isNullConstant(Op0))
2995 return TLO.CombineTo(Op, Op1);
2996
2997 // Attempt to avoid multi-use ops if we don't need anything from them.
2998 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) {
3000 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
3002 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
3003 if (DemandedOp0 || DemandedOp1) {
3004 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
3005 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
3006 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1,
3007 Flags & ~SDNodeFlags::NoWrap);
3008 return TLO.CombineTo(Op, NewOp);
3009 }
3010 }
3011
3012 // If we have a constant operand, we may be able to turn it into -1 if we
3013 // do not demand the high bits. This can make the constant smaller to
3014 // encode, allow more general folding, or match specialized instruction
3015 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
3016 // is probably not useful (and could be detrimental).
3018 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
3019 if (C && !C->isAllOnes() && !C->isOne() &&
3020 (C->getAPIntValue() | HighMask).isAllOnes()) {
3021 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
3022 // Disable the nsw and nuw flags. We can no longer guarantee that we
3023 // won't wrap after simplification.
3024 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1,
3025 Flags & ~SDNodeFlags::NoWrap);
3026 return TLO.CombineTo(Op, NewOp);
3027 }
3028
3029 // Match a multiply with a disguised negated-power-of-2 and convert to a
3030 // an equivalent shift-left amount.
3031 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
3032 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned {
3033 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse())
3034 return 0;
3035
3036 // Don't touch opaque constants. Also, ignore zero and power-of-2
3037 // multiplies. Those will get folded later.
3038 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1));
3039 if (MulC && !MulC->isOpaque() && !MulC->isZero() &&
3040 !MulC->getAPIntValue().isPowerOf2()) {
3041 APInt UnmaskedC = MulC->getAPIntValue() | HighMask;
3042 if (UnmaskedC.isNegatedPowerOf2())
3043 return (-UnmaskedC).logBase2();
3044 }
3045 return 0;
3046 };
3047
3048 auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y,
3049 unsigned ShlAmt) {
3050 SDValue ShlAmtC = TLO.DAG.getShiftAmountConstant(ShlAmt, VT, dl);
3051 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC);
3052 SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl);
3053 return TLO.CombineTo(Op, Res);
3054 };
3055
3057 if (Op.getOpcode() == ISD::ADD) {
3058 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
3059 if (unsigned ShAmt = getShiftLeftAmt(Op0))
3060 return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt);
3061 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC))
3062 if (unsigned ShAmt = getShiftLeftAmt(Op1))
3063 return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt);
3064 }
3065 if (Op.getOpcode() == ISD::SUB) {
3066 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC))
3067 if (unsigned ShAmt = getShiftLeftAmt(Op1))
3068 return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt);
3069 }
3070 }
3071
3072 if (Op.getOpcode() == ISD::MUL) {
3073 Known = KnownBits::mul(KnownOp0, KnownOp1);
3074 } else { // Op.getOpcode() is either ISD::ADD, ISD::PTRADD, or ISD::SUB.
3076 Op.getOpcode() != ISD::SUB, Flags.hasNoSignedWrap(),
3077 Flags.hasNoUnsignedWrap(), KnownOp0, KnownOp1);
3078 }
3079 break;
3080 }
3081 case ISD::FABS: {
3082 SDValue Op0 = Op.getOperand(0);
3083 APInt SignMask = APInt::getSignMask(BitWidth);
3084
3085 if (!DemandedBits.intersects(SignMask))
3086 return TLO.CombineTo(Op, Op0);
3087
3088 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3089 Depth + 1))
3090 return true;
3091
3092 if (Known.isNonNegative())
3093 return TLO.CombineTo(Op, Op0);
3094 if (Known.isNegative())
3095 return TLO.CombineTo(
3096 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT, Op0, Op->getFlags()));
3097
3098 Known.Zero |= SignMask;
3099 Known.One &= ~SignMask;
3100
3101 break;
3102 }
3103 case ISD::FCOPYSIGN: {
3104 SDValue Op0 = Op.getOperand(0);
3105 SDValue Op1 = Op.getOperand(1);
3106
3107 unsigned BitWidth0 = Op0.getScalarValueSizeInBits();
3108 unsigned BitWidth1 = Op1.getScalarValueSizeInBits();
3109 APInt SignMask0 = APInt::getSignMask(BitWidth0);
3110 APInt SignMask1 = APInt::getSignMask(BitWidth1);
3111
3112 if (!DemandedBits.intersects(SignMask0))
3113 return TLO.CombineTo(Op, Op0);
3114
3115 if (SimplifyDemandedBits(Op0, ~SignMask0 & DemandedBits, DemandedElts,
3116 Known, TLO, Depth + 1) ||
3117 SimplifyDemandedBits(Op1, SignMask1, DemandedElts, Known2, TLO,
3118 Depth + 1))
3119 return true;
3120
3121 if (Known2.isNonNegative())
3122 return TLO.CombineTo(
3123 Op, TLO.DAG.getNode(ISD::FABS, dl, VT, Op0, Op->getFlags()));
3124
3125 if (Known2.isNegative())
3126 return TLO.CombineTo(
3127 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT,
3128 TLO.DAG.getNode(ISD::FABS, SDLoc(Op0), VT, Op0)));
3129
3130 Known.Zero &= ~SignMask0;
3131 Known.One &= ~SignMask0;
3132 break;
3133 }
3134 case ISD::FNEG: {
3135 SDValue Op0 = Op.getOperand(0);
3136 APInt SignMask = APInt::getSignMask(BitWidth);
3137
3138 if (!DemandedBits.intersects(SignMask))
3139 return TLO.CombineTo(Op, Op0);
3140
3141 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3142 Depth + 1))
3143 return true;
3144
3145 if (!Known.isSignUnknown()) {
3146 Known.Zero ^= SignMask;
3147 Known.One ^= SignMask;
3148 }
3149
3150 break;
3151 }
3152 default:
3153 // We also ask the target about intrinsics (which could be specific to it).
3154 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3155 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
3156 // TODO: Probably okay to remove after audit; here to reduce change size
3157 // in initial enablement patch for scalable vectors
3158 if (Op.getValueType().isScalableVector())
3159 break;
3161 Known, TLO, Depth))
3162 return true;
3163 break;
3164 }
3165
3166 // Just use computeKnownBits to compute output bits.
3167 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
3168 break;
3169 }
3170
3171 // If we know the value of all of the demanded bits, return this as a
3172 // constant.
3174 DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
3175 // Avoid folding to a constant if any OpaqueConstant is involved.
3176 if (llvm::any_of(Op->ops(), [](SDValue V) {
3177 auto *C = dyn_cast<ConstantSDNode>(V);
3178 return C && C->isOpaque();
3179 }))
3180 return false;
3181 if (VT.isInteger())
3182 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
3183 if (VT.isFloatingPoint())
3184 return TLO.CombineTo(
3186 dl, VT));
3187 }
3188
3189 // A multi use 'all demanded elts' simplify failed to find any knownbits.
3190 // Try again just for the original demanded elts.
3191 // Ensure we do this AFTER constant folding above.
3192 if (HasMultiUse && Known.isUnknown() && !OriginalDemandedElts.isAllOnes())
3193 Known = TLO.DAG.computeKnownBits(Op, OriginalDemandedElts, Depth);
3194
3195 return false;
3196}
3197
3199 const APInt &DemandedElts,
3200 DAGCombinerInfo &DCI) const {
3201 SelectionDAG &DAG = DCI.DAG;
3202 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
3203 !DCI.isBeforeLegalizeOps());
3204
3205 APInt KnownUndef, KnownZero;
3206 bool Simplified =
3207 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
3208 if (Simplified) {
3209 DCI.AddToWorklist(Op.getNode());
3210 DCI.CommitTargetLoweringOpt(TLO);
3211 }
3212
3213 return Simplified;
3214}
3215
3216/// Given a vector binary operation and known undefined elements for each input
3217/// operand, compute whether each element of the output is undefined.
3219 const APInt &UndefOp0,
3220 const APInt &UndefOp1) {
3221 EVT VT = BO.getValueType();
3223 "Vector binop only");
3224
3225 EVT EltVT = VT.getVectorElementType();
3226 unsigned NumElts = VT.isFixedLengthVector() ? VT.getVectorNumElements() : 1;
3227 assert(UndefOp0.getBitWidth() == NumElts &&
3228 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
3229
3230 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
3231 const APInt &UndefVals) {
3232 if (UndefVals[Index])
3233 return DAG.getUNDEF(EltVT);
3234
3235 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
3236 // Try hard to make sure that the getNode() call is not creating temporary
3237 // nodes. Ignore opaque integers because they do not constant fold.
3238 SDValue Elt = BV->getOperand(Index);
3239 auto *C = dyn_cast<ConstantSDNode>(Elt);
3240 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
3241 return Elt;
3242 }
3243
3244 return SDValue();
3245 };
3246
3247 APInt KnownUndef = APInt::getZero(NumElts);
3248 for (unsigned i = 0; i != NumElts; ++i) {
3249 // If both inputs for this element are either constant or undef and match
3250 // the element type, compute the constant/undef result for this element of
3251 // the vector.
3252 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
3253 // not handle FP constants. The code within getNode() should be refactored
3254 // to avoid the danger of creating a bogus temporary node here.
3255 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
3256 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
3257 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
3258 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
3259 KnownUndef.setBit(i);
3260 }
3261 return KnownUndef;
3262}
3263
3265 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
3266 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
3267 bool AssumeSingleUse) const {
3268 EVT VT = Op.getValueType();
3269 unsigned Opcode = Op.getOpcode();
3270 APInt DemandedElts = OriginalDemandedElts;
3271 unsigned NumElts = DemandedElts.getBitWidth();
3272 assert(VT.isVector() && "Expected vector op");
3273
3274 KnownUndef = KnownZero = APInt::getZero(NumElts);
3275
3277 return false;
3278
3279 // TODO: For now we assume we know nothing about scalable vectors.
3280 if (VT.isScalableVector())
3281 return false;
3282
3283 assert(VT.getVectorNumElements() == NumElts &&
3284 "Mask size mismatches value type element count!");
3285
3286 // Undef operand.
3287 if (Op.isUndef()) {
3288 KnownUndef.setAllBits();
3289 return false;
3290 }
3291
3292 // If Op has other users, assume that all elements are needed.
3293 if (!AssumeSingleUse && !Op.getNode()->hasOneUse())
3294 DemandedElts.setAllBits();
3295
3296 // Not demanding any elements from Op.
3297 if (DemandedElts == 0) {
3298 KnownUndef.setAllBits();
3299 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3300 }
3301
3302 // Limit search depth.
3304 return false;
3305
3306 SDLoc DL(Op);
3307 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3308 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
3309
3310 auto TryShrinkBinOp = [&](SDValue Op0, SDValue Op1) {
3311 unsigned ShrunkSize = getPreferredShrunkVectorSizeInBits(Op, DemandedElts);
3312 if (!ShrunkSize)
3313 return false;
3314
3315 assert(ShrunkSize % EltSizeInBits == 0 &&
3316 "Shrunk size not a multiple of element size");
3317 assert(ShrunkSize < VT.getSizeInBits() &&
3318 "Shrunk size must be < original vector size");
3319 assert(ShrunkSize >= EltSizeInBits * DemandedElts.getActiveBits() &&
3320 "Shrunk size must be >= demanded size");
3321
3322 EVT ShrunkVT = VT.changeVectorElementCount(
3323 *TLO.DAG.getContext(),
3324 ElementCount::getFixed(ShrunkSize / EltSizeInBits));
3325 Op0 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op0, 0);
3326 Op1 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op1, 0);
3327 SDValue NewOp =
3328 TLO.DAG.getNode(Opcode, DL, ShrunkVT, Op0, Op1, Op->getFlags());
3329 return TLO.CombineTo(
3330 Op, TLO.DAG.getInsertSubvector(DL, TLO.DAG.getUNDEF(VT), NewOp, 0));
3331 };
3332
3333 // Helper for demanding the specified elements and all the bits of both binary
3334 // operands.
3335 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
3336 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts,
3337 TLO.DAG, Depth + 1);
3338 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts,
3339 TLO.DAG, Depth + 1);
3340 if (NewOp0 || NewOp1) {
3341 SDValue NewOp =
3342 TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0,
3343 NewOp1 ? NewOp1 : Op1, Op->getFlags());
3344 return TLO.CombineTo(Op, NewOp);
3345 }
3346
3347 if (TryShrinkBinOp(Op0, Op1))
3348 return true;
3349
3350 return false;
3351 };
3352
3353 switch (Opcode) {
3354 case ISD::SCALAR_TO_VECTOR: {
3355 if (!DemandedElts[0])
3356 return TLO.CombineTo(Op, TLO.DAG.getPOISON(VT));
3357 // Upper elements are poison, not undef - don't mark them as KnownUndef.
3358 break;
3359 }
3360 case ISD::BITCAST: {
3361 SDValue Src = Op.getOperand(0);
3362 EVT SrcVT = Src.getValueType();
3363
3364 if (!SrcVT.isVector()) {
3365 // TODO - bigendian once we have test coverage.
3366 if (IsLE) {
3367 APInt DemandedSrcBits = APInt::getZero(SrcVT.getSizeInBits());
3368 unsigned EltSize = VT.getScalarSizeInBits();
3369 for (unsigned I = 0; I != NumElts; ++I) {
3370 if (DemandedElts[I]) {
3371 unsigned Offset = I * EltSize;
3372 DemandedSrcBits.setBits(Offset, Offset + EltSize);
3373 }
3374 }
3376 if (SimplifyDemandedBits(Src, DemandedSrcBits, Known, TLO, Depth + 1))
3377 return true;
3378 }
3379 break;
3380 }
3381
3382 // Fast handling of 'identity' bitcasts.
3383 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3384 if (NumSrcElts == NumElts)
3385 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
3386 KnownZero, TLO, Depth + 1);
3387
3388 APInt SrcDemandedElts, SrcZero, SrcUndef;
3389
3390 // Bitcast from 'large element' src vector to 'small element' vector, we
3391 // must demand a source element if any DemandedElt maps to it.
3392 if ((NumElts % NumSrcElts) == 0) {
3393 unsigned Scale = NumElts / NumSrcElts;
3394 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3395 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3396 TLO, Depth + 1))
3397 return true;
3398
3399 // Try calling SimplifyDemandedBits, converting demanded elts to the bits
3400 // of the large element.
3401 // TODO - bigendian once we have test coverage.
3402 if (IsLE) {
3403 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
3404 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits);
3405 for (unsigned i = 0; i != NumElts; ++i)
3406 if (DemandedElts[i]) {
3407 unsigned Ofs = (i % Scale) * EltSizeInBits;
3408 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
3409 }
3410
3412 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
3413 TLO, Depth + 1))
3414 return true;
3415
3416 // The bitcast has split each wide element into a number of
3417 // narrow subelements. We have just computed the Known bits
3418 // for wide elements. See if element splitting results in
3419 // some subelements being zero. Only for demanded elements!
3420 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) {
3421 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits)
3422 .isAllOnes())
3423 continue;
3424 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) {
3425 unsigned Elt = Scale * SrcElt + SubElt;
3426 // A wholly-undef source lane is reported as undef below; don't also
3427 // flag it as zero, keeping the undef and zero sets disjoint.
3428 if (DemandedElts[Elt] && !SrcUndef[SrcElt])
3429 KnownZero.setBit(Elt);
3430 }
3431 }
3432 }
3433
3434 // If the src element is zero/undef then all the output elements will be -
3435 // only demanded elements are guaranteed to be correct.
3436 for (unsigned i = 0; i != NumSrcElts; ++i) {
3437 if (SrcDemandedElts[i]) {
3438 if (SrcZero[i])
3439 KnownZero.setBits(i * Scale, (i + 1) * Scale);
3440 if (SrcUndef[i])
3441 KnownUndef.setBits(i * Scale, (i + 1) * Scale);
3442 }
3443 }
3444 }
3445
3446 // Bitcast from 'small element' src vector to 'large element' vector, we
3447 // demand all smaller source elements covered by the larger demanded element
3448 // of this vector.
3449 if ((NumSrcElts % NumElts) == 0) {
3450 unsigned Scale = NumSrcElts / NumElts;
3451 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3452 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3453 TLO, Depth + 1))
3454 return true;
3455
3456 // If all the src elements covering an output element are zero/undef, then
3457 // the output element will be as well, assuming it was demanded.
3458 for (unsigned i = 0; i != NumElts; ++i) {
3459 if (DemandedElts[i]) {
3460 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes())
3461 KnownZero.setBit(i);
3462 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes())
3463 KnownUndef.setBit(i);
3464 }
3465 }
3466 }
3467 break;
3468 }
3469 case ISD::FREEZE: {
3470 SDValue N0 = Op.getOperand(0);
3472 N0, DemandedElts, UndefPoisonKind::UndefOrPoison, Depth + 1))
3473 return TLO.CombineTo(Op, N0);
3474
3475 // TODO: Replace this with the general fold from DAGCombiner::visitFREEZE
3476 // freeze(op(x, ...)) -> op(freeze(x), ...).
3477 // Don't sink the freeze below SCALAR_TO_VECTOR when the scalar is a load
3478 // of a promoted (wider than the element) type: freeze(load) can never be
3479 // folded away (the loaded value may be poison in memory), and the extra
3480 // freeze node then blocks ISel patterns matching scalar_to_vector of a
3481 // load, e.g. the AArch64 scalar_to_vector(extload) -> ldr b/h forms.
3482 // freeze(scalar_to_vector(load)) is equivalent for the demanded element
3483 // zero, and ISel selects the freeze as a plain copy.
3484 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && DemandedElts == 1) {
3485 SDValue Scalar = N0.getOperand(0);
3486 bool IsPromotedLoad = Scalar.getOpcode() == ISD::LOAD &&
3487 Scalar.getValueType() != VT.getVectorElementType();
3488 if (!IsPromotedLoad)
3489 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT,
3490 TLO.DAG.getFreeze(Scalar)));
3491 }
3492 break;
3493 }
3494 case ISD::BUILD_VECTOR: {
3495 // Check all elements and simplify any unused elements with UNDEF.
3496 if (!DemandedElts.isAllOnes()) {
3497 // Don't simplify BROADCASTS.
3498 if (llvm::any_of(Op->op_values(),
3499 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
3501 bool Updated = false;
3502 for (unsigned i = 0; i != NumElts; ++i) {
3503 if (!DemandedElts[i] && !Ops[i].isUndef()) {
3504 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
3505 KnownUndef.setBit(i);
3506 Updated = true;
3507 }
3508 }
3509 if (Updated)
3510 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
3511 }
3512 }
3513 for (unsigned i = 0; i != NumElts; ++i) {
3514 SDValue SrcOp = Op.getOperand(i);
3515 if (SrcOp.isUndef()) {
3516 KnownUndef.setBit(i);
3517 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
3519 KnownZero.setBit(i);
3520 }
3521 }
3522 break;
3523 }
3524 case ISD::CONCAT_VECTORS: {
3525 EVT SubVT = Op.getOperand(0).getValueType();
3526 unsigned NumSubVecs = Op.getNumOperands();
3527 unsigned NumSubElts = SubVT.getVectorNumElements();
3528 for (unsigned i = 0; i != NumSubVecs; ++i) {
3529 SDValue SubOp = Op.getOperand(i);
3530 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3531 APInt SubUndef, SubZero;
3532 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
3533 Depth + 1))
3534 return true;
3535 KnownUndef.insertBits(SubUndef, i * NumSubElts);
3536 KnownZero.insertBits(SubZero, i * NumSubElts);
3537 }
3538
3539 // Attempt to avoid multi-use ops if we don't need anything from them.
3540 if (!DemandedElts.isAllOnes()) {
3541 bool FoundNewSub = false;
3542 SmallVector<SDValue, 2> DemandedSubOps;
3543 for (unsigned i = 0; i != NumSubVecs; ++i) {
3544 SDValue SubOp = Op.getOperand(i);
3545 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3547 SubOp, SubElts, TLO.DAG, Depth + 1);
3548 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp);
3549 FoundNewSub = NewSubOp ? true : FoundNewSub;
3550 }
3551 if (FoundNewSub) {
3552 SDValue NewOp =
3553 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps);
3554 return TLO.CombineTo(Op, NewOp);
3555 }
3556 }
3557 break;
3558 }
3559 case ISD::INSERT_SUBVECTOR: {
3560 // Demand any elements from the subvector and the remainder from the src it
3561 // is inserted into.
3562 SDValue Src = Op.getOperand(0);
3563 SDValue Sub = Op.getOperand(1);
3564 uint64_t Idx = Op.getConstantOperandVal(2);
3565 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3566 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3567 APInt DemandedSrcElts = DemandedElts;
3568 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3569
3570 // If none of the sub operand elements are demanded, bypass the insert.
3571 if (!DemandedSubElts)
3572 return TLO.CombineTo(Op, Src);
3573
3574 APInt SubUndef, SubZero;
3575 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
3576 Depth + 1))
3577 return true;
3578
3579 // If none of the src operand elements are demanded, replace it with undef.
3580 if (!DemandedSrcElts && !Src.isUndef())
3581 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
3582 TLO.DAG.getUNDEF(VT), Sub,
3583 Op.getOperand(2)));
3584
3585 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
3586 TLO, Depth + 1))
3587 return true;
3588 KnownUndef.insertBits(SubUndef, Idx);
3589 KnownZero.insertBits(SubZero, Idx);
3590
3591 // Attempt to avoid multi-use ops if we don't need anything from them.
3592 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) {
3594 Src, DemandedSrcElts, TLO.DAG, Depth + 1);
3596 Sub, DemandedSubElts, TLO.DAG, Depth + 1);
3597 if (NewSrc || NewSub) {
3598 NewSrc = NewSrc ? NewSrc : Src;
3599 NewSub = NewSub ? NewSub : Sub;
3600 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3601 NewSub, Op.getOperand(2));
3602 return TLO.CombineTo(Op, NewOp);
3603 }
3604 }
3605 break;
3606 }
3608 // Offset the demanded elts by the subvector index.
3609 SDValue Src = Op.getOperand(0);
3610 if (Src.getValueType().isScalableVector())
3611 break;
3612 uint64_t Idx = Op.getConstantOperandVal(1);
3613 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3614 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3615
3616 APInt SrcUndef, SrcZero;
3617 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3618 Depth + 1))
3619 return true;
3620 KnownUndef = SrcUndef.extractBits(NumElts, Idx);
3621 KnownZero = SrcZero.extractBits(NumElts, Idx);
3622
3623 // Attempt to avoid multi-use ops if we don't need anything from them.
3624 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(Src, DemandedSrcElts,
3625 TLO.DAG, Depth + 1);
3626 if (NewSrc) {
3627 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3628 Op.getOperand(1));
3629 return TLO.CombineTo(Op, NewOp);
3630 }
3631 break;
3632 }
3634 SDValue Vec = Op.getOperand(0);
3635 SDValue Scl = Op.getOperand(1);
3636 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3637
3638 // For a legal, constant insertion index, if we don't need this insertion
3639 // then strip it, else remove it from the demanded elts.
3640 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
3641 unsigned Idx = CIdx->getZExtValue();
3642 if (!DemandedElts[Idx])
3643 return TLO.CombineTo(Op, Vec);
3644
3645 APInt DemandedVecElts(DemandedElts);
3646 DemandedVecElts.clearBit(Idx);
3647 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
3648 KnownZero, TLO, Depth + 1))
3649 return true;
3650
3651 KnownUndef.setBitVal(Idx, Scl.isUndef());
3652
3653 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
3654 break;
3655 }
3656
3657 APInt VecUndef, VecZero;
3658 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
3659 Depth + 1))
3660 return true;
3661 // Without knowing the insertion index we can't set KnownUndef/KnownZero.
3662 break;
3663 }
3664 case ISD::VSELECT: {
3665 SDValue Sel = Op.getOperand(0);
3666 SDValue LHS = Op.getOperand(1);
3667 SDValue RHS = Op.getOperand(2);
3668
3669 // Try to transform the select condition based on the current demanded
3670 // elements.
3671 APInt UndefSel, ZeroSel;
3672 if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, ZeroSel, TLO,
3673 Depth + 1))
3674 return true;
3675
3676 // See if we can simplify either vselect operand.
3677 APInt DemandedLHS(DemandedElts);
3678 APInt DemandedRHS(DemandedElts);
3679 APInt UndefLHS, ZeroLHS;
3680 APInt UndefRHS, ZeroRHS;
3681 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3682 Depth + 1))
3683 return true;
3684 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3685 Depth + 1))
3686 return true;
3687
3688 KnownUndef = UndefLHS & UndefRHS;
3689 KnownZero = ZeroLHS & ZeroRHS;
3690
3691 // If we know that the selected element is always zero, we don't need the
3692 // select value element.
3693 APInt DemandedSel = DemandedElts & ~KnownZero;
3694 if (DemandedSel != DemandedElts)
3695 if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, ZeroSel, TLO,
3696 Depth + 1))
3697 return true;
3698
3699 break;
3700 }
3701 case ISD::VECTOR_SHUFFLE: {
3702 SDValue LHS = Op.getOperand(0);
3703 SDValue RHS = Op.getOperand(1);
3704 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
3705
3706 // Collect demanded elements from shuffle operands..
3707 APInt DemandedLHS(NumElts, 0);
3708 APInt DemandedRHS(NumElts, 0);
3709 for (unsigned i = 0; i != NumElts; ++i) {
3710 int M = ShuffleMask[i];
3711 if (M < 0 || !DemandedElts[i])
3712 continue;
3713 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
3714 if (M < (int)NumElts)
3715 DemandedLHS.setBit(M);
3716 else
3717 DemandedRHS.setBit(M - NumElts);
3718 }
3719
3720 // If either side isn't demanded, replace it by UNDEF. We handle this
3721 // explicitly here to also simplify in case of multiple uses (on the
3722 // contrary to the SimplifyDemandedVectorElts calls below).
3723 bool FoldLHS = !DemandedLHS && !LHS.isUndef();
3724 bool FoldRHS = !DemandedRHS && !RHS.isUndef();
3725 if (FoldLHS || FoldRHS) {
3726 LHS = FoldLHS ? TLO.DAG.getUNDEF(LHS.getValueType()) : LHS;
3727 RHS = FoldRHS ? TLO.DAG.getUNDEF(RHS.getValueType()) : RHS;
3728 SDValue NewOp =
3729 TLO.DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, ShuffleMask);
3730 return TLO.CombineTo(Op, NewOp);
3731 }
3732
3733 // See if we can simplify either shuffle operand.
3734 APInt UndefLHS, ZeroLHS;
3735 APInt UndefRHS, ZeroRHS;
3736 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3737 Depth + 1))
3738 return true;
3739 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3740 Depth + 1))
3741 return true;
3742
3743 // Simplify mask using undef elements from LHS/RHS.
3744 bool Updated = false;
3745 bool IdentityLHS = true, IdentityRHS = true;
3746 SmallVector<int, 32> NewMask(ShuffleMask);
3747 for (unsigned i = 0; i != NumElts; ++i) {
3748 int &M = NewMask[i];
3749 if (M < 0)
3750 continue;
3751 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
3752 (M >= (int)NumElts && UndefRHS[M - NumElts])) {
3753 Updated = true;
3754 M = -1;
3755 }
3756 IdentityLHS &= (M < 0) || (M == (int)i);
3757 IdentityRHS &= (M < 0) || ((M - NumElts) == i);
3758 }
3759
3760 // Update legal shuffle masks based on demanded elements if it won't reduce
3761 // to Identity which can cause premature removal of the shuffle mask.
3762 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
3763 SDValue LegalShuffle =
3764 buildLegalVectorShuffle(VT, DL, LHS, RHS, NewMask, TLO.DAG);
3765 if (LegalShuffle)
3766 return TLO.CombineTo(Op, LegalShuffle);
3767 }
3768
3769 // Propagate undef/zero elements from LHS/RHS.
3770 for (unsigned i = 0; i != NumElts; ++i) {
3771 int M = ShuffleMask[i];
3772 if (M < 0) {
3773 KnownUndef.setBit(i);
3774 } else if (M < (int)NumElts) {
3775 if (UndefLHS[M])
3776 KnownUndef.setBit(i);
3777 if (ZeroLHS[M])
3778 KnownZero.setBit(i);
3779 } else {
3780 if (UndefRHS[M - NumElts])
3781 KnownUndef.setBit(i);
3782 if (ZeroRHS[M - NumElts])
3783 KnownZero.setBit(i);
3784 }
3785 }
3786 break;
3787 }
3791 APInt SrcUndef, SrcZero;
3792 SDValue Src = Op.getOperand(0);
3793 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3794 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3795 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3796 Depth + 1))
3797 return true;
3798 KnownZero = SrcZero.zextOrTrunc(NumElts);
3799 KnownUndef = SrcUndef.zextOrTrunc(NumElts);
3800
3801 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
3802 Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
3803 DemandedSrcElts == 1) {
3804 // aext - if we just need the bottom element then we can bitcast.
3805 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
3806 }
3807
3808 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
3809 // zext(undef) upper bits are guaranteed to be zero.
3810 if (DemandedElts.isSubsetOf(KnownUndef))
3811 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3812 KnownUndef.clearAllBits();
3813
3814 // zext - if we just need the bottom element then we can mask:
3815 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
3816 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
3817 Op->isOnlyUserOf(Src.getNode()) &&
3818 Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
3819 SDLoc DL(Op);
3820 EVT SrcVT = Src.getValueType();
3821 EVT SrcSVT = SrcVT.getScalarType();
3822
3823 // If we're after type legalization and SrcSVT is not legal, use the
3824 // promoted type for creating constants to avoid creating nodes with
3825 // illegal types.
3826 if (TLO.LegalTypes())
3827 SrcSVT = getLegalTypeToTransformTo(*TLO.DAG.getContext(), SrcSVT);
3828
3829 SmallVector<SDValue> MaskElts;
3830 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
3831 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
3832 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
3833 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
3834 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
3835 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
3836 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
3837 }
3838 }
3839 }
3840 break;
3841 }
3842
3843 // TODO: There are more binop opcodes that could be handled here - MIN,
3844 // MAX, saturated math, etc.
3845 case ISD::ADD: {
3846 SDValue Op0 = Op.getOperand(0);
3847 SDValue Op1 = Op.getOperand(1);
3848 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
3849 APInt UndefLHS, ZeroLHS;
3850 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3851 Depth + 1, /*AssumeSingleUse*/ true))
3852 return true;
3853 }
3854 [[fallthrough]];
3855 }
3856 case ISD::AVGCEILS:
3857 case ISD::AVGCEILU:
3858 case ISD::AVGFLOORS:
3859 case ISD::AVGFLOORU:
3860 case ISD::OR:
3861 case ISD::XOR:
3862 case ISD::SUB:
3863 case ISD::FADD:
3864 case ISD::FSUB:
3865 case ISD::FMUL:
3866 case ISD::FDIV:
3867 case ISD::FREM:
3868 case ISD::PSEUDO_FMIN:
3869 case ISD::PSEUDO_FMAX: {
3870 SDValue Op0 = Op.getOperand(0);
3871 SDValue Op1 = Op.getOperand(1);
3872
3873 APInt UndefRHS, ZeroRHS;
3874 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3875 Depth + 1))
3876 return true;
3877 APInt UndefLHS, ZeroLHS;
3878 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3879 Depth + 1))
3880 return true;
3881
3882 KnownZero = ZeroLHS & ZeroRHS;
3883 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
3884
3885 // Attempt to avoid multi-use ops if we don't need anything from them.
3886 // TODO - use KnownUndef to relax the demandedelts?
3887 if (!DemandedElts.isAllOnes())
3888 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3889 return true;
3890 break;
3891 }
3892 case ISD::SHL:
3893 case ISD::SRL:
3894 case ISD::SRA:
3895 case ISD::ROTL:
3896 case ISD::ROTR: {
3897 SDValue Op0 = Op.getOperand(0);
3898 SDValue Op1 = Op.getOperand(1);
3899
3900 APInt UndefRHS, ZeroRHS;
3901 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3902 Depth + 1))
3903 return true;
3904 APInt UndefLHS, ZeroLHS;
3905 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3906 Depth + 1))
3907 return true;
3908
3909 KnownZero = ZeroLHS;
3910 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
3911
3912 // Attempt to avoid multi-use ops if we don't need anything from them.
3913 // TODO - use KnownUndef to relax the demandedelts?
3914 if (!DemandedElts.isAllOnes())
3915 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3916 return true;
3917 break;
3918 }
3919 case ISD::MUL:
3920 case ISD::MULHU:
3921 case ISD::MULHS:
3922 case ISD::AND: {
3923 SDValue Op0 = Op.getOperand(0);
3924 SDValue Op1 = Op.getOperand(1);
3925
3926 APInt SrcUndef, SrcZero;
3927 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
3928 Depth + 1))
3929 return true;
3930 // FIXME: If we know that a demanded element was zero in Op1 we don't need
3931 // to demand it in Op0 - its guaranteed to be zero. There is however a
3932 // restriction, as we must not make any of the originally demanded elements
3933 // more poisonous. We could reduce amount of elements demanded, but then we
3934 // also need a to inform SimplifyDemandedVectorElts that some elements must
3935 // not be made more poisonous.
3936 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
3937 TLO, Depth + 1))
3938 return true;
3939
3940 KnownUndef &= DemandedElts;
3941 KnownZero &= DemandedElts;
3942
3943 // If every element pair has a zero/undef/poison then just fold to zero.
3944 // fold (and x, undef/poison) -> 0 / (and x, 0) -> 0
3945 // fold (mul x, undef/poison) -> 0 / (mul x, 0) -> 0
3946 if (DemandedElts.isSubsetOf(SrcZero | KnownZero | SrcUndef | KnownUndef))
3947 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3948
3949 // If either side has a zero element, then the result element is zero, even
3950 // if the other is an UNDEF.
3951 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
3952 // and then handle 'and' nodes with the rest of the binop opcodes.
3953 KnownZero |= SrcZero;
3954 KnownUndef &= SrcUndef;
3955 KnownUndef &= ~KnownZero;
3956
3957 // Attempt to avoid multi-use ops if we don't need anything from them.
3958 if (!DemandedElts.isAllOnes())
3959 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3960 return true;
3961 break;
3962 }
3963 case ISD::TRUNCATE:
3964 case ISD::SIGN_EXTEND:
3965 case ISD::ZERO_EXTEND:
3966 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
3967 KnownZero, TLO, Depth + 1))
3968 return true;
3969
3970 if (!DemandedElts.isAllOnes())
3972 Op.getOperand(0), DemandedElts, TLO.DAG, Depth + 1))
3973 return TLO.CombineTo(Op, TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp));
3974
3975 if (Op.getOpcode() == ISD::ZERO_EXTEND) {
3976 // zext(undef) upper bits are guaranteed to be zero.
3977 if (DemandedElts.isSubsetOf(KnownUndef))
3978 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3979 KnownUndef.clearAllBits();
3980 }
3981 break;
3982 case ISD::SINT_TO_FP:
3983 case ISD::UINT_TO_FP:
3984 case ISD::FP_TO_SINT:
3985 case ISD::FP_TO_UINT:
3986 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
3987 KnownZero, TLO, Depth + 1))
3988 return true;
3989 // Don't fall through to generic undef -> undef handling.
3990 return false;
3991 default: {
3992 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
3993 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
3994 KnownZero, TLO, Depth))
3995 return true;
3996 } else {
3998 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
3999 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
4000 TLO, Depth, AssumeSingleUse))
4001 return true;
4002 }
4003 break;
4004 }
4005 }
4006
4007 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
4008
4009 // Constant fold all undef cases.
4010 // TODO: Handle zero cases as well.
4011 if (DemandedElts.isSubsetOf(KnownUndef))
4012 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
4013
4014 return false;
4015}
4016
4017/// Determine which of the bits specified in Mask are known to be either zero or
4018/// one and return them in the Known.
4021 const APInt &DemandedElts,
4022 const SelectionDAG &DAG,
4023 unsigned Depth) const {
4024 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4025 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4026 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4027 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4028 "Should use MaskedValueIsZero if you don't know whether Op"
4029 " is a target node!");
4030 Known.resetAll();
4031}
4032
4035 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4036 unsigned Depth) const {
4037 Known.resetAll();
4038}
4039
4042 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4043 unsigned Depth) const {
4044 Known.resetAll();
4045}
4046
4048 KnownBits &Known, const MachineFunction &, Align Alignment) const {
4049 // The low bits are known zero if the pointer is aligned.
4050 Known.Zero.setLowBits(Log2(Alignment));
4051}
4052
4054 SelectionDAG &DAG,
4055 const SDLoc &DL,
4056 Align Alignment) const {
4057 // Materialize leading-zero stack object pointer facts as AssertZext.
4058 // Alignment-derived low zero bits are not represented on the returned DAG
4059 // value here.
4060 EVT PtrVT = Ptr.getValueType();
4061
4062 unsigned RegSize = PtrVT.getScalarSizeInBits();
4065 Alignment);
4066
4067 unsigned NumZeroBits = Known.countMinLeadingZeros();
4068 if (!NumZeroBits)
4069 return Ptr;
4070
4071 EVT FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
4072 return DAG.getNode(ISD::AssertZext, DL, PtrVT, Ptr, DAG.getValueType(FromVT));
4073}
4074
4080
4081/// This method can be implemented by targets that want to expose additional
4082/// information about sign bits to the DAG Combiner.
4084 const APInt &,
4085 const SelectionDAG &,
4086 unsigned Depth) const {
4087 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4088 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4089 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4090 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4091 "Should use ComputeNumSignBits if you don't know whether Op"
4092 " is a target node!");
4093 return 1;
4094}
4095
4097 GISelValueTracking &Analysis, Register R, const APInt &DemandedElts,
4098 const MachineRegisterInfo &MRI, unsigned Depth) const {
4099 return 1;
4100}
4101
4103 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
4104 TargetLoweringOpt &TLO, unsigned Depth) const {
4105 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4106 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4107 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4108 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4109 "Should use SimplifyDemandedVectorElts if you don't know whether Op"
4110 " is a target node!");
4111 return false;
4112}
4113
4115 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4116 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
4117 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4118 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4119 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4120 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4121 "Should use SimplifyDemandedBits if you don't know whether Op"
4122 " is a target node!");
4123 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
4124 return false;
4125}
4126
4128 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4129 SelectionDAG &DAG, unsigned Depth) const {
4130 assert(
4131 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4132 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4133 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4134 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4135 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
4136 " is a target node!");
4137 return SDValue();
4138}
4139
4140SDValue
4143 SelectionDAG &DAG) const {
4144 bool LegalMask = isShuffleMaskLegal(Mask, VT);
4145 if (!LegalMask) {
4146 std::swap(N0, N1);
4148 LegalMask = isShuffleMaskLegal(Mask, VT);
4149 }
4150
4151 if (!LegalMask)
4152 return SDValue();
4153
4154 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
4155}
4156
4158 return nullptr;
4159}
4160
4162 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4163 UndefPoisonKind Kind, unsigned Depth) const {
4164 assert(
4165 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4166 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4167 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4168 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4169 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
4170 " is a target node!");
4171
4172 // If Op can't create undef/poison and none of its operands are undef/poison
4173 // then Op is never undef/poison.
4174 return !canCreateUndefOrPoisonForTargetNode(Op, DemandedElts, DAG, Kind,
4175 /*ConsiderFlags*/ true, Depth) &&
4176 all_of(Op->ops(), [&](SDValue V) {
4177 return DAG.isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
4178 });
4179}
4180
4182 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4183 UndefPoisonKind Kind, bool ConsiderFlags, unsigned Depth) const {
4184 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4185 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4186 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4187 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4188 "Should use canCreateUndefOrPoison if you don't know whether Op"
4189 " is a target node!");
4190 // Be conservative and return true.
4191 return true;
4192}
4193
4196 const APInt &DemandedElts,
4197 const SelectionDAG &DAG,
4198 unsigned Depth) const {
4199 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4200 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4201 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4202 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4203 "Should use computeKnownFPClass if you don't know whether Op"
4204 " is a target node!");
4205}
4206
4208 const APInt &DemandedElts,
4209 const SelectionDAG &DAG,
4210 bool SNaN,
4211 unsigned Depth) const {
4212 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4213 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4214 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4215 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4216 "Should use isKnownNeverNaN if you don't know whether Op"
4217 " is a target node!");
4218 return false;
4219}
4220
4222 const APInt &DemandedElts,
4223 APInt &UndefElts,
4224 const SelectionDAG &DAG,
4225 unsigned Depth) const {
4226 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4227 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4228 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4229 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4230 "Should use isSplatValue if you don't know whether Op"
4231 " is a target node!");
4232 return false;
4233}
4234
4235// FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
4236// work with truncating build vectors and vectors with elements of less than
4237// 8 bits.
4239 if (!N)
4240 return false;
4241
4242 unsigned EltWidth;
4243 APInt CVal;
4244 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
4245 /*AllowTruncation=*/true)) {
4246 CVal = CN->getAPIntValue();
4247 EltWidth = N.getValueType().getScalarSizeInBits();
4248 } else
4249 return false;
4250
4251 // If this is a truncating splat, truncate the splat value.
4252 // Otherwise, we may fail to match the expected values below.
4253 if (EltWidth < CVal.getBitWidth())
4254 CVal = CVal.trunc(EltWidth);
4255
4256 switch (getBooleanContents(N.getValueType())) {
4258 return CVal[0];
4260 return CVal.isOne();
4262 return CVal.isAllOnes();
4263 }
4264
4265 llvm_unreachable("Invalid boolean contents");
4266}
4267
4269 if (!N)
4270 return false;
4271
4273 if (!CN) {
4275 if (!BV)
4276 return false;
4277
4278 // Only interested in constant splats, we don't care about undef
4279 // elements in identifying boolean constants and getConstantSplatNode
4280 // returns NULL if all ops are undef;
4281 CN = BV->getConstantSplatNode();
4282 if (!CN)
4283 return false;
4284 }
4285
4286 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
4287 return !CN->getAPIntValue()[0];
4288
4289 return CN->isZero();
4290}
4291
4293 bool SExt) const {
4294 if (VT == MVT::i1)
4295 return N->isOne();
4296
4298 switch (Cnt) {
4300 // An extended value of 1 is always true, unless its original type is i1,
4301 // in which case it will be sign extended to -1.
4302 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
4305 return N->isAllOnes() && SExt;
4306 }
4307 llvm_unreachable("Unexpected enumeration.");
4308}
4309
4310/// This helper function of SimplifySetCC tries to optimize the comparison when
4311/// either operand of the SetCC node is a bitwise-and instruction.
4312SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
4313 ISD::CondCode Cond, const SDLoc &DL,
4314 DAGCombinerInfo &DCI) const {
4315 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
4316 std::swap(N0, N1);
4317
4318 SelectionDAG &DAG = DCI.DAG;
4319 EVT OpVT = N0.getValueType();
4320 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
4321 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4322 return SDValue();
4323
4324 // (X & Y) != 0 --> zextOrTrunc(X & Y)
4325 // iff everything but LSB is known zero:
4326 if (Cond == ISD::SETNE && isNullConstant(N1) &&
4329 unsigned NumEltBits = OpVT.getScalarSizeInBits();
4330 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
4331 if (DAG.MaskedValueIsZero(N0, UpperBits))
4332 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
4333 }
4334
4335 // Try to eliminate a power-of-2 mask constant by converting to a signbit
4336 // test in a narrow type that we can truncate to with no cost. Examples:
4337 // (i32 X & 32768) == 0 --> (trunc X to i16) >= 0
4338 // (i32 X & 32768) != 0 --> (trunc X to i16) < 0
4339 // TODO: This conservatively checks for type legality on the source and
4340 // destination types. That may inhibit optimizations, but it also
4341 // allows setcc->shift transforms that may be more beneficial.
4342 auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4343 if (AndC && isNullConstant(N1) && AndC->getAPIntValue().isPowerOf2() &&
4344 isTypeLegal(OpVT) && N0.hasOneUse()) {
4345 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(),
4346 AndC->getAPIntValue().getActiveBits());
4347 if (isTruncateFree(OpVT, NarrowVT) && isTypeLegal(NarrowVT)) {
4348 SDValue Trunc = DAG.getZExtOrTrunc(N0.getOperand(0), DL, NarrowVT);
4349 SDValue Zero = DAG.getConstant(0, DL, NarrowVT);
4350 return DAG.getSetCC(DL, VT, Trunc, Zero,
4352 }
4353 }
4354
4355 // Match these patterns in any of their permutations:
4356 // (X & Y) == Y
4357 // (X & Y) != Y
4358 SDValue X, Y;
4359 if (N0.getOperand(0) == N1) {
4360 X = N0.getOperand(1);
4361 Y = N0.getOperand(0);
4362 } else if (N0.getOperand(1) == N1) {
4363 X = N0.getOperand(0);
4364 Y = N0.getOperand(1);
4365 } else {
4366 return SDValue();
4367 }
4368
4369 // TODO: We should invert (X & Y) eq/ne 0 -> (X & Y) ne/eq Y if
4370 // `isXAndYEqZeroPreferableToXAndYEqY` is false. This is a bit difficult as
4371 // its liable to create and infinite loop.
4372 SDValue Zero = DAG.getConstant(0, DL, OpVT);
4373 if (isXAndYEqZeroPreferableToXAndYEqY(Cond, OpVT) &&
4375 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
4376 // Note that where Y is variable and is known to have at most one bit set
4377 // (for example, if it is Z & 1) we cannot do this; the expressions are not
4378 // equivalent when Y == 0.
4379 assert(OpVT.isInteger());
4381 if (DCI.isBeforeLegalizeOps() ||
4383 return DAG.getSetCC(DL, VT, N0, Zero, Cond);
4384 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
4385 // If the target supports an 'and-not' or 'and-complement' logic operation,
4386 // try to use that to make a comparison operation more efficient.
4387 // But don't do this transform if the mask is a single bit because there are
4388 // more efficient ways to deal with that case (for example, 'bt' on x86 or
4389 // 'rlwinm' on PPC).
4390
4391 // Bail out if the compare operand that we want to turn into a zero is
4392 // already a zero (otherwise, infinite loop).
4393 if (isNullConstant(Y))
4394 return SDValue();
4395
4396 // Transform this into: ~X & Y == 0.
4397 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
4398 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
4399 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
4400 }
4401
4402 return SDValue();
4403}
4404
4405/// This helper function of SimplifySetCC tries to optimize the comparison when
4406/// either operand of the SetCC node is a bitwise-or instruction.
4407/// For now, this just transforms (X | Y) ==/!= Y into X & ~Y ==/!= 0.
4408SDValue TargetLowering::foldSetCCWithOr(EVT VT, SDValue N0, SDValue N1,
4409 ISD::CondCode Cond, const SDLoc &DL,
4410 DAGCombinerInfo &DCI) const {
4411 if (N1.getOpcode() == ISD::OR && N0.getOpcode() != ISD::OR)
4412 std::swap(N0, N1);
4413
4414 SelectionDAG &DAG = DCI.DAG;
4415 EVT OpVT = N0.getValueType();
4416 if (!N0.hasOneUse() || !OpVT.isInteger() ||
4417 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4418 return SDValue();
4419
4420 // (X | Y) == Y
4421 // (X | Y) != Y
4422 SDValue X;
4423 if (sd_match(N0, m_Or(m_Value(X), m_Specific(N1))) && hasAndNotCompare(X)) {
4424 // If the target supports an 'and-not' or 'and-complement' logic operation,
4425 // try to use that to make a comparison operation more efficient.
4426
4427 // Bail out if the compare operand that we want to turn into a zero is
4428 // already a zero (otherwise, infinite loop).
4429 if (isNullConstant(N1))
4430 return SDValue();
4431
4432 // Transform this into: X & ~Y ==/!= 0.
4433 SDValue NotY = DAG.getNOT(SDLoc(N1), N1, OpVT);
4434 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, X, NotY);
4435 return DAG.getSetCC(DL, VT, NewAnd, DAG.getConstant(0, DL, OpVT), Cond);
4436 }
4437
4438 return SDValue();
4439}
4440
4441/// There are multiple IR patterns that could be checking whether certain
4442/// truncation of a signed number would be lossy or not. The pattern which is
4443/// best at IR level, may not lower optimally. Thus, we want to unfold it.
4444/// We are looking for the following pattern: (KeptBits is a constant)
4445/// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
4446/// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
4447/// KeptBits also can't be 1, that would have been folded to %x dstcond 0
4448/// We will unfold it into the natural trunc+sext pattern:
4449/// ((%x << C) a>> C) dstcond %x
4450/// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x)
4451SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
4452 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
4453 const SDLoc &DL) const {
4454 // We must be comparing with a constant.
4455 ConstantSDNode *C1;
4456 if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
4457 return SDValue();
4458
4459 // N0 should be: add %x, (1 << (KeptBits-1))
4460 if (N0->getOpcode() != ISD::ADD)
4461 return SDValue();
4462
4463 // And we must be 'add'ing a constant.
4464 ConstantSDNode *C01;
4465 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
4466 return SDValue();
4467
4468 SDValue X = N0->getOperand(0);
4469 EVT XVT = X.getValueType();
4470
4471 // Validate constants ...
4472
4473 APInt I1 = C1->getAPIntValue();
4474
4475 ISD::CondCode NewCond;
4476 if (Cond == ISD::CondCode::SETULT) {
4477 NewCond = ISD::CondCode::SETEQ;
4478 } else if (Cond == ISD::CondCode::SETULE) {
4479 NewCond = ISD::CondCode::SETEQ;
4480 // But need to 'canonicalize' the constant.
4481 I1 += 1;
4482 } else if (Cond == ISD::CondCode::SETUGT) {
4483 NewCond = ISD::CondCode::SETNE;
4484 // But need to 'canonicalize' the constant.
4485 I1 += 1;
4486 } else if (Cond == ISD::CondCode::SETUGE) {
4487 NewCond = ISD::CondCode::SETNE;
4488 } else
4489 return SDValue();
4490
4491 APInt I01 = C01->getAPIntValue();
4492
4493 auto checkConstants = [&I1, &I01]() -> bool {
4494 // Both of them must be power-of-two, and the constant from setcc is bigger.
4495 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
4496 };
4497
4498 if (checkConstants()) {
4499 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256
4500 } else {
4501 // What if we invert constants? (and the target predicate)
4502 I1.negate();
4503 I01.negate();
4504 assert(XVT.isInteger());
4505 NewCond = getSetCCInverse(NewCond, XVT);
4506 if (!checkConstants())
4507 return SDValue();
4508 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256
4509 }
4510
4511 // They are power-of-two, so which bit is set?
4512 const unsigned KeptBits = I1.logBase2();
4513 const unsigned KeptBitsMinusOne = I01.logBase2();
4514
4515 // Magic!
4516 if (KeptBits != (KeptBitsMinusOne + 1))
4517 return SDValue();
4518 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
4519
4520 // We don't want to do this in every single case.
4521 SelectionDAG &DAG = DCI.DAG;
4522 if (!shouldTransformSignedTruncationCheck(XVT, KeptBits))
4523 return SDValue();
4524
4525 // Unfold into: sext_inreg(%x) cond %x
4526 // Where 'cond' will be either 'eq' or 'ne'.
4527 SDValue SExtInReg = DAG.getNode(
4529 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), KeptBits)));
4530 return DAG.getSetCC(DL, SCCVT, SExtInReg, X, NewCond);
4531}
4532
4533// (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
4534SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
4535 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
4536 DAGCombinerInfo &DCI, const SDLoc &DL) const {
4538 "Should be a comparison with 0.");
4539 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4540 "Valid only for [in]equality comparisons.");
4541
4542 unsigned NewShiftOpcode;
4543 SDValue X, C, Y;
4544
4545 SelectionDAG &DAG = DCI.DAG;
4546
4547 // Look for '(C l>>/<< Y)'.
4548 auto Match = [&NewShiftOpcode, &X, &C, &Y, &DAG, this](SDValue V) {
4549 // The shift should be one-use.
4550 if (!V.hasOneUse())
4551 return false;
4552 unsigned OldShiftOpcode = V.getOpcode();
4553 switch (OldShiftOpcode) {
4554 case ISD::SHL:
4555 NewShiftOpcode = ISD::SRL;
4556 break;
4557 case ISD::SRL:
4558 NewShiftOpcode = ISD::SHL;
4559 break;
4560 default:
4561 return false; // must be a logical shift.
4562 }
4563 // We should be shifting a constant.
4564 // FIXME: best to use isConstantOrConstantVector().
4565 C = V.getOperand(0);
4566 ConstantSDNode *CC =
4567 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4568 if (!CC)
4569 return false;
4570 Y = V.getOperand(1);
4571
4572 ConstantSDNode *XC =
4573 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4575 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
4576 };
4577
4578 // LHS of comparison should be an one-use 'and'.
4579 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
4580 return SDValue();
4581
4582 X = N0.getOperand(0);
4583 SDValue Mask = N0.getOperand(1);
4584
4585 // 'and' is commutative!
4586 if (!Match(Mask)) {
4587 std::swap(X, Mask);
4588 if (!Match(Mask))
4589 return SDValue();
4590 }
4591
4592 EVT VT = X.getValueType();
4593
4594 // Produce:
4595 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
4596 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
4597 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
4598 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
4599 return T2;
4600}
4601
4602/// Try to fold an equality comparison with a {add/sub/xor} binary operation as
4603/// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
4604/// handle the commuted versions of these patterns.
4605SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
4606 ISD::CondCode Cond, const SDLoc &DL,
4607 DAGCombinerInfo &DCI) const {
4608 unsigned BOpcode = N0.getOpcode();
4609 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
4610 "Unexpected binop");
4611 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
4612
4613 // (X + Y) == X --> Y == 0
4614 // (X - Y) == X --> Y == 0
4615 // (X ^ Y) == X --> Y == 0
4616 SelectionDAG &DAG = DCI.DAG;
4617 EVT OpVT = N0.getValueType();
4618 SDValue X = N0.getOperand(0);
4619 SDValue Y = N0.getOperand(1);
4620 if (X == N1)
4621 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
4622
4623 if (Y != N1)
4624 return SDValue();
4625
4626 // (X + Y) == Y --> X == 0
4627 // (X ^ Y) == Y --> X == 0
4628 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
4629 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
4630
4631 // The shift would not be valid if the operands are boolean (i1).
4632 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
4633 return SDValue();
4634
4635 // (X - Y) == Y --> X == Y << 1
4636 SDValue One = DAG.getShiftAmountConstant(1, OpVT, DL);
4637 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
4638 if (!DCI.isCalledByLegalizer())
4639 DCI.AddToWorklist(YShl1.getNode());
4640 return DAG.getSetCC(DL, VT, X, YShl1, Cond);
4641}
4642
4644 SDValue N0, const APInt &C1,
4645 ISD::CondCode Cond, const SDLoc &dl,
4646 SelectionDAG &DAG) {
4647 // Look through truncs that don't change the value of a ctpop.
4648 // FIXME: Add vector support? Need to be careful with setcc result type below.
4649 SDValue CTPOP = N0;
4650 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
4652 CTPOP = N0.getOperand(0);
4653
4654 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
4655 return SDValue();
4656
4657 EVT CTVT = CTPOP.getValueType();
4658 SDValue CTOp = CTPOP.getOperand(0);
4659
4660 // Expand a power-of-2-or-zero comparison based on ctpop:
4661 // (ctpop x) u< 2 -> (x & x-1) == 0
4662 // (ctpop x) u> 1 -> (x & x-1) != 0
4663 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
4664 // Keep the CTPOP if it is a cheap vector op.
4665 if (CTVT.isVector() && TLI.isCtpopFast(CTVT))
4666 return SDValue();
4667
4668 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
4669 if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
4670 return SDValue();
4671 if (C1 == 0 && (Cond == ISD::SETULT))
4672 return SDValue(); // This is handled elsewhere.
4673
4674 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
4675
4676 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4677 SDValue Result = CTOp;
4678 for (unsigned i = 0; i < Passes; i++) {
4679 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
4680 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
4681 }
4683 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
4684 }
4685
4686 // Expand a power-of-2 comparison based on ctpop
4687 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
4688 // Keep the CTPOP if it is cheap.
4689 if (TLI.isCtpopFast(CTVT))
4690 return SDValue();
4691
4692 SDValue Zero = DAG.getConstant(0, dl, CTVT);
4693 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4694 assert(CTVT.isInteger());
4695 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
4696
4697 // Its not uncommon for known-never-zero X to exist in (ctpop X) eq/ne 1, so
4698 // check before emitting a potentially unnecessary op.
4699 if (DAG.isKnownNeverZero(CTOp)) {
4700 // (ctpop x) == 1 --> (x & x-1) == 0
4701 // (ctpop x) != 1 --> (x & x-1) != 0
4702 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
4703 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
4704 return RHS;
4705 }
4706
4707 // (ctpop x) == 1 --> (x ^ x-1) > x-1
4708 // (ctpop x) != 1 --> (x ^ x-1) <= x-1
4709 SDValue Xor = DAG.getNode(ISD::XOR, dl, CTVT, CTOp, Add);
4711 return DAG.getSetCC(dl, VT, Xor, Add, CmpCond);
4712 }
4713
4714 return SDValue();
4715}
4716
4718 ISD::CondCode Cond, const SDLoc &dl,
4719 SelectionDAG &DAG) {
4720 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4721 return SDValue();
4722
4723 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4724 if (!C1 || !(C1->isZero() || C1->isAllOnes()))
4725 return SDValue();
4726
4727 auto getRotateSource = [](SDValue X) {
4728 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR)
4729 return X.getOperand(0);
4730 return SDValue();
4731 };
4732
4733 // Peek through a rotated value compared against 0 or -1:
4734 // (rot X, Y) == 0/-1 --> X == 0/-1
4735 // (rot X, Y) != 0/-1 --> X != 0/-1
4736 if (SDValue R = getRotateSource(N0))
4737 return DAG.getSetCC(dl, VT, R, N1, Cond);
4738
4739 // Peek through an 'or' of a rotated value compared against 0:
4740 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0
4741 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0
4742 //
4743 // TODO: Add the 'and' with -1 sibling.
4744 // TODO: Recurse through a series of 'or' ops to find the rotate.
4745 EVT OpVT = N0.getValueType();
4746 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) {
4747 if (SDValue R = getRotateSource(N0.getOperand(0))) {
4748 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1));
4749 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4750 }
4751 if (SDValue R = getRotateSource(N0.getOperand(1))) {
4752 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0));
4753 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4754 }
4755 }
4756
4757 return SDValue();
4758}
4759
4761 ISD::CondCode Cond, const SDLoc &dl,
4762 SelectionDAG &DAG) {
4763 // If we are testing for all-bits-clear, we might be able to do that with
4764 // less shifting since bit-order does not matter.
4765 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4766 return SDValue();
4767
4768 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4769 if (!C1 || !C1->isZero())
4770 return SDValue();
4771
4772 if (!N0.hasOneUse() ||
4773 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR))
4774 return SDValue();
4775
4776 unsigned BitWidth = N0.getScalarValueSizeInBits();
4777 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2));
4778 if (!ShAmtC)
4779 return SDValue();
4780
4781 uint64_t ShAmt = ShAmtC->getAPIntValue().urem(BitWidth);
4782 if (ShAmt == 0)
4783 return SDValue();
4784
4785 // Canonicalize fshr as fshl to reduce pattern-matching.
4786 if (N0.getOpcode() == ISD::FSHR)
4787 ShAmt = BitWidth - ShAmt;
4788
4789 // Match an 'or' with a specific operand 'Other' in either commuted variant.
4790 SDValue X, Y;
4791 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) {
4792 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse())
4793 return false;
4794 if (Or.getOperand(0) == Other) {
4795 X = Or.getOperand(0);
4796 Y = Or.getOperand(1);
4797 return true;
4798 }
4799 if (Or.getOperand(1) == Other) {
4800 X = Or.getOperand(1);
4801 Y = Or.getOperand(0);
4802 return true;
4803 }
4804 return false;
4805 };
4806
4807 EVT OpVT = N0.getValueType();
4808 EVT ShAmtVT = N0.getOperand(2).getValueType();
4809 SDValue F0 = N0.getOperand(0);
4810 SDValue F1 = N0.getOperand(1);
4811 if (matchOr(F0, F1)) {
4812 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0
4813 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT);
4814 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt);
4815 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4816 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4817 }
4818 if (matchOr(F1, F0)) {
4819 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0
4820 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT);
4821 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt);
4822 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4823 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4824 }
4825
4826 return SDValue();
4827}
4828
4829/// Try to simplify a setcc built with the specified operands and cc. If it is
4830/// unable to simplify it, return a null SDValue.
4832 ISD::CondCode Cond, bool foldBooleans,
4833 DAGCombinerInfo &DCI,
4834 const SDLoc &dl) const {
4835 SelectionDAG &DAG = DCI.DAG;
4836 const DataLayout &Layout = DAG.getDataLayout();
4837 EVT OpVT = N0.getValueType();
4839
4840 // Constant fold or commute setcc.
4841 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
4842 return Fold;
4843
4844 bool N0ConstOrSplat =
4845 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4846 bool N1ConstOrSplat =
4847 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4848
4849 // Canonicalize toward having the constant on the RHS.
4850 // TODO: Handle non-splat vector constants. All undef causes trouble.
4851 // FIXME: We can't yet fold constant scalable vector splats, so avoid an
4852 // infinite loop here when we encounter one.
4854 if (N0ConstOrSplat && !N1ConstOrSplat &&
4855 (DCI.isBeforeLegalizeOps() ||
4856 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
4857 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4858
4859 // If we have a subtract with the same 2 non-constant operands as this setcc
4860 // -- but in reverse order -- then try to commute the operands of this setcc
4861 // to match. A matching pair of setcc (cmp) and sub may be combined into 1
4862 // instruction on some targets.
4863 if (!N0ConstOrSplat && !N1ConstOrSplat &&
4864 (DCI.isBeforeLegalizeOps() ||
4865 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
4866 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
4867 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
4868 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4869
4870 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG))
4871 return V;
4872
4873 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG))
4874 return V;
4875
4876 if (auto *N1C = isConstOrConstSplat(N1)) {
4877 const APInt &C1 = N1C->getAPIntValue();
4878
4879 // Optimize some CTPOP cases.
4880 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
4881 return V;
4882
4883 // For equality to 0 of a no-wrap multiply, decompose and test each op:
4884 // X * Y == 0 --> (X == 0) || (Y == 0)
4885 // X * Y != 0 --> (X != 0) && (Y != 0)
4886 // TODO: This bails out if minsize is set, but if the target doesn't have a
4887 // single instruction multiply for this type, it would likely be
4888 // smaller to decompose.
4889 if (C1.isZero() && (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4890 N0.getOpcode() == ISD::MUL && N0.hasOneUse() &&
4891 (N0->getFlags().hasNoUnsignedWrap() ||
4892 N0->getFlags().hasNoSignedWrap()) &&
4893 !Attr.hasFnAttr(Attribute::MinSize)) {
4894 SDValue IsXZero = DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
4895 SDValue IsYZero = DAG.getSetCC(dl, VT, N0.getOperand(1), N1, Cond);
4896 unsigned LogicOp = Cond == ISD::SETEQ ? ISD::OR : ISD::AND;
4897 return DAG.getNode(LogicOp, dl, VT, IsXZero, IsYZero);
4898 }
4899
4900 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
4901 // equality comparison, then we're just comparing whether X itself is
4902 // zero.
4903 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
4904 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
4906 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
4907 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4908 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
4909 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
4910 // (srl (ctlz x), 5) == 0 -> X != 0
4911 // (srl (ctlz x), 5) != 1 -> X != 0
4912 Cond = ISD::SETNE;
4913 } else {
4914 // (srl (ctlz x), 5) != 0 -> X == 0
4915 // (srl (ctlz x), 5) == 1 -> X == 0
4916 Cond = ISD::SETEQ;
4917 }
4918 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
4919 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
4920 Cond);
4921 }
4922 }
4923 }
4924 }
4925
4926 // setcc X, 0, setlt --> X (when X is all sign bits)
4927 // setcc X, 0, setne --> X (when X is all sign bits)
4928 //
4929 // When we know that X has 0 or -1 in each element (or scalar), this
4930 // comparison will produce X. This is only true when boolean contents are
4931 // represented via 0s and -1s.
4932 if (VT == OpVT &&
4933 // Check that the result of setcc is 0 and -1.
4935 // Match only for checks X < 0 and X != 0
4936 (Cond == ISD::SETLT || Cond == ISD::SETNE) && isNullOrNullSplat(N1) &&
4937 // The identity holds iff we know all sign bits for all lanes.
4939 return N0;
4940
4941 // FIXME: Support vectors.
4942 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
4943 const APInt &C1 = N1C->getAPIntValue();
4944
4945 // (zext x) == C --> x == (trunc C)
4946 // (sext x) == C --> x == (trunc C)
4947 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4948 DCI.isBeforeLegalize() && N0->hasOneUse()) {
4949 unsigned MinBits = N0.getValueSizeInBits();
4950 SDValue PreExt;
4951 bool Signed = false;
4952 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
4953 // ZExt
4954 MinBits = N0->getOperand(0).getValueSizeInBits();
4955 PreExt = N0->getOperand(0);
4956 } else if (N0->getOpcode() == ISD::AND) {
4957 // DAGCombine turns costly ZExts into ANDs
4958 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
4959 if ((C->getAPIntValue()+1).isPowerOf2()) {
4960 MinBits = C->getAPIntValue().countr_one();
4961 PreExt = N0->getOperand(0);
4962 }
4963 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
4964 // SExt
4965 MinBits = N0->getOperand(0).getValueSizeInBits();
4966 PreExt = N0->getOperand(0);
4967 Signed = true;
4968 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
4969 // ZEXTLOAD / SEXTLOAD
4970 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
4971 MinBits = LN0->getMemoryVT().getSizeInBits();
4972 PreExt = N0;
4973 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
4974 Signed = true;
4975 MinBits = LN0->getMemoryVT().getSizeInBits();
4976 PreExt = N0;
4977 }
4978 }
4979
4980 // Figure out how many bits we need to preserve this constant.
4981 unsigned ReqdBits = Signed ? C1.getSignificantBits() : C1.getActiveBits();
4982
4983 // Make sure we're not losing bits from the constant.
4984 if (MinBits > 0 &&
4985 MinBits < C1.getBitWidth() &&
4986 MinBits >= ReqdBits) {
4987 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
4988 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
4989 // Will get folded away.
4990 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
4991 if (MinBits == 1 && C1 == 1)
4992 // Invert the condition.
4993 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
4995 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
4996 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
4997 }
4998
4999 // If truncating the setcc operands is not desirable, we can still
5000 // simplify the expression in some cases:
5001 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
5002 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
5003 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
5004 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
5005 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
5006 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
5007 SDValue TopSetCC = N0->getOperand(0);
5008 unsigned N0Opc = N0->getOpcode();
5009 bool SExt = (N0Opc == ISD::SIGN_EXTEND);
5010 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
5011 TopSetCC.getOpcode() == ISD::SETCC &&
5012 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
5013 (isConstFalseVal(N1) ||
5014 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
5015
5016 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
5017 (!N1C->isZero() && Cond == ISD::SETNE);
5018
5019 if (!Inverse)
5020 return TopSetCC;
5021
5023 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
5024 TopSetCC.getOperand(0).getValueType());
5025 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
5026 TopSetCC.getOperand(1),
5027 InvCond);
5028 }
5029 }
5030 }
5031
5032 // If the LHS is '(and load, const)', the RHS is 0, the test is for
5033 // equality or unsigned, and all 1 bits of the const are in the same
5034 // partial word, see if we can shorten the load.
5035 if (DCI.isBeforeLegalize() &&
5037 N0.getOpcode() == ISD::AND && C1 == 0 &&
5038 N0.getNode()->hasOneUse() &&
5039 isa<LoadSDNode>(N0.getOperand(0)) &&
5040 N0.getOperand(0).getNode()->hasOneUse() &&
5042 auto *Lod = cast<LoadSDNode>(N0.getOperand(0));
5043 APInt bestMask;
5044 unsigned bestWidth = 0, bestOffset = 0;
5045 if (Lod->isSimple() && Lod->isUnindexed() &&
5046 (Lod->getMemoryVT().isByteSized() ||
5047 isPaddedAtMostSignificantBitsWhenStored(Lod->getMemoryVT()))) {
5048 unsigned memWidth = Lod->getMemoryVT().getStoreSizeInBits();
5049 unsigned origWidth = N0.getValueSizeInBits();
5050 unsigned maskWidth = origWidth;
5051 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
5052 // 8 bits, but have to be careful...
5053 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
5054 origWidth = Lod->getMemoryVT().getSizeInBits();
5055 const APInt &Mask = N0.getConstantOperandAPInt(1);
5056 // Only consider power-of-2 widths (and at least one byte) as candiates
5057 // for the narrowed load.
5058 for (unsigned width = 8; width < origWidth; width *= 2) {
5059 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), width);
5060 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
5061 // Avoid accessing any padding here for now (we could use memWidth
5062 // instead of origWidth here otherwise).
5063 unsigned maxOffset = origWidth - width;
5064 for (unsigned offset = 0; offset <= maxOffset; offset += 8) {
5065 if (Mask.isSubsetOf(newMask)) {
5066 unsigned ptrOffset =
5067 Layout.isLittleEndian() ? offset : memWidth - width - offset;
5068 unsigned IsFast = 0;
5069 assert((ptrOffset % 8) == 0 && "Non-Bytealigned pointer offset");
5070 Align NewAlign = commonAlignment(Lod->getAlign(), ptrOffset / 8);
5072 ptrOffset / 8) &&
5074 *DAG.getContext(), Layout, newVT, Lod->getAddressSpace(),
5075 NewAlign, Lod->getMemOperand()->getFlags(), &IsFast) &&
5076 IsFast) {
5077 bestOffset = ptrOffset / 8;
5078 bestMask = Mask.lshr(offset);
5079 bestWidth = width;
5080 break;
5081 }
5082 }
5083 newMask <<= 8;
5084 }
5085 if (bestWidth)
5086 break;
5087 }
5088 }
5089 if (bestWidth) {
5090 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
5091 SDValue Ptr = Lod->getBasePtr();
5092 if (bestOffset != 0)
5093 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(bestOffset));
5094 SDValue NewLoad =
5095 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
5096 Lod->getPointerInfo().getWithOffset(bestOffset),
5097 Lod->getBaseAlign());
5098 SDValue And =
5099 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
5100 DAG.getConstant(bestMask.trunc(bestWidth), dl, newVT));
5101 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0LL, dl, newVT), Cond);
5102 }
5103 }
5104
5105 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
5106 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
5107 unsigned InSize = N0.getOperand(0).getValueSizeInBits();
5108
5109 // If the comparison constant has bits in the upper part, the
5110 // zero-extended value could never match.
5112 C1.getBitWidth() - InSize))) {
5113 switch (Cond) {
5114 case ISD::SETUGT:
5115 case ISD::SETUGE:
5116 case ISD::SETEQ:
5117 return DAG.getConstant(0, dl, VT);
5118 case ISD::SETULT:
5119 case ISD::SETULE:
5120 case ISD::SETNE:
5121 return DAG.getConstant(1, dl, VT);
5122 case ISD::SETGT:
5123 case ISD::SETGE:
5124 // True if the sign bit of C1 is set.
5125 return DAG.getConstant(C1.isNegative(), dl, VT);
5126 case ISD::SETLT:
5127 case ISD::SETLE:
5128 // True if the sign bit of C1 isn't set.
5129 return DAG.getConstant(C1.isNonNegative(), dl, VT);
5130 default:
5131 break;
5132 }
5133 }
5134
5135 // Otherwise, we can perform the comparison with the low bits.
5136 switch (Cond) {
5137 case ISD::SETEQ:
5138 case ISD::SETNE:
5139 case ISD::SETUGT:
5140 case ISD::SETUGE:
5141 case ISD::SETULT:
5142 case ISD::SETULE: {
5143 EVT newVT = N0.getOperand(0).getValueType();
5144 // FIXME: Should use isNarrowingProfitable.
5145 if (DCI.isBeforeLegalizeOps() ||
5146 (isOperationLegal(ISD::SETCC, newVT) &&
5147 isCondCodeLegal(Cond, newVT.getSimpleVT()) &&
5149 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
5150 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
5151
5152 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
5153 NewConst, Cond);
5154 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
5155 }
5156 break;
5157 }
5158 default:
5159 break; // todo, be more careful with signed comparisons
5160 }
5161 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5162 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5164 OpVT)) {
5165 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
5166 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
5167 EVT ExtDstTy = N0.getValueType();
5168 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
5169
5170 // If the constant doesn't fit into the number of bits for the source of
5171 // the sign extension, it is impossible for both sides to be equal.
5172 if (C1.getSignificantBits() > ExtSrcTyBits)
5173 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
5174
5175 assert(ExtDstTy == N0.getOperand(0).getValueType() &&
5176 ExtDstTy != ExtSrcTy && "Unexpected types!");
5177 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
5178 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
5179 DAG.getConstant(Imm, dl, ExtDstTy));
5180 if (!DCI.isCalledByLegalizer())
5181 DCI.AddToWorklist(ZextOp.getNode());
5182 // Otherwise, make this a use of a zext.
5183 return DAG.getSetCC(dl, VT, ZextOp,
5184 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
5185 } else if ((N1C->isZero() || N1C->isOne()) &&
5186 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5187 // SETCC (X), [0|1], [EQ|NE] -> X if X is known 0/1. i1 types are
5188 // excluded as they are handled below whilst checking for foldBooleans.
5189 if ((N0.getOpcode() == ISD::SETCC || VT.getScalarType() != MVT::i1) &&
5190 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
5191 (N0.getValueType() == MVT::i1 ||
5195 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
5196 if (TrueWhenTrue)
5197 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
5198 // Invert the condition.
5199 if (N0.getOpcode() == ISD::SETCC) {
5202 if (DCI.isBeforeLegalizeOps() ||
5204 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
5205 }
5206 }
5207
5208 if ((N0.getOpcode() == ISD::XOR ||
5209 (N0.getOpcode() == ISD::AND &&
5210 N0.getOperand(0).getOpcode() == ISD::XOR &&
5211 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
5212 isOneConstant(N0.getOperand(1))) {
5213 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
5214 // can only do this if the top bits are known zero.
5215 unsigned BitWidth = N0.getValueSizeInBits();
5216 if (DAG.MaskedValueIsZero(N0,
5218 BitWidth-1))) {
5219 // Okay, get the un-inverted input value.
5220 SDValue Val;
5221 if (N0.getOpcode() == ISD::XOR) {
5222 Val = N0.getOperand(0);
5223 } else {
5224 assert(N0.getOpcode() == ISD::AND &&
5225 N0.getOperand(0).getOpcode() == ISD::XOR);
5226 // ((X^1)&1)^1 -> X & 1
5227 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
5228 N0.getOperand(0).getOperand(0),
5229 N0.getOperand(1));
5230 }
5231
5232 return DAG.getSetCC(dl, VT, Val, N1,
5234 }
5235 } else if (N1C->isOne()) {
5236 SDValue Op0 = N0;
5237 if (Op0.getOpcode() == ISD::TRUNCATE)
5238 Op0 = Op0.getOperand(0);
5239
5240 if ((Op0.getOpcode() == ISD::XOR) &&
5241 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
5242 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
5243 SDValue XorLHS = Op0.getOperand(0);
5244 SDValue XorRHS = Op0.getOperand(1);
5245 // Ensure that the input setccs return an i1 type or 0/1 value.
5246 if (Op0.getValueType() == MVT::i1 ||
5251 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
5253 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
5254 }
5255 }
5256 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
5257 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
5258 if (Op0.getValueType().bitsGT(VT))
5259 Op0 = DAG.getNode(ISD::AND, dl, VT,
5260 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
5261 DAG.getConstant(1, dl, VT));
5262 else if (Op0.getValueType().bitsLT(VT))
5263 Op0 = DAG.getNode(ISD::AND, dl, VT,
5264 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
5265 DAG.getConstant(1, dl, VT));
5266
5267 return DAG.getSetCC(dl, VT, Op0,
5268 DAG.getConstant(0, dl, Op0.getValueType()),
5270 }
5271 if (Op0.getOpcode() == ISD::AssertZext &&
5272 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
5273 return DAG.getSetCC(dl, VT, Op0,
5274 DAG.getConstant(0, dl, Op0.getValueType()),
5276 }
5277 }
5278
5279 // Given:
5280 // icmp eq/ne (urem %x, %y), 0
5281 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
5282 // icmp eq/ne %x, 0
5283 if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
5284 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5285 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
5286 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
5287 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
5288 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
5289 }
5290
5291 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
5292 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
5293 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5295 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
5296 N1C->isAllOnes()) {
5297 return DAG.getSetCC(dl, VT, N0.getOperand(0),
5298 DAG.getConstant(0, dl, OpVT),
5300 }
5301
5302 // fold (setcc (trunc x) c) -> (setcc x c)
5303 if (N0.getOpcode() == ISD::TRUNCATE &&
5305 (N0->getFlags().hasNoSignedWrap() &&
5308 EVT NewVT = N0.getOperand(0).getValueType();
5309 SDValue NewConst = DAG.getConstant(
5311 ? C1.sext(NewVT.getSizeInBits())
5312 : C1.zext(NewVT.getSizeInBits()),
5313 dl, NewVT);
5314 return DAG.getSetCC(dl, VT, N0.getOperand(0), NewConst, Cond);
5315 }
5316
5317 if (SDValue V =
5318 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
5319 return V;
5320 }
5321
5322 // These simplifications apply to splat vectors as well.
5323 // TODO: Handle more splat vector cases.
5324 if (auto *N1C = isConstOrConstSplat(N1)) {
5325 const APInt &C1 = N1C->getAPIntValue();
5326
5327 APInt MinVal, MaxVal;
5328 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
5330 MinVal = APInt::getSignedMinValue(OperandBitSize);
5331 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
5332 } else {
5333 MinVal = APInt::getMinValue(OperandBitSize);
5334 MaxVal = APInt::getMaxValue(OperandBitSize);
5335 }
5336
5337 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
5338 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
5339 // X >= MIN --> true
5340 if (C1 == MinVal)
5341 return DAG.getBoolConstant(true, dl, VT, OpVT);
5342
5343 if (!VT.isVector()) { // TODO: Support this for vectors.
5344 // X >= C0 --> X > (C0 - 1)
5345 APInt C = C1 - 1;
5347 if ((DCI.isBeforeLegalizeOps() ||
5348 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5349 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5350 isLegalICmpImmediate(C.getSExtValue())))) {
5351 return DAG.getSetCC(dl, VT, N0,
5352 DAG.getConstant(C, dl, N1.getValueType()),
5353 NewCC);
5354 }
5355 }
5356 }
5357
5358 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
5359 // X <= MAX --> true
5360 if (C1 == MaxVal)
5361 return DAG.getBoolConstant(true, dl, VT, OpVT);
5362
5363 // X <= C0 --> X < (C0 + 1)
5364 if (!VT.isVector()) { // TODO: Support this for vectors.
5365 APInt C = C1 + 1;
5367 if ((DCI.isBeforeLegalizeOps() ||
5368 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5369 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5370 isLegalICmpImmediate(C.getSExtValue())))) {
5371 return DAG.getSetCC(dl, VT, N0,
5372 DAG.getConstant(C, dl, N1.getValueType()),
5373 NewCC);
5374 }
5375 }
5376 }
5377
5378 if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
5379 if (C1 == MinVal)
5380 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
5381
5382 // TODO: Support this for vectors after legalize ops.
5383 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5384 // Canonicalize setlt X, Max --> setne X, Max
5385 if (C1 == MaxVal)
5386 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5387
5388 // If we have setult X, 1, turn it into seteq X, 0
5389 if (C1 == MinVal+1)
5390 return DAG.getSetCC(dl, VT, N0,
5391 DAG.getConstant(MinVal, dl, N0.getValueType()),
5392 ISD::SETEQ);
5393 }
5394 }
5395
5396 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
5397 if (C1 == MaxVal)
5398 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
5399
5400 // TODO: Support this for vectors after legalize ops.
5401 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5402 // Canonicalize setgt X, Min --> setne X, Min
5403 if (C1 == MinVal)
5404 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5405
5406 // If we have setugt X, Max-1, turn it into seteq X, Max
5407 if (C1 == MaxVal-1)
5408 return DAG.getSetCC(dl, VT, N0,
5409 DAG.getConstant(MaxVal, dl, N0.getValueType()),
5410 ISD::SETEQ);
5411 }
5412 }
5413
5414 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
5415 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
5416 if (C1.isZero())
5417 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
5418 VT, N0, N1, Cond, DCI, dl))
5419 return CC;
5420
5421 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
5422 // For example, when high 32-bits of i64 X are known clear:
5423 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0
5424 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1
5425 bool CmpZero = N1C->isZero();
5426 bool CmpNegOne = N1C->isAllOnes();
5427 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
5428 // Match or(lo,shl(hi,bw/2)) pattern.
5429 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
5430 unsigned EltBits = V.getScalarValueSizeInBits();
5431 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
5432 return false;
5433 SDValue LHS = V.getOperand(0);
5434 SDValue RHS = V.getOperand(1);
5435 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
5436 // Unshifted element must have zero upperbits.
5437 if (RHS.getOpcode() == ISD::SHL &&
5438 isa<ConstantSDNode>(RHS.getOperand(1)) &&
5439 RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5440 DAG.MaskedValueIsZero(LHS, HiBits)) {
5441 Lo = LHS;
5442 Hi = RHS.getOperand(0);
5443 return true;
5444 }
5445 if (LHS.getOpcode() == ISD::SHL &&
5446 isa<ConstantSDNode>(LHS.getOperand(1)) &&
5447 LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5448 DAG.MaskedValueIsZero(RHS, HiBits)) {
5449 Lo = RHS;
5450 Hi = LHS.getOperand(0);
5451 return true;
5452 }
5453 return false;
5454 };
5455
5456 auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
5457 unsigned EltBits = N0.getScalarValueSizeInBits();
5458 unsigned HalfBits = EltBits / 2;
5459 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
5460 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
5461 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
5462 SDValue NewN0 =
5463 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
5464 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
5465 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
5466 };
5467
5468 SDValue Lo, Hi;
5469 if (IsConcat(N0, Lo, Hi))
5470 return MergeConcat(Lo, Hi);
5471
5472 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
5473 SDValue Lo0, Lo1, Hi0, Hi1;
5474 if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
5475 IsConcat(N0.getOperand(1), Lo1, Hi1)) {
5476 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
5477 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
5478 }
5479 }
5480 }
5481 }
5482
5483 // If we have "setcc X, C0", check to see if we can shrink the immediate
5484 // by changing cc.
5485 // TODO: Support this for vectors after legalize ops.
5486 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5487 // SETUGT X, SINTMAX -> SETLT X, 0
5488 // SETUGE X, SINTMIN -> SETLT X, 0
5489 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
5490 (Cond == ISD::SETUGE && C1.isMinSignedValue()))
5491 return DAG.getSetCC(dl, VT, N0,
5492 DAG.getConstant(0, dl, N1.getValueType()),
5493 ISD::SETLT);
5494
5495 // SETULT X, SINTMIN -> SETGT X, -1
5496 // SETULE X, SINTMAX -> SETGT X, -1
5497 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
5498 (Cond == ISD::SETULE && C1.isMaxSignedValue()))
5499 return DAG.getSetCC(dl, VT, N0,
5500 DAG.getAllOnesConstant(dl, N1.getValueType()),
5501 ISD::SETGT);
5502 }
5503 }
5504
5505 // Back to non-vector simplifications.
5506 // TODO: Can we do these for vector splats?
5507 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5508 const APInt &C1 = N1C->getAPIntValue();
5509 EVT ShValTy = N0.getValueType();
5510
5511 // Fold bit comparisons when we can. This will result in an
5512 // incorrect value when boolean false is negative one, unless
5513 // the bitsize is 1 in which case the false value is the same
5514 // in practice regardless of the representation.
5515 if ((VT.getSizeInBits() == 1 ||
5517 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5518 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
5519 N0.getOpcode() == ISD::AND) {
5520 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5521 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
5522 // Perform the xform if the AND RHS is a single bit.
5523 unsigned ShCt = AndRHS->getAPIntValue().logBase2();
5524 if (AndRHS->getAPIntValue().isPowerOf2() &&
5525 !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5526 return DAG.getNode(
5527 ISD::TRUNCATE, dl, VT,
5528 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5529 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5530 }
5531 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
5532 // (X & 8) == 8 --> (X & 8) >> 3
5533 // Perform the xform if C1 is a single bit.
5534 unsigned ShCt = C1.logBase2();
5535 if (C1.isPowerOf2() && !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5536 return DAG.getNode(
5537 ISD::TRUNCATE, dl, VT,
5538 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5539 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5540 }
5541 }
5542 }
5543 }
5544
5545 if (C1.getSignificantBits() <= 64 &&
5547 // (X & -256) == 256 -> (X >> 8) == 1
5548 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5549 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
5550 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5551 const APInt &AndRHSC = AndRHS->getAPIntValue();
5552 if (AndRHSC.isNegatedPowerOf2() && C1.isSubsetOf(AndRHSC)) {
5553 unsigned ShiftBits = AndRHSC.countr_zero();
5554 if (!shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5555 // If using an unsigned shift doesn't yield a legal compare
5556 // immediate, try using sra instead.
5557 APInt NewC = C1.lshr(ShiftBits);
5558 if (NewC.getSignificantBits() <= 64 &&
5560 APInt SignedC = C1.ashr(ShiftBits);
5561 if (SignedC.getSignificantBits() <= 64 &&
5563 SDValue Shift = DAG.getNode(
5564 ISD::SRA, dl, ShValTy, N0.getOperand(0),
5565 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5566 SDValue CmpRHS = DAG.getConstant(SignedC, dl, ShValTy);
5567 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5568 }
5569 }
5570 SDValue Shift = DAG.getNode(
5571 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5572 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5573 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5574 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5575 }
5576 }
5577 }
5578 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
5579 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
5580 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
5581 // X < 0x100000000 -> (X >> 32) < 1
5582 // X >= 0x100000000 -> (X >> 32) >= 1
5583 // X <= 0x0ffffffff -> (X >> 32) < 1
5584 // X > 0x0ffffffff -> (X >> 32) >= 1
5585 unsigned ShiftBits;
5586 APInt NewC = C1;
5587 ISD::CondCode NewCond = Cond;
5588 if (AdjOne) {
5589 ShiftBits = C1.countr_one();
5590 NewC = NewC + 1;
5591 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
5592 } else {
5593 ShiftBits = C1.countr_zero();
5594 }
5595 APInt RangeWidth = NewC;
5596 NewC.lshrInPlace(ShiftBits);
5597 if (ShiftBits && NewC.getSignificantBits() <= 64 &&
5599 !shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5600 // If this is an offset range check, try to move the offset after the
5601 // shift to avoid preserving the pre-shift add with a mask.
5602 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse()) {
5603 if (auto *AddC = isConstOrConstSplat(N0.getOperand(1))) {
5604 const APInt &AddVal = AddC->getAPIntValue();
5605 if (AddVal.countr_zero() >= ShiftBits) {
5606 APInt RangeLower = -AddVal;
5607 bool Overflow;
5608 (void)RangeLower.uadd_ov(RangeWidth, Overflow);
5609 if (!RangeWidth.isZero() && !Overflow) {
5610 SDValue Shift = DAG.getNode(
5611 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5612 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5613 APInt Offset = -RangeLower.lshr(ShiftBits);
5614 SDValue ShiftedAdd =
5615 DAG.getNode(ISD::ADD, dl, ShValTy, Shift,
5616 DAG.getConstant(Offset, dl, ShValTy));
5617 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5618 return DAG.getSetCC(dl, VT, ShiftedAdd, CmpRHS, NewCond);
5619 }
5620 }
5621 }
5622 }
5623 SDValue Shift =
5624 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5625 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5626 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5627 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
5628 }
5629 }
5630 }
5631 }
5632
5634 auto *CFP = cast<ConstantFPSDNode>(N1);
5635 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
5636
5637 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
5638 // constant if knowing that the operand is non-nan is enough. We prefer to
5639 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
5640 // materialize 0.0.
5641 if (Cond == ISD::SETO || Cond == ISD::SETUO)
5642 return DAG.getSetCC(dl, VT, N0, N0, Cond);
5643
5644 // setcc (fneg x), C -> setcc swap(pred) x, -C
5645 if (N0.getOpcode() == ISD::FNEG) {
5647 if (DCI.isBeforeLegalizeOps() ||
5648 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
5649 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
5650 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
5651 }
5652 }
5653
5654 // setueq/setoeq X, (fabs Inf) -> is_fpclass X, fcInf
5656 !isFPImmLegal(CFP->getValueAPF(), CFP->getValueType(0))) {
5657 bool IsFabs = N0.getOpcode() == ISD::FABS;
5658 SDValue Op = IsFabs ? N0.getOperand(0) : N0;
5659 if ((Cond == ISD::SETOEQ || Cond == ISD::SETUEQ) && CFP->isInfinity()) {
5660 FPClassTest Flag = CFP->isNegative() ? (IsFabs ? fcNone : fcNegInf)
5661 : (IsFabs ? fcInf : fcPosInf);
5662 if (Cond == ISD::SETUEQ)
5663 Flag |= fcNan;
5664 return DAG.getNode(ISD::IS_FPCLASS, dl, VT, Op,
5665 DAG.getTargetConstant(Flag, dl, MVT::i32));
5666 }
5667 }
5668
5669 // If the condition is not legal, see if we can find an equivalent one
5670 // which is legal.
5672 // If the comparison was an awkward floating-point == or != and one of
5673 // the comparison operands is infinity or negative infinity, convert the
5674 // condition to a less-awkward <= or >=.
5675 if (CFP->getValueAPF().isInfinity()) {
5676 bool IsNegInf = CFP->getValueAPF().isNegative();
5678 switch (Cond) {
5679 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
5680 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
5681 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
5682 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
5683 default: break;
5684 }
5685 if (NewCond != ISD::SETCC_INVALID &&
5686 isCondCodeLegal(NewCond, N0.getSimpleValueType()))
5687 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5688 }
5689 }
5690 }
5691
5692 if (N0 == N1) {
5693 // The sext(setcc()) => setcc() optimization relies on the appropriate
5694 // constant being emitted.
5695 assert(!N0.getValueType().isInteger() &&
5696 "Integer types should be handled by FoldSetCC");
5697
5698 bool EqTrue = ISD::isTrueWhenEqual(Cond);
5699 unsigned UOF = ISD::getUnorderedFlavor(Cond);
5700 if (UOF == 2) // FP operators that are undefined on NaNs.
5701 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5702 if (UOF == unsigned(EqTrue))
5703 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5704 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
5705 // if it is not already.
5706 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
5707 if (NewCond != Cond &&
5708 (DCI.isBeforeLegalizeOps() ||
5709 isCondCodeLegal(NewCond, N0.getSimpleValueType())))
5710 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5711 }
5712
5713 // ~X > ~Y --> Y > X
5714 // ~X < ~Y --> Y < X
5715 // ~X < C --> X > ~C
5716 // ~X > C --> X < ~C
5717 if ((isSignedIntSetCC(Cond) || isUnsignedIntSetCC(Cond)) &&
5718 N0.getValueType().isInteger()) {
5719 if (isBitwiseNot(N0)) {
5720 if (isBitwiseNot(N1))
5721 return DAG.getSetCC(dl, VT, N1.getOperand(0), N0.getOperand(0), Cond);
5722
5725 SDValue Not = DAG.getNOT(dl, N1, OpVT);
5726 return DAG.getSetCC(dl, VT, Not, N0.getOperand(0), Cond);
5727 }
5728 }
5729 }
5730
5731 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5732 N0.getValueType().isInteger()) {
5733 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
5734 N0.getOpcode() == ISD::XOR) {
5735 // Simplify (X+Y) == (X+Z) --> Y == Z
5736 if (N0.getOpcode() == N1.getOpcode()) {
5737 if (N0.getOperand(0) == N1.getOperand(0))
5738 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
5739 if (N0.getOperand(1) == N1.getOperand(1))
5740 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
5741 if (isCommutativeBinOp(N0.getOpcode())) {
5742 // If X op Y == Y op X, try other combinations.
5743 if (N0.getOperand(0) == N1.getOperand(1))
5744 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
5745 Cond);
5746 if (N0.getOperand(1) == N1.getOperand(0))
5747 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
5748 Cond);
5749 }
5750 }
5751
5752 // If RHS is a legal immediate value for a compare instruction, we need
5753 // to be careful about increasing register pressure needlessly.
5754 bool LegalRHSImm = false;
5755
5756 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
5757 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5758 // Turn (X+C1) == C2 --> X == C2-C1
5759 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse())
5760 return DAG.getSetCC(
5761 dl, VT, N0.getOperand(0),
5762 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(),
5763 dl, N0.getValueType()),
5764 Cond);
5765
5766 // Turn (X^C1) == C2 --> X == C1^C2
5767 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse())
5768 return DAG.getSetCC(
5769 dl, VT, N0.getOperand(0),
5770 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(),
5771 dl, N0.getValueType()),
5772 Cond);
5773 }
5774
5775 // Turn (C1-X) == C2 --> X == C1-C2
5776 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
5777 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse())
5778 return DAG.getSetCC(
5779 dl, VT, N0.getOperand(1),
5780 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(),
5781 dl, N0.getValueType()),
5782 Cond);
5783
5784 // Could RHSC fold directly into a compare?
5785 if (RHSC->getValueType(0).getSizeInBits() <= 64)
5786 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
5787 }
5788
5789 // (X+Y) == X --> Y == 0 and similar folds.
5790 // Don't do this if X is an immediate that can fold into a cmp
5791 // instruction and X+Y has other uses. It could be an induction variable
5792 // chain, and the transform would increase register pressure.
5793 if (!LegalRHSImm || N0.hasOneUse())
5794 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
5795 return V;
5796 }
5797
5798 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
5799 N1.getOpcode() == ISD::XOR)
5800 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
5801 return V;
5802
5803 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
5804 return V;
5805
5806 if (SDValue V = foldSetCCWithOr(VT, N0, N1, Cond, dl, DCI))
5807 return V;
5808 }
5809
5810 // Fold remainder of division by a constant.
5811 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
5812 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5813 // When division is cheap or optimizing for minimum size,
5814 // fall through to DIVREM creation by skipping this fold.
5815 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
5816 if (N0.getOpcode() == ISD::UREM) {
5817 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
5818 return Folded;
5819 } else if (N0.getOpcode() == ISD::SREM) {
5820 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
5821 return Folded;
5822 }
5823 }
5824 }
5825
5826 // Fold away ALL boolean setcc's.
5827 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
5828 SDValue Temp;
5829 switch (Cond) {
5830 default: llvm_unreachable("Unknown integer setcc!");
5831 case ISD::SETEQ: // X == Y -> ~(X^Y)
5832 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
5833 N0 = DAG.getNOT(dl, Temp, OpVT);
5834 if (!DCI.isCalledByLegalizer())
5835 DCI.AddToWorklist(Temp.getNode());
5836 break;
5837 case ISD::SETNE: // X != Y --> (X^Y)
5838 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
5839 break;
5840 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
5841 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
5842 Temp = DAG.getNOT(dl, N0, OpVT);
5843 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
5844 if (!DCI.isCalledByLegalizer())
5845 DCI.AddToWorklist(Temp.getNode());
5846 break;
5847 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
5848 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
5849 Temp = DAG.getNOT(dl, N1, OpVT);
5850 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
5851 if (!DCI.isCalledByLegalizer())
5852 DCI.AddToWorklist(Temp.getNode());
5853 break;
5854 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
5855 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
5856 Temp = DAG.getNOT(dl, N0, OpVT);
5857 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
5858 if (!DCI.isCalledByLegalizer())
5859 DCI.AddToWorklist(Temp.getNode());
5860 break;
5861 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
5862 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
5863 Temp = DAG.getNOT(dl, N1, OpVT);
5864 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
5865 break;
5866 }
5867 if (VT.getScalarType() != MVT::i1) {
5868 if (!DCI.isCalledByLegalizer())
5869 DCI.AddToWorklist(N0.getNode());
5870 // FIXME: If running after legalize, we probably can't do this.
5872 N0 = DAG.getNode(ExtendCode, dl, VT, N0);
5873 }
5874 return N0;
5875 }
5876
5877 // Fold (setcc (trunc x) (trunc y)) -> (setcc x y)
5878 if (N0.getOpcode() == ISD::TRUNCATE && N1.getOpcode() == ISD::TRUNCATE &&
5879 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
5881 N1->getFlags().hasNoUnsignedWrap()) ||
5883 N1->getFlags().hasNoSignedWrap())) &&
5885 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
5886 }
5887
5888 // Fold (setcc (sub nsw a, b), zero, s??) -> (setcc a, b, s??)
5889 // TODO: Remove that .isVector() check
5890 if (VT.isVector() && isZeroOrZeroSplat(N1) && N0.getOpcode() == ISD::SUB &&
5892 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), Cond);
5893 }
5894
5895 // Could not fold it.
5896 return SDValue();
5897}
5898
5899/// Returns true (and the GlobalValue and the offset) if the node is a
5900/// GlobalAddress + offset.
5902 int64_t &Offset) const {
5903
5904 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
5905
5906 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
5907 GA = GASD->getGlobal();
5908 Offset += GASD->getOffset();
5909 return true;
5910 }
5911
5912 if (N->isAnyAdd()) {
5913 SDValue N1 = N->getOperand(0);
5914 SDValue N2 = N->getOperand(1);
5915 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
5916 if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
5917 Offset += V->getSExtValue();
5918 return true;
5919 }
5920 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
5921 if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
5922 Offset += V->getSExtValue();
5923 return true;
5924 }
5925 }
5926 }
5927
5928 return false;
5929}
5930
5932 DAGCombinerInfo &DCI) const {
5933 // Default implementation: no optimization.
5934 return SDValue();
5935}
5936
5937//===----------------------------------------------------------------------===//
5938// Inline Assembler Implementation Methods
5939//===----------------------------------------------------------------------===//
5940
5943 unsigned S = Constraint.size();
5944
5945 if (S == 1) {
5946 switch (Constraint[0]) {
5947 default: break;
5948 case 'r':
5949 return C_RegisterClass;
5950 case 'm': // memory
5951 case 'o': // offsetable
5952 case 'V': // not offsetable
5953 return C_Memory;
5954 case 'p': // Address.
5955 return C_Address;
5956 case 'n': // Simple Integer
5957 case 'E': // Floating Point Constant
5958 case 'F': // Floating Point Constant
5959 return C_Immediate;
5960 case 'i': // Simple Integer or Relocatable Constant
5961 case 's': // Relocatable Constant
5962 case 'X': // Allow ANY value.
5963 case 'I': // Target registers.
5964 case 'J':
5965 case 'K':
5966 case 'L':
5967 case 'M':
5968 case 'N':
5969 case 'O':
5970 case 'P':
5971 case '<':
5972 case '>':
5973 return C_Other;
5974 }
5975 }
5976
5977 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
5978 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
5979 return C_Memory;
5980 return C_Register;
5981 }
5982 return C_Unknown;
5983}
5984
5985/// Try to replace an X constraint, which matches anything, with another that
5986/// has more specific requirements based on the type of the corresponding
5987/// operand.
5988const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5989 if (ConstraintVT.isInteger())
5990 return "r";
5991 if (ConstraintVT.isFloatingPoint())
5992 return "f"; // works for many targets
5993 return nullptr;
5994}
5995
5997 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
5998 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
5999 return SDValue();
6000}
6001
6002/// Lower the specified operand into the Ops vector.
6003/// If it is invalid, don't add anything to Ops.
6005 StringRef Constraint,
6006 std::vector<SDValue> &Ops,
6007 SelectionDAG &DAG) const {
6008
6009 if (Constraint.size() > 1)
6010 return;
6011
6012 char ConstraintLetter = Constraint[0];
6013 switch (ConstraintLetter) {
6014 default: break;
6015 case 'X': // Allows any operand
6016 case 'i': // Simple Integer or Relocatable Constant
6017 case 'n': // Simple Integer
6018 case 's': { // Relocatable Constant
6019
6021 uint64_t Offset = 0;
6022
6023 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
6024 // etc., since getelementpointer is variadic. We can't use
6025 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
6026 // while in this case the GA may be furthest from the root node which is
6027 // likely an ISD::ADD.
6028 while (true) {
6029 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
6030 // gcc prints these as sign extended. Sign extend value to 64 bits
6031 // now; without this it would get ZExt'd later in
6032 // ScheduleDAGSDNodes::EmitNode, which is very generic.
6033 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
6034 BooleanContent BCont = getBooleanContents(MVT::i64);
6035 ISD::NodeType ExtOpc =
6036 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
6037 int64_t ExtVal =
6038 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
6039 Ops.push_back(
6040 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
6041 return;
6042 }
6043 if (ConstraintLetter != 'n') {
6044 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6045 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6046 GA->getValueType(0),
6047 Offset + GA->getOffset()));
6048 return;
6049 }
6050 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
6051 Ops.push_back(DAG.getTargetBlockAddress(
6052 BA->getBlockAddress(), BA->getValueType(0),
6053 Offset + BA->getOffset(), BA->getTargetFlags()));
6054 return;
6055 }
6057 Ops.push_back(Op);
6058 return;
6059 }
6060 }
6061 const unsigned OpCode = Op.getOpcode();
6062 if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
6063 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
6064 Op = Op.getOperand(1);
6065 // Subtraction is not commutative.
6066 else if (OpCode == ISD::ADD &&
6067 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
6068 Op = Op.getOperand(0);
6069 else
6070 return;
6071 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
6072 continue;
6073 }
6074 return;
6075 }
6076 break;
6077 }
6078 }
6079}
6080
6084
6085std::pair<unsigned, const TargetRegisterClass *>
6087 StringRef Constraint,
6088 MVT VT) const {
6089 if (!Constraint.starts_with("{"))
6090 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
6091 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
6092
6093 // Remove the braces from around the name.
6094 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
6095
6096 std::pair<unsigned, const TargetRegisterClass *> R =
6097 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
6098
6099 // Figure out which register class contains this reg.
6100 for (const TargetRegisterClass &RC : RI->regclasses()) {
6101 // If none of the value types for this register class are valid, we
6102 // can't use it. For example, 64-bit reg classes on 32-bit targets.
6103 if (!isLegalRC(*RI, RC))
6104 continue;
6105
6106 for (const MCPhysReg &PR : RC) {
6107 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
6108 std::pair<unsigned, const TargetRegisterClass *> S =
6109 std::make_pair(PR, &RC);
6110
6111 // If this register class has the requested value type, return it,
6112 // otherwise keep searching and return the first class found
6113 // if no other is found which explicitly has the requested type.
6114 if (RI->isTypeLegalForClass(RC, VT))
6115 return S;
6116 if (!R.second)
6117 R = S;
6118 }
6119 }
6120 }
6121
6122 return R;
6123}
6124
6125//===----------------------------------------------------------------------===//
6126// Constraint Selection.
6127
6128/// Return true of this is an input operand that is a matching constraint like
6129/// "4".
6131 assert(!ConstraintCode.empty() && "No known constraint!");
6132 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
6133}
6134
6135/// If this is an input matching constraint, this method returns the output
6136/// operand it matches.
6138 assert(!ConstraintCode.empty() && "No known constraint!");
6139 return atoi(ConstraintCode.c_str());
6140}
6141
6142/// Split up the constraint string from the inline assembly value into the
6143/// specific constraints and their prefixes, and also tie in the associated
6144/// operand values.
6145/// If this returns an empty vector, and if the constraint string itself
6146/// isn't empty, there was an error parsing.
6149 const TargetRegisterInfo *TRI,
6150 const CallBase &Call) const {
6151 /// Information about all of the constraints.
6152 AsmOperandInfoVector ConstraintOperands;
6153 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
6154 unsigned maCount = 0; // Largest number of multiple alternative constraints.
6155
6156 // Do a prepass over the constraints, canonicalizing them, and building up the
6157 // ConstraintOperands list.
6158 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6159 unsigned ResNo = 0; // ResNo - The result number of the next output.
6160 unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number.
6161
6162 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
6163 ConstraintOperands.emplace_back(std::move(CI));
6164 AsmOperandInfo &OpInfo = ConstraintOperands.back();
6165
6166 // Update multiple alternative constraint count.
6167 if (OpInfo.multipleAlternatives.size() > maCount)
6168 maCount = OpInfo.multipleAlternatives.size();
6169
6170 OpInfo.ConstraintVT = MVT::Other;
6171
6172 // Compute the value type for each operand.
6173 switch (OpInfo.Type) {
6174 case InlineAsm::isOutput: {
6175 // Indirect outputs just consume an argument.
6176 if (OpInfo.isIndirect) {
6177 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6178 break;
6179 }
6180
6181 // The return value of the call is this value. As such, there is no
6182 // corresponding argument.
6183 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
6184 EVT VT;
6185 if (auto *STy = dyn_cast<StructType>(Call.getType())) {
6186 VT = getAsmOperandValueType(DL, STy->getElementType(ResNo));
6187 } else {
6188 assert(ResNo == 0 && "Asm only has one result!");
6189 VT = getAsmOperandValueType(DL, Call.getType());
6190 }
6191 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6192 ++ResNo;
6193 break;
6194 }
6195 case InlineAsm::isInput:
6196 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6197 break;
6198 case InlineAsm::isLabel:
6199 OpInfo.CallOperandVal = cast<CallBrInst>(&Call)->getIndirectDest(LabelNo);
6200 ++LabelNo;
6201 continue;
6203 // Nothing to do.
6204 break;
6205 }
6206
6207 if (OpInfo.CallOperandVal) {
6208 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
6209 if (OpInfo.isIndirect) {
6210 OpTy = Call.getParamElementType(ArgNo);
6211 assert(OpTy && "Indirect operand must have elementtype attribute");
6212 }
6213
6214 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6216 if (STy->getNumElements() == 1)
6217 OpTy = STy->getElementType(0);
6218
6219 // If OpTy is not a single value, it may be a struct/union that we
6220 // can tile with integers.
6221 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6222 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6223 switch (BitSize) {
6224 default: break;
6225 case 1:
6226 case 8:
6227 case 16:
6228 case 32:
6229 case 64:
6230 case 128:
6231 OpTy = IntegerType::get(OpTy->getContext(), BitSize);
6232 break;
6233 }
6234 }
6235
6236 EVT VT = getAsmOperandValueType(DL, OpTy, true);
6237 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6238 ArgNo++;
6239 }
6240 }
6241
6242 // If we have multiple alternative constraints, select the best alternative.
6243 if (!ConstraintOperands.empty()) {
6244 if (maCount) {
6245 unsigned bestMAIndex = 0;
6246 int bestWeight = -1;
6247 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
6248 int weight = -1;
6249 unsigned maIndex;
6250 // Compute the sums of the weights for each alternative, keeping track
6251 // of the best (highest weight) one so far.
6252 for (maIndex = 0; maIndex < maCount; ++maIndex) {
6253 int weightSum = 0;
6254 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6255 cIndex != eIndex; ++cIndex) {
6256 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6257 if (OpInfo.Type == InlineAsm::isClobber)
6258 continue;
6259
6260 // If this is an output operand with a matching input operand,
6261 // look up the matching input. If their types mismatch, e.g. one
6262 // is an integer, the other is floating point, or their sizes are
6263 // different, flag it as an maCantMatch.
6264 if (OpInfo.hasMatchingInput()) {
6265 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6266 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6267 if ((OpInfo.ConstraintVT.isInteger() !=
6268 Input.ConstraintVT.isInteger()) ||
6269 (OpInfo.ConstraintVT.getSizeInBits() !=
6270 Input.ConstraintVT.getSizeInBits())) {
6271 weightSum = -1; // Can't match.
6272 break;
6273 }
6274 }
6275 }
6276 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
6277 if (weight == -1) {
6278 weightSum = -1;
6279 break;
6280 }
6281 weightSum += weight;
6282 }
6283 // Update best.
6284 if (weightSum > bestWeight) {
6285 bestWeight = weightSum;
6286 bestMAIndex = maIndex;
6287 }
6288 }
6289
6290 // Now select chosen alternative in each constraint.
6291 for (AsmOperandInfo &cInfo : ConstraintOperands)
6292 if (cInfo.Type != InlineAsm::isClobber)
6293 cInfo.selectAlternative(bestMAIndex);
6294 }
6295 }
6296
6297 // Check and hook up tied operands, choose constraint code to use.
6298 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6299 cIndex != eIndex; ++cIndex) {
6300 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6301
6302 // If this is an output operand with a matching input operand, look up the
6303 // matching input. If their types mismatch, e.g. one is an integer, the
6304 // other is floating point, or their sizes are different, flag it as an
6305 // error.
6306 if (OpInfo.hasMatchingInput()) {
6307 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6308
6309 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6310 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6311 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6312 OpInfo.ConstraintVT);
6313 std::pair<unsigned, const TargetRegisterClass *> InputRC =
6314 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
6315 Input.ConstraintVT);
6316 const bool OutOpIsIntOrFP = OpInfo.ConstraintVT.isInteger() ||
6317 OpInfo.ConstraintVT.isFloatingPoint();
6318 const bool InOpIsIntOrFP = Input.ConstraintVT.isInteger() ||
6319 Input.ConstraintVT.isFloatingPoint();
6320 if ((OutOpIsIntOrFP != InOpIsIntOrFP) ||
6321 (MatchRC.second != InputRC.second)) {
6322 report_fatal_error("Unsupported asm: input constraint"
6323 " with a matching output constraint of"
6324 " incompatible type!");
6325 }
6326 }
6327 }
6328 }
6329
6330 return ConstraintOperands;
6331}
6332
6333/// Return a number indicating our preference for chosing a type of constraint
6334/// over another, for the purpose of sorting them. Immediates are almost always
6335/// preferrable (when they can be emitted). A higher return value means a
6336/// stronger preference for one constraint type relative to another.
6337/// FIXME: We should prefer registers over memory but doing so may lead to
6338/// unrecoverable register exhaustion later.
6339/// https://github.com/llvm/llvm-project/issues/20571
6341 switch (CT) {
6344 return 4;
6347 return 3;
6349 return 2;
6351 return 1;
6353 return 0;
6354 }
6355 llvm_unreachable("Invalid constraint type");
6356}
6357
6358/// Examine constraint type and operand type and determine a weight value.
6359/// This object must already have been set up with the operand type
6360/// and the current alternative constraint selected.
6363 AsmOperandInfo &info, int maIndex) const {
6365 if (maIndex >= (int)info.multipleAlternatives.size())
6366 rCodes = &info.Codes;
6367 else
6368 rCodes = &info.multipleAlternatives[maIndex].Codes;
6369 ConstraintWeight BestWeight = CW_Invalid;
6370
6371 // Loop over the options, keeping track of the most general one.
6372 for (const std::string &rCode : *rCodes) {
6373 ConstraintWeight weight =
6374 getSingleConstraintMatchWeight(info, rCode.c_str());
6375 if (weight > BestWeight)
6376 BestWeight = weight;
6377 }
6378
6379 return BestWeight;
6380}
6381
6382/// Examine constraint type and operand type and determine a weight value.
6383/// This object must already have been set up with the operand type
6384/// and the current alternative constraint selected.
6387 AsmOperandInfo &info, const char *constraint) const {
6389 Value *CallOperandVal = info.CallOperandVal;
6390 // If we don't have a value, we can't do a match,
6391 // but allow it at the lowest weight.
6392 if (!CallOperandVal)
6393 return CW_Default;
6394 // Look at the constraint type.
6395 switch (*constraint) {
6396 case 'i': // immediate integer.
6397 case 'n': // immediate integer with a known value.
6398 if (isa<ConstantInt>(CallOperandVal))
6399 weight = CW_Constant;
6400 break;
6401 case 's': // non-explicit intregal immediate.
6402 if (isa<GlobalValue>(CallOperandVal))
6403 weight = CW_Constant;
6404 break;
6405 case 'E': // immediate float if host format.
6406 case 'F': // immediate float.
6407 if (isa<ConstantFP>(CallOperandVal))
6408 weight = CW_Constant;
6409 break;
6410 case '<': // memory operand with autodecrement.
6411 case '>': // memory operand with autoincrement.
6412 case 'm': // memory operand.
6413 case 'o': // offsettable memory operand
6414 case 'V': // non-offsettable memory operand
6415 weight = CW_Memory;
6416 break;
6417 case 'r': // general register.
6418 case 'g': // general register, memory operand or immediate integer.
6419 // note: Clang converts "g" to "imr".
6420 if (CallOperandVal->getType()->isIntegerTy())
6421 weight = CW_Register;
6422 break;
6423 case 'X': // any operand.
6424 default:
6425 weight = CW_Default;
6426 break;
6427 }
6428 return weight;
6429}
6430
6431/// If there are multiple different constraints that we could pick for this
6432/// operand (e.g. "imr") try to pick the 'best' one.
6433/// This is somewhat tricky: constraints (TargetLowering::ConstraintType) fall
6434/// into seven classes:
6435/// Register -> one specific register
6436/// RegisterClass -> a group of regs
6437/// Memory -> memory
6438/// Address -> a symbolic memory reference
6439/// Immediate -> immediate values
6440/// Other -> magic values (such as "Flag Output Operands")
6441/// Unknown -> something we don't recognize yet and can't handle
6442/// Ideally, we would pick the most specific constraint possible: if we have
6443/// something that fits into a register, we would pick it. The problem here
6444/// is that if we have something that could either be in a register or in
6445/// memory that use of the register could cause selection of *other*
6446/// operands to fail: they might only succeed if we pick memory. Because of
6447/// this the heuristic we use is:
6448///
6449/// 1) If there is an 'other' constraint, and if the operand is valid for
6450/// that constraint, use it. This makes us take advantage of 'i'
6451/// constraints when available.
6452/// 2) Otherwise, pick the most general constraint present. This prefers
6453/// 'm' over 'r', for example.
6454///
6456 TargetLowering::AsmOperandInfo &OpInfo) const {
6457 ConstraintGroup Ret;
6458
6459 Ret.reserve(OpInfo.Codes.size());
6460 for (StringRef Code : OpInfo.Codes) {
6462
6463 // Indirect 'other' or 'immediate' constraints are not allowed.
6464 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
6465 CType == TargetLowering::C_Register ||
6467 continue;
6468
6469 // Things with matching constraints can only be registers, per gcc
6470 // documentation. This mainly affects "g" constraints.
6471 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
6472 continue;
6473
6474 Ret.emplace_back(Code, CType);
6475 }
6476
6478 return getConstraintPiority(a.second) > getConstraintPiority(b.second);
6479 });
6480
6481 return Ret;
6482}
6483
6484/// If we have an immediate, see if we can lower it. Return true if we can,
6485/// false otherwise.
6487 SDValue Op, SelectionDAG *DAG,
6488 const TargetLowering &TLI) {
6489
6490 assert((P.second == TargetLowering::C_Other ||
6491 P.second == TargetLowering::C_Immediate) &&
6492 "need immediate or other");
6493
6494 if (!Op.getNode())
6495 return false;
6496
6497 std::vector<SDValue> ResultOps;
6498 TLI.LowerAsmOperandForConstraint(Op, P.first, ResultOps, *DAG);
6499 return !ResultOps.empty();
6500}
6501
6502/// Determines the constraint code and constraint type to use for the specific
6503/// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
6505 SDValue Op,
6506 SelectionDAG *DAG) const {
6507 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
6508
6509 // Single-letter constraints ('r') are very common.
6510 if (OpInfo.Codes.size() == 1) {
6511 OpInfo.ConstraintCode = OpInfo.Codes[0];
6512 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6513 } else {
6515 if (G.empty())
6516 return;
6517
6518 unsigned BestIdx = 0;
6519 for (const unsigned E = G.size();
6520 BestIdx < E && (G[BestIdx].second == TargetLowering::C_Other ||
6521 G[BestIdx].second == TargetLowering::C_Immediate);
6522 ++BestIdx) {
6523 if (lowerImmediateIfPossible(G[BestIdx], Op, DAG, *this))
6524 break;
6525 // If we're out of constraints, just pick the first one.
6526 if (BestIdx + 1 == E) {
6527 BestIdx = 0;
6528 break;
6529 }
6530 }
6531
6532 OpInfo.ConstraintCode = G[BestIdx].first;
6533 OpInfo.ConstraintType = G[BestIdx].second;
6534 }
6535
6536 // 'X' matches anything.
6537 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
6538 // Constants are handled elsewhere. For Functions, the type here is the
6539 // type of the result, which is not what we want to look at; leave them
6540 // alone.
6541 Value *v = OpInfo.CallOperandVal;
6542 if (isa<ConstantInt>(v) || isa<Function>(v)) {
6543 return;
6544 }
6545
6546 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
6547 OpInfo.ConstraintCode = "i";
6548 return;
6549 }
6550
6551 // Otherwise, try to resolve it to something we know about by looking at
6552 // the actual operand type.
6553 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
6554 OpInfo.ConstraintCode = Repl;
6555 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6556 }
6557 }
6558}
6559
6560/// Given an exact SDIV by a constant, create a multiplication
6561/// with the multiplicative inverse of the constant.
6562/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6564 const SDLoc &dl, SelectionDAG &DAG,
6565 SmallVectorImpl<SDNode *> &Created) {
6566 SDValue Op0 = N->getOperand(0);
6567 SDValue Op1 = N->getOperand(1);
6568 EVT VT = N->getValueType(0);
6569 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6570 EVT ShSVT = ShVT.getScalarType();
6571
6572 bool UseSRA = false;
6573 SmallVector<SDValue, 16> Shifts, Factors;
6574
6575 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6576 if (C->isZero())
6577 return false;
6578
6579 EVT CT = C->getValueType(0);
6580 APInt Divisor = C->getAPIntValue();
6581 unsigned Shift = Divisor.countr_zero();
6582 if (Shift) {
6583 Divisor.ashrInPlace(Shift);
6584 UseSRA = true;
6585 }
6586 APInt Factor = Divisor.multiplicativeInverse();
6587 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6588 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6589 return true;
6590 };
6591
6592 // Collect all magic values from the build vector.
6593 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
6594 return SDValue();
6595
6596 SDValue Shift, Factor;
6597 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6598 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6599 Factor = DAG.getBuildVector(VT, dl, Factors);
6600 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6601 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6602 "Expected matchUnaryPredicate to return one element for scalable "
6603 "vectors");
6604 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6605 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6606 } else {
6607 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6608 Shift = Shifts[0];
6609 Factor = Factors[0];
6610 }
6611
6612 SDValue Res = Op0;
6613 if (UseSRA) {
6614 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, SDNodeFlags::Exact);
6615 Created.push_back(Res.getNode());
6616 }
6617
6618 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6619}
6620
6621/// Given an exact UDIV by a constant, create a multiplication
6622/// with the multiplicative inverse of the constant.
6623/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6625 const SDLoc &dl, SelectionDAG &DAG,
6626 SmallVectorImpl<SDNode *> &Created) {
6627 EVT VT = N->getValueType(0);
6628 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6629 EVT ShSVT = ShVT.getScalarType();
6630
6631 bool UseSRL = false;
6632 SmallVector<SDValue, 16> Shifts, Factors;
6633
6634 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
6635 if (C->isZero())
6636 return false;
6637
6638 EVT CT = C->getValueType(0);
6639 APInt Divisor = C->getAPIntValue();
6640 unsigned Shift = Divisor.countr_zero();
6641 if (Shift) {
6642 Divisor.lshrInPlace(Shift);
6643 UseSRL = true;
6644 }
6645 // Calculate the multiplicative inverse modulo BW.
6646 APInt Factor = Divisor.multiplicativeInverse();
6647 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6648 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6649 return true;
6650 };
6651
6652 SDValue Op1 = N->getOperand(1);
6653
6654 // Collect all magic values from the build vector.
6655 if (!ISD::matchUnaryPredicate(Op1, BuildUDIVPattern))
6656 return SDValue();
6657
6658 SDValue Shift, Factor;
6659 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6660 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6661 Factor = DAG.getBuildVector(VT, dl, Factors);
6662 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6663 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6664 "Expected matchUnaryPredicate to return one element for scalable "
6665 "vectors");
6666 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6667 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6668 } else {
6669 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6670 Shift = Shifts[0];
6671 Factor = Factors[0];
6672 }
6673
6674 SDValue Res = N->getOperand(0);
6675 if (UseSRL) {
6676 Res = DAG.getNode(ISD::SRL, dl, VT, Res, Shift, SDNodeFlags::Exact);
6677 Created.push_back(Res.getNode());
6678 }
6679
6680 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6681}
6682
6684 SelectionDAG &DAG,
6685 SmallVectorImpl<SDNode *> &Created) const {
6687 if (isIntDivCheap(N->getValueType(0), Attr))
6688 return SDValue(N, 0); // Lower SDIV as SDIV
6689 return SDValue();
6690}
6691
6692SDValue
6694 SelectionDAG &DAG,
6695 SmallVectorImpl<SDNode *> &Created) const {
6697 if (isIntDivCheap(N->getValueType(0), Attr))
6698 return SDValue(N, 0); // Lower SREM as SREM
6699 return SDValue();
6700}
6701
6702/// Build sdiv by power-of-2 with conditional move instructions
6703/// Ref: "Hacker's Delight" by Henry Warren 10-1
6704/// If conditional move/branch is preferred, we lower sdiv x, +/-2**k into:
6705/// bgez x, label
6706/// add x, x, 2**k-1
6707/// label:
6708/// sra res, x, k
6709/// neg res, res (when the divisor is negative)
6711 SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
6712 SmallVectorImpl<SDNode *> &Created) const {
6713 unsigned Lg2 = Divisor.countr_zero();
6714 EVT VT = N->getValueType(0);
6715
6716 SDLoc DL(N);
6717 SDValue N0 = N->getOperand(0);
6718 SDValue Zero = DAG.getConstant(0, DL, VT);
6719 APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
6720 SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
6721
6722 // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
6723 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6724 SDValue Cmp = DAG.getSetCC(DL, CCVT, N0, Zero, ISD::SETLT);
6725 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
6726 SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
6727
6728 Created.push_back(Cmp.getNode());
6729 Created.push_back(Add.getNode());
6730 Created.push_back(CMov.getNode());
6731
6732 // Divide by pow2.
6733 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, CMov,
6734 DAG.getShiftAmountConstant(Lg2, VT, DL));
6735
6736 // If we're dividing by a positive value, we're done. Otherwise, we must
6737 // negate the result.
6738 if (Divisor.isNonNegative())
6739 return SRA;
6740
6741 Created.push_back(SRA.getNode());
6742 return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
6743}
6744
6745/// Given an ISD::SDIV node expressing a divide by constant,
6746/// return a DAG expression to select that will generate the same value by
6747/// multiplying by a magic number.
6748/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
6750 bool IsAfterLegalization,
6751 bool IsAfterLegalTypes,
6752 SmallVectorImpl<SDNode *> &Created) const {
6753 SDLoc dl(N);
6754
6755 // If the sdiv has an 'exact' bit we can use a simpler lowering.
6756 if (N->getFlags().hasExact())
6757 return BuildExactSDIV(*this, N, dl, DAG, Created);
6758
6759 EVT VT = N->getValueType(0);
6760 EVT SVT = VT.getScalarType();
6761 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
6762 EVT ShSVT = ShVT.getScalarType();
6763 unsigned EltBits = VT.getScalarSizeInBits();
6764 EVT MulVT;
6765
6766 // Check to see if we can do this.
6767 // FIXME: We should be more aggressive here.
6768 EVT QueryVT = VT;
6769 if (VT.isVector()) {
6770 // If the vector type will be legalized to a vector type with the same
6771 // element type, allow the transform before type legalization if MULHS or
6772 // SMUL_LOHI are supported.
6773 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
6774 if (!QueryVT.isVector() ||
6776 return SDValue();
6777 } else if (!isTypeLegal(VT)) {
6778 // Limit this to simple scalars for now.
6779 if (!VT.isSimple())
6780 return SDValue();
6781
6782 // If this type will be promoted to a large enough type with a legal
6783 // multiply operation, we can go ahead and do this transform.
6785 return SDValue();
6786
6787 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
6788 if (MulVT.getSizeInBits() < (2 * EltBits) ||
6789 !isOperationLegal(ISD::MUL, MulVT))
6790 return SDValue();
6791 }
6792
6793 bool HasMULHS =
6794 isOperationLegalOrCustom(ISD::MULHS, QueryVT, IsAfterLegalization);
6795 bool HasSMUL_LOHI =
6796 isOperationLegalOrCustom(ISD::SMUL_LOHI, QueryVT, IsAfterLegalization);
6797
6798 if (isTypeLegal(VT) && !HasMULHS && !HasSMUL_LOHI && MulVT == EVT()) {
6799 // If type twice as wide legal, widen and use a mul plus a shift.
6800 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
6801 // Some targets like AMDGPU try to go from SDIV to SDIVREM which is then
6802 // custom lowered. This is very expensive so avoid it at all costs for
6803 // constant divisors.
6804 if ((!IsAfterLegalTypes && isOperationExpand(ISD::SDIV, VT) &&
6807 MulVT = WideVT;
6808 }
6809
6810 if (!HasMULHS && !HasSMUL_LOHI && MulVT == EVT())
6811 return SDValue();
6812
6813 // If we're after type legalization and SVT is not legal, use the
6814 // promoted type for creating constants to avoid creating nodes with
6815 // illegal types.
6816 if (IsAfterLegalTypes && VT.isVector()) {
6817 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
6818 if (SVT.bitsLT(VT.getScalarType()))
6819 return SDValue();
6820 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
6821 if (ShSVT.bitsLT(ShVT.getScalarType()))
6822 return SDValue();
6823 }
6824 const unsigned SVTBits = SVT.getSizeInBits();
6825
6826 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
6827
6828 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6829 if (C->isZero())
6830 return false;
6831 // Truncate the divisor to the target scalar type in case it was promoted
6832 // during type legalization.
6833 APInt Divisor = C->getAPIntValue().trunc(EltBits);
6835 int NumeratorFactor = 0;
6836 int ShiftMask = -1;
6837
6838 if (Divisor.isOne() || Divisor.isAllOnes()) {
6839 // If d is +1/-1, we just multiply the numerator by +1/-1.
6840 NumeratorFactor = Divisor.getSExtValue();
6841 magics.Magic = 0;
6842 magics.ShiftAmount = 0;
6843 ShiftMask = 0;
6844 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
6845 // If d > 0 and m < 0, add the numerator.
6846 NumeratorFactor = 1;
6847 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
6848 // If d < 0 and m > 0, subtract the numerator.
6849 NumeratorFactor = -1;
6850 }
6851
6852 MagicFactors.push_back(
6853 DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT));
6854 Factors.push_back(DAG.getSignedConstant(NumeratorFactor, dl, SVT));
6855 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
6856 ShiftMasks.push_back(DAG.getSignedConstant(ShiftMask, dl, SVT));
6857 return true;
6858 };
6859
6860 SDValue N0 = N->getOperand(0);
6861 SDValue N1 = N->getOperand(1);
6862
6863 // Collect the shifts / magic values from each element.
6864 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern, /*AllowUndefs=*/false,
6865 /*AllowTruncation=*/true))
6866 return SDValue();
6867
6868 SDValue MagicFactor, Factor, Shift, ShiftMask;
6869 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
6870 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
6871 Factor = DAG.getBuildVector(VT, dl, Factors);
6872 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6873 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
6874 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
6875 assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
6876 Shifts.size() == 1 && ShiftMasks.size() == 1 &&
6877 "Expected matchUnaryPredicate to return one element for scalable "
6878 "vectors");
6879 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
6880 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6881 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6882 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
6883 } else {
6884 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
6885 MagicFactor = MagicFactors[0];
6886 Factor = Factors[0];
6887 Shift = Shifts[0];
6888 ShiftMask = ShiftMasks[0];
6889 }
6890
6891 // Multiply the numerator (operand 0) by the magic value.
6892 auto GetMULHS = [&](SDValue X, SDValue Y) {
6893 if (HasMULHS)
6894 return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
6895 if (HasSMUL_LOHI) {
6896 SDValue LoHi =
6897 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
6898 return LoHi.getValue(1);
6899 }
6900
6901 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
6902 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
6903 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
6904 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
6905 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
6906 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
6907 };
6908
6909 SDValue Q = GetMULHS(N0, MagicFactor);
6910 if (!Q)
6911 return SDValue();
6912
6913 Created.push_back(Q.getNode());
6914
6915 // (Optionally) Add/subtract the numerator using Factor.
6916 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
6917 Created.push_back(Factor.getNode());
6918 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
6919 Created.push_back(Q.getNode());
6920
6921 // Shift right algebraic by shift value.
6922 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
6923 Created.push_back(Q.getNode());
6924
6925 // Extract the sign bit, mask it and add it to the quotient.
6926 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
6927 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
6928 Created.push_back(T.getNode());
6929 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
6930 Created.push_back(T.getNode());
6931 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
6932}
6933
6934/// Given an ISD::UDIV node expressing a divide by constant,
6935/// return a DAG expression to select that will generate the same value by
6936/// multiplying by a magic number.
6937/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
6939 bool IsAfterLegalization,
6940 bool IsAfterLegalTypes,
6941 SmallVectorImpl<SDNode *> &Created) const {
6942 SDLoc dl(N);
6943
6944 // If the udiv has an 'exact' bit we can use a simpler lowering.
6945 if (N->getFlags().hasExact())
6946 return BuildExactUDIV(*this, N, dl, DAG, Created);
6947
6948 EVT VT = N->getValueType(0);
6949 EVT SVT = VT.getScalarType();
6950 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
6951 EVT ShSVT = ShVT.getScalarType();
6952 unsigned EltBits = VT.getScalarSizeInBits();
6953 EVT MulVT;
6954
6955 // Check to see if we can do this.
6956 // FIXME: We should be more aggressive here.
6957 EVT QueryVT = VT;
6958 if (VT.isVector()) {
6959 // If the vector type will be legalized to a vector type with the same
6960 // element type, allow the transform before type legalization if MULHU or
6961 // UMUL_LOHI are supported.
6962 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
6963 if (!QueryVT.isVector() ||
6965 return SDValue();
6966 } else if (!isTypeLegal(VT)) {
6967 // Limit this to simple scalars for now.
6968 if (!VT.isSimple())
6969 return SDValue();
6970
6971 // If this type will be promoted to a large enough type with a legal
6972 // multiply operation, we can go ahead and do this transform.
6974 return SDValue();
6975
6976 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
6977 if (MulVT.getSizeInBits() < (2 * EltBits) ||
6978 !isOperationLegal(ISD::MUL, MulVT))
6979 return SDValue();
6980 }
6981
6982 bool HasMULHU =
6983 isOperationLegalOrCustom(ISD::MULHU, QueryVT, IsAfterLegalization);
6984 bool HasUMUL_LOHI =
6985 isOperationLegalOrCustom(ISD::UMUL_LOHI, QueryVT, IsAfterLegalization);
6986
6987 if (isTypeLegal(VT) && !HasMULHU && !HasUMUL_LOHI && MulVT == EVT()) {
6988 // If type twice as wide legal, widen and use a mul plus a shift.
6989 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
6990 // Some targets like AMDGPU try to go from UDIV to UDIVREM which is then
6991 // custom lowered. This is very expensive so avoid it at all costs for
6992 // constant divisors.
6993 if ((!IsAfterLegalTypes && isOperationExpand(ISD::UDIV, VT) &&
6996 MulVT = WideVT;
6997 }
6998
6999 if (!HasMULHU && !HasUMUL_LOHI && MulVT == EVT())
7000 return SDValue();
7001
7002 SDValue N0 = N->getOperand(0);
7003 SDValue N1 = N->getOperand(1);
7004
7005 // Try to use leading zeros of the dividend to reduce the multiplier and
7006 // avoid expensive fixups.
7007 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
7008
7009 // If we're after type legalization and SVT is not legal, use the
7010 // promoted type for creating constants to avoid creating nodes with
7011 // illegal types.
7012 if (IsAfterLegalTypes && VT.isVector()) {
7013 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
7014 if (SVT.bitsLT(VT.getScalarType()))
7015 return SDValue();
7016 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
7017 if (ShSVT.bitsLT(ShVT.getScalarType()))
7018 return SDValue();
7019 }
7020 const unsigned SVTBits = SVT.getSizeInBits();
7021
7022 // Allow i32 to be widened to i64 for uncooperative divisors if i64 MULHU or
7023 // UMUL_LOHI is supported.
7024 const EVT WideSVT = MVT::i64;
7025 const bool HasWideMULHU =
7026 VT == MVT::i32 &&
7027 isOperationLegalOrCustom(ISD::MULHU, WideSVT, IsAfterLegalization);
7028 const bool HasWideUMUL_LOHI =
7029 VT == MVT::i32 &&
7030 isOperationLegalOrCustom(ISD::UMUL_LOHI, WideSVT, IsAfterLegalization);
7031 const bool AllowWiden = (HasWideMULHU || HasWideUMUL_LOHI);
7032
7033 // For even divisors with a 33-bit magic number, the widened high-multiply
7034 // path is only worthwhile over the even-divisor rewrite on targets that
7035 // zero-extend i32 to i64 for free (e.g. x86-64 and AArch64). Elsewhere (e.g.
7036 // RISC-V) keep the even-divisor rewrite, which avoids the explicit extension.
7037 const bool AllowEvenToWiden = AllowWiden && isZExtFree(VT, WideSVT);
7038
7039 bool UseNPQ = false, UsePreShift = false, UsePostShift = false;
7040 bool UseWiden = false;
7041 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
7042
7043 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
7044 if (C->isZero())
7045 return false;
7046 // Truncate the divisor to the target scalar type in case it was promoted
7047 // during type legalization.
7048 APInt Divisor = C->getAPIntValue().trunc(EltBits);
7049
7050 SDValue PreShift, MagicFactor, NPQFactor, PostShift;
7051
7052 // Magic algorithm doesn't work for division by 1. We need to emit a select
7053 // at the end.
7054 if (Divisor.isOne()) {
7055 PreShift = PostShift = DAG.getUNDEF(ShSVT);
7056 MagicFactor = NPQFactor = DAG.getUNDEF(SVT);
7057 } else {
7060 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()),
7061 /*AllowEvenDivisorOptimization=*/!AllowEvenToWiden,
7062 /*AllowWidenOptimization=*/AllowWiden);
7063
7064 if (magics.Widen) {
7065 UseWiden = true;
7066 MagicFactor = DAG.getConstant(magics.Magic, dl, WideSVT);
7067 } else {
7068 MagicFactor = DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT);
7069 }
7070
7071 assert(magics.PreShift < Divisor.getBitWidth() &&
7072 "We shouldn't generate an undefined shift!");
7073 assert(magics.PostShift < Divisor.getBitWidth() &&
7074 "We shouldn't generate an undefined shift!");
7075 assert((!magics.IsAdd || magics.PreShift == 0) &&
7076 "Unexpected pre-shift");
7077 PreShift = DAG.getConstant(magics.PreShift, dl, ShSVT);
7078 PostShift = DAG.getConstant(magics.PostShift, dl, ShSVT);
7079 NPQFactor = DAG.getConstant(
7080 magics.IsAdd ? APInt::getOneBitSet(SVTBits, EltBits - 1)
7081 : APInt::getZero(SVTBits),
7082 dl, SVT);
7083 UseNPQ |= magics.IsAdd;
7084 UsePreShift |= magics.PreShift != 0;
7085 UsePostShift |= magics.PostShift != 0;
7086 }
7087
7088 PreShifts.push_back(PreShift);
7089 MagicFactors.push_back(MagicFactor);
7090 NPQFactors.push_back(NPQFactor);
7091 PostShifts.push_back(PostShift);
7092 return true;
7093 };
7094
7095 // Collect the shifts/magic values from each element.
7096 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern, /*AllowUndefs=*/false,
7097 /*AllowTruncation=*/true))
7098 return SDValue();
7099
7100 SDValue PreShift, PostShift, MagicFactor, NPQFactor;
7101 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
7102 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
7103 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
7104 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
7105 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
7106 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
7107 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
7108 NPQFactors.size() == 1 && PostShifts.size() == 1 &&
7109 "Expected matchUnaryPredicate to return one for scalable vectors");
7110 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
7111 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
7112 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
7113 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
7114 } else {
7115 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
7116 PreShift = PreShifts[0];
7117 MagicFactor = MagicFactors[0];
7118 PostShift = PostShifts[0];
7119 }
7120
7121 if (UseWiden) {
7122 // Compute: (WideSVT(x) * MagicFactor) >> WideSVTBits.
7123 SDValue WideN0 = DAG.getNode(ISD::ZERO_EXTEND, dl, WideSVT, N0);
7124
7125 // Perform WideSVTxWideSVT -> 2*WideSVT multiplication and extract high
7126 // WideSVT bits
7127 SDValue High;
7128 if (HasWideMULHU) {
7129 High = DAG.getNode(ISD::MULHU, dl, WideSVT, WideN0, MagicFactor);
7130 } else {
7131 assert(HasWideUMUL_LOHI);
7132 SDValue LoHi =
7133 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(WideSVT, WideSVT),
7134 WideN0, MagicFactor);
7135 High = LoHi.getValue(1);
7136 }
7137
7138 Created.push_back(High.getNode());
7139 return DAG.getNode(ISD::TRUNCATE, dl, VT, High);
7140 }
7141
7142 SDValue Q = N0;
7143 if (UsePreShift) {
7144 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
7145 Created.push_back(Q.getNode());
7146 }
7147
7148 auto GetMULHU = [&](SDValue X, SDValue Y) {
7149 if (HasMULHU)
7150 return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
7151 if (HasUMUL_LOHI) {
7152 SDValue LoHi =
7153 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
7154 return LoHi.getValue(1);
7155 }
7156
7157 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
7158 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
7159 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
7160 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
7161 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
7162 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
7163 };
7164
7165 // Multiply the numerator (operand 0) by the magic value.
7166 Q = GetMULHU(Q, MagicFactor);
7167 if (!Q)
7168 return SDValue();
7169
7170 Created.push_back(Q.getNode());
7171
7172 if (UseNPQ) {
7173 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
7174 Created.push_back(NPQ.getNode());
7175
7176 // For vectors we might have a mix of non-NPQ/NPQ paths, so use
7177 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
7178 if (VT.isVector())
7179 NPQ = GetMULHU(NPQ, NPQFactor);
7180 else
7181 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
7182
7183 Created.push_back(NPQ.getNode());
7184
7185 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
7186 Created.push_back(Q.getNode());
7187 }
7188
7189 if (UsePostShift) {
7190 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
7191 Created.push_back(Q.getNode());
7192 }
7193
7194 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7195
7196 SDValue One = DAG.getConstant(1, dl, VT);
7197 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
7198 return DAG.getSelect(dl, VT, IsOne, N0, Q);
7199}
7200
7201/// If all values in Values that *don't* match the predicate are same 'splat'
7202/// value, then replace all values with that splat value.
7203/// Else, if AlternativeReplacement was provided, then replace all values that
7204/// do match predicate with AlternativeReplacement value.
7205static void
7207 std::function<bool(SDValue)> Predicate,
7208 SDValue AlternativeReplacement = SDValue()) {
7209 SDValue Replacement;
7210 // Is there a value for which the Predicate does *NOT* match? What is it?
7211 auto SplatValue = llvm::find_if_not(Values, Predicate);
7212 if (SplatValue != Values.end()) {
7213 // Does Values consist only of SplatValue's and values matching Predicate?
7214 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
7215 return Value == *SplatValue || Predicate(Value);
7216 })) // Then we shall replace values matching predicate with SplatValue.
7217 Replacement = *SplatValue;
7218 }
7219 if (!Replacement) {
7220 // Oops, we did not find the "baseline" splat value.
7221 if (!AlternativeReplacement)
7222 return; // Nothing to do.
7223 // Let's replace with provided value then.
7224 Replacement = AlternativeReplacement;
7225 }
7226 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
7227}
7228
7229/// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
7230/// where the divisor and comparison target are constants,
7231/// return a DAG expression that will generate the same comparison result
7232/// using only multiplications, additions and shifts/rotations.
7233/// Ref: "Hacker's Delight" 10-17.
7234SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
7235 SDValue CompTargetNode,
7237 DAGCombinerInfo &DCI,
7238 const SDLoc &DL) const {
7240 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7241 DCI, DL, Built)) {
7242 for (SDNode *N : Built)
7243 DCI.AddToWorklist(N);
7244 return Folded;
7245 }
7246
7247 return SDValue();
7248}
7249
7250SDValue
7251TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
7252 SDValue CompTargetNode, ISD::CondCode Cond,
7253 DAGCombinerInfo &DCI, const SDLoc &DL,
7254 SmallVectorImpl<SDNode *> &Created) const {
7255 // fold (seteq/ne (urem N, D), C) ->
7256 // (setule/ugt (rotr (mul (sub N, C), P), K), Q)
7257 // - D must be constant, with D = D0 * 2^K where D0 is odd
7258 // - P is the multiplicative inverse of D0 modulo 2^W
7259 // - Q = floor(((2^W) - 1) / D)
7260 // where W is the width of the common type of N and D.
7261 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7262 "Only applicable for (in)equality comparisons.");
7263
7264 SelectionDAG &DAG = DCI.DAG;
7265
7266 EVT VT = REMNode.getValueType();
7267 EVT SVT = VT.getScalarType();
7268 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7269 EVT ShSVT = ShVT.getScalarType();
7270
7271 // If MUL is unavailable, we cannot proceed in any case.
7272 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7273 return SDValue();
7274
7275 bool ComparingWithAllZeros = true;
7276 bool AllComparisonsWithNonZerosAreTautological = true;
7277 bool HadTautologicalLanes = false;
7278 bool AllLanesAreTautological = true;
7279 bool HadEvenDivisor = false;
7280 bool AllDivisorsArePowerOfTwo = true;
7281 bool HadTautologicalInvertedLanes = false;
7282 SmallVector<SDValue, 16> PAmts, KAmts, QAmts;
7283
7284 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
7285 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7286 if (CDiv->isZero())
7287 return false;
7288
7289 const APInt &D = CDiv->getAPIntValue();
7290 const APInt &Cmp = CCmp->getAPIntValue();
7291
7292 ComparingWithAllZeros &= Cmp.isZero();
7293
7294 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7295 // if C2 is not less than C1, the comparison is always false.
7296 // But we will only be able to produce the comparison that will give the
7297 // opposive tautological answer. So this lane would need to be fixed up.
7298 bool TautologicalInvertedLane = D.ule(Cmp);
7299 HadTautologicalInvertedLanes |= TautologicalInvertedLane;
7300
7301 // If all lanes are tautological (either all divisors are ones, or divisor
7302 // is not greater than the constant we are comparing with),
7303 // we will prefer to avoid the fold.
7304 bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
7305 HadTautologicalLanes |= TautologicalLane;
7306 AllLanesAreTautological &= TautologicalLane;
7307
7308 // If we are comparing with non-zero, we need'll need to subtract said
7309 // comparison value from the LHS. But there is no point in doing that if
7310 // every lane where we are comparing with non-zero is tautological..
7311 if (!Cmp.isZero())
7312 AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
7313
7314 // Decompose D into D0 * 2^K
7315 unsigned K = D.countr_zero();
7316 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7317 APInt D0 = D.lshr(K);
7318
7319 // D is even if it has trailing zeros.
7320 HadEvenDivisor |= (K != 0);
7321 // D is a power-of-two if D0 is one.
7322 // If all divisors are power-of-two, we will prefer to avoid the fold.
7323 AllDivisorsArePowerOfTwo &= D0.isOne();
7324
7325 // P = inv(D0, 2^W)
7326 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7327 unsigned W = D.getBitWidth();
7328 APInt P = D0.multiplicativeInverse();
7329 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7330
7331 // Q = floor((2^W - 1) u/ D)
7332 // R = ((2^W - 1) u% D)
7333 APInt Q, R;
7335
7336 // If we are comparing with zero, then that comparison constant is okay,
7337 // else it may need to be one less than that.
7338 if (Cmp.ugt(R))
7339 Q -= 1;
7340
7342 "We are expecting that K is always less than all-ones for ShSVT");
7343
7344 // If the lane is tautological the result can be constant-folded.
7345 if (TautologicalLane) {
7346 // Set P and K amount to a bogus values so we can try to splat them.
7347 P = 0;
7348 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7349 // And ensure that comparison constant is tautological,
7350 // it will always compare true/false.
7351 Q.setAllBits();
7352 } else {
7353 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7354 }
7355
7356 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7357 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7358 return true;
7359 };
7360
7361 SDValue N = REMNode.getOperand(0);
7362 SDValue D = REMNode.getOperand(1);
7363
7364 // Collect the values from each element.
7365 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
7366 return SDValue();
7367
7368 // If all lanes are tautological, the result can be constant-folded.
7369 if (AllLanesAreTautological)
7370 return SDValue();
7371
7372 // If this is a urem by a powers-of-two, avoid the fold since it can be
7373 // best implemented as a bit test.
7374 if (AllDivisorsArePowerOfTwo)
7375 return SDValue();
7376
7377 SDValue PVal, KVal, QVal;
7378 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7379 if (HadTautologicalLanes) {
7380 // Try to turn PAmts into a splat, since we don't care about the values
7381 // that are currently '0'. If we can't, just keep '0'`s.
7383 // Try to turn KAmts into a splat, since we don't care about the values
7384 // that are currently '-1'. If we can't, change them to '0'`s.
7386 DAG.getConstant(0, DL, ShSVT));
7387 }
7388
7389 PVal = DAG.getBuildVector(VT, DL, PAmts);
7390 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7391 QVal = DAG.getBuildVector(VT, DL, QAmts);
7392 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7393 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
7394 "Expected matchBinaryPredicate to return one element for "
7395 "SPLAT_VECTORs");
7396 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7397 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7398 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7399 } else {
7400 PVal = PAmts[0];
7401 KVal = KAmts[0];
7402 QVal = QAmts[0];
7403 }
7404
7405 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
7406 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
7407 return SDValue(); // FIXME: Could/should use `ISD::ADD`?
7408 assert(CompTargetNode.getValueType() == N.getValueType() &&
7409 "Expecting that the types on LHS and RHS of comparisons match.");
7410 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
7411 }
7412
7413 // (mul N, P)
7414 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7415 Created.push_back(Op0.getNode());
7416
7417 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7418 // divisors as a performance improvement, since rotating by 0 is a no-op.
7419 if (HadEvenDivisor) {
7420 // We need ROTR to do this.
7421 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7422 return SDValue();
7423 // UREM: (rotr (mul N, P), K)
7424 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7425 Created.push_back(Op0.getNode());
7426 }
7427
7428 // UREM: (setule/setugt (rotr (mul N, P), K), Q)
7429 SDValue NewCC =
7430 DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7432 if (!HadTautologicalInvertedLanes)
7433 return NewCC;
7434
7435 // If any lanes previously compared always-false, the NewCC will give
7436 // always-true result for them, so we need to fixup those lanes.
7437 // Or the other way around for inequality predicate.
7438 assert(VT.isVector() && "Can/should only get here for vectors.");
7439 Created.push_back(NewCC.getNode());
7440
7441 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7442 // if C2 is not less than C1, the comparison is always false.
7443 // But we have produced the comparison that will give the
7444 // opposive tautological answer. So these lanes would need to be fixed up.
7445 SDValue TautologicalInvertedChannels =
7446 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
7447 Created.push_back(TautologicalInvertedChannels.getNode());
7448
7449 // NOTE: we avoid letting illegal types through even if we're before legalize
7450 // ops – legalization has a hard time producing good code for this.
7451 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
7452 // If we have a vector select, let's replace the comparison results in the
7453 // affected lanes with the correct tautological result.
7454 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
7455 DL, SETCCVT, SETCCVT);
7456 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
7457 Replacement, NewCC);
7458 }
7459
7460 // Else, we can just invert the comparison result in the appropriate lanes.
7461 //
7462 // NOTE: see the note above VSELECT above.
7463 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
7464 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
7465 TautologicalInvertedChannels);
7466
7467 return SDValue(); // Don't know how to lower.
7468}
7469
7470/// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
7471/// where the divisor is constant and the comparison target is zero,
7472/// return a DAG expression that will generate the same comparison result
7473/// using only multiplications, additions and shifts/rotations.
7474/// Ref: "Hacker's Delight" 10-17.
7475SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
7476 SDValue CompTargetNode,
7478 DAGCombinerInfo &DCI,
7479 const SDLoc &DL) const {
7481 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7482 DCI, DL, Built)) {
7483 assert(Built.size() <= 7 && "Max size prediction failed.");
7484 for (SDNode *N : Built)
7485 DCI.AddToWorklist(N);
7486 return Folded;
7487 }
7488
7489 return SDValue();
7490}
7491
7492SDValue
7493TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
7494 SDValue CompTargetNode, ISD::CondCode Cond,
7495 DAGCombinerInfo &DCI, const SDLoc &DL,
7496 SmallVectorImpl<SDNode *> &Created) const {
7497 // Derived from Hacker's Delight, 2nd Edition, by Hank Warren. Section 10-17.
7498 // Fold:
7499 // (seteq/ne (srem N, D), 0)
7500 // To:
7501 // (setule/ugt (rotr (add (mul N, P), A), K), Q)
7502 //
7503 // - D must be constant, with D = D0 * 2^K where D0 is odd
7504 // - P is the multiplicative inverse of D0 modulo 2^W
7505 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
7506 // - Q = floor((2 * A) / (2^K))
7507 // where W is the width of the common type of N and D.
7508 //
7509 // When D is a power of two (and thus D0 is 1), the normal
7510 // formula for A and Q don't apply, because the derivation
7511 // depends on D not dividing 2^(W-1), and thus theorem ZRS
7512 // does not apply. This specifically fails when N = INT_MIN.
7513 //
7514 // Instead, for power-of-two D, we use:
7515 // - A = 0
7516 // | -> No offset needed. We're effectively treating it the same as urem.
7517 // - Q = 2^(W-K) - 1
7518 // |-> Test that the top K bits are zero after rotation
7519 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7520 "Only applicable for (in)equality comparisons.");
7521
7522 SelectionDAG &DAG = DCI.DAG;
7523
7524 EVT VT = REMNode.getValueType();
7525 EVT SVT = VT.getScalarType();
7526 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7527 EVT ShSVT = ShVT.getScalarType();
7528
7529 // If we are after ops legalization, and MUL is unavailable, we can not
7530 // proceed.
7531 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7532 return SDValue();
7533
7534 // TODO: Could support comparing with non-zero too.
7535 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
7536 if (!CompTarget || !CompTarget->isZero())
7537 return SDValue();
7538
7539 bool HadOneDivisor = false;
7540 bool AllDivisorsAreOnes = true;
7541 bool HadEvenDivisor = false;
7542 bool AllDivisorsArePowerOfTwo = true;
7543 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
7544
7545 auto BuildSREMPattern = [&](ConstantSDNode *C) {
7546 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7547 if (C->isZero())
7548 return false;
7549
7550 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
7551
7552 // WARNING: this fold is only valid for positive divisors!
7553 // `rem %X, -C` is equivalent to `rem %X, C`
7554 APInt D = C->getAPIntValue().abs();
7555
7556 // If all divisors are ones, we will prefer to avoid the fold.
7557 HadOneDivisor |= D.isOne();
7558 AllDivisorsAreOnes &= D.isOne();
7559
7560 // Decompose D into D0 * 2^K
7561 unsigned K = D.countr_zero();
7562 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7563 APInt D0 = D.lshr(K);
7564
7565 // D is even if it has trailing zeros.
7566 HadEvenDivisor |= (K != 0);
7567
7568 // D is a power-of-two if D0 is one. This includes INT_MIN.
7569 // If all divisors are power-of-two, we will prefer to avoid the fold.
7570 AllDivisorsArePowerOfTwo &= D0.isOne();
7571
7572 // P = inv(D0, 2^W)
7573 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7574 unsigned W = D.getBitWidth();
7575 APInt P = D0.multiplicativeInverse();
7576 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7577
7578 // A = floor((2^(W - 1) - 1) / D0) & -2^K
7579 APInt A = APInt::getSignedMaxValue(W).udiv(D0);
7580 A.clearLowBits(K);
7581
7582 // Q = floor((2 * A) / (2^K))
7583 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
7584
7586 "We are expecting that A is always less than all-ones for SVT");
7588 "We are expecting that K is always less than all-ones for ShSVT");
7589
7590 // If D was a power of two, apply the alternate constant derivation.
7591 if (D0.isOne()) {
7592 // A = 0
7593 A = APInt(W, 0);
7594 // - Q = 2^(W-K) - 1
7595 Q = APInt::getLowBitsSet(W, W - K);
7596 }
7597
7598 // If the divisor is 1 the result can be constant-folded.
7599 if (D.isOne()) {
7600 // Set P, A and K to a bogus values so we can try to splat them.
7601 P = 0;
7602 A.setAllBits();
7603 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7604
7605 // x ?% 1 == 0 <--> true <--> x u<= -1
7606 Q.setAllBits();
7607 } else {
7608 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7609 }
7610
7611 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7612 AAmts.push_back(DAG.getConstant(A, DL, SVT));
7613 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7614 return true;
7615 };
7616
7617 SDValue N = REMNode.getOperand(0);
7618 SDValue D = REMNode.getOperand(1);
7619
7620 // Collect the values from each element.
7621 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
7622 return SDValue();
7623
7624 // If this is a srem by a one, avoid the fold since it can be constant-folded.
7625 if (AllDivisorsAreOnes)
7626 return SDValue();
7627
7628 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
7629 // since it can be best implemented as a bit test.
7630 if (AllDivisorsArePowerOfTwo)
7631 return SDValue();
7632
7633 SDValue PVal, AVal, KVal, QVal;
7634 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7635 if (HadOneDivisor) {
7636 // Try to turn PAmts into a splat, since we don't care about the values
7637 // that are currently '0'. If we can't, just keep '0'`s.
7639 // Try to turn AAmts into a splat, since we don't care about the
7640 // values that are currently '-1'. If we can't, change them to '0'`s.
7642 DAG.getConstant(0, DL, SVT));
7643 // Try to turn KAmts into a splat, since we don't care about the values
7644 // that are currently '-1'. If we can't, change them to '0'`s.
7646 DAG.getConstant(0, DL, ShSVT));
7647 }
7648
7649 PVal = DAG.getBuildVector(VT, DL, PAmts);
7650 AVal = DAG.getBuildVector(VT, DL, AAmts);
7651 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7652 QVal = DAG.getBuildVector(VT, DL, QAmts);
7653 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7654 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
7655 QAmts.size() == 1 &&
7656 "Expected matchUnaryPredicate to return one element for scalable "
7657 "vectors");
7658 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7659 AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
7660 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7661 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7662 } else {
7663 assert(isa<ConstantSDNode>(D) && "Expected a constant");
7664 PVal = PAmts[0];
7665 AVal = AAmts[0];
7666 KVal = KAmts[0];
7667 QVal = QAmts[0];
7668 }
7669
7670 // (mul N, P)
7671 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7672 Created.push_back(Op0.getNode());
7673
7674 // We need ADD to do this.
7675 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
7676 return SDValue();
7677
7678 // (add (mul N, P), A)
7679 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
7680 Created.push_back(Op0.getNode());
7681
7682 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7683 // divisors as a performance improvement, since rotating by 0 is a no-op.
7684 if (HadEvenDivisor) {
7685 // We need ROTR to do this.
7686 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7687 return SDValue();
7688 // SREM: (rotr (add (mul N, P), A), K)
7689 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7690 Created.push_back(Op0.getNode());
7691 }
7692
7693 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
7694 return DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7696}
7697
7699 const DenormalMode &Mode,
7700 SDNodeFlags Flags) const {
7701 SDLoc DL(Op);
7702 EVT VT = Op.getValueType();
7703 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7704 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
7705
7706 // This is specifically a check for the handling of denormal inputs, not the
7707 // result.
7708 if (Mode.Input == DenormalMode::PreserveSign ||
7709 Mode.Input == DenormalMode::PositiveZero) {
7710 // Test = X == 0.0
7711 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ, /*Chain=*/{},
7712 /*Signaling=*/false, Flags);
7713 }
7714
7715 // Testing it with denormal inputs to avoid wrong estimate.
7716 //
7717 // Test = fabs(X) < SmallestNormal
7718 const fltSemantics &FltSem = VT.getFltSemantics();
7719 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
7720 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
7721 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op, Flags);
7722 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT, /*Chain=*/{},
7723 /*Signaling=*/false, Flags);
7724}
7725
7727 bool LegalOps, bool OptForSize,
7729 unsigned Depth) const {
7730 // fneg is removable even if it has multiple uses.
7731 if (Op.getOpcode() == ISD::FNEG) {
7733 return Op.getOperand(0);
7734 }
7735
7736 // Don't recurse exponentially.
7738 return SDValue();
7739
7740 // Pre-increment recursion depth for use in recursive calls.
7741 ++Depth;
7742 const SDNodeFlags Flags = Op->getFlags();
7743 EVT VT = Op.getValueType();
7744 unsigned Opcode = Op.getOpcode();
7745
7746 // Don't allow anything with multiple uses unless we know it is free.
7747 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
7748 bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
7749 isFPExtFree(VT, Op.getOperand(0).getValueType());
7750 if (!IsFreeExtend)
7751 return SDValue();
7752 }
7753
7754 auto RemoveDeadNode = [&](SDValue N) {
7755 if (N && N.getNode()->use_empty())
7756 DAG.RemoveDeadNode(N.getNode());
7757 };
7758
7759 SDLoc DL(Op);
7760
7761 // Because getNegatedExpression can delete nodes we need a handle to keep
7762 // temporary nodes alive in case the recursion manages to create an identical
7763 // node.
7764 std::list<HandleSDNode> Handles;
7765
7766 switch (Opcode) {
7767 case ISD::ConstantFP: {
7768 // Don't invert constant FP values after legalization unless the target says
7769 // the negated constant is legal.
7770 bool IsOpLegal =
7772 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
7773 OptForSize);
7774
7775 if (LegalOps && !IsOpLegal)
7776 break;
7777
7778 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
7779 V.changeSign();
7780 SDValue CFP = DAG.getConstantFP(V, DL, VT);
7781
7782 // If we already have the use of the negated floating constant, it is free
7783 // to negate it even it has multiple uses.
7784 if (!Op.hasOneUse() && CFP.use_empty())
7785 break;
7787 return CFP;
7788 }
7789 case ISD::SPLAT_VECTOR: {
7790 // fold splat_vector(fneg(X)) -> splat_vector(-X)
7791 SDValue X = Op.getOperand(0);
7793 break;
7794
7795 SDValue NegX = getCheaperNegatedExpression(X, DAG, LegalOps, OptForSize);
7796 if (!NegX)
7797 break;
7799 return DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, NegX);
7800 }
7801 case ISD::BUILD_VECTOR: {
7802 // Only permit BUILD_VECTOR of constants.
7803 if (llvm::any_of(Op->op_values(), [&](SDValue N) {
7804 return !N.isUndef() && !isa<ConstantFPSDNode>(N);
7805 }))
7806 break;
7807
7808 bool IsOpLegal =
7811 llvm::all_of(Op->op_values(), [&](SDValue N) {
7812 return N.isUndef() ||
7813 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
7814 OptForSize);
7815 });
7816
7817 if (LegalOps && !IsOpLegal)
7818 break;
7819
7821 for (SDValue C : Op->op_values()) {
7822 if (C.isUndef()) {
7823 Ops.push_back(C);
7824 continue;
7825 }
7826 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
7827 V.changeSign();
7828 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
7829 }
7831 return DAG.getBuildVector(VT, DL, Ops);
7832 }
7833 case ISD::FADD: {
7834 if (!Flags.hasNoSignedZeros())
7835 break;
7836
7837 // After operation legalization, it might not be legal to create new FSUBs.
7838 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
7839 break;
7840 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7841
7842 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
7844 SDValue NegX =
7845 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
7846 // Prevent this node from being deleted by the next call.
7847 if (NegX)
7848 Handles.emplace_back(NegX);
7849
7850 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
7852 SDValue NegY =
7853 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
7854
7855 // We're done with the handles.
7856 Handles.clear();
7857
7858 // Negate the X if its cost is less or equal than Y.
7859 if (NegX && (CostX <= CostY)) {
7860 Cost = CostX;
7861 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
7862 if (NegY != N)
7863 RemoveDeadNode(NegY);
7864 return N;
7865 }
7866
7867 // Negate the Y if it is not expensive.
7868 if (NegY) {
7869 Cost = CostY;
7870 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
7871 if (NegX != N)
7872 RemoveDeadNode(NegX);
7873 return N;
7874 }
7875 break;
7876 }
7877 case ISD::FSUB: {
7878 // We can't turn -(A-B) into B-A when we honor signed zeros.
7879 if (!Flags.hasNoSignedZeros())
7880 break;
7881
7882 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7883 // fold (fneg (fsub 0, Y)) -> Y
7884 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
7885 if (C->isZero()) {
7887 return Y;
7888 }
7889
7890 // fold (fneg (fsub X, Y)) -> (fsub Y, X)
7892 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
7893 }
7894 case ISD::FMUL:
7895 case ISD::FDIV: {
7896 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7897
7898 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
7900 SDValue NegX =
7901 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
7902 // Prevent this node from being deleted by the next call.
7903 if (NegX)
7904 Handles.emplace_back(NegX);
7905
7906 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
7908 SDValue NegY =
7909 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
7910
7911 // We're done with the handles.
7912 Handles.clear();
7913
7914 // Negate the X if its cost is less or equal than Y.
7915 if (NegX && (CostX <= CostY)) {
7916 Cost = CostX;
7917 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
7918 if (NegY != N)
7919 RemoveDeadNode(NegY);
7920 return N;
7921 }
7922
7923 // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
7924 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
7925 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
7926 break;
7927
7928 // Negate the Y if it is not expensive.
7929 if (NegY) {
7930 Cost = CostY;
7931 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
7932 if (NegX != N)
7933 RemoveDeadNode(NegX);
7934 return N;
7935 }
7936 break;
7937 }
7938 case ISD::FMA:
7939 case ISD::FMULADD:
7940 case ISD::FMAD: {
7941 if (!Flags.hasNoSignedZeros())
7942 break;
7943
7944 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
7946 SDValue NegZ =
7947 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
7948 // Give up if fail to negate the Z.
7949 if (!NegZ)
7950 break;
7951
7952 // Prevent this node from being deleted by the next two calls.
7953 Handles.emplace_back(NegZ);
7954
7955 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
7957 SDValue NegX =
7958 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
7959 // Prevent this node from being deleted by the next call.
7960 if (NegX)
7961 Handles.emplace_back(NegX);
7962
7963 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
7965 SDValue NegY =
7966 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
7967
7968 // We're done with the handles.
7969 Handles.clear();
7970
7971 // Negate the X if its cost is less or equal than Y.
7972 if (NegX && (CostX <= CostY)) {
7973 Cost = std::min(CostX, CostZ);
7974 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
7975 if (NegY != N)
7976 RemoveDeadNode(NegY);
7977 return N;
7978 }
7979
7980 // Negate the Y if it is not expensive.
7981 if (NegY) {
7982 Cost = std::min(CostY, CostZ);
7983 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
7984 if (NegX != N)
7985 RemoveDeadNode(NegX);
7986 return N;
7987 }
7988 break;
7989 }
7990
7991 case ISD::FP_EXTEND:
7992 case ISD::FSIN:
7993 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
7994 OptForSize, Cost, Depth))
7995 return DAG.getNode(Opcode, DL, VT, NegV);
7996 break;
7997 case ISD::FP_ROUND:
7998 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
7999 OptForSize, Cost, Depth))
8000 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
8001 break;
8002 case ISD::SELECT:
8003 case ISD::VSELECT: {
8004 // fold (fneg (select C, LHS, RHS)) -> (select C, (fneg LHS), (fneg RHS))
8005 // iff at least one cost is cheaper and the other is neutral/cheaper
8006 SDValue LHS = Op.getOperand(1);
8008 SDValue NegLHS =
8009 getNegatedExpression(LHS, DAG, LegalOps, OptForSize, CostLHS, Depth);
8010 if (!NegLHS || CostLHS > NegatibleCost::Neutral) {
8011 RemoveDeadNode(NegLHS);
8012 break;
8013 }
8014
8015 // Prevent this node from being deleted by the next call.
8016 Handles.emplace_back(NegLHS);
8017
8018 SDValue RHS = Op.getOperand(2);
8020 SDValue NegRHS =
8021 getNegatedExpression(RHS, DAG, LegalOps, OptForSize, CostRHS, Depth);
8022
8023 // We're done with the handles.
8024 Handles.clear();
8025
8026 if (!NegRHS || CostRHS > NegatibleCost::Neutral ||
8027 (CostLHS != NegatibleCost::Cheaper &&
8028 CostRHS != NegatibleCost::Cheaper)) {
8029 RemoveDeadNode(NegLHS);
8030 RemoveDeadNode(NegRHS);
8031 break;
8032 }
8033
8034 Cost = std::min(CostLHS, CostRHS);
8035 return DAG.getSelect(DL, VT, Op.getOperand(0), NegLHS, NegRHS);
8036 }
8037 }
8038
8039 return SDValue();
8040}
8041
8042//===----------------------------------------------------------------------===//
8043// Legalization Utilities
8044//===----------------------------------------------------------------------===//
8045
8046bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
8047 SDValue LHS, SDValue RHS,
8049 EVT HiLoVT, SelectionDAG &DAG,
8050 MulExpansionKind Kind, SDValue LL,
8051 SDValue LH, SDValue RL, SDValue RH) const {
8052 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
8053 Opcode == ISD::SMUL_LOHI);
8054
8055 bool HasMULHS = (Kind == MulExpansionKind::Always) ||
8057 bool HasMULHU = (Kind == MulExpansionKind::Always) ||
8059 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8061 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8063
8064 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
8065 return false;
8066
8067 unsigned OuterBitSize = VT.getScalarSizeInBits();
8068 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
8069
8070 // LL, LH, RL, and RH must be either all NULL or all set to a value.
8071 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
8072 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
8073
8074 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
8075 bool Signed) -> bool {
8076 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
8077 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
8078 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
8079 Hi = Lo.getValue(1);
8080 return true;
8081 }
8082 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
8083 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
8084 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
8085 return true;
8086 }
8087 return false;
8088 };
8089
8090 SDValue Lo, Hi;
8091
8092 if (!LL.getNode() && !RL.getNode() &&
8094 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
8095 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
8096 }
8097
8098 if (!LL.getNode())
8099 return false;
8100
8101 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
8102 if (DAG.MaskedValueIsZero(LHS, HighMask) &&
8103 DAG.MaskedValueIsZero(RHS, HighMask)) {
8104 // The inputs are both zero-extended.
8105 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
8106 Result.push_back(Lo);
8107 Result.push_back(Hi);
8108 if (Opcode != ISD::MUL) {
8109 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8110 Result.push_back(Zero);
8111 Result.push_back(Zero);
8112 }
8113 return true;
8114 }
8115 }
8116
8117 if (!VT.isVector() && Opcode == ISD::MUL &&
8118 DAG.ComputeMaxSignificantBits(LHS) <= InnerBitSize &&
8119 DAG.ComputeMaxSignificantBits(RHS) <= InnerBitSize) {
8120 // The input values are both sign-extended.
8121 // TODO non-MUL case?
8122 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
8123 Result.push_back(Lo);
8124 Result.push_back(Hi);
8125 return true;
8126 }
8127 }
8128
8129 unsigned ShiftAmount = OuterBitSize - InnerBitSize;
8130 SDValue Shift = DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
8131
8132 if (!LH.getNode() && !RH.getNode() &&
8135 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
8136 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
8137 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
8138 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
8139 }
8140
8141 if (!LH.getNode())
8142 return false;
8143
8144 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
8145 return false;
8146
8147 Result.push_back(Lo);
8148
8149 if (Opcode == ISD::MUL) {
8150 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
8151 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
8152 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
8153 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
8154 Result.push_back(Hi);
8155 return true;
8156 }
8157
8158 // Compute the full width result.
8159 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
8160 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
8161 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8162 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
8163 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
8164 };
8165
8166 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8167 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
8168 return false;
8169
8170 // This is effectively the add part of a multiply-add of half-sized operands,
8171 // so it cannot overflow.
8172 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8173
8174 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
8175 return false;
8176
8177 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8178 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8179
8180 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
8182 if (UseGlue)
8183 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
8184 Merge(Lo, Hi));
8185 else
8186 Next = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(VT, BoolType), Next,
8187 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
8188
8189 SDValue Carry = Next.getValue(1);
8190 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8191 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8192
8193 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
8194 return false;
8195
8196 if (UseGlue)
8197 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
8198 Carry);
8199 else
8200 Hi = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
8201 Zero, Carry);
8202
8203 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8204
8205 if (Opcode == ISD::SMUL_LOHI) {
8206 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8207 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
8208 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
8209
8210 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8211 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
8212 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
8213 }
8214
8215 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8216 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8217 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8218 return true;
8219}
8220
8222 SelectionDAG &DAG, MulExpansionKind Kind,
8223 SDValue LL, SDValue LH, SDValue RL,
8224 SDValue RH) const {
8226 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
8227 N->getOperand(0), N->getOperand(1), Result, HiLoVT,
8228 DAG, Kind, LL, LH, RL, RH);
8229 if (Ok) {
8230 assert(Result.size() == 2);
8231 Lo = Result[0];
8232 Hi = Result[1];
8233 }
8234 return Ok;
8235}
8236
8237// Optimize unsigned division or remainder by constants for types twice as large
8238// as a legal VT.
8239//
8240// If (1 << (BitWidth / 2)) % Constant == 1, then the remainder
8241// can be computed
8242// as:
8243// Sum = __builtin_uadd_overflow(Lo, High, &Sum);
8244// Remainder = Sum % Constant;
8245//
8246// If (1 << (BitWidth / 2)) % Constant != 1, we can search for a smaller value
8247// W such that W != (BitWidth / 2) and (1 << W) % Constant == 1. We can break
8248// High:Low into 3 chunks of W bits and compute remainder as
8249// Sum = Chunk0 + Chunk1 + Chunk2;
8250// Remainder = Sum % Constant;
8251//
8252// This is based on "Remainder by Summing Digits" from Hacker's Delight.
8253//
8254// For division, we can compute the remainder using the algorithm described
8255// above, subtract it from the dividend to get an exact multiple of Constant.
8256// Then multiply that exact multiply by the multiplicative inverse modulo
8257// (1 << (BitWidth / 2)) to get the quotient.
8258
8259// If Constant is even, we can shift right the dividend and the divisor by the
8260// number of trailing zeros in Constant before applying the remainder algorithm.
8261// If we're after the quotient, we can subtract this value from the shifted
8262// dividend and multiply by the multiplicative inverse of the shifted divisor.
8263// If we want the remainder, we shift the value left by the number of trailing
8264// zeros and add the bits that were shifted out of the dividend.
8265bool TargetLowering::expandUDIVREMByConstantViaUREMDecomposition(
8266 SDNode *N, APInt Divisor, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
8267 SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8268 unsigned Opcode = N->getOpcode();
8269 EVT VT = N->getValueType(0);
8270
8271 unsigned BitWidth = Divisor.getBitWidth();
8272 unsigned HBitWidth = BitWidth / 2;
8274 HiLoVT.getScalarSizeInBits() == HBitWidth && "Unexpected VTs");
8275
8276 // If the divisor is even, shift it until it becomes odd.
8277 unsigned TrailingZeros = 0;
8278 if (!Divisor[0]) {
8279 TrailingZeros = Divisor.countr_zero();
8280 Divisor.lshrInPlace(TrailingZeros);
8281 }
8282
8283 // After removing trailing zeros, the divisor needs to be less than
8284 // (1 << HBitWidth).
8285 APInt HalfMaxPlus1 = APInt::getOneBitSet(BitWidth, HBitWidth);
8286 if (Divisor.uge(HalfMaxPlus1))
8287 return false;
8288
8289 // Look for the largest chunk width W such that (1 << W) % Divisor == 1 or
8290 // (1 << W) % Divisor == -1.
8291 unsigned BestChunkWidth = 0, AltChunkWidth = 0;
8292 for (unsigned I = HBitWidth, E = HBitWidth / 2; I > E; --I) {
8293 // Skip HBitWidth-1, it doesn't have enough bits for carries.
8294 if (I == HBitWidth - 1)
8295 continue;
8296
8297 APInt Mod = APInt::getOneBitSet(Divisor.getBitWidth(), I).urem(Divisor);
8298
8299 if (Mod.isOne()) {
8300 BestChunkWidth = I;
8301 break;
8302 }
8303
8304 // We have an alternate strategy for Remainder == Divisor - 1.
8305 // FIXME: Support HBitWidth.
8306 if (I != HBitWidth && Mod == Divisor - 1)
8307 AltChunkWidth = I;
8308 }
8309
8310 bool Alternate = false;
8311 if (!BestChunkWidth) {
8312 if (!AltChunkWidth)
8313 return false;
8314 Alternate = true;
8315 BestChunkWidth = AltChunkWidth;
8316 }
8317
8318 SDLoc dl(N);
8319
8320 assert(!LL == !LH && "Expected both input halves or no input halves!");
8321 if (!LL)
8322 std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT);
8323
8324 bool HasFSHR = isOperationLegal(ISD::FSHR, HiLoVT);
8325
8326 auto GetFSHR = [&](SDValue Lo, SDValue Hi, unsigned ShiftAmt) {
8327 assert(ShiftAmt > 0 && ShiftAmt < HBitWidth);
8328 if (HasFSHR)
8329 return DAG.getNode(ISD::FSHR, dl, HiLoVT, Hi, Lo,
8330 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8331 return DAG.getNode(
8332 ISD::OR, dl, HiLoVT,
8333 DAG.getNode(ISD::SRL, dl, HiLoVT, Lo,
8334 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl)),
8335 DAG.getNode(
8336 ISD::SHL, dl, HiLoVT, Hi,
8337 DAG.getShiftAmountConstant(HBitWidth - ShiftAmt, HiLoVT, dl)));
8338 };
8339
8340 // Helper to perform a right shift on a 128-bit value split into two halves.
8341 // Handles shifts >= HBitWidth by moving Hi to Lo and shifting Hi.
8342 auto ShiftRight = [&](SDValue &Lo, SDValue &Hi, unsigned ShiftAmt) {
8343 if (ShiftAmt == 0)
8344 return;
8345 if (ShiftAmt < HBitWidth) {
8346 Lo = GetFSHR(Lo, Hi, ShiftAmt);
8347 Hi = DAG.getNode(ISD::SRL, dl, HiLoVT, Hi,
8348 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8349 } else if (ShiftAmt == HBitWidth) {
8350 Lo = Hi;
8351 Hi = DAG.getConstant(0, dl, HiLoVT);
8352 } else {
8353 Lo = DAG.getNode(
8354 ISD::SRL, dl, HiLoVT, Hi,
8355 DAG.getShiftAmountConstant(ShiftAmt - HBitWidth, HiLoVT, dl));
8356 Hi = DAG.getConstant(0, dl, HiLoVT);
8357 }
8358 };
8359
8360 // Shift the input by the number of TrailingZeros in the divisor. The
8361 // shifted out bits will be added to the remainder later.
8362 SDValue PartialRemL, PartialRemH;
8363 if (TrailingZeros && Opcode != ISD::UDIV) {
8364 // Save the shifted off bits if we need the remainder.
8365 if (TrailingZeros < HBitWidth) {
8366 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
8367 PartialRemL = DAG.getNode(ISD::AND, dl, HiLoVT, LL,
8368 DAG.getConstant(Mask, dl, HiLoVT));
8369 } else if (TrailingZeros == HBitWidth) {
8370 // All of LL is part of the remainder.
8371 PartialRemL = LL;
8372 } else {
8373 // TrailingZeros > HBitWidth: LL and part of LH are the remainder.
8374 PartialRemL = LL;
8375 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros - HBitWidth);
8376 PartialRemH = DAG.getNode(ISD::AND, dl, HiLoVT, LH,
8377 DAG.getConstant(Mask, dl, HiLoVT));
8378 }
8379 }
8380
8381 SDValue Sum;
8382 // If BestChunkWidth is HBitWidth add low and high half. If there is a carry
8383 // out, add that to the final sum.
8384 if (BestChunkWidth == HBitWidth) {
8385 assert(!Alternate);
8386 // Shift LH:LL right if there were trailing zeros in the divisor.
8387 ShiftRight(LL, LH, TrailingZeros);
8388
8389 // Use uaddo_carry if we can, otherwise use a compare to detect overflow.
8390 EVT SetCCType =
8391 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), HiLoVT);
8393 SDVTList VTList = DAG.getVTList(HiLoVT, SetCCType);
8394 Sum = DAG.getNode(ISD::UADDO, dl, VTList, LL, LH);
8395 Sum = DAG.getNode(ISD::UADDO_CARRY, dl, VTList, Sum,
8396 DAG.getConstant(0, dl, HiLoVT), Sum.getValue(1));
8397 } else {
8398 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, LL, LH);
8399 SDValue Carry = DAG.getSetCC(dl, SetCCType, Sum, LL, ISD::SETULT);
8400 // If the boolean for the target is 0 or 1, we can add the setcc result
8401 // directly.
8402 if (getBooleanContents(HiLoVT) ==
8404 Carry = DAG.getZExtOrTrunc(Carry, dl, HiLoVT);
8405 else
8406 Carry = DAG.getSelect(dl, HiLoVT, Carry, DAG.getConstant(1, dl, HiLoVT),
8407 DAG.getConstant(0, dl, HiLoVT));
8408 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, Carry);
8409 }
8410 } else {
8411 // Otherwise split into multple chunks and add them together. We chose
8412 // BestChunkWidth so that the sum will not overflow.
8413 SDValue Mask = DAG.getConstant(
8414 APInt::getLowBitsSet(HBitWidth, BestChunkWidth), dl, HiLoVT);
8415
8416 for (unsigned I = 0; I < BitWidth - TrailingZeros; I += BestChunkWidth) {
8417 // If there were trailing zeros in the divisor, increase the shift amount.
8418 unsigned Shift = I + TrailingZeros;
8419 SDValue Chunk;
8420 if (Shift == 0)
8421 Chunk = LL;
8422 else if (Shift >= HBitWidth)
8423 Chunk = DAG.getNode(
8424 ISD::SRL, dl, HiLoVT, LH,
8425 DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, dl));
8426 else
8427 Chunk = GetFSHR(LL, LH, Shift);
8428 // If we're on the last chunk, we don't need an AND.
8429 if (I + BestChunkWidth < BitWidth - TrailingZeros)
8430 Chunk = DAG.getNode(ISD::AND, dl, HiLoVT, Chunk, Mask);
8431 if (!Sum) {
8432 Sum = Chunk;
8433 } else {
8434 // For Alternate, we need to subtract odd chunks.
8435 unsigned ChunkNum = I / BestChunkWidth;
8436 unsigned Opc = (Alternate && (ChunkNum % 2) != 0) ? ISD::SUB : ISD::ADD;
8437 Sum = DAG.getNode(Opc, dl, HiLoVT, Sum, Chunk);
8438 }
8439 }
8440
8441 // For Alternate, the sum may be negative, but we need a positive sum. We
8442 // can increase it by a multiple of the divisor to make it positive. For 3
8443 // chunks the largest negative value is -(2^BestChunkWidth - 1). For 4
8444 // chunks, it's 2*-(2^BestChunkWidth - 1). We know that 2^BestChunkWidth + 1
8445 // is a multiple of the divisor. Add that 1 or 2 times to make the sum
8446 // positive.
8447 if (Alternate) {
8448 unsigned NumChunks = divideCeil(BitWidth - TrailingZeros, BestChunkWidth);
8449 assert(NumChunks <= 4);
8450
8451 APInt Adjust = APInt::getOneBitSet(HBitWidth, BestChunkWidth);
8452 Adjust.setBit(0);
8453 // If there are 4 chunks, we need to adjust twice.
8454 if (NumChunks == 4)
8455 Adjust <<= 1;
8456 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum,
8457 DAG.getConstant(Adjust, dl, HiLoVT));
8458 }
8459 }
8460
8461 // Perform a HiLoVT urem on the Sum using truncated divisor.
8462 SDValue RemL =
8463 DAG.getNode(ISD::UREM, dl, HiLoVT, Sum,
8464 DAG.getConstant(Divisor.trunc(HBitWidth), dl, HiLoVT));
8465 SDValue RemH = DAG.getConstant(0, dl, HiLoVT);
8466
8467 if (Opcode != ISD::UREM) {
8468 // If we didn't shift LH/LR earlier, do it now.
8469 if (BestChunkWidth != HBitWidth)
8470 ShiftRight(LL, LH, TrailingZeros);
8471
8472 // Subtract the remainder from the shifted dividend.
8473 SDValue Dividend = DAG.getNode(ISD::BUILD_PAIR, dl, VT, LL, LH);
8474 SDValue Rem = DAG.getNode(ISD::BUILD_PAIR, dl, VT, RemL, RemH);
8475
8476 Dividend = DAG.getNode(ISD::SUB, dl, VT, Dividend, Rem);
8477
8478 // Multiply by the multiplicative inverse of the divisor modulo
8479 // (1 << BitWidth).
8480 APInt MulFactor = Divisor.multiplicativeInverse();
8481
8482 SDValue Quotient = DAG.getNode(ISD::MUL, dl, VT, Dividend,
8483 DAG.getConstant(MulFactor, dl, VT));
8484
8485 // Split the quotient into low and high parts.
8486 SDValue QuotL, QuotH;
8487 std::tie(QuotL, QuotH) = DAG.SplitScalar(Quotient, dl, HiLoVT, HiLoVT);
8488 Result.push_back(QuotL);
8489 Result.push_back(QuotH);
8490 }
8491
8492 if (Opcode != ISD::UDIV) {
8493 // If we shifted the input, shift the remainder left and add the bits we
8494 // shifted off the input.
8495 if (TrailingZeros) {
8496 if (TrailingZeros < HBitWidth) {
8497 // Shift RemH:RemL left by TrailingZeros.
8498 // RemH gets the high bits shifted out of RemL.
8499 RemH = DAG.getNode(
8500 ISD::SRL, dl, HiLoVT, RemL,
8501 DAG.getShiftAmountConstant(HBitWidth - TrailingZeros, HiLoVT, dl));
8502 RemL =
8503 DAG.getNode(ISD::SHL, dl, HiLoVT, RemL,
8504 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
8505 // OR in the partial remainder.
8506 RemL = DAG.getNode(ISD::OR, dl, HiLoVT, RemL, PartialRemL,
8508 } else if (TrailingZeros == HBitWidth) {
8509 // Shift left by exactly HBitWidth: RemH becomes RemL, RemL becomes
8510 // PartialRemL.
8511 RemH = RemL;
8512 RemL = PartialRemL;
8513 } else {
8514 // Shift left by more than HBitWidth.
8515 RemH = DAG.getNode(
8516 ISD::SHL, dl, HiLoVT, RemL,
8517 DAG.getShiftAmountConstant(TrailingZeros - HBitWidth, HiLoVT, dl));
8518 RemH = DAG.getNode(ISD::OR, dl, HiLoVT, RemH, PartialRemH,
8520 RemL = PartialRemL;
8521 }
8522 }
8523 Result.push_back(RemL);
8524 Result.push_back(RemH);
8525 }
8526
8527 return true;
8528}
8529
8530bool TargetLowering::expandUDIVREMByConstantViaUMulHiMagic(
8531 SDNode *N, const APInt &Divisor, SmallVectorImpl<SDValue> &Result,
8532 EVT HiLoVT, SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8533
8534 SDValue N0 = N->getOperand(0);
8535 EVT VT = N0->getValueType(0);
8536 SDLoc DL{N};
8537
8538 assert(!Divisor.isOne() && "Magic algorithm does not work for division by 1");
8539
8540 // This helper creates a MUL_LOHI of the pair (LL, LH) by a constant.
8541 auto MakeMUL_LOHIByConst = [&](unsigned Opc, SDValue LL, SDValue LH,
8542 const APInt &Const,
8543 SmallVectorImpl<SDValue> &Result) {
8544 SDValue LHS = DAG.getNode(ISD::BUILD_PAIR, DL, VT, LL, LH);
8545 SDValue RHS = DAG.getConstant(Const, DL, VT);
8546 auto [RL, RH] = DAG.SplitScalar(RHS, DL, HiLoVT, HiLoVT);
8547 return expandMUL_LOHI(Opc, VT, DL, LHS, RHS, Result, HiLoVT, DAG,
8549 LL, LH, RL, RH);
8550 };
8551
8552 // This helper creates an ADD/SUB of the pairs (LL, LH) and (RL, RH).
8553 auto MakeAddSubLong = [&](unsigned Opc, SDValue LL, SDValue LH, SDValue RL,
8554 SDValue RH) {
8555 SDValue AddSubNode =
8557 DAG.getVTList(HiLoVT, MVT::i1), LL, RL);
8558 SDValue OutL = AddSubNode.getValue(0);
8559 SDValue Overflow = AddSubNode.getValue(1);
8560 SDValue AddSubWithOverflow =
8562 DAG.getVTList(HiLoVT, MVT::i1), LH, RH, Overflow);
8563 SDValue OutH = AddSubWithOverflow.getValue(0);
8564 return std::make_pair(OutL, OutH);
8565 };
8566
8567 // This helper creates a SRL of the pair (LL, LH) by Shift.
8568 auto MakeSRLLong = [&](SDValue LL, SDValue LH, unsigned Shift) {
8569 unsigned HBitWidth = HiLoVT.getScalarSizeInBits();
8570 if (Shift < HBitWidth) {
8571 SDValue ShAmt = DAG.getShiftAmountConstant(Shift, HiLoVT, DL);
8572 SDValue ResL = DAG.getNode(ISD::FSHR, DL, HiLoVT, LH, LL, ShAmt);
8573 SDValue ResH = DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt);
8574 return std::make_pair(ResL, ResH);
8575 }
8576 SDValue Zero = DAG.getConstant(0, DL, HiLoVT);
8577 if (Shift == HBitWidth)
8578 return std::make_pair(LH, Zero);
8579 assert(Shift - HBitWidth < HBitWidth &&
8580 "We shouldn't generate an undefined shift");
8581 SDValue ShAmt = DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, DL);
8582 return std::make_pair(DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt), Zero);
8583 };
8584
8585 // Knowledge of leading zeros may help to reduce the multiplier.
8586 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
8587
8588 UnsignedDivisionByConstantInfo Magics = UnsignedDivisionByConstantInfo::get(
8589 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()));
8590
8591 assert(!LL == !LH && "Expected both input halves or no input halves!");
8592 if (!LL)
8593 std::tie(LL, LH) = DAG.SplitScalar(N0, DL, HiLoVT, HiLoVT);
8594 SDValue QL = LL;
8595 SDValue QH = LH;
8596 if (Magics.PreShift != 0)
8597 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PreShift);
8598
8599 SmallVector<SDValue, 4> UMulResult;
8600 if (!MakeMUL_LOHIByConst(ISD::UMUL_LOHI, QL, QH, Magics.Magic, UMulResult))
8601 return false;
8602
8603 QL = UMulResult[2];
8604 QH = UMulResult[3];
8605
8606 if (Magics.IsAdd) {
8607 auto [NPQL, NPQH] = MakeAddSubLong(ISD::SUB, LL, LH, QL, QH);
8608 std::tie(NPQL, NPQH) = MakeSRLLong(NPQL, NPQH, 1);
8609 std::tie(QL, QH) = MakeAddSubLong(ISD::ADD, NPQL, NPQH, QL, QH);
8610 }
8611
8612 if (Magics.PostShift != 0)
8613 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PostShift);
8614
8615 unsigned Opcode = N->getOpcode();
8616 if (Opcode != ISD::UREM) {
8617 Result.push_back(QL);
8618 Result.push_back(QH);
8619 }
8620
8621 if (Opcode != ISD::UDIV) {
8622 SmallVector<SDValue, 2> MulResult;
8623 if (!MakeMUL_LOHIByConst(ISD::MUL, QL, QH, Divisor, MulResult))
8624 return false;
8625
8626 assert(MulResult.size() == 2);
8627
8628 auto [RemL, RemH] =
8629 MakeAddSubLong(ISD::SUB, LL, LH, MulResult[0], MulResult[1]);
8630
8631 Result.push_back(RemL);
8632 Result.push_back(RemH);
8633 }
8634
8635 return true;
8636}
8637
8640 EVT HiLoVT, SelectionDAG &DAG,
8641 SDValue LL, SDValue LH) const {
8642 unsigned Opcode = N->getOpcode();
8643
8644 // TODO: Support signed division/remainder.
8645 if (Opcode == ISD::SREM || Opcode == ISD::SDIV || Opcode == ISD::SDIVREM)
8646 return false;
8647 assert(
8648 (Opcode == ISD::UREM || Opcode == ISD::UDIV || Opcode == ISD::UDIVREM) &&
8649 "Unexpected opcode");
8650
8651 auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(1));
8652 if (!CN)
8653 return false;
8654
8655 APInt Divisor = CN->getAPIntValue();
8656
8657 // The generated half-width UREM is normally optimized using high multiply.
8658 // If the wide UREM libcall is unavailable, a legal or custom half-width
8659 // UDIVREM can lower it instead.
8660 bool CanDecomposeUREMWithoutMulHi =
8661 Opcode == ISD::UREM &&
8662 getLibcallImpl(RTLIB::getUREM(N->getValueType(0))) ==
8663 RTLIB::Unsupported &&
8665 if (!CanDecomposeUREMWithoutMulHi &&
8668 return false;
8669
8670 // Prefer the smaller libcall when one is available.
8671 if (DAG.shouldOptForSize() && !CanDecomposeUREMWithoutMulHi)
8672 return false;
8673
8674 // Early out for 0 or 1 divisors.
8675 if (Divisor.ule(1))
8676 return false;
8677
8678 if (expandUDIVREMByConstantViaUREMDecomposition(N, Divisor, Result, HiLoVT,
8679 DAG, LL, LH))
8680 return true;
8681
8682 if (expandUDIVREMByConstantViaUMulHiMagic(N, Divisor, Result, HiLoVT, DAG, LL,
8683 LH))
8684 return true;
8685
8686 return false;
8687}
8688
8689// Check that (every element of) Z is undef or not an exact multiple of BW.
8690static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
8692 Z,
8693 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
8694 /*AllowUndefs=*/true, /*AllowTruncation=*/true);
8695}
8696
8698 SelectionDAG &DAG) const {
8699 EVT VT = Node->getValueType(0);
8700
8701 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
8705 return SDValue();
8706
8707 SDValue X = Node->getOperand(0);
8708 SDValue Y = Node->getOperand(1);
8709 SDValue Z = Node->getOperand(2);
8710
8711 unsigned BW = VT.getScalarSizeInBits();
8712 bool IsFSHL = Node->getOpcode() == ISD::FSHL;
8713 SDLoc DL(SDValue(Node, 0));
8714
8715 EVT ShVT = Z.getValueType();
8716
8717 // If a funnel shift in the other direction is more supported, use it.
8718 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
8719 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
8720 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
8721 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
8722 // fshl X, Y, Z -> fshr X, Y, -Z
8723 // fshr X, Y, Z -> fshl X, Y, -Z
8724 Z = DAG.getNegative(Z, DL, ShVT);
8725 } else {
8726 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
8727 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
8728 SDValue One = DAG.getConstant(1, DL, ShVT);
8729 if (IsFSHL) {
8730 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
8731 X = DAG.getNode(ISD::SRL, DL, VT, X, One);
8732 } else {
8733 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
8734 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
8735 }
8736 Z = DAG.getNOT(DL, Z, ShVT);
8737 }
8738 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
8739 }
8740
8741 SDValue ShX, ShY;
8742 SDValue ShAmt, InvShAmt;
8743 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
8744 // fshl: X << C | Y >> (BW - C)
8745 // fshr: X << (BW - C) | Y >> C
8746 // where C = Z % BW is not zero
8747 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
8748 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
8749 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
8750 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
8751 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
8752 } else {
8753 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
8754 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
8755 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
8756 if (isPowerOf2_32(BW)) {
8757 // Z % BW -> Z & (BW - 1)
8758 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
8759 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
8760 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
8761 } else {
8762 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
8763 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
8764 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
8765 }
8766
8767 SDValue One = DAG.getConstant(1, DL, ShVT);
8768 if (IsFSHL) {
8769 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
8770 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
8771 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
8772 } else {
8773 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
8774 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
8775 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
8776 }
8777 }
8778 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
8779}
8780
8781// TODO: Merge with expandFunnelShift.
8783 SelectionDAG &DAG) const {
8784 EVT VT = Node->getValueType(0);
8785 unsigned EltSizeInBits = VT.getScalarSizeInBits();
8786 bool IsLeft = Node->getOpcode() == ISD::ROTL;
8787 SDValue Op0 = Node->getOperand(0);
8788 SDValue Op1 = Node->getOperand(1);
8789 SDLoc DL(SDValue(Node, 0));
8790
8791 EVT ShVT = Op1.getValueType();
8792 SDValue Zero = DAG.getConstant(0, DL, ShVT);
8793
8794 // If a rotate in the other direction is more supported, use it.
8795 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
8796 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
8797 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
8798 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
8799 return DAG.getNode(RevRot, DL, VT, Op0, Sub);
8800 }
8801
8802 if (!AllowVectorOps && VT.isVector() &&
8808 return SDValue();
8809
8810 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
8811 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
8812 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
8813 SDValue ShVal;
8814 SDValue HsVal;
8815 if (isPowerOf2_32(EltSizeInBits)) {
8816 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
8817 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
8818 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
8819 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
8820 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
8821 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
8822 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
8823 } else {
8824 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
8825 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
8826 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
8827 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
8828 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
8829 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
8830 SDValue One = DAG.getConstant(1, DL, ShVT);
8831 HsVal =
8832 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
8833 }
8834 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
8835}
8836
8837/// Check if CLMUL on VT can eventually reach a type with legal CLMUL through
8838/// a chain of halving decompositions (halving element width) and/or vector
8839/// widening (doubling element count). This guides expansion strategy selection:
8840/// if true, the halving/widening path produces better code than bit-by-bit.
8841///
8842/// HalveDepth tracks halving steps only (each creates ~4x more operations).
8843/// Widening steps are cheap (O(1) pad/extract) and don't count.
8844/// Limiting halvings to 2 prevents exponential blowup:
8845/// 1 halving: ~4 sub-CLMULs (good, e.g. v8i16 -> v8i8)
8846/// 2 halvings: ~16 sub-CLMULs (acceptable, e.g. v4i32 -> v4i16 -> v8i8)
8847/// 3 halvings: ~64 sub-CLMULs (worse than bit-by-bit expansion)
8849 EVT VT, unsigned HalveDepth = 0,
8850 unsigned TotalDepth = 0) {
8851 if (HalveDepth > 2 || TotalDepth > 8 || !VT.isFixedLengthVector())
8852 return false;
8854 return true;
8855 if (!TLI.isTypeLegal(VT))
8856 return false;
8857
8858 unsigned BW = VT.getScalarSizeInBits();
8859
8860 // Halve: halve element width, same element count.
8861 // This is the expensive step -- each halving creates ~4x more operations.
8862 if (BW % 2 == 0) {
8863 EVT HalfEltVT = EVT::getIntegerVT(Ctx, BW / 2);
8864 EVT HalfVT = VT.changeVectorElementType(Ctx, HalfEltVT);
8865 if (TLI.isTypeLegal(HalfVT) &&
8866 canNarrowCLMULToLegal(TLI, Ctx, HalfVT, HalveDepth + 1, TotalDepth + 1))
8867 return true;
8868 }
8869
8870 // Widen: double element count (fixed-width vectors only).
8871 // This is cheap -- just INSERT_SUBVECTOR + EXTRACT_SUBVECTOR.
8872 EVT WideVT = VT.getDoubleNumVectorElementsVT(Ctx);
8873 if (TLI.isTypeLegal(WideVT) &&
8874 canNarrowCLMULToLegal(TLI, Ctx, WideVT, HalveDepth, TotalDepth + 1))
8875 return true;
8876
8877 return false;
8878}
8879
8881 SDLoc DL(Node);
8882 EVT VT = Node->getValueType(0);
8883 SDValue X = Node->getOperand(0);
8884 SDValue Y = Node->getOperand(1);
8885 unsigned BW = VT.getScalarSizeInBits();
8886 unsigned Opcode = Node->getOpcode();
8887 LLVMContext &Ctx = *DAG.getContext();
8888
8889 switch (Opcode) {
8890 case ISD::CLMUL: {
8891 // For vector types, try decomposition strategies that leverage legal
8892 // CLMUL on narrower or wider element types, avoiding the expensive
8893 // bit-by-bit expansion.
8894 if (VT.isVector()) {
8895 // Strategy 1: Halving decomposition to half-element-width CLMUL.
8896 // Applies ExpandIntRes_CLMUL's identity element-wise:
8897 // CLMUL(X, Y) = (Hi << HalfBW) | Lo
8898 // where:
8899 // Lo = CLMUL(XLo, YLo)
8900 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
8901 unsigned HalfBW = BW / 2;
8902 if (BW % 2 == 0) {
8903 EVT HalfEltVT = EVT::getIntegerVT(Ctx, HalfBW);
8904 EVT HalfVT =
8905 EVT::getVectorVT(Ctx, HalfEltVT, VT.getVectorElementCount());
8906 if (isTypeLegal(HalfVT) && canNarrowCLMULToLegal(*this, Ctx, HalfVT,
8907 /*HalveDepth=*/1)) {
8908 SDValue ShAmt = DAG.getShiftAmountConstant(HalfBW, VT, DL);
8909
8910 // Extract low and high halves of each element.
8911 SDValue XLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, X);
8912 SDValue XHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
8913 DAG.getNode(ISD::SRL, DL, VT, X, ShAmt));
8914 SDValue YLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, Y);
8915 SDValue YHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
8916 DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt));
8917
8918 // Lo = CLMUL(XLo, YLo)
8919 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YLo);
8920
8921 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
8922 SDValue LoH = DAG.getNode(ISD::CLMULH, DL, HalfVT, XLo, YLo);
8923 SDValue Cross1 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YHi);
8924 SDValue Cross2 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XHi, YLo);
8925 SDValue Cross = DAG.getNode(ISD::XOR, DL, HalfVT, Cross1, Cross2);
8926 SDValue Hi = DAG.getNode(ISD::XOR, DL, HalfVT, LoH, Cross);
8927
8928 // Reassemble: Result = ZExt(Lo) | (AnyExt(Hi) << HalfBW)
8929 SDValue LoExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo);
8930 SDValue HiExt = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Hi);
8931 SDValue HiShifted = DAG.getNode(ISD::SHL, DL, VT, HiExt, ShAmt);
8932 return DAG.getNode(ISD::OR, DL, VT, LoExt, HiShifted);
8933 }
8934 }
8935
8936 // Strategy 2: Promote to double-element-width CLMUL.
8937 // CLMUL(X, Y) = Trunc(CLMUL(AnyExt(X), AnyExt(Y)))
8938 {
8939 EVT ExtVT = VT.widenIntegerElementType(Ctx);
8940 if (isTypeLegal(ExtVT) && isOperationLegalOrCustom(ISD::CLMUL, ExtVT)) {
8941 // If CLMUL on ExtVT is Custom (not Legal), the target may
8942 // scalarize it, costing O(NumElements) scalar ops. The bit-by-bit
8943 // fallback costs O(BW) vectorized iterations. Only widen when
8944 // element count is small enough that scalarization is cheaper.
8945 unsigned NumElts = VT.getVectorMinNumElements();
8946 if (isOperationLegal(ISD::CLMUL, ExtVT) || NumElts < BW) {
8947 SDValue XExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, X);
8948 SDValue YExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, Y);
8949 SDValue Mul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
8950 return DAG.getNode(ISD::TRUNCATE, DL, VT, Mul);
8951 }
8952 }
8953 }
8954
8955 // Strategy 3: Widen element count (pad with undef, do CLMUL on wider
8956 // vector, extract lower result). CLMUL is element-wise, so upper
8957 // (undef) lanes don't affect the lower results.
8958 // e.g. v4i16 => pad to v8i16 => halve to v8i8 PMUL => extract v4i16.
8959 if (auto EC = VT.getVectorElementCount(); EC.isFixed()) {
8960 EVT WideVT = EVT::getVectorVT(Ctx, VT.getVectorElementType(), EC * 2);
8961 if (isTypeLegal(WideVT) && canNarrowCLMULToLegal(*this, Ctx, WideVT)) {
8962 SDValue Undef = DAG.getUNDEF(WideVT);
8963 SDValue XWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
8964 X, DAG.getVectorIdxConstant(0, DL));
8965 SDValue YWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
8966 Y, DAG.getVectorIdxConstant(0, DL));
8967 SDValue WideRes = DAG.getNode(ISD::CLMUL, DL, WideVT, XWide, YWide);
8968 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WideRes,
8969 DAG.getVectorIdxConstant(0, DL));
8970 }
8971 }
8972 }
8973
8974 // Special case: clmul(X, Y) where Y is a known constant (splat) that forms
8975 // a contiguous block of trailing ones whose length N is a power of two
8976 // (e.g. i8 0xFF, i8 0x0F, ...) or equal to the operand width. In this
8977 // special case, clmul(X, Y) is equivalent to a "parallel prefix XOR" or
8978 // "bitwise parity" operation on X.
8979 //
8980 // Note: This special currently dose NOT apply when the mask is neither a
8981 // power of two nor equal to the operand width because the loop inside
8982 // behaves as if the mask was bit-ceiled, and "undoing" the XOR with parts
8983 // of that CLMUL is a recursive problem (e.g. CLMUL with a 20-bit mask
8984 // requires correction XOR with CLMUL with 12-bit mask).
8985 if (auto *C = isConstOrConstSplat(Y, /*AllowUndefs=*/true)) {
8986 const APInt &YVal = C->getAPIntValue();
8987 unsigned N = YVal.countr_one();
8988 if (YVal.isAllOnes() || (YVal.isMask() && isPowerOf2_32(N))) {
8989 SDValue R = X;
8990 for (unsigned I = 1; I < N; I <<= 1) {
8991 SDValue ShAmt = DAG.getShiftAmountConstant(I, VT, DL);
8992 SDValue Shifted = DAG.getNode(ISD::SHL, DL, VT, R, ShAmt);
8993 R = DAG.getNode(ISD::XOR, DL, VT, R, Shifted);
8994 }
8995 return R;
8996 }
8997 }
8998
8999 // NOTE: If you change this expansion, please update the cost model
9000 // calculation in BasicTTIImpl::getTypeBasedIntrinsicInstrCost for
9001 // Intrinsic::clmul.
9002
9003 // Strategy 4: multiplication with holes.
9004 //
9005 // Uses "holes" (sequences of zeroes) to avoid carry spilling. When carries
9006 // do occur, they wind up in a "hole" and are subsequently masked out of the
9007 // result.
9008 //
9009 // A hole of 3 bits is optimal for 32-bit and 64-bit inputs. 128-bit
9010 // integers need a larger hole, and for smaller integers the fallback below
9011 // is more efficient.
9012 //
9013 // Based on bmul64 in bearssl and bmul in the rust polyval crate.
9014 if (BW >= 32 && BW <= 64 &&
9016
9017 // Set every fourth bit of each nibble, equivalent to 0b00010001...0001.
9018 APInt MaskVal = APInt::getSplat(BW, APInt(4, 0b0001));
9019
9020 // Create versions of X and Y that keep only the I-th bit of
9021 // each nibble.
9022 SDValue M[4], Xp[4], Yp[4];
9023 for (unsigned I = 0; I < 4; ++I) {
9024 M[I] = DAG.getConstant(MaskVal.shl(I), DL, VT);
9025 Xp[I] = DAG.getNode(ISD::AND, DL, VT, X, M[I]);
9026 Yp[I] = DAG.getNode(ISD::AND, DL, VT, Y, M[I]);
9027 }
9028
9029 // Codegens these expressions (16 multiplications):
9030 //
9031 // z0 = (x0 * y0) ^ (x1 * y3) ^ (x2 * y2) ^ (x3 * y1);
9032 // z1 = (x0 * y1) ^ (x1 * y0) ^ (x2 * y3) ^ (x3 * y2);
9033 // z2 = (x0 * y2) ^ (x1 * y1) ^ (x2 * y0) ^ (x3 * y3);
9034 // z3 = (x0 * y3) ^ (x1 * y2) ^ (x2 * y1) ^ (x3 * y0);
9035 SDValue Res = DAG.getConstant(0, DL, VT);
9036 for (unsigned I = 0; I < 4; ++I) {
9037 SDValue Zi = DAG.getConstant(0, DL, VT);
9038 for (unsigned J = 0; J < 4; ++J) {
9039 unsigned K = (I + 4 - J) % 4;
9040 SDValue P = DAG.getNode(ISD::MUL, DL, VT, Xp[J], Yp[K]);
9041 Zi = DAG.getNode(ISD::XOR, DL, VT, Zi, P);
9042 }
9043
9044 // Keep only the bits belonging to this iteration, and bitwise or it all
9045 // together.
9046 Zi = DAG.getNode(ISD::AND, DL, VT, Zi, M[I]);
9047 Res = DAG.getNode(ISD::OR, DL, VT, Res, Zi, SDNodeFlags::Disjoint);
9048 }
9049 return Res;
9050 }
9051
9052 // Strategy 5: the naive fallback.
9053 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
9054
9055 SDValue Res = DAG.getConstant(0, DL, VT);
9056 for (unsigned I = 0; I < BW; ++I) {
9057 SDValue ShiftAmt = DAG.getShiftAmountConstant(I, VT, DL);
9058 SDValue Mask = DAG.getConstant(APInt::getOneBitSet(BW, I), DL, VT);
9059 SDValue YMasked = DAG.getNode(ISD::AND, DL, VT, Y, Mask);
9060
9061 // For targets with a fast bit test instruction (e.g., x86 BT) or without
9062 // multiply, use a shift-based expansion to avoid expensive MUL
9063 // instructions.
9064 SDValue Part;
9065 if (!hasBitTest(Y, ShiftAmt) &&
9068 Part = DAG.getNode(ISD::MUL, DL, VT, X, YMasked);
9069 } else {
9070 // Canonical bit test: (Y & (1 << I)) != 0
9071 SDValue Zero = DAG.getConstant(0, DL, VT);
9072 SDValue Cond = DAG.getSetCC(DL, SetCCVT, YMasked, Zero, ISD::SETEQ);
9073 SDValue XShifted = DAG.getNode(ISD::SHL, DL, VT, X, ShiftAmt);
9074 Part = DAG.getSelect(DL, VT, Cond, Zero, XShifted);
9075 }
9076 Res = DAG.getNode(ISD::XOR, DL, VT, Res, Part);
9077 }
9078 return Res;
9079 }
9080 case ISD::CLMULR:
9081 // If we have CLMUL/CLMULH, merge the shifted results to form CLMULR.
9084 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, VT, X, Y);
9085 SDValue Hi = DAG.getNode(ISD::CLMULH, DL, VT, X, Y);
9086 Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
9087 DAG.getShiftAmountConstant(BW - 1, VT, DL));
9088 Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
9089 DAG.getShiftAmountConstant(1, VT, DL));
9090 return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
9091 }
9092 [[fallthrough]];
9093 case ISD::CLMULH: {
9094 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9095 // Use bitreverse-based lowering (CLMULR/H = rev(CLMUL(rev,rev)) >> S)
9096 // when any of these hold:
9097 // (a) ZERO_EXTEND to ExtVT or SRL on ExtVT isn't legal.
9098 // (b) CLMUL is legal on VT but not on ExtVT (e.g. v8i8 on AArch64).
9099 // (c) CLMUL on ExtVT isn't legal, but CLMUL on VT can be efficiently
9100 // expanded via halving/widening to reach legal CLMUL. The bitreverse
9101 // path creates CLMUL(VT) which will be expanded efficiently. The
9102 // promote path would create CLMUL(ExtVT) => halving => CLMULH(VT),
9103 // causing a cycle.
9104 // Note: when CLMUL is legal on ExtVT, the zext => CLMUL(ExtVT) => shift
9105 // => trunc path is preferred over the bitreverse path, as it avoids the
9106 // cost of 3 bitreverse operations.
9111 canNarrowCLMULToLegal(*this, Ctx, VT)))) {
9112 SDValue XRev = DAG.getNode(ISD::BITREVERSE, DL, VT, X);
9113 SDValue YRev = DAG.getNode(ISD::BITREVERSE, DL, VT, Y);
9114 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, VT, XRev, YRev);
9115 SDValue Res = DAG.getNode(ISD::BITREVERSE, DL, VT, ClMul);
9116 if (Opcode == ISD::CLMULH)
9117 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
9118 DAG.getShiftAmountConstant(1, VT, DL));
9119 return Res;
9120 }
9121 SDValue XExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, X);
9122 SDValue YExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, Y);
9123 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9124 unsigned ShAmt = Opcode == ISD::CLMULR ? BW - 1 : BW;
9125 SDValue HiBits = DAG.getNode(ISD::SRL, DL, ExtVT, ClMul,
9126 DAG.getShiftAmountConstant(ShAmt, ExtVT, DL));
9127 return DAG.getNode(ISD::TRUNCATE, DL, VT, HiBits);
9128 }
9129 }
9130 llvm_unreachable("Expected CLMUL, CLMULR, or CLMULH");
9131}
9132
9134 SDLoc DL(Node);
9135 EVT VT = Node->getValueType(0);
9136 SDValue Val = Node->getOperand(0);
9137 SDValue Msk = Node->getOperand(1);
9138 unsigned BW = VT.getScalarSizeInBits();
9139
9140 // Just scalarize if scalar PEXT is legal
9142 return DAG.UnrollVectorOp(Node);
9143
9144 // Hacker's Delight §7-4: Compress, or Generalized Extract
9145 SDValue X = DAG.getNode(ISD::AND, DL, VT, Val, Msk);
9146 SDValue M = Msk;
9147 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9148 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, M, VT), One);
9149
9150 // Repeatedly compute which bits would shift to the right by an odd amount,
9151 // shift all such bits in parallel using a mask, and double the shift amount.
9152 for (unsigned I = 1; I < BW; I *= 2) {
9153 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9154 SDValue Mp =
9155 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9156 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, M);
9157 SDValue ShiftI = DAG.getShiftAmountConstant(I, VT, DL);
9158 SDValue MvS = DAG.getNode(ISD::SRL, DL, VT, Mv, ShiftI);
9159 M = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, M, Mv), MvS,
9161 SDValue T = DAG.getNode(ISD::AND, DL, VT, X, Mv);
9162 SDValue TS = DAG.getNode(ISD::SRL, DL, VT, T, ShiftI);
9163 X = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, X, T), TS,
9165 if (I * 2 < BW)
9166 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9167 }
9168
9169 return X;
9170}
9171
9173 SDLoc DL(Node);
9174 EVT VT = Node->getValueType(0);
9175 SDValue Val = Node->getOperand(0);
9176 SDValue Msk = Node->getOperand(1);
9177 unsigned BW = VT.getScalarSizeInBits();
9178
9179 // Just scalarize if scalar PDEP is legal
9181 return DAG.UnrollVectorOp(Node);
9182
9183 // Hacker's Delight §7-5: Expand, or Generalized Insert.
9184 unsigned LogBW = Log2_32_Ceil(BW);
9185 SmallVector<SDValue, 8> MvArray(LogBW);
9186 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9187 SDValue Mc = Msk;
9188 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, Msk, VT), One);
9189
9190 // First pass: compute move masks for each power of two that a bit moves by.
9191 for (unsigned S = 0; S < LogBW; ++S) {
9192 unsigned ShiftS = 1u << S;
9193 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9194 SDValue Mp =
9195 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9196 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, Mc);
9197 MvArray[S] = Mv;
9198 if (S + 1 < LogBW) {
9199 SDValue McXorMv = DAG.getNode(ISD::XOR, DL, VT, Mc, Mv);
9200 SDValue MvShifted = DAG.getNode(
9201 ISD::SRL, DL, VT, Mv, DAG.getShiftAmountConstant(ShiftS, VT, DL));
9202 Mc = DAG.getNode(ISD::OR, DL, VT, McXorMv, MvShifted,
9204 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9205 }
9206 }
9207
9208 // Second pass: move bits by 32, 16, 8, 4, 2, 1, using masks, in parallel.
9209 // Each pass handles half the shift amount of the previous pass.
9210 SDValue X = Val;
9211 for (int S = (int)LogBW - 1; S >= 0; --S) {
9212 SDValue ShiftSv = DAG.getShiftAmountConstant(1ull << S, VT, DL);
9213 SDValue T = DAG.getNode(ISD::SHL, DL, VT, X, ShiftSv);
9214 SDValue UnshiftedBits =
9215 DAG.getNode(ISD::AND, DL, VT, X, DAG.getNOT(DL, MvArray[S], VT));
9216 SDValue ShiftedBits = DAG.getNode(ISD::AND, DL, VT, T, MvArray[S]);
9217 X = DAG.getNode(ISD::OR, DL, VT, UnshiftedBits, ShiftedBits,
9219 }
9220
9221 return DAG.getNode(ISD::AND, DL, VT, X, Msk);
9222}
9223
9225 SelectionDAG &DAG) const {
9226 assert(Node->getNumOperands() == 3 && "Not a double-shift!");
9227 EVT VT = Node->getValueType(0);
9228 unsigned VTBits = VT.getScalarSizeInBits();
9229 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
9230
9231 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
9232 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
9233 SDValue ShOpLo = Node->getOperand(0);
9234 SDValue ShOpHi = Node->getOperand(1);
9235 SDValue ShAmt = Node->getOperand(2);
9236 EVT ShAmtVT = ShAmt.getValueType();
9237 EVT ShAmtCCVT =
9238 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
9239 SDLoc dl(Node);
9240
9241 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
9242 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
9243 // away during isel.
9244 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9245 DAG.getConstant(VTBits - 1, dl, ShAmtVT));
9246 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9247 DAG.getConstant(VTBits - 1, dl, ShAmtVT))
9248 : DAG.getConstant(0, dl, VT);
9249
9250 SDValue Tmp2, Tmp3;
9251 if (IsSHL) {
9252 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
9253 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9254 } else {
9255 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
9256 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9257 }
9258
9259 // If the shift amount is larger or equal than the width of a part we don't
9260 // use the result from the FSHL/FSHR. Insert a test and select the appropriate
9261 // values for large shift amounts.
9262 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9263 DAG.getConstant(VTBits, dl, ShAmtVT));
9264 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
9265 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
9266
9267 if (IsSHL) {
9268 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9269 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9270 } else {
9271 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9272 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9273 }
9274}
9275
9277 SelectionDAG &DAG) const {
9278 // This implements llvm.canonicalize.f* by multiplication with 1.0, as
9279 // suggested in
9280 // https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic.
9281 // It uses strict_fp operations even outside a strict_fp context in order
9282 // to guarantee that the canonicalization is not optimized away by later
9283 // passes. The result chain introduced by that is intentionally ignored
9284 // since no ordering requirement is intended here.
9285 EVT VT = Node->getValueType(0);
9286 SDLoc DL(Node);
9287 SDNodeFlags Flags = Node->getFlags();
9288 Flags.setNoFPExcept(true);
9289 SDValue One = DAG.getConstantFP(1.0, DL, VT);
9290 SDValue Mul =
9291 DAG.getNode(ISD::STRICT_FMUL, DL, {VT, MVT::Other},
9292 {DAG.getEntryNode(), Node->getOperand(0), One}, Flags);
9293 return Mul;
9294}
9295
9297 SelectionDAG &DAG) const {
9298 // Expand conversion from a native IEEE float type to an arbitrary FP format
9299 // returning the result as an integer using bit manipulation.
9300 EVT ResVT = Node->getValueType(0);
9301 SDLoc dl(Node);
9302
9303 SDValue FloatVal = Node->getOperand(0);
9304 const uint64_t SemEnum = Node->getConstantOperandVal(1);
9305 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
9306 const auto RoundMode =
9307 static_cast<RoundingMode>(Node->getConstantOperandVal(2));
9308 const bool Saturate = Node->getConstantOperandVal(3) != 0;
9309
9310 // Supported destination formats.
9311 switch (Sem) {
9318 break;
9319 default:
9320 DAG.getContext()->emitError("CONVERT_TO_ARBITRARY_FP: not implemented "
9321 "destination format (semantics enum " +
9322 Twine(SemEnum) + ")");
9323 return SDValue();
9324 }
9325
9326 // Supported rounding modes.
9327 switch (RoundMode) {
9333 break;
9334 default:
9335 DAG.getContext()->emitError(
9336 "CONVERT_TO_ARBITRARY_FP: unsupported rounding mode (enum " +
9337 Twine(static_cast<int>(RoundMode)) + ")");
9338 return SDValue();
9339 }
9340
9341 // Destination format parameters.
9342 const fltSemantics &DstSem = APFloatBase::EnumToSemantics(Sem);
9343 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
9344 const unsigned DstPrecision = APFloat::semanticsPrecision(DstSem);
9345 const unsigned DstMant = DstPrecision - 1;
9346 // Unsigned formats spend no bit on the sign.
9347 const bool DstHasSign = APFloat::semanticsHasSignedRepr(DstSem);
9348 const unsigned DstExpBits = DstBits - (DstHasSign ? 1 : 0) - DstMant;
9349 const int DstBias = 1 - APFloat::semanticsMinExponent(DstSem);
9350 const unsigned DstExpMax = (1U << DstExpBits) - 1;
9351 const uint64_t DstMantMask = (DstMant > 0) ? ((1ULL << DstMant) - 1) : 0;
9352 const fltNonfiniteBehavior DstNFBehavior = DstSem.nonFiniteBehavior;
9353 const fltNanEncoding DstNanEnc = DstSem.nanEncoding;
9354
9355 // Compute the maximum normal exponent for the destination format.
9356 const unsigned DstExpMaxNormal =
9357 DstNFBehavior == fltNonfiniteBehavior::IEEE754 ? DstExpMax - 1
9358 : DstExpMax;
9359
9360 // For NanOnly formats the max exponent field for finite values
9361 // is DstExpMax, but the encoding with exp = DstExpMax and
9362 // mant = all-ones is NaN. So DstExpMaxNormal = DstExpMax, but max
9363 // mantissa at that exponent is DstMantMask - 1 (if NanEnc == AllOnes) to
9364 // avoid the NaN encoding.
9365 uint64_t DstMaxMantAtMaxExp = DstMantMask;
9366 if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9367 DstNanEnc == fltNanEncoding::AllOnes)
9368 DstMaxMantAtMaxExp = DstMantMask - 1;
9369
9370 // Source format parameters.
9371 EVT SrcVT = FloatVal.getValueType();
9372 const fltSemantics &SrcSem = SrcVT.getScalarType().getFltSemantics();
9373 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
9374 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
9375 const unsigned SrcMant = SrcPrecision - 1;
9376 const uint64_t SrcMantMask = (1ULL << SrcMant) - 1;
9377
9378 // Work in the source integer type. Match the destination shape so the
9379 // expansion stays vector when ResVT is a vector.
9380 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), SrcBits);
9381 EVT IntVT = ResVT.changeElementType(*DAG.getContext(), IntScalarVT);
9382 EVT SetCCVT =
9383 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
9384 EVT FPSetCCVT =
9385 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
9386
9387 SDValue Zero = DAG.getConstant(0, dl, IntVT);
9388 SDValue One = DAG.getConstant(1, dl, IntVT);
9389
9390 // Bitcast source float to integer to extract the sign bit.
9391 SDValue Src = DAG.getNode(ISD::BITCAST, dl, IntVT, FloatVal);
9392 SDValue SignBit =
9393 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9394 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl));
9395
9396 // Classify the input.
9397 SDValue FPZero = DAG.getConstantFP(0.0, dl, SrcVT);
9398 SDValue FPInf = DAG.getConstantFP(APFloat::getInf(SrcSem), dl, SrcVT);
9399 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, SrcVT, FloatVal);
9400 SDValue IsNaN = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETUO);
9401 SDValue IsInf = DAG.getSetCC(dl, FPSetCCVT, AbsVal, FPInf, ISD::SETOEQ);
9402 SDValue IsZero = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOEQ);
9403
9404 // Split into a normalized fraction and unbiased exponent. FFREXP normalizes
9405 // source denormals automatically. The result is unspecified for Inf/NaN, but
9406 // those inputs are detected above and override the final result.
9407 EVT FrexpExpScalarVT =
9409 EVT FrexpExpVT = SrcVT.changeElementType(*DAG.getContext(), FrexpExpScalarVT);
9410 SDValue Frexp =
9411 DAG.getNode(ISD::FFREXP, dl, DAG.getVTList(SrcVT, FrexpExpVT), FloatVal);
9412 SDValue FrexpFrac = Frexp.getValue(0);
9413 SDValue FrexpExp = Frexp.getValue(1);
9414
9415 SDValue FrexpFracInt = DAG.getNode(ISD::BITCAST, dl, IntVT, FrexpFrac);
9416 SDValue EffSrcMant = DAG.getNode(ISD::AND, dl, IntVT, FrexpFracInt,
9417 DAG.getConstant(SrcMantMask, dl, IntVT));
9418
9419 SDValue FrexpExpExt = DAG.getSExtOrTrunc(FrexpExp, dl, IntVT);
9420 SDValue NewExp = DAG.getNode(ISD::ADD, dl, IntVT, FrexpExpExt,
9421 DAG.getConstant(DstBias - 1, dl, IntVT));
9422
9423 // Compute rounding increment given the round bit, sticky bits, and LSB
9424 // of the truncated mantissa.
9425 auto ComputeRoundUp = [&](SDValue RoundBit, SDValue StickyBits,
9426 SDValue LSB) -> SDValue {
9427 switch (RoundMode) {
9429 // Round up if round_bit && (sticky || lsb)
9430 SDValue StickyOrLSB = DAG.getNode(ISD::OR, dl, IntVT, StickyBits, LSB);
9431 return DAG.getNode(ISD::AND, dl, IntVT, RoundBit, StickyOrLSB);
9432 }
9434 return Zero;
9436 // Round up if positive and any truncated bits are set.
9437 SDValue AnyTruncBits =
9438 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9439 SDValue HasTruncBits =
9440 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9441 SDValue IsPositive = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETEQ);
9442 SDValue DoRound =
9443 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsPositive);
9444 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9445 }
9447 // Round up if negative and any truncated bits are set (to -Inf).
9448 SDValue AnyTruncBits =
9449 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9450 SDValue HasTruncBits =
9451 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9452 SDValue IsNegative = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETNE);
9453 SDValue DoRound =
9454 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsNegative);
9455 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9456 }
9458 return RoundBit;
9459 default:
9460 llvm_unreachable("unsupported rounding mode");
9461 }
9462 };
9463
9464 // Round mantissa from SrcMant bits to DstMant bits.
9465 SDValue TruncMant;
9466 SDValue RoundUp;
9467 if (SrcMant > DstMant) {
9468 const unsigned Shift = SrcMant - DstMant;
9469 SDValue ShiftConst = DAG.getShiftAmountConstant(Shift, IntVT, dl);
9470 TruncMant = DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, ShiftConst);
9471
9472 // Check bit at position Shift - 1 aka the round bit.
9473 SDValue RoundBit;
9474 if (Shift >= 1) {
9475 SDValue RoundBitShift = DAG.getShiftAmountConstant(Shift - 1, IntVT, dl);
9476 SDValue ShiftedMant =
9477 DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, RoundBitShift);
9478 RoundBit = DAG.getNode(ISD::AND, dl, IntVT, ShiftedMant, One);
9479 } else {
9480 RoundBit = Zero;
9481 }
9482
9483 // OR of all bits below the round bit to get sticky bits.
9484 SDValue StickyBits;
9485 if (Shift >= 2) {
9486 uint64_t StickyMask = maskTrailingOnes<uint64_t>(Shift - 1);
9487 StickyBits = DAG.getNode(ISD::AND, dl, IntVT, EffSrcMant,
9488 DAG.getConstant(StickyMask, dl, IntVT));
9489 StickyBits = DAG.getSetCC(dl, SetCCVT, StickyBits, Zero, ISD::SETNE);
9490 StickyBits = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, StickyBits);
9491 } else {
9492 StickyBits = Zero;
9493 }
9494
9495 // LSB of truncated mantissa.
9496 SDValue LSB = DAG.getNode(ISD::AND, dl, IntVT, TruncMant, One);
9497
9498 RoundUp = ComputeRoundUp(RoundBit, StickyBits, LSB);
9499 } else {
9500 // If DstMant >= SrcMant, then no rounding needed, just shift left.
9501 SDValue MantShift =
9502 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
9503 TruncMant = DAG.getNode(ISD::SHL, dl, IntVT, EffSrcMant, MantShift);
9504 RoundUp = Zero;
9505 }
9506
9507 // Apply rounding.
9508 SDValue RoundedMant = DAG.getNode(ISD::ADD, dl, IntVT, TruncMant, RoundUp);
9509
9510 // Handle mantissa overflow from rounding.
9511 // If rounded_mant > DstMantMask, carry into exponent.
9512 SDValue MantOverflow =
9513 DAG.getSetCC(dl, SetCCVT, RoundedMant,
9514 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9515 // On overflow: mant = 0, exp += 1.
9516 SDValue AdjMant = DAG.getSelect(dl, IntVT, MantOverflow, Zero, RoundedMant);
9517 SDValue AdjExp =
9518 DAG.getNode(ISD::ADD, dl, IntVT, NewExp,
9519 DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, MantOverflow));
9520
9521 // Precompute sign shifted to MSB of destination. Unsigned formats have no
9522 // sign bit to merge in.
9523 SDValue SignShifted =
9524 DstHasSign
9525 ? DAG.getNode(ISD::SHL, dl, IntVT, SignBit,
9526 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
9527 : Zero;
9528
9529 // Destination denormal conversion (when new_exp <= 0).
9530 // Shift the mantissa right by 1 - new_exp additional bits and set the
9531 // exponent field to 0.
9532 SDValue ExpIsNeg = DAG.getSetCC(dl, SetCCVT, AdjExp,
9533 DAG.getConstant(1, dl, IntVT), ISD::SETLT);
9534
9535 SDValue DenormResult;
9536 {
9537 // denorm_shift = 1 - NewExp.
9538 SDValue DenormShift = DAG.getNode(ISD::SUB, dl, IntVT, One, NewExp);
9539
9540 // full_src_mant = (1 << SrcMant) | EffSrcMant.
9541 SDValue ImplicitOne =
9542 DAG.getNode(ISD::SHL, dl, IntVT, One,
9543 DAG.getShiftAmountConstant(SrcMant, IntVT, dl));
9544 SDValue FullSrcMant =
9545 DAG.getNode(ISD::OR, dl, IntVT, EffSrcMant, ImplicitOne);
9546
9547 // Total right shift = DenormShift + (SrcMant - DstMant).
9548 int64_t MantDelta = static_cast<int64_t>(SrcMant) - DstMant;
9549 SDValue TotalShift =
9550 DAG.getNode(ISD::ADD, dl, IntVT, DenormShift,
9551 DAG.getSignedConstant(MantDelta, dl, IntVT));
9552
9553 // Clamp total shift to avoid UB, then truncate denorm mantissa.
9554 EVT ShiftVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
9555 SDValue MaxShift = DAG.getConstant(SrcBits - 1, dl, IntVT);
9556 SDValue ClampedShift =
9557 DAG.getNode(ISD::UMIN, dl, IntVT, TotalShift, MaxShift);
9558 SDValue DenormTruncMant =
9559 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant,
9560 DAG.getZExtOrTrunc(ClampedShift, dl, ShiftVT));
9561
9562 // Rounding for denorm path.
9563 SDValue DenormRoundUp;
9564 {
9565 // Round bit is at position TotalShift - 1 of FullSrcMant.
9566 // Clamp to at least 1 so the subtraction doesn't underflow and create
9567 // shift nodes with invalid shift amounts.
9568 SDValue SafeShift = DAG.getNode(ISD::UMAX, dl, IntVT, ClampedShift, One);
9569 SDValue RoundBitPos = DAG.getNode(ISD::SUB, dl, IntVT, SafeShift, One);
9570 SDValue RoundBitPosAmt = DAG.getZExtOrTrunc(RoundBitPos, dl, ShiftVT);
9571 SDValue DenormRoundBit = DAG.getNode(
9572 ISD::AND, dl, IntVT,
9573 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant, RoundBitPosAmt), One);
9574
9575 // Sticky: all bits below round bit.
9576 // sticky_mask = (1 << RoundBitPos) - 1
9577 SDValue StickyMask = DAG.getNode(
9578 ISD::SUB, dl, IntVT,
9579 DAG.getNode(ISD::SHL, dl, IntVT, One, RoundBitPosAmt), One);
9580 SDValue DenormStickyBits =
9581 DAG.getNode(ISD::AND, dl, IntVT, FullSrcMant, StickyMask);
9582 SDValue HasSticky = DAG.getNode(
9583 ISD::ZERO_EXTEND, dl, IntVT,
9584 DAG.getSetCC(dl, SetCCVT, DenormStickyBits, Zero, ISD::SETNE));
9585
9586 SDValue DenormLSB =
9587 DAG.getNode(ISD::AND, dl, IntVT, DenormTruncMant, One);
9588
9589 DenormRoundUp = ComputeRoundUp(DenormRoundBit, HasSticky, DenormLSB);
9590
9591 // Only apply rounding if TotalShift >= 1 (i.e., there are bits to round).
9592 SDValue ShiftGEOne =
9593 DAG.getSetCC(dl, SetCCVT, ClampedShift, One, ISD::SETUGE);
9594 DenormRoundUp = DAG.getSelect(dl, IntVT, ShiftGEOne, DenormRoundUp, Zero);
9595 }
9596
9597 SDValue DenormRoundedMant =
9598 DAG.getNode(ISD::ADD, dl, IntVT, DenormTruncMant, DenormRoundUp);
9599
9600 // If rounding caused overflow into the normal range, then we get the
9601 // smallest normal number.
9602 SDValue DenormMantOF =
9603 DAG.getSetCC(dl, SetCCVT, DenormRoundedMant,
9604 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9605 SDValue DenormFinalMant =
9606 DAG.getSelect(dl, IntVT, DenormMantOF, Zero, DenormRoundedMant);
9607 SDValue DenormFinalExp = DAG.getSelect(dl, IntVT, DenormMantOF, One, Zero);
9608
9609 // Assemble: sign | (exp << DstMant) | mant
9610 SDValue DenormExpShifted =
9611 DAG.getNode(ISD::SHL, dl, IntVT, DenormFinalExp,
9612 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
9613 DenormResult = DAG.getNode(
9614 ISD::OR, dl, IntVT,
9615 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
9616 DenormFinalMant);
9617 }
9618
9619 // Exponent overflow detection.
9620 SDValue ExpOF =
9621 DAG.getSetCC(dl, SetCCVT, AdjExp,
9622 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETGT);
9623
9624 // Also check if AdjExp == DstExpMaxNormal and mantissa overflow into
9625 // a value that exceeds the max allowed mantissa at that exponent.
9626 SDValue ExpAtMax =
9627 DAG.getSetCC(dl, SetCCVT, AdjExp,
9628 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETEQ);
9629 SDValue MantExceedsMax =
9630 DAG.getSetCC(dl, SetCCVT, AdjMant,
9631 DAG.getConstant(DstMaxMantAtMaxExp, dl, IntVT), ISD::SETGT);
9632 SDValue ExpMantOF =
9633 DAG.getNode(ISD::AND, dl, SetCCVT, ExpAtMax, MantExceedsMax);
9634 SDValue IsOverflow = DAG.getNode(ISD::OR, dl, SetCCVT, ExpOF, ExpMantOF);
9635
9636 // Build overflow result.
9638
9639 if (Saturate) {
9640 // Clamp to max finite value:
9641 // sign | (DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp
9642 uint64_t MaxFinite =
9643 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
9644 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9645 DAG.getConstant(MaxFinite, dl, IntVT));
9646 } else if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9647 // Produce infinity.
9648 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
9649 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9650 DAG.getConstant(InfBits, dl, IntVT));
9651 } else {
9652 // Emit poison if no Inf in format and not saturating.
9653 OverflowResult = DAG.getPOISON(IntVT);
9654 }
9655
9656 // Assemble normal result: sign | (AdjExp << DstMant) | AdjMant
9657 SDValue NormExpShifted =
9658 DAG.getNode(ISD::SHL, dl, IntVT, AdjExp,
9659 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
9660 SDValue NormResult = DAG.getNode(
9661 ISD::OR, dl, IntVT,
9662 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted), AdjMant);
9663
9664 // Build special-value results.
9665 SDValue NaNResult;
9666 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9667 // Produce canonical NaN.
9668 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
9669 NaNResult =
9670 DAG.getConstant(((uint64_t)DstExpMax << DstMant) | QNaNBit, dl, IntVT);
9671 } else if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9672 DstNanEnc == fltNanEncoding::AllOnes) {
9673 // E4M3FN-style: NaN is exp=all-ones, mant=all-ones.
9674 NaNResult = DAG.getConstant(((uint64_t)DstExpMax << DstMant) | DstMantMask,
9675 dl, IntVT);
9676 } else {
9677 // NaN -> poison for finite only values.
9678 NaNResult = DAG.getPOISON(IntVT);
9679 }
9680
9681 // Inf handling.
9682 SDValue InfResult;
9683 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9684 // Produce signed infinity.
9685 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
9686 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9687 DAG.getConstant(InfBits, dl, IntVT));
9688 } else if (Saturate) {
9689 // Inf saturates to max finite.
9690 uint64_t MaxFinite =
9691 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
9692 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9693 DAG.getConstant(MaxFinite, dl, IntVT));
9694 } else {
9695 // No Inf and not saturating -> poison.
9696 InfResult = DAG.getPOISON(IntVT);
9697 }
9698
9699 SDValue ZeroResult = SignShifted;
9700
9701 // Final selection in an order: NaN takes priority, then Inf, then Zero.
9702 SDValue FiniteResult =
9703 DAG.getSelect(dl, IntVT, ExpIsNeg, DenormResult, NormResult);
9704 FiniteResult =
9705 DAG.getSelect(dl, IntVT, IsOverflow, OverflowResult, FiniteResult);
9706
9707 SDValue Result = FiniteResult;
9708 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
9709 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
9710
9711 // Negative values are unrepresentable in an unsigned format: clamp to zero
9712 // when saturating, poison otherwise so no select is needed. -0.0 is handled
9713 // by IsZero above. Run before the NaN case so a negative NaN still yields
9714 // NaN.
9715 if (!DstHasSign && Saturate) {
9716 SDValue IsNegative =
9717 DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOLT);
9718 Result = DAG.getSelect(dl, IntVT, IsNegative, Zero, Result);
9719 }
9720
9721 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
9722
9723 // Truncate to destination integer type.
9724 return DAG.getZExtOrTrunc(Result, dl, ResVT);
9725}
9726
9727SDValue
9729 SelectionDAG &DAG) const {
9730 SDLoc dl(Node);
9731 EVT DstVT = Node->getValueType(0);
9732 EVT DstScalarVT = DstVT.getScalarType();
9733
9734 SDValue IntVal = Node->getOperand(0);
9735 const uint64_t SemEnum = Node->getConstantOperandVal(1);
9736 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
9737
9738 // Supported source formats.
9739 switch (Sem) {
9746 break;
9747 default:
9748 DAG.getContext()->emitError("CONVERT_FROM_ARBITRARY_FP: not implemented "
9749 "source format (semantics enum " +
9750 Twine(SemEnum) + ")");
9751 return SDValue();
9752 }
9753
9754 const fltSemantics &SrcSem = APFloatBase::EnumToSemantics(Sem);
9755 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
9756 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
9757 const unsigned SrcMant = SrcPrecision - 1;
9758 // Unsigned formats spend no bit on the sign.
9759 const bool SrcHasSign = APFloat::semanticsHasSignedRepr(SrcSem);
9760 const unsigned SrcExp = SrcBits - (SrcHasSign ? 1 : 0) - SrcMant;
9761 const int SrcBias = 1 - APFloat::semanticsMinExponent(SrcSem);
9762 const fltNonfiniteBehavior NFBehavior = SrcSem.nonFiniteBehavior;
9763
9764 // Destination format parameters.
9765 const fltSemantics &DstSem = DstScalarVT.getFltSemantics();
9766 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
9767 const unsigned DstMant = APFloat::semanticsPrecision(DstSem) - 1;
9768 const unsigned DstExpBits = DstBits - DstMant - 1;
9769 const int DstMinExp = APFloat::semanticsMinExponent(DstSem);
9770 const int DstBias = 1 - DstMinExp;
9771 const uint64_t DstExpAllOnes = (1ULL << DstExpBits) - 1;
9772
9773 // Work in an integer type matching the destination float width.
9774 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), DstBits);
9775 EVT IntVT = IntScalarVT;
9776 if (DstVT.isVector()) {
9777 IntVT = EVT::getVectorVT(*DAG.getContext(), IntScalarVT,
9778 DstVT.getVectorElementCount());
9779 } else if (!isTypeLegal(IntScalarVT)) {
9780 // Avoid generating illegal type as there is no other places that'll
9781 // legalize it. Vector types don't have this problem because they
9782 // are subject to LegalizeVectorOps and another type legalization phase
9783 // will follow.
9784 if (getTypeAction(*DAG.getContext(), IntScalarVT) != TypePromoteInteger) {
9785 // We only know how to handle situations where the legal type is wider.
9786 DAG.getContext()->emitError(
9787 "CONVERT_FROM_ARBITRARY_FP: the requested integer value type for its "
9788 "legalization is not supported");
9789 return SDValue();
9790 }
9791 IntVT = getTypeToTransformTo(*DAG.getContext(), IntScalarVT);
9792 }
9793
9794 SDValue Src = DAG.getZExtOrTrunc(IntVal, dl, IntVT);
9795
9796 EVT SetCCVT =
9797 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
9798
9799 SDValue Zero = DAG.getConstant(0, dl, IntVT);
9800 SDValue One = DAG.getConstant(1, dl, IntVT);
9801
9802 // Extract bit fields.
9803 const uint64_t MantMask = (SrcMant > 0) ? ((1ULL << SrcMant) - 1) : 0;
9804 const uint64_t ExpMask = (1ULL << SrcExp) - 1;
9805
9806 SDValue MantField = DAG.getNode(ISD::AND, dl, IntVT, Src,
9807 DAG.getConstant(MantMask, dl, IntVT));
9808
9809 SDValue ExpField =
9810 DAG.getNode(ISD::AND, dl, IntVT,
9811 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9812 DAG.getShiftAmountConstant(SrcMant, IntVT, dl)),
9813 DAG.getConstant(ExpMask, dl, IntVT));
9814
9815 // An unsigned source has no sign bit; bit SrcBits - 1 is part of the
9816 // exponent.
9817 SDValue SignShifted =
9818 SrcHasSign
9819 ? DAG.getNode(
9820 ISD::SHL, dl, IntVT,
9821 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9822 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl)),
9823 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
9824 : Zero;
9825
9826 // Classify the input.
9827 SDValue ExpAllOnes = DAG.getConstant(ExpMask, dl, IntVT);
9828 SDValue IsExpAllOnes =
9829 DAG.getSetCC(dl, SetCCVT, ExpField, ExpAllOnes, ISD::SETEQ);
9830 SDValue IsExpZero = DAG.getSetCC(dl, SetCCVT, ExpField, Zero, ISD::SETEQ);
9831 SDValue IsMantZero = DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETEQ);
9832 SDValue IsMantNonZero =
9833 DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETNE);
9834
9835 SDValue IsNaN;
9836 if (NFBehavior == fltNonfiniteBehavior::FiniteOnly) {
9837 IsNaN = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
9838 } else if (NFBehavior == fltNonfiniteBehavior::IEEE754) {
9839 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantNonZero);
9840 } else {
9842 SDValue MantAllOnes = DAG.getConstant(MantMask, dl, IntVT);
9843 SDValue IsMantAllOnes =
9844 DAG.getSetCC(dl, SetCCVT, MantField, MantAllOnes, ISD::SETEQ);
9845 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantAllOnes);
9846 }
9847
9848 SDValue IsInf;
9849 if (NFBehavior == fltNonfiniteBehavior::IEEE754)
9850 IsInf = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantZero);
9851 else
9852 IsInf = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
9853
9854 SDValue IsZero = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantZero);
9855 SDValue IsDenorm =
9856 DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantNonZero);
9857
9858 // Normal value conversion.
9859 const int BiasAdjust = DstBias - SrcBias;
9860 SDValue NormDstExp = DAG.getNode(
9861 ISD::ADD, dl, IntVT, ExpField,
9862 DAG.getConstant(APInt(IntVT.getScalarSizeInBits(), BiasAdjust, true), dl,
9863 IntVT));
9864
9865 SDValue NormDstMant;
9866 if (DstMant > SrcMant) {
9867 SDValue NormDstMantShift =
9868 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
9869 NormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, MantField, NormDstMantShift);
9870 } else {
9871 NormDstMant = MantField;
9872 }
9873
9874 SDValue DstMantShift = DAG.getShiftAmountConstant(DstMant, IntVT, dl);
9875 SDValue NormExpShifted =
9876 DAG.getNode(ISD::SHL, dl, IntVT, NormDstExp, DstMantShift);
9877 SDValue NormResult =
9878 DAG.getNode(ISD::OR, dl, IntVT,
9879 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted),
9880 NormDstMant);
9881
9882 // Denormal value conversion.
9883 SDValue DenormResult;
9884 {
9885 const unsigned IntVTBits = IntVT.getScalarSizeInBits();
9886 SDValue LeadingZeros =
9887 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, IntVT, MantField);
9888
9889 const int DenormExpConst =
9890 (int)IntVTBits + DstBias - SrcBias - (int)SrcMant;
9891 SDValue DenormDstExp = DAG.getNode(
9892 ISD::SUB, dl, IntVT,
9893 DAG.getConstant(APInt(IntVTBits, DenormExpConst, true), dl, IntVT),
9894 LeadingZeros);
9895
9896 SDValue MantMSB =
9897 DAG.getNode(ISD::SUB, dl, IntVT,
9898 DAG.getConstant(IntVTBits - 1, dl, IntVT), LeadingZeros);
9899
9900 SDValue LeadingOne = DAG.getNode(ISD::SHL, dl, IntVT, One, MantMSB);
9901 SDValue Frac = DAG.getNode(ISD::XOR, dl, IntVT, MantField, LeadingOne);
9902
9903 const unsigned ShiftSub = IntVTBits - 1 - DstMant;
9904 SDValue ShiftAmount = DAG.getNode(ISD::SUB, dl, IntVT, LeadingZeros,
9905 DAG.getConstant(ShiftSub, dl, IntVT));
9906
9907 SDValue DenormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, Frac, ShiftAmount);
9908
9909 SDValue DenormExpShifted =
9910 DAG.getNode(ISD::SHL, dl, IntVT, DenormDstExp, DstMantShift);
9911 DenormResult = DAG.getNode(
9912 ISD::OR, dl, IntVT,
9913 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
9914 DenormDstMant);
9915 }
9916
9917 SDValue FiniteResult =
9918 DAG.getSelect(dl, IntVT, IsDenorm, DenormResult, NormResult);
9919
9920 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
9921 SDValue NaNResult =
9922 DAG.getConstant((DstExpAllOnes << DstMant) | QNaNBit, dl, IntVT);
9923
9924 SDValue InfResult =
9925 DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9926 DAG.getConstant(DstExpAllOnes << DstMant, dl, IntVT));
9927
9928 SDValue ZeroResult = SignShifted;
9929
9930 SDValue Result = FiniteResult;
9931 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
9932 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
9933 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
9934
9935 if (!DstVT.bitsEq(IntVT)) {
9936 // Store to stack before loading it back.
9937 assert(!IntVT.isVector() && IntVT.bitsGT(DstVT));
9938 // IntScalarVT is the original type that has the same width as DstVT.
9939 Align Alignment = DAG.getReducedAlign(IntScalarVT, /*UseABI=*/false);
9940 SDValue StackPtr =
9941 DAG.CreateStackTemporary(IntScalarVT.getStoreSize(), Alignment);
9942 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
9944 MachinePointerInfo PtrInfo =
9945 MachinePointerInfo::getFixedStack(MF, FrameIndex);
9946 SDValue Store = DAG.getTruncStore(DAG.getEntryNode(), dl, Result, StackPtr,
9947 PtrInfo, IntScalarVT, Alignment);
9948
9949 SDValue Load = DAG.getLoad(DstVT, dl, Store, StackPtr, PtrInfo, Alignment);
9950 return DAG.getMergeValues({Load, Load.getValue(1)}, dl);
9951 }
9952
9953 return DAG.getNode(ISD::BITCAST, dl, DstVT, Result);
9954}
9955
9957 SelectionDAG &DAG) const {
9958 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
9959 SDValue Src = Node->getOperand(OpNo);
9960 EVT SrcVT = Src.getValueType();
9961 EVT DstVT = Node->getValueType(0);
9962 SDLoc dl(SDValue(Node, 0));
9963
9964 // FIXME: Only f32 to i64 conversions are supported.
9965 if (SrcVT != MVT::f32 || DstVT != MVT::i64)
9966 return false;
9967
9968 if (Node->isStrictFPOpcode())
9969 // When a NaN is converted to an integer a trap is allowed. We can't
9970 // use this expansion here because it would eliminate that trap. Other
9971 // traps are also allowed and cannot be eliminated. See
9972 // IEEE 754-2008 sec 5.8.
9973 return false;
9974
9975 // Expand f32 -> i64 conversion
9976 // This algorithm comes from compiler-rt's implementation of fixsfdi:
9977 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
9978 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
9979 EVT IntVT = SrcVT.changeTypeToInteger();
9980 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
9981
9982 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
9983 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
9984 SDValue Bias = DAG.getConstant(127, dl, IntVT);
9985 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
9986 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
9987 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
9988
9989 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
9990
9991 SDValue ExponentBits = DAG.getNode(
9992 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
9993 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
9994 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
9995
9996 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
9997 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
9998 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
9999 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
10000
10001 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
10002 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
10003 DAG.getConstant(0x00800000, dl, IntVT));
10004
10005 R = DAG.getZExtOrTrunc(R, dl, DstVT);
10006
10007 R = DAG.getSelectCC(
10008 dl, Exponent, ExponentLoBit,
10009 DAG.getNode(ISD::SHL, dl, DstVT, R,
10010 DAG.getZExtOrTrunc(
10011 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
10012 dl, IntShVT)),
10013 DAG.getNode(ISD::SRL, dl, DstVT, R,
10014 DAG.getZExtOrTrunc(
10015 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
10016 dl, IntShVT)),
10017 ISD::SETGT);
10018
10019 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
10020 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
10021
10022 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
10023 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
10024 return true;
10025}
10026
10028 SDValue &Chain,
10029 SelectionDAG &DAG) const {
10030 SDLoc dl(SDValue(Node, 0));
10031 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10032 SDValue Src = Node->getOperand(OpNo);
10033
10034 EVT SrcVT = Src.getValueType();
10035 EVT DstVT = Node->getValueType(0);
10036 EVT SetCCVT =
10037 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
10038 EVT DstSetCCVT =
10039 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
10040
10041 // Only expand vector types if we have the appropriate vector bit operations.
10042 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
10044 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
10046 return false;
10047
10048 // If the maximum float value is smaller then the signed integer range,
10049 // the destination signmask can't be represented by the float, so we can
10050 // just use FP_TO_SINT directly.
10051 const fltSemantics &APFSem = SrcVT.getFltSemantics();
10052 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
10053 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
10055 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
10056 if (Node->isStrictFPOpcode()) {
10057 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10058 { Node->getOperand(0), Src });
10059 Chain = Result.getValue(1);
10060 } else
10061 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10062 return true;
10063 }
10064
10065 // Don't expand it if there isn't cheap fsub instruction.
10067 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
10068 return false;
10069
10070 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
10071 SDValue Sel;
10072
10073 if (Node->isStrictFPOpcode()) {
10074 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
10075 Node->getOperand(0), /*IsSignaling*/ true);
10076 Chain = Sel.getValue(1);
10077 } else {
10078 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
10079 }
10080
10081 bool Strict = Node->isStrictFPOpcode() ||
10082 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
10083
10084 if (Strict) {
10085 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
10086 // signmask then offset (the result of which should be fully representable).
10087 // Sel = Src < 0x8000000000000000
10088 // FltOfs = select Sel, 0, 0x8000000000000000
10089 // IntOfs = select Sel, 0, 0x8000000000000000
10090 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
10091
10092 // TODO: Should any fast-math-flags be set for the FSUB?
10093 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
10094 DAG.getConstantFP(0.0, dl, SrcVT), Cst);
10095 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10096 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
10097 DAG.getConstant(0, dl, DstVT),
10098 DAG.getConstant(SignMask, dl, DstVT));
10099 SDValue SInt;
10100 if (Node->isStrictFPOpcode()) {
10101 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
10102 { Chain, Src, FltOfs });
10103 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10104 { Val.getValue(1), Val });
10105 Chain = SInt.getValue(1);
10106 } else {
10107 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
10108 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
10109 }
10110 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
10111 } else {
10112 // Expand based on maximum range of FP_TO_SINT:
10113 // True = fp_to_sint(Src)
10114 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
10115 // Result = select (Src < 0x8000000000000000), True, False
10116
10117 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10118 // TODO: Should any fast-math-flags be set for the FSUB?
10119 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
10120 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
10121 False = DAG.getNode(ISD::XOR, dl, DstVT, False,
10122 DAG.getConstant(SignMask, dl, DstVT));
10123 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10124 Result = DAG.getSelect(dl, DstVT, Sel, True, False);
10125 }
10126 return true;
10127}
10128
10130 SDValue &Chain, SelectionDAG &DAG) const {
10131 // This transform is not correct for converting 0 when rounding mode is set
10132 // to round toward negative infinity which will produce -0.0. So disable
10133 // under strictfp.
10134 if (Node->isStrictFPOpcode())
10135 return false;
10136
10137 SDValue Src = Node->getOperand(0);
10138 EVT SrcVT = Src.getValueType();
10139 EVT DstVT = Node->getValueType(0);
10140
10141 // If the input is known to be non-negative and SINT_TO_FP is legal then use
10142 // it.
10143 if (Node->getFlags().hasNonNeg() &&
10145 Result =
10146 DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), DstVT, Node->getOperand(0));
10147 return true;
10148 }
10149
10150 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
10151 return false;
10152
10153 // Only expand vector types if we have the appropriate vector bit
10154 // operations.
10155 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
10160 return false;
10161
10162 SDLoc dl(SDValue(Node, 0));
10163
10164 // Implementation of unsigned i64 to f64 following the algorithm in
10165 // __floatundidf in compiler_rt. This implementation performs rounding
10166 // correctly in all rounding modes with the exception of converting 0
10167 // when rounding toward negative infinity. In that case the fsub will
10168 // produce -0.0. This will be added to +0.0 and produce -0.0 which is
10169 // incorrect.
10170 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
10171 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
10172 llvm::bit_cast<double>(UINT64_C(0x4530000000100000)), dl, DstVT);
10173 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
10174 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
10175 SDValue HiShift = DAG.getShiftAmountConstant(32, SrcVT, dl);
10176
10177 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
10178 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
10179 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
10180 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
10181 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
10182 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
10183 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
10184 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
10185 return true;
10186}
10187
10188SDValue
10190 SelectionDAG &DAG) const {
10191 unsigned Opcode = Node->getOpcode();
10192 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
10193 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
10194 "Wrong opcode");
10195
10196 if (Node->getFlags().hasNoNaNs()) {
10197 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
10198 EVT VT = Node->getValueType(0);
10199 if ((!isCondCodeLegal(Pred, VT.getSimpleVT()) ||
10201 VT.isVector())
10202 return SDValue();
10203 SDValue Op1 = Node->getOperand(0);
10204 SDValue Op2 = Node->getOperand(1);
10205 return DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred,
10206 Node->getFlags());
10207 }
10208
10209 return SDValue();
10210}
10211
10213 SelectionDAG &DAG) const {
10214 if (SDValue Expanded = expandVectorNaryOpBySplitting(Node, DAG))
10215 return Expanded;
10216
10217 EVT VT = Node->getValueType(0);
10218 if (VT.isScalableVector())
10220 "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
10221
10222 SDLoc dl(Node);
10223 unsigned NewOp =
10225
10226 if (isOperationLegalOrCustom(NewOp, VT)) {
10227 SDValue Quiet0 = Node->getOperand(0);
10228 SDValue Quiet1 = Node->getOperand(1);
10229
10230 if (!Node->getFlags().hasNoNaNs()) {
10231 // Insert canonicalizes if it's possible we need to quiet to get correct
10232 // sNaN behavior.
10233 if (!DAG.isKnownNeverSNaN(Quiet0)) {
10234 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
10235 Node->getFlags());
10236 }
10237 if (!DAG.isKnownNeverSNaN(Quiet1)) {
10238 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
10239 Node->getFlags());
10240 }
10241 }
10242
10243 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
10244 }
10245
10246 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
10247 // instead if there are no NaNs.
10248 if (Node->getFlags().hasNoNaNs() ||
10249 (DAG.isKnownNeverNaN(Node->getOperand(0)) &&
10250 DAG.isKnownNeverNaN(Node->getOperand(1)))) {
10251 unsigned IEEE2018Op =
10252 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
10253 if (isOperationLegalOrCustom(IEEE2018Op, VT))
10254 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
10255 Node->getOperand(1), Node->getFlags());
10256 }
10257
10259 return SelCC;
10260
10261 return SDValue();
10262}
10263
10265 const TargetLowering &TLI,
10266 const SDLoc &DL, SDValue Val,
10267 FPClassTest FPClass) {
10268 EVT VT = Val.getValueType();
10269 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10270 EVT IntVT = VT.changeTypeToInteger();
10271 EVT FloatVT = VT.changeElementType(*DAG.getContext(), MVT::f32);
10272 SDValue TestZero = DAG.getTargetConstant(FPClass, DL, MVT::i32);
10273 if (!TLI.isTypeLegal(IntVT) &&
10275 Val = DAG.getNode(ISD::FP_ROUND, DL, FloatVT, Val,
10276 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true));
10277 return DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, Val, TestZero);
10278}
10279
10281 SelectionDAG &DAG) const {
10282 if (SDValue Expanded = expandVectorNaryOpBySplitting(N, DAG))
10283 return Expanded;
10284
10285 SDLoc DL(N);
10286 SDValue LHS = N->getOperand(0);
10287 SDValue RHS = N->getOperand(1);
10288 unsigned Opc = N->getOpcode();
10289 EVT VT = N->getValueType(0);
10290 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10291 bool IsMax = Opc == ISD::FMAXIMUM;
10292 SDNodeFlags Flags = N->getFlags();
10293
10294 // First, implement comparison not propagating NaN. If no native fmin or fmax
10295 // available, use plain select with setcc instead.
10297 unsigned CompOpcIeee = IsMax ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
10298 unsigned CompOpc = IsMax ? ISD::FMAXNUM : ISD::FMINNUM;
10299
10300 // FIXME: We should probably define fminnum/fmaxnum variants with correct
10301 // signed zero behavior.
10302 bool MinMaxMustRespectOrderedZero = false;
10303
10304 if (isOperationLegalOrCustom(CompOpcIeee, VT)) {
10305 MinMax = DAG.getNode(CompOpcIeee, DL, VT, LHS, RHS, Flags);
10306 MinMaxMustRespectOrderedZero = true;
10307 } else if (isOperationLegalOrCustom(CompOpc, VT)) {
10308 MinMax = DAG.getNode(CompOpc, DL, VT, LHS, RHS, Flags);
10309 } else {
10311 return DAG.UnrollVectorOp(N);
10312
10313 // NaN (if exists) will be propagated later, so orderness doesn't matter.
10314 SDValue Compare =
10315 DAG.getSetCC(DL, CCVT, LHS, RHS, IsMax ? ISD::SETOGT : ISD::SETOLT);
10316 MinMax = DAG.getSelect(DL, VT, Compare, LHS, RHS, Flags);
10317 }
10318
10319 // Propagate any NaN of both operands
10320 if (!N->getFlags().hasNoNaNs() &&
10321 (!DAG.isKnownNeverNaN(RHS) || !DAG.isKnownNeverNaN(LHS))) {
10322 ConstantFP *FPNaN = ConstantFP::get(*DAG.getContext(),
10324 MinMax = DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETUO),
10325 DAG.getConstantFP(*FPNaN, DL, VT), MinMax, Flags);
10326 }
10327
10328 // fminimum/fmaximum requires -0.0 less than +0.0
10329 if (!MinMaxMustRespectOrderedZero && !N->getFlags().hasNoSignedZeros() &&
10330 !DAG.isKnownNeverLogicalZero(RHS) && !DAG.isKnownNeverLogicalZero(LHS)) {
10331 SDValue IsEqual = DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETOEQ);
10333 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10334 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, RHS, Flags);
10335 MinMax = DAG.getSelect(DL, VT, IsEqual, RetZero, MinMax, Flags);
10336 }
10337
10338 return MinMax;
10339}
10340
10342 SelectionDAG &DAG) const {
10343 SDLoc DL(Node);
10344 SDValue LHS = Node->getOperand(0);
10345 SDValue RHS = Node->getOperand(1);
10346 unsigned Opc = Node->getOpcode();
10347 EVT VT = Node->getValueType(0);
10348 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10349 bool IsMax = Opc == ISD::FMAXIMUMNUM;
10350 SDNodeFlags Flags = Node->getFlags();
10351
10352 unsigned NewOp =
10354
10355 if (isOperationLegalOrCustom(NewOp, VT)) {
10356 if (!Flags.hasNoNaNs()) {
10357 // Insert canonicalizes if it's possible we need to quiet to get correct
10358 // sNaN behavior.
10359 if (!DAG.isKnownNeverSNaN(LHS)) {
10360 LHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, LHS, Flags);
10361 }
10362 if (!DAG.isKnownNeverSNaN(RHS)) {
10363 RHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, RHS, Flags);
10364 }
10365 }
10366
10367 return DAG.getNode(NewOp, DL, VT, LHS, RHS, Flags);
10368 }
10369
10370 // We can use FMINIMUM/FMAXIMUM if there is no NaN, since it has
10371 // same behaviors for all of other cases: +0.0 vs -0.0 included.
10372 if (Flags.hasNoNaNs() ||
10373 (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS))) {
10374 unsigned IEEE2019Op =
10376 if (isOperationLegalOrCustom(IEEE2019Op, VT))
10377 return DAG.getNode(IEEE2019Op, DL, VT, LHS, RHS, Flags);
10378 }
10379
10380 // FMINNUM/FMAXMUM returns qNaN if either operand is sNaN, and it may return
10381 // either one for +0.0 vs -0.0.
10382 if ((Flags.hasNoNaNs() ||
10383 (DAG.isKnownNeverSNaN(LHS) && DAG.isKnownNeverSNaN(RHS))) &&
10384 (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10385 DAG.isKnownNeverLogicalZero(RHS))) {
10386 unsigned IEEE2008Op = Opc == ISD::FMINIMUMNUM ? ISD::FMINNUM : ISD::FMAXNUM;
10387 if (isOperationLegalOrCustom(IEEE2008Op, VT))
10388 return DAG.getNode(IEEE2008Op, DL, VT, LHS, RHS, Flags);
10389 }
10390
10391 if (VT.isVector() &&
10394 return DAG.UnrollVectorOp(Node);
10395
10396 // If only one operand is NaN, override it with another operand.
10397 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(LHS)) {
10398 LHS = DAG.getSelectCC(DL, LHS, LHS, RHS, LHS, ISD::SETUO);
10399 }
10400 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(RHS)) {
10401 RHS = DAG.getSelectCC(DL, RHS, RHS, LHS, RHS, ISD::SETUO);
10402 }
10403
10404 // Always prefer RHS if equal.
10405 SDValue MinMax =
10406 DAG.getSelectCC(DL, LHS, RHS, LHS, RHS, IsMax ? ISD::SETGT : ISD::SETLT);
10407
10408 // TODO: We need quiet sNaN if strictfp.
10409
10410 // Fixup signed zero behavior.
10411 if (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10412 DAG.isKnownNeverLogicalZero(RHS)) {
10413 return MinMax;
10414 }
10415 SDValue IsZero = DAG.getSetCC(DL, CCVT, MinMax,
10416 DAG.getConstantFP(0.0, DL, VT), ISD::SETEQ);
10418 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10419 // It's OK to select from LHS and MinMax, with only one ISD::IS_FPCLASS, as
10420 // we preferred RHS when generate MinMax, if the operands are equal.
10421 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, MinMax, Flags);
10422 return DAG.getSelect(DL, VT, IsZero, RetZero, MinMax, Flags);
10423}
10424
10425/// Returns a true value if if this FPClassTest can be performed with an ordered
10426/// fcmp to 0, and a false value if it's an unordered fcmp to 0. Returns
10427/// std::nullopt if it cannot be performed as a compare with 0.
10428static std::optional<bool> isFCmpEqualZero(FPClassTest Test,
10429 const fltSemantics &Semantics,
10430 const MachineFunction &MF) {
10431 FPClassTest OrderedMask = Test & ~fcNan;
10432 FPClassTest NanTest = Test & fcNan;
10433 bool IsOrdered = NanTest == fcNone;
10434 bool IsUnordered = NanTest == fcNan;
10435
10436 // Skip cases that are testing for only a qnan or snan.
10437 if (!IsOrdered && !IsUnordered)
10438 return std::nullopt;
10439
10440 if (OrderedMask == fcZero &&
10441 MF.getDenormalMode(Semantics).Input == DenormalMode::IEEE)
10442 return IsOrdered;
10443 if (OrderedMask == (fcZero | fcSubnormal) &&
10444 MF.getDenormalMode(Semantics).inputsAreZero())
10445 return IsOrdered;
10446 return std::nullopt;
10447}
10448
10450 const FPClassTest OrigTestMask,
10451 SDNodeFlags Flags, const SDLoc &DL,
10452 SelectionDAG &DAG) const {
10453 EVT OperandVT = Op.getValueType();
10454 assert(OperandVT.isFloatingPoint());
10455 FPClassTest Test = OrigTestMask;
10456
10457 // Degenerated cases.
10458 if (Test == fcNone)
10459 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT);
10460 if (Test == fcAllFlags)
10461 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT);
10462
10463 // PPC double double is a pair of doubles, of which the higher part determines
10464 // the value class.
10465 if (OperandVT == MVT::ppcf128) {
10466 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op,
10467 DAG.getConstant(1, DL, MVT::i32));
10468 OperandVT = MVT::f64;
10469 }
10470
10471 // Floating-point type properties.
10472 EVT ScalarFloatVT = OperandVT.getScalarType();
10473 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext());
10474 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics();
10475 bool IsF80 = (ScalarFloatVT == MVT::f80);
10476
10477 // Some checks can be implemented using float comparisons, if floating point
10478 // exceptions are ignored.
10479 if (Flags.hasNoFPExcept() &&
10481 FPClassTest FPTestMask = Test;
10482 bool IsInvertedFP = false;
10483
10484 if (FPClassTest InvertedFPCheck =
10485 invertFPClassTestIfSimpler(FPTestMask, true)) {
10486 FPTestMask = InvertedFPCheck;
10487 IsInvertedFP = true;
10488 }
10489
10490 ISD::CondCode OrderedCmpOpcode = IsInvertedFP ? ISD::SETUNE : ISD::SETOEQ;
10491 ISD::CondCode UnorderedCmpOpcode = IsInvertedFP ? ISD::SETONE : ISD::SETUEQ;
10492
10493 // See if we can fold an | fcNan into an unordered compare.
10494 FPClassTest OrderedFPTestMask = FPTestMask & ~fcNan;
10495
10496 // Can't fold the ordered check if we're only testing for snan or qnan
10497 // individually.
10498 if ((FPTestMask & fcNan) != fcNan)
10499 OrderedFPTestMask = FPTestMask;
10500
10501 const bool IsOrdered = FPTestMask == OrderedFPTestMask;
10502
10503 if (std::optional<bool> IsCmp0 =
10504 isFCmpEqualZero(FPTestMask, Semantics, DAG.getMachineFunction());
10505 IsCmp0 && (isCondCodeLegalOrCustom(
10506 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode,
10507 OperandVT.getScalarType().getSimpleVT()))) {
10508
10509 // If denormals could be implicitly treated as 0, this is not equivalent
10510 // to a compare with 0 since it will also be true for denormals.
10511 return DAG.getSetCC(DL, ResultVT, Op,
10512 DAG.getConstantFP(0.0, DL, OperandVT),
10513 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode);
10514 }
10515
10516 if (FPTestMask == fcNan &&
10518 OperandVT.getScalarType().getSimpleVT()))
10519 return DAG.getSetCC(DL, ResultVT, Op, Op,
10520 IsInvertedFP ? ISD::SETO : ISD::SETUO);
10521
10522 bool IsOrderedInf = FPTestMask == fcInf;
10523 if ((FPTestMask == fcInf || FPTestMask == (fcInf | fcNan)) &&
10524 isCondCodeLegalOrCustom(IsOrderedInf ? OrderedCmpOpcode
10525 : UnorderedCmpOpcode,
10526 OperandVT.getScalarType().getSimpleVT()) &&
10529 (OperandVT.isVector() &&
10531 // isinf(x) --> fabs(x) == inf
10532 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10533 SDValue Inf =
10534 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10535 return DAG.getSetCC(DL, ResultVT, Abs, Inf,
10536 IsOrderedInf ? OrderedCmpOpcode : UnorderedCmpOpcode);
10537 }
10538
10539 if ((OrderedFPTestMask == fcPosInf || OrderedFPTestMask == fcNegInf) &&
10540 isCondCodeLegalOrCustom(IsOrdered ? OrderedCmpOpcode
10541 : UnorderedCmpOpcode,
10542 OperandVT.getSimpleVT())) {
10543 // isposinf(x) --> x == inf
10544 // isneginf(x) --> x == -inf
10545 // isposinf(x) || nan --> x u== inf
10546 // isneginf(x) || nan --> x u== -inf
10547
10548 SDValue Inf = DAG.getConstantFP(
10549 APFloat::getInf(Semantics, OrderedFPTestMask == fcNegInf), DL,
10550 OperandVT);
10551 return DAG.getSetCC(DL, ResultVT, Op, Inf,
10552 IsOrdered ? OrderedCmpOpcode : UnorderedCmpOpcode);
10553 }
10554
10555 if (OrderedFPTestMask == (fcSubnormal | fcZero) && !IsOrdered) {
10556 // TODO: Could handle ordered case, but it produces worse code for
10557 // x86. Maybe handle ordered if fabs is free?
10558
10559 ISD::CondCode OrderedOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10560 ISD::CondCode UnorderedOp = IsInvertedFP ? ISD::SETOGE : ISD::SETULT;
10561
10562 if (isCondCodeLegalOrCustom(IsOrdered ? OrderedOp : UnorderedOp,
10563 OperandVT.getScalarType().getSimpleVT())) {
10564 // (issubnormal(x) || iszero(x)) --> fabs(x) < smallest_normal
10565
10566 // TODO: Maybe only makes sense if fabs is free. Integer test of
10567 // exponent bits seems better for x86.
10568 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10569 SDValue SmallestNormal = DAG.getConstantFP(
10570 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
10571 return DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal,
10572 IsOrdered ? OrderedOp : UnorderedOp);
10573 }
10574 }
10575
10576 if (FPTestMask == fcNormal) {
10577 // TODO: Handle unordered
10578 ISD::CondCode IsFiniteOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10579 ISD::CondCode IsNormalOp = IsInvertedFP ? ISD::SETOLT : ISD::SETUGE;
10580
10581 if (isCondCodeLegalOrCustom(IsFiniteOp,
10582 OperandVT.getScalarType().getSimpleVT()) &&
10583 isCondCodeLegalOrCustom(IsNormalOp,
10584 OperandVT.getScalarType().getSimpleVT()) &&
10585 isFAbsFree(OperandVT)) {
10586 // isnormal(x) --> fabs(x) < infinity && !(fabs(x) < smallest_normal)
10587 SDValue Inf =
10588 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10589 SDValue SmallestNormal = DAG.getConstantFP(
10590 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
10591
10592 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10593 SDValue IsFinite = DAG.getSetCC(DL, ResultVT, Abs, Inf, IsFiniteOp);
10594 SDValue IsNormal =
10595 DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal, IsNormalOp);
10596 unsigned LogicOp = IsInvertedFP ? ISD::OR : ISD::AND;
10597 return DAG.getNode(LogicOp, DL, ResultVT, IsFinite, IsNormal);
10598 }
10599 }
10600 }
10601
10602 // Some checks may be represented as inversion of simpler check, for example
10603 // "inf|normal|subnormal|zero" => !"nan".
10604 bool IsInverted = false;
10605
10606 if (FPClassTest InvertedCheck = invertFPClassTestIfSimpler(Test, false)) {
10607 Test = InvertedCheck;
10608 IsInverted = true;
10609 }
10610
10611 // In the general case use integer operations.
10612 unsigned BitSize = OperandVT.getScalarSizeInBits();
10613 EVT IntVT = OperandVT.changeElementType(
10614 *DAG.getContext(), EVT::getIntegerVT(*DAG.getContext(), BitSize));
10615 SDValue OpAsInt = DAG.getBitcast(IntVT, Op);
10616
10617 // Various masks.
10618 APInt SignBit = APInt::getSignMask(BitSize);
10619 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign.
10620 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit.
10621 const unsigned ExplicitIntBitInF80 = 63;
10622 APInt ExpMask = Inf;
10623 if (IsF80)
10624 ExpMask.clearBit(ExplicitIntBitInF80);
10625 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf;
10626 APInt QNaNBitMask =
10627 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1);
10628 APInt InversionMask = APInt::getAllOnes(ResultVT.getScalarSizeInBits());
10629
10630 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT);
10631 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT);
10632 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT);
10633 SDValue ZeroV = DAG.getConstant(0, DL, IntVT);
10634 SDValue InfV = DAG.getConstant(Inf, DL, IntVT);
10635 SDValue ResultInversionMask = DAG.getConstant(InversionMask, DL, ResultVT);
10636
10637 SDValue Res;
10638 const auto appendResult = [&](SDValue PartialRes) {
10639 if (PartialRes) {
10640 if (Res)
10641 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes);
10642 else
10643 Res = PartialRes;
10644 }
10645 };
10646
10647 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set.
10648 const auto getIntBitIsSet = [&]() -> SDValue {
10649 if (!IntBitIsSetV) {
10650 APInt IntBitMask(BitSize, 0);
10651 IntBitMask.setBit(ExplicitIntBitInF80);
10652 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT);
10653 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV);
10654 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE);
10655 }
10656 return IntBitIsSetV;
10657 };
10658
10659 // Split the value into sign bit and absolute value.
10660 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV);
10661 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt,
10662 DAG.getConstant(0, DL, IntVT), ISD::SETLT);
10663
10664 // Tests that involve more than one class should be processed first.
10665 SDValue PartialRes;
10666
10667 if (IsF80)
10668 ; // Detect finite numbers of f80 by checking individual classes because
10669 // they have different settings of the explicit integer bit.
10670 else if ((Test & fcFinite) == fcFinite) {
10671 // finite(V) ==> (a << 1) < (inf << 1)
10672 //
10673 // See https://github.com/llvm/llvm-project/issues/169270, this is slightly
10674 // shorter than the `finite(V) ==> abs(V) < exp_mask` formula used before.
10675
10677 "finite check requires IEEE-like FP");
10678
10679 SDValue One = DAG.getShiftAmountConstant(1, IntVT, DL);
10680 SDValue TwiceOp = DAG.getNode(ISD::SHL, DL, IntVT, OpAsInt, One);
10681 SDValue TwiceInf = DAG.getNode(ISD::SHL, DL, IntVT, ExpMaskV, One);
10682
10683 PartialRes = DAG.getSetCC(DL, ResultVT, TwiceOp, TwiceInf, ISD::SETULT);
10684 Test &= ~fcFinite;
10685 } else if ((Test & fcFinite) == fcPosFinite) {
10686 // finite(V) && V > 0 ==> V < exp_mask
10687 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT);
10688 Test &= ~fcPosFinite;
10689 } else if ((Test & fcFinite) == fcNegFinite) {
10690 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1
10691 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
10692 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
10693 Test &= ~fcNegFinite;
10694 }
10695 appendResult(PartialRes);
10696
10697 if (FPClassTest PartialCheck = Test & (fcZero | fcSubnormal)) {
10698 // fcZero | fcSubnormal => test all exponent bits are 0
10699 // TODO: Handle sign bit specific cases
10700 if (PartialCheck == (fcZero | fcSubnormal)) {
10701 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ExpMaskV);
10702 SDValue ExpIsZero =
10703 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
10704 appendResult(ExpIsZero);
10705 Test &= ~PartialCheck & fcAllFlags;
10706 }
10707 }
10708
10709 // Check for individual classes.
10710
10711 if (unsigned PartialCheck = Test & fcZero) {
10712 if (PartialCheck == fcPosZero)
10713 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ);
10714 else if (PartialCheck == fcZero)
10715 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ);
10716 else // ISD::fcNegZero
10717 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ);
10718 appendResult(PartialRes);
10719 }
10720
10721 if (unsigned PartialCheck = Test & fcSubnormal) {
10722 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set)
10723 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set)
10724 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV;
10725 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT);
10726 SDValue VMinusOneV =
10727 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT));
10728 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT);
10729 if (PartialCheck == fcNegSubnormal)
10730 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
10731 appendResult(PartialRes);
10732 }
10733
10734 if (unsigned PartialCheck = Test & fcInf) {
10735 if (PartialCheck == fcPosInf)
10736 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ);
10737 else if (PartialCheck == fcInf)
10738 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ);
10739 else { // ISD::fcNegInf
10740 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt();
10741 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT);
10742 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ);
10743 }
10744 appendResult(PartialRes);
10745 }
10746
10747 if (unsigned PartialCheck = Test & fcNan) {
10748 APInt InfWithQnanBit = Inf | QNaNBitMask;
10749 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT);
10750 if (PartialCheck == fcNan) {
10751 // isnan(V) ==> abs(V) > int(inf)
10752 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
10753 if (IsF80) {
10754 // Recognize unsupported values as NaNs for compatibility with glibc.
10755 // In them (exp(V)==0) == int_bit.
10756 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV);
10757 SDValue ExpIsZero =
10758 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
10759 SDValue IsPseudo =
10760 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ);
10761 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo);
10762 }
10763 } else if (PartialCheck == fcQNan) {
10764 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit)
10765 PartialRes =
10766 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE);
10767 } else { // ISD::fcSNan
10768 // issignaling(V) ==> abs(V) > unsigned(Inf) &&
10769 // abs(V) < (unsigned(Inf) | quiet_bit)
10770 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
10771 SDValue IsNotQnan =
10772 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT);
10773 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan);
10774 }
10775 appendResult(PartialRes);
10776 }
10777
10778 if (unsigned PartialCheck = Test & fcNormal) {
10779 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1))
10780 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1));
10781 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT);
10782 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV);
10783 APInt ExpLimit = ExpMask - ExpLSB;
10784 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT);
10785 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT);
10786 if (PartialCheck == fcNegNormal)
10787 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
10788 else if (PartialCheck == fcPosNormal) {
10789 SDValue PosSignV =
10790 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInversionMask);
10791 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV);
10792 }
10793 if (IsF80)
10794 PartialRes =
10795 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet());
10796 appendResult(PartialRes);
10797 }
10798
10799 if (!Res)
10800 return DAG.getConstant(IsInverted, DL, ResultVT);
10801 if (IsInverted)
10802 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInversionMask);
10803 return Res;
10804}
10805
10806// Only expand vector types if we have the appropriate vector bit operations.
10807static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) {
10808 assert(VT.isVector() && "Expected vector type");
10809 unsigned Len = VT.getScalarSizeInBits();
10810 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
10813 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
10815}
10816
10818 SDLoc dl(Node);
10819 EVT VT = Node->getValueType(0);
10820 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
10821 SDValue Op = Node->getOperand(0);
10822 unsigned Len = VT.getScalarSizeInBits();
10823
10824 // Compute effective bit width from known bits, allowing us to shift the
10825 // active bits down if necessary to fit into smaller specialized expansions.
10827 unsigned LZ = Known.countMinLeadingZeros();
10828 unsigned TZ = Known.countMinTrailingZeros();
10829 unsigned ShiftedActiveBits = Known.getBitWidth() - (LZ + TZ);
10830
10831 // Round up to 8-bit boundary for byte-oriented SWAR algorithm
10832 unsigned EffectiveLen = Len;
10833 if (ShiftedActiveBits > 0 && ShiftedActiveBits < Len)
10834 EffectiveLen = std::min(alignTo(ShiftedActiveBits, 8), Len);
10835
10836 assert(VT.isInteger() && "CTPOP not implemented for this type.");
10837
10838 // TODO: Add support for irregular type lengths.
10839 if (!(Len <= 128 && Len % 8 == 0))
10840 return SDValue();
10841
10842 // Only expand vector types if we have the appropriate vector bit operations.
10843 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
10844 return SDValue();
10845
10846 // If the active bits are not at the low end, shift them down
10847 if (EffectiveLen < Len && TZ > 0) {
10848 Op = DAG.getNode(ISD::SRL, dl, VT, Op,
10849 DAG.getShiftAmountConstant(TZ, VT, dl));
10850 }
10851
10852 // This is the "best" algorithm from
10853 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
10854 SDValue Mask55 =
10855 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
10856 SDValue Mask33 =
10857 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
10858 SDValue Mask0F =
10859 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
10860
10861 // v = v - ((v >> 1) & 0x55555555...)
10862 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
10863 DAG.getNode(ISD::AND, dl, VT,
10864 DAG.getNode(ISD::SRL, dl, VT, Op,
10865 DAG.getConstant(1, dl, ShVT)),
10866 Mask55));
10867 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
10868 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
10869 DAG.getNode(ISD::AND, dl, VT,
10870 DAG.getNode(ISD::SRL, dl, VT, Op,
10871 DAG.getConstant(2, dl, ShVT)),
10872 Mask33));
10873 // v = (v + (v >> 4)) & 0x0F0F0F0F...
10874 Op = DAG.getNode(ISD::AND, dl, VT,
10875 DAG.getNode(ISD::ADD, dl, VT, Op,
10876 DAG.getNode(ISD::SRL, dl, VT, Op,
10877 DAG.getConstant(4, dl, ShVT))),
10878 Mask0F);
10879
10880 if (EffectiveLen <= 8)
10881 return Op;
10882
10883 // Avoid the multiply if we only have 2 bytes to add.
10884 // TODO: Only doing this for scalars because vectors weren't as obviously
10885 // improved.
10886 if (EffectiveLen == 16 && !VT.isVector()) {
10887 // v = (v + (v >> 8)) & 0x00FF;
10888 return DAG.getNode(ISD::AND, dl, VT,
10889 DAG.getNode(ISD::ADD, dl, VT, Op,
10890 DAG.getNode(ISD::SRL, dl, VT, Op,
10891 DAG.getConstant(8, dl, ShVT))),
10892 DAG.getConstant(0xFF, dl, VT));
10893 }
10894
10895 // v = (v * 0x01010101...) >> (Len - 8)
10896 SDValue V;
10899 SDValue Mask01 =
10900 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
10901 V = DAG.getNode(ISD::MUL, dl, VT, Op, Mask01);
10902 } else {
10903 V = Op;
10904 for (unsigned Shift = 8; Shift < EffectiveLen; Shift *= 2) {
10905 SDValue ShiftC = DAG.getShiftAmountConstant(Shift, VT, dl);
10906 V = DAG.getNode(ISD::ADD, dl, VT, V,
10907 DAG.getNode(ISD::SHL, dl, VT, V, ShiftC));
10908 }
10909 }
10910 return DAG.getNode(ISD::SRL, dl, VT, V, DAG.getConstant(Len - 8, dl, ShVT));
10911}
10912
10914 SDLoc dl(Node);
10915 EVT VT = Node->getValueType(0);
10916 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
10917 SDValue Op = Node->getOperand(0);
10918 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
10919
10920 // If the non-ZERO_POISON version is supported we can use that instead.
10921 if (Node->getOpcode() == ISD::CTLZ_ZERO_POISON &&
10923 return DAG.getNode(ISD::CTLZ, dl, VT, Op);
10924
10925 // If the ZERO_POISON version is supported use that and handle the zero case.
10927 EVT SetCCVT =
10928 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10929 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Op);
10930 SDValue Zero = DAG.getConstant(0, dl, VT);
10931 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
10932 return DAG.getSelect(dl, VT, SrcIsZero,
10933 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
10934 }
10935
10936 // Only expand vector types if we have the appropriate vector bit operations.
10937 // This includes the operations needed to expand CTPOP if it isn't supported.
10938 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
10940 !canExpandVectorCTPOP(*this, VT)) ||
10943 return SDValue();
10944
10945 // for now, we do this:
10946 // x = x | (x >> 1);
10947 // x = x | (x >> 2);
10948 // ...
10949 // x = x | (x >>16);
10950 // x = x | (x >>32); // for 64-bit input
10951 // return popcount(~x);
10952 //
10953 // Ref: "Hacker's Delight" by Henry Warren
10954 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) {
10955 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
10956 Op = DAG.getNode(ISD::OR, dl, VT, Op,
10957 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
10958 }
10959 Op = DAG.getNOT(dl, Op, VT);
10960 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
10961}
10962
10964 SDLoc dl(Node);
10965 EVT VT = Node->getValueType(0);
10966 SDValue Op = DAG.getFreeze(Node->getOperand(0));
10967 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
10968
10969 // CTLS(x) = CTLZ(OR(SHL(XOR(x, SRA(x, BW-1)), 1), 1))
10970 // This transforms the sign bits into leading zeros that can be counted.
10971 SDValue ShiftAmt = DAG.getShiftAmountConstant(NumBitsPerElt - 1, VT, dl);
10972 SDValue SignBit = DAG.getNode(ISD::SRA, dl, VT, Op, ShiftAmt);
10973 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, SignBit);
10974 SDValue Shl =
10975 DAG.getNode(ISD::SHL, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
10976 SDValue Or = DAG.getNode(ISD::OR, dl, VT, Shl, DAG.getConstant(1, dl, VT));
10977 return DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Or);
10978}
10979
10981 const SDLoc &DL, EVT VT, SDValue Op,
10982 unsigned BitWidth) const {
10983 if (BitWidth != 32 && BitWidth != 64)
10984 return SDValue();
10985
10986 const DataLayout &TD = DAG.getDataLayout();
10988 return SDValue();
10989
10990 APInt DeBruijn = BitWidth == 32 ? APInt(32, 0x077CB531U)
10991 : APInt(64, 0x0218A392CD3D5DBFULL);
10992 MachinePointerInfo PtrInfo =
10994 unsigned ShiftAmt = BitWidth - Log2_32(BitWidth);
10995 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
10996 SDValue Lookup = DAG.getNode(
10997 ISD::SRL, DL, VT,
10998 DAG.getNode(ISD::MUL, DL, VT, DAG.getNode(ISD::AND, DL, VT, Op, Neg),
10999 DAG.getConstant(DeBruijn, DL, VT)),
11000 DAG.getShiftAmountConstant(ShiftAmt, VT, DL));
11002
11004 for (unsigned i = 0; i < BitWidth; i++) {
11005 APInt Shl = DeBruijn.shl(i);
11006 APInt Lshr = Shl.lshr(ShiftAmt);
11007 Table[Lshr.getZExtValue()] = i;
11008 }
11009
11010 // Create a ConstantArray in Constant Pool
11011 auto *CA = ConstantDataArray::get(*DAG.getContext(), Table);
11012 SDValue CPIdx = DAG.getConstantPool(CA, getPointerTy(TD),
11013 TD.getPrefTypeAlign(CA->getType()));
11014 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getEntryNode(),
11015 DAG.getMemBasePlusOffset(CPIdx, Lookup, DL),
11016 PtrInfo, MVT::i8);
11017 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON)
11018 return ExtLoad;
11019
11020 EVT SetCCVT =
11021 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11022 SDValue Zero = DAG.getConstant(0, DL, VT);
11023 SDValue SrcIsZero = DAG.getSetCC(DL, SetCCVT, Op, Zero, ISD::SETEQ);
11024 return DAG.getSelect(DL, VT, SrcIsZero,
11025 DAG.getConstant(BitWidth, DL, VT), ExtLoad);
11026}
11027
11029 SDLoc dl(Node);
11030 EVT VT = Node->getValueType(0);
11031 SDValue Op = Node->getOperand(0);
11032 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11033
11034 // If the non-ZERO_POISON version is supported we can use that instead.
11035 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON &&
11037 return DAG.getNode(ISD::CTTZ, dl, VT, Op);
11038
11039 // If the ZERO_POISON version is supported use that and handle the zero case.
11041 EVT SetCCVT =
11042 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11043 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_POISON, dl, VT, Op);
11044 SDValue Zero = DAG.getConstant(0, dl, VT);
11045 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11046 return DAG.getSelect(dl, VT, SrcIsZero,
11047 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
11048 }
11049
11050 // Only expand vector types if we have the appropriate vector bit operations.
11051 // This includes the operations needed to expand CTPOP if it isn't supported.
11052 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11055 !canExpandVectorCTPOP(*this, VT)) ||
11059 return SDValue();
11060
11061 // Emit Table Lookup if ISD::CTPOP used in the fallback path below is going
11062 // to be expanded or converted to a libcall.
11065 if (SDValue V = CTTZTableLookup(Node, DAG, dl, VT, Op, NumBitsPerElt))
11066 return V;
11067
11068 bool UseCTLZ =
11070
11071 // When only ctlz is available and the operand is nonzero we can use:
11072 // { return nlz(x & -x) ^ 31; }
11073 // which is more efficient than:
11074 // { return 32 - nlz(~x & (x - 1)); }.
11075 if (UseCTLZ && Node->getOpcode() == ISD::CTTZ_ZERO_POISON) {
11076 SDValue LowestBit =
11077 DAG.getNode(ISD::AND, dl, VT, Op, DAG.getNegative(Op, dl, VT));
11078 return DAG.getNode(ISD::XOR, dl, VT,
11079 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, LowestBit),
11080 DAG.getConstant(NumBitsPerElt - 1, dl, VT));
11081 }
11082
11083 // If ctpop is available, we use:
11084 // { return popcount(~x & (x-1)); }
11085 // If the target has ctlz but not ctpop, we use:
11086 // { return 32 - nlz(~x & (x-1)); }
11087 // Ref: "Hacker's Delight" by Henry Warren
11088 SDValue Tmp = DAG.getNode(
11089 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
11090 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
11091
11092 if (UseCTLZ)
11093 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
11094 DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
11095
11096 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
11097}
11098
11100 SelectionDAG &DAG) const {
11101 // %cond = to_bool_vec %source
11102 // %splat = splat /*val=*/VL
11103 // %tz = step_vector
11104 // %v = select %cond, /*true=*/tz, /*false=*/%splat
11105 // %r = vp.reduce.umin %v
11106 SDLoc DL(N);
11107 SDValue Source = N->getOperand(0);
11108 SDValue Mask = N->getOperand(1);
11109 SDValue EVL = N->getOperand(2);
11110 EVT SrcVT = Source.getValueType();
11111 EVT ResVT = N->getValueType(0);
11112 EVT ResVecVT =
11113 EVT::getVectorVT(*DAG.getContext(), ResVT, SrcVT.getVectorElementCount());
11114
11115 // Convert to boolean vector.
11116 if (SrcVT.getScalarType() != MVT::i1) {
11117 SDValue AllZero = DAG.getConstant(0, DL, SrcVT);
11118 SrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
11119 SrcVT.getVectorElementCount());
11120 Source = DAG.getSetCC(DL, SrcVT, Source, AllZero, ISD::SETNE);
11121 }
11122
11123 SDValue ExtEVL = DAG.getZExtOrTrunc(EVL, DL, ResVT);
11124 SDValue Splat = DAG.getSplat(ResVecVT, DL, ExtEVL);
11125 SDValue StepVec = DAG.getStepVector(DL, ResVecVT);
11126 SDValue Select = DAG.getSelect(DL, ResVecVT, Source, StepVec, Splat);
11127 return DAG.getNode(ISD::VP_REDUCE_UMIN, DL, ResVT, ExtEVL, Select, Mask, EVL);
11128}
11129
11130/// Returns a type-legalized version of \p Mask as the first item in the
11131/// pair. The second item contains a type-legalized step vector that's
11132/// guaranteed to fit the number of elements in \p Mask.
11133/// If the stepvector would require splitting, returns an empty SDValue
11134/// as the second item to signal that the operation should be split instead.
11135static std::pair<SDValue, SDValue>
11137 SelectionDAG &DAG) {
11138 EVT MaskVT = Mask.getValueType();
11139 EVT BoolVT = MaskVT.getScalarType();
11140
11141 // Find a suitable type for a stepvector.
11142 // If zero is poison, we can assume the upper limit of the result is VF-1.
11143 ConstantRange VScaleRange(1, /*isFullSet=*/true); // Fixed length default.
11144 if (MaskVT.isScalableVector())
11145 VScaleRange = getVScaleRange(&DAG.getMachineFunction().getFunction(), 64);
11146 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11147 uint64_t EltWidth = TLI.getBitWidthForCttzElements(
11148 EVT(TLI.getVectorIdxTy(DAG.getDataLayout())),
11149 MaskVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
11150 // If the step vector element type is smaller than the mask element type,
11151 // use the mask type directly to avoid widening issues.
11152 EltWidth = std::max(EltWidth, BoolVT.getFixedSizeInBits());
11153 EVT StepVT = MVT::getIntegerVT(EltWidth);
11154 EVT StepVecVT = MaskVT.changeVectorElementType(*DAG.getContext(), StepVT);
11155
11156 // If promotion or widening is required to make the type legal, do it here.
11157 // Promotion of integers within LegalizeVectorOps is looking for types of
11158 // the same size but with a smaller number of larger elements, not the usual
11159 // larger size with the same number of larger elements.
11161 TLI.getTypeAction(*DAG.getContext(), StepVecVT);
11162 SDValue StepVec;
11163 if (TypeAction == TargetLowering::TypePromoteInteger) {
11164 StepVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11165 StepVec = DAG.getStepVector(DL, StepVecVT);
11166 } else if (TypeAction == TargetLowering::TypeWidenVector) {
11167 // For widening, the element count changes. Create a step vector with only
11168 // the original elements valid and zeros for padding. Also widen the mask.
11169 EVT WideVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11170 unsigned WideNumElts = WideVecVT.getVectorNumElements();
11171
11172 // Build widened step vector: <0, 1, ..., OrigNumElts-1, poison, poison, ..>
11173 SDValue OrigStepVec = DAG.getStepVector(DL, StepVecVT);
11174 SDValue UndefStep = DAG.getPOISON(WideVecVT);
11175 StepVec = DAG.getInsertSubvector(DL, UndefStep, OrigStepVec, 0);
11176
11177 // Widen mask: pad with zeros.
11178 EVT WideMaskVT = EVT::getVectorVT(*DAG.getContext(), BoolVT, WideNumElts);
11179 SDValue ZeroMask = DAG.getConstant(0, DL, WideMaskVT);
11180 Mask = DAG.getInsertSubvector(DL, ZeroMask, Mask, 0);
11181 } else if (TypeAction == TargetLowering::TypeSplitVector) {
11182 // The stepvector type would require splitting. Signal to the caller
11183 // that the operation should be split instead of expanded.
11184 return {Mask, SDValue()};
11185 } else {
11186 StepVec = DAG.getStepVector(DL, StepVecVT);
11187 }
11188
11189 return {Mask, StepVec};
11190}
11191
11193 SelectionDAG &DAG) const {
11194 SDLoc DL(N);
11195 auto [Mask, StepVec] = getLegalMaskAndStepVector(
11196 N->getOperand(0), /*ZeroIsPoison=*/true, DL, DAG);
11197
11198 // If StepVec is empty, the stepvector would require splitting.
11199 // Split the operation instead and let it be recursively legalized.
11200 if (!StepVec) {
11201 EVT MaskVT = N->getOperand(0).getValueType();
11202 EVT ResVT = N->getValueType(0);
11203
11204 // Split the mask
11205 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(MaskVT);
11206 auto [MaskLo, MaskHi] = DAG.SplitVector(N->getOperand(0), DL);
11207
11208 // Create split VECTOR_FIND_LAST_ACTIVE operations
11209 SDValue LoResult =
11210 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskLo);
11211 SDValue HiResult =
11212 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskHi);
11213
11214 // Check if any lane is active in the high mask.
11215 SDValue AnyHiActive = DAG.getNode(ISD::VECREDUCE_OR, DL, MVT::i1, MaskHi);
11217 AnyHiActive, DL,
11218 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i1),
11219 MVT::i1);
11220
11221 // Adjust HiResult by adding the number of elements in Lo
11222 SDValue LoNumElts =
11223 DAG.getElementCount(DL, ResVT, LoVT.getVectorElementCount());
11224 SDValue AdjustedHiResult =
11225 DAG.getNode(ISD::ADD, DL, ResVT, HiResult, LoNumElts);
11226
11227 // Return: AnyHiActive ? AdjustedHiResult : LoResult;
11228 return DAG.getNode(ISD::SELECT, DL, ResVT, Cond, AdjustedHiResult,
11229 LoResult);
11230 }
11231
11232 EVT StepVecVT = StepVec.getValueType();
11233 EVT StepVT = StepVec.getValueType().getVectorElementType();
11234
11235 // Zero out lanes with inactive elements, then find the highest remaining
11236 // value from the stepvector.
11237 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
11238 SDValue ActiveElts = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
11239 SDValue HighestIdx = DAG.getNode(ISD::VECREDUCE_UMAX, DL, StepVT, ActiveElts);
11240 return DAG.getZExtOrTrunc(HighestIdx, DL, N->getValueType(0));
11241}
11242
11244 SelectionDAG &DAG) const {
11245 SDLoc DL(N);
11246 EVT VT = N->getValueType(0);
11247 SDValue SourceValue = N->getOperand(0);
11248 SDValue SinkValue = N->getOperand(1);
11249 SDValue EltSizeInBytes = N->getOperand(2);
11250
11251 // Note: The lane offset is scalable if the mask is scalable.
11252 ElementCount LaneOffsetEC =
11253 ElementCount::get(N->getConstantOperandVal(3), VT.isScalableVT());
11254
11255 EVT AddrVT = SourceValue->getValueType(0);
11256 bool IsReadAfterWrite = N->getOpcode() == ISD::LOOP_DEPENDENCE_RAW_MASK;
11257
11258 EVT CmpVT =
11259 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), AddrVT);
11260
11261 // Unsigned compare: Source >= Sink.
11262 SDValue SourceAheadOfOrEqualToSink =
11263 DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETUGE);
11264
11265 // Take the difference between the pointers and divided by the element size,
11266 // to see how many lanes separate them.
11267 SDValue Diff = DAG.getNode(ISD::SUB, DL, AddrVT, SinkValue, SourceValue);
11268
11269 // RAW_MASK: Diff = Source >= Sink ? (Source - Sink) : (Sink - Source)
11270 if (IsReadAfterWrite)
11271 Diff = DAG.getSelect(DL, AddrVT, SourceAheadOfOrEqualToSink,
11272 DAG.getNegative(Diff, DL, AddrVT), Diff);
11273
11274 Diff = DAG.getNode(ISD::SDIV, DL, AddrVT, Diff, EltSizeInBytes);
11275
11276 // The pointers do not alias if:
11277 // - Source >= Sink (WAR_MASK)
11278 // - Source == Sink (RAW_MASK)
11279 SDValue NoAlias = SourceAheadOfOrEqualToSink;
11280 if (IsReadAfterWrite)
11281 NoAlias = DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETEQ);
11282
11283 // The pointers do not alias if:
11284 // Lane + LaneOffset < Diff (WAR/RAW_MASK)
11285 SDValue LaneOffset = DAG.getElementCount(DL, AddrVT, LaneOffsetEC);
11286 SDValue MaskN = DAG.getSelect(
11287 DL, AddrVT, NoAlias,
11289 AddrVT),
11290 Diff);
11291
11292 return DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, VT, LaneOffset, MaskN);
11293}
11294
11296 bool IsNegative) const {
11297 SDLoc dl(N);
11298 EVT VT = N->getValueType(0);
11299 SDValue Op = N->getOperand(0);
11300
11301 // If expanding ABS_MIN_POISON, fall back to ABS if the target supports it.
11302 if (N->getOpcode() == ISD::ABS_MIN_POISON &&
11304 SDValue AbsVal = DAG.getNode(ISD::ABS, dl, VT, Op);
11305 if (IsNegative)
11306 return DAG.getNegative(AbsVal, dl, VT);
11307 return AbsVal;
11308 }
11309
11310 // abs(x) -> smax(x,sub(0,x))
11311 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11313 SDValue Zero = DAG.getConstant(0, dl, VT);
11314 Op = DAG.getFreeze(Op);
11315 return DAG.getNode(ISD::SMAX, dl, VT, Op,
11316 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11317 }
11318
11319 // abs(x) -> umin(x,sub(0,x))
11320 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11322 SDValue Zero = DAG.getConstant(0, dl, VT);
11323 Op = DAG.getFreeze(Op);
11324 return DAG.getNode(ISD::UMIN, dl, VT, Op,
11325 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11326 }
11327
11328 // 0 - abs(x) -> smin(x, sub(0,x))
11329 if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
11331 SDValue Zero = DAG.getConstant(0, dl, VT);
11332 Op = DAG.getFreeze(Op);
11333 return DAG.getNode(ISD::SMIN, dl, VT, Op,
11334 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11335 }
11336
11337 // Only expand vector types if we have the appropriate vector operations.
11338 if (VT.isVector() &&
11340 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
11341 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
11343 return SDValue();
11344
11345 Op = DAG.getFreeze(Op);
11346 SDValue Shift = DAG.getNode(
11347 ISD::SRA, dl, VT, Op,
11348 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11349 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
11350
11351 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
11352 if (!IsNegative)
11353 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
11354
11355 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
11356 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
11357}
11358
11360 SDLoc dl(N);
11361 EVT VT = N->getValueType(0);
11362 SDValue LHS = N->getOperand(0);
11363 SDValue RHS = N->getOperand(1);
11364 bool IsSigned = N->getOpcode() == ISD::ABDS;
11365
11366 // abds(lhs, rhs) -> sub(smax(lhs,rhs), smin(lhs,rhs))
11367 // abdu(lhs, rhs) -> sub(umax(lhs,rhs), umin(lhs,rhs))
11368 unsigned MaxOpc = IsSigned ? ISD::SMAX : ISD::UMAX;
11369 unsigned MinOpc = IsSigned ? ISD::SMIN : ISD::UMIN;
11370 if (isOperationLegal(MaxOpc, VT) && isOperationLegal(MinOpc, VT)) {
11371 LHS = DAG.getFreeze(LHS);
11372 RHS = DAG.getFreeze(RHS);
11373 SDValue Max = DAG.getNode(MaxOpc, dl, VT, LHS, RHS);
11374 SDValue Min = DAG.getNode(MinOpc, dl, VT, LHS, RHS);
11375 return DAG.getNode(ISD::SUB, dl, VT, Max, Min);
11376 }
11377
11378 // abdu(lhs, rhs) -> or(usubsat(lhs,rhs), usubsat(rhs,lhs))
11379 if (!IsSigned && isOperationLegal(ISD::USUBSAT, VT)) {
11380 LHS = DAG.getFreeze(LHS);
11381 RHS = DAG.getFreeze(RHS);
11382 return DAG.getNode(ISD::OR, dl, VT,
11383 DAG.getNode(ISD::USUBSAT, dl, VT, LHS, RHS),
11384 DAG.getNode(ISD::USUBSAT, dl, VT, RHS, LHS));
11385 }
11386
11387 // If the subtract doesn't overflow then just use abs(sub())
11388 bool IsNonNegative = DAG.SignBitIsZero(LHS) && DAG.SignBitIsZero(RHS);
11389
11390 if (DAG.willNotOverflowSub(IsSigned || IsNonNegative, LHS, RHS))
11391 return DAG.getNode(ISD::ABS, dl, VT,
11392 DAG.getNode(ISD::SUB, dl, VT, LHS, RHS));
11393
11394 if (DAG.willNotOverflowSub(IsSigned || IsNonNegative, RHS, LHS))
11395 return DAG.getNode(ISD::ABS, dl, VT,
11396 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11397
11398 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11400 LHS = DAG.getFreeze(LHS);
11401 RHS = DAG.getFreeze(RHS);
11402 SDValue Cmp = DAG.getSetCC(dl, CCVT, LHS, RHS, CC);
11403
11404 // Branchless expansion iff cmp result is allbits:
11405 // abds(lhs, rhs) -> sub(sgt(lhs, rhs), xor(sgt(lhs, rhs), sub(lhs, rhs)))
11406 // abdu(lhs, rhs) -> sub(ugt(lhs, rhs), xor(ugt(lhs, rhs), sub(lhs, rhs)))
11407 if (CCVT == VT && getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
11408 SDValue Diff = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
11409 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Diff, Cmp);
11410 return DAG.getNode(ISD::SUB, dl, VT, Cmp, Xor);
11411 }
11412
11413 // Similar to the branchless expansion, if we don't prefer selects, use the
11414 // (sign-extended) usubo overflow flag if the (scalar) type is illegal as this
11415 // is more likely to legalize cleanly: abdu(lhs, rhs) -> sub(xor(sub(lhs,
11416 // rhs), uof(lhs, rhs)), uof(lhs, rhs))
11417 if (!IsSigned && VT.isScalarInteger() && !isTypeLegal(VT) &&
11419 SDValue USubO =
11420 DAG.getNode(ISD::USUBO, dl, DAG.getVTList(VT, MVT::i1), {LHS, RHS});
11421 SDValue Cmp = DAG.getNode(ISD::SIGN_EXTEND, dl, VT, USubO.getValue(1));
11422 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, USubO.getValue(0), Cmp);
11423 return DAG.getNode(ISD::SUB, dl, VT, Xor, Cmp);
11424 }
11425
11426 // FIXME: Should really try to split the vector in case it's legal on a
11427 // subvector.
11429 return DAG.UnrollVectorOp(N);
11430
11431 // abds(lhs, rhs) -> select(sgt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11432 // abdu(lhs, rhs) -> select(ugt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11433 return DAG.getSelect(dl, VT, Cmp, DAG.getNode(ISD::SUB, dl, VT, LHS, RHS),
11434 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11435}
11436
11438 SDLoc dl(N);
11439 EVT VT = N->getValueType(0);
11440 SDValue LHS = N->getOperand(0);
11441 SDValue RHS = N->getOperand(1);
11442
11443 unsigned Opc = N->getOpcode();
11444 bool IsFloor = Opc == ISD::AVGFLOORS || Opc == ISD::AVGFLOORU;
11445 bool IsSigned = Opc == ISD::AVGCEILS || Opc == ISD::AVGFLOORS;
11446 unsigned SumOpc = IsFloor ? ISD::ADD : ISD::SUB;
11447 unsigned SignOpc = IsFloor ? ISD::AND : ISD::OR;
11448 unsigned ShiftOpc = IsSigned ? ISD::SRA : ISD::SRL;
11449 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
11451 Opc == ISD::AVGFLOORU || Opc == ISD::AVGCEILU) &&
11452 "Unknown AVG node");
11453
11454 // If the operands are already extended, we can add+shift.
11455 bool IsExt =
11456 (IsSigned && DAG.ComputeNumSignBits(LHS) >= 2 &&
11457 DAG.ComputeNumSignBits(RHS) >= 2) ||
11458 (!IsSigned && DAG.computeKnownBits(LHS).countMinLeadingZeros() >= 1 &&
11459 DAG.computeKnownBits(RHS).countMinLeadingZeros() >= 1);
11460 if (IsExt) {
11461 SDValue Sum = DAG.getNode(ISD::ADD, dl, VT, LHS, RHS);
11462 if (!IsFloor)
11463 Sum = DAG.getNode(ISD::ADD, dl, VT, Sum, DAG.getConstant(1, dl, VT));
11464 return DAG.getNode(ShiftOpc, dl, VT, Sum,
11465 DAG.getShiftAmountConstant(1, VT, dl));
11466 }
11467
11468 // For scalars, see if we can efficiently extend/truncate to use add+shift.
11469 if (VT.isScalarInteger()) {
11470 EVT ExtVT = VT.widenIntegerElementType(*DAG.getContext());
11471 if (isTypeLegal(ExtVT) && isTruncateFree(ExtVT, VT)) {
11472 LHS = DAG.getNode(ExtOpc, dl, ExtVT, LHS);
11473 RHS = DAG.getNode(ExtOpc, dl, ExtVT, RHS);
11474 SDValue Avg = DAG.getNode(ISD::ADD, dl, ExtVT, LHS, RHS);
11475 if (!IsFloor)
11476 Avg = DAG.getNode(ISD::ADD, dl, ExtVT, Avg,
11477 DAG.getConstant(1, dl, ExtVT));
11478 // Just use SRL as we will be truncating away the extended sign bits.
11479 Avg = DAG.getNode(ISD::SRL, dl, ExtVT, Avg,
11480 DAG.getShiftAmountConstant(1, ExtVT, dl));
11481 return DAG.getNode(ISD::TRUNCATE, dl, VT, Avg);
11482 }
11483 }
11484
11485 // avgflooru(lhs, rhs) -> or(lshr(add(lhs, rhs),1),shl(overflow, typesize-1))
11486 if (Opc == ISD::AVGFLOORU && VT.isScalarInteger() && !isTypeLegal(VT) &&
11489 SDValue UAddWithOverflow =
11490 DAG.getNode(ISD::UADDO, dl, DAG.getVTList(VT, MVT::i1), {RHS, LHS});
11491
11492 SDValue Sum = UAddWithOverflow.getValue(0);
11493 SDValue Overflow = UAddWithOverflow.getValue(1);
11494
11495 // Right shift the sum by 1
11496 SDValue LShrVal = DAG.getNode(ISD::SRL, dl, VT, Sum,
11497 DAG.getShiftAmountConstant(1, VT, dl));
11498
11499 SDValue ZeroExtOverflow = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Overflow);
11500 SDValue OverflowShl = DAG.getNode(
11501 ISD::SHL, dl, VT, ZeroExtOverflow,
11502 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11503
11504 return DAG.getNode(ISD::OR, dl, VT, LShrVal, OverflowShl);
11505 }
11506
11507 // avgceils(lhs, rhs) -> sub(or(lhs,rhs),ashr(xor(lhs,rhs),1))
11508 // avgceilu(lhs, rhs) -> sub(or(lhs,rhs),lshr(xor(lhs,rhs),1))
11509 // avgfloors(lhs, rhs) -> add(and(lhs,rhs),ashr(xor(lhs,rhs),1))
11510 // avgflooru(lhs, rhs) -> add(and(lhs,rhs),lshr(xor(lhs,rhs),1))
11511 LHS = DAG.getFreeze(LHS);
11512 RHS = DAG.getFreeze(RHS);
11513 SDValue Sign = DAG.getNode(SignOpc, dl, VT, LHS, RHS);
11514 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
11515 SDValue Shift =
11516 DAG.getNode(ShiftOpc, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11517 return DAG.getNode(SumOpc, dl, VT, Sign, Shift);
11518}
11519
11521 SDLoc dl(N);
11522 EVT VT = N->getValueType(0);
11523 SDValue Op = N->getOperand(0);
11524
11525 if (!VT.isSimple())
11526 return SDValue();
11527
11528 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11529 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
11530 switch (VT.getSimpleVT().getScalarType().SimpleTy) {
11531 default:
11532 return SDValue();
11533 case MVT::i16:
11534 // Use a rotate by 8. This can be further expanded if necessary.
11535 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11536 case MVT::i32:
11537 // This is meant for ARM specifically, which has ROTR but no ROTL.
11538 // t = x ^ rotr(x, 16)
11539 // t = bic(t, 0x00ff0000)
11540 // t = lshr(t, 8)
11541 // x = t ^ rotr(x, 8)
11543 SDValue Rotr16 =
11544 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(16, dl, SHVT));
11545 SDValue Tmp = DAG.getNode(ISD::XOR, dl, VT, Op, Rotr16);
11546 Tmp = DAG.getNode(ISD::AND, dl, VT, Tmp,
11547 DAG.getConstant(0xFF00FFFF, dl, VT));
11548 Tmp = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(8, dl, SHVT));
11549 SDValue Rotr8 =
11550 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11551 return DAG.getNode(ISD::XOR, dl, VT, Tmp, Rotr8);
11552 }
11553 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11554 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Op,
11555 DAG.getConstant(0xFF00, dl, VT));
11556 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT));
11557 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11558 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
11559 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11560 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
11561 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
11562 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
11563 case MVT::i64:
11564 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
11565 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Op,
11566 DAG.getConstant(255ULL<<8, dl, VT));
11567 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT));
11568 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Op,
11569 DAG.getConstant(255ULL<<16, dl, VT));
11570 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT));
11571 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Op,
11572 DAG.getConstant(255ULL<<24, dl, VT));
11573 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT));
11574 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11575 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
11576 DAG.getConstant(255ULL<<24, dl, VT));
11577 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11578 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
11579 DAG.getConstant(255ULL<<16, dl, VT));
11580 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
11581 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
11582 DAG.getConstant(255ULL<<8, dl, VT));
11583 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
11584 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
11585 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
11586 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
11587 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
11588 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
11589 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
11590 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
11591 }
11592}
11593
11595 SDLoc dl(N);
11596 EVT VT = N->getValueType(0);
11597 SDValue Op = N->getOperand(0);
11598 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11599 unsigned Sz = VT.getScalarSizeInBits();
11600
11601 SDValue Tmp, Tmp2, Tmp3;
11602
11603 // If we can, perform BSWAP first and then the mask+swap the i4, then i2
11604 // and finally the i1 pairs.
11605 // TODO: We can easily support i4/i2 legal types if any target ever does.
11606 if (Sz >= 8 && isPowerOf2_32(Sz)) {
11607 // Create the masks - repeating the pattern every byte.
11608 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
11609 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
11610 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
11611
11612 // BSWAP if the type is wider than a single byte.
11613 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
11614
11615 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
11616 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
11617 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
11618 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
11619 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
11620 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11621
11622 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
11623 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
11624 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
11625 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
11626 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
11627 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11628
11629 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
11630 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
11631 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
11632 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
11633 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
11634 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11635 return Tmp;
11636 }
11637
11638 Tmp = DAG.getConstant(0, dl, VT);
11639 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
11640 if (I < J)
11641 Tmp2 =
11642 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
11643 else
11644 Tmp2 =
11645 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
11646
11647 APInt Shift = APInt::getOneBitSet(Sz, J);
11648 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
11649 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
11650 }
11651
11652 return Tmp;
11653}
11654
11655std::pair<SDValue, SDValue>
11657 SelectionDAG &DAG) const {
11658 SDLoc SL(LD);
11659 SDValue Chain = LD->getChain();
11660 SDValue BasePTR = LD->getBasePtr();
11661 EVT SrcVT = LD->getMemoryVT();
11662 EVT DstVT = LD->getValueType(0);
11663 ISD::LoadExtType ExtType = LD->getExtensionType();
11664
11665 if (SrcVT.isScalableVector())
11666 report_fatal_error("Cannot scalarize scalable vector loads");
11667
11668 unsigned NumElem = SrcVT.getVectorNumElements();
11669
11670 EVT SrcEltVT = SrcVT.getScalarType();
11671 EVT DstEltVT = DstVT.getScalarType();
11672
11673 // A vector must always be stored in memory as-is, i.e. without any padding
11674 // between the elements, since various code depend on it, e.g. in the
11675 // handling of a bitcast of a vector type to int, which may be done with a
11676 // vector store followed by an integer load. A vector that does not have
11677 // elements that are byte-sized must therefore be stored as an integer
11678 // built out of the extracted vector elements.
11679 if (!SrcEltVT.isByteSized()) {
11680 unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
11681 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
11682
11683 unsigned NumSrcBits = SrcVT.getSizeInBits();
11684 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
11685
11686 unsigned SrcEltBits = SrcEltVT.getSizeInBits();
11687 SDValue SrcEltBitMask = DAG.getConstant(
11688 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
11689
11690 // Load the whole vector and avoid masking off the top bits as it makes
11691 // the codegen worse.
11692 SDValue Load =
11693 DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR,
11694 LD->getPointerInfo(), SrcIntVT, LD->getBaseAlign(),
11695 LD->getMemOperand()->getFlags(), LD->getAAInfo());
11696
11698 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11699 unsigned ShiftIntoIdx =
11700 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
11701 SDValue ShiftAmount = DAG.getShiftAmountConstant(
11702 ShiftIntoIdx * SrcEltVT.getSizeInBits(), LoadVT, SL);
11703 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
11704 SDValue Elt =
11705 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
11706 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
11707
11708 if (ExtType != ISD::NON_EXTLOAD) {
11709 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
11710 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
11711 }
11712
11713 Vals.push_back(Scalar);
11714 }
11715
11716 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
11717 return std::make_pair(Value, Load.getValue(1));
11718 }
11719
11720 unsigned Stride = SrcEltVT.getSizeInBits() / 8;
11721 assert(SrcEltVT.isByteSized());
11722
11724 SmallVector<SDValue, 8> LoadChains;
11725
11726 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11727 SDValue ScalarLoad = DAG.getExtLoad(
11728 ExtType, SL, DstEltVT, Chain, BasePTR,
11729 LD->getPointerInfo().getWithOffset(Idx * Stride), SrcEltVT,
11730 LD->getBaseAlign(), LD->getMemOperand()->getFlags(), LD->getAAInfo());
11731
11732 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::getFixed(Stride));
11733
11734 Vals.push_back(ScalarLoad.getValue(0));
11735 LoadChains.push_back(ScalarLoad.getValue(1));
11736 }
11737
11738 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
11739 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
11740
11741 return std::make_pair(Value, NewChain);
11742}
11743
11745 SelectionDAG &DAG) const {
11746 SDLoc SL(ST);
11747
11748 SDValue Chain = ST->getChain();
11749 SDValue BasePtr = ST->getBasePtr();
11750 SDValue Value = ST->getValue();
11751 EVT StVT = ST->getMemoryVT();
11752
11753 if (StVT.isScalableVector())
11754 report_fatal_error("Cannot scalarize scalable vector stores");
11755
11756 // The type of the data we want to save
11757 EVT RegVT = Value.getValueType();
11758 EVT RegSclVT = RegVT.getScalarType();
11759
11760 // The type of data as saved in memory.
11761 EVT MemSclVT = StVT.getScalarType();
11762
11763 unsigned NumElem = StVT.getVectorNumElements();
11764
11765 // A vector must always be stored in memory as-is, i.e. without any padding
11766 // between the elements, since various code depend on it, e.g. in the
11767 // handling of a bitcast of a vector type to int, which may be done with a
11768 // vector store followed by an integer load. A vector that does not have
11769 // elements that are byte-sized must therefore be stored as an integer
11770 // built out of the extracted vector elements.
11771 if (!MemSclVT.isByteSized()) {
11772 unsigned NumBits = StVT.getSizeInBits();
11773 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
11774
11775 SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
11776
11777 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11778 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
11779 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
11780 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
11781 unsigned ShiftIntoIdx =
11782 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
11783 SDValue ShiftAmount =
11784 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
11785 SDValue ShiftedElt =
11786 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
11787 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
11788 }
11789
11790 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
11791 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
11792 ST->getAAInfo());
11793 }
11794
11795 // Store Stride in bytes
11796 unsigned Stride = MemSclVT.getSizeInBits() / 8;
11797 assert(Stride && "Zero stride!");
11798 // Extract each of the elements from the original vector and save them into
11799 // memory individually.
11801 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11802 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
11803
11804 SDValue Ptr =
11805 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Idx * Stride));
11806
11807 // This scalar TruncStore may be illegal, but we legalize it later.
11809 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
11810 MemSclVT, ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
11811 ST->getAAInfo());
11812
11813 Stores.push_back(Store);
11814 }
11815
11816 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
11817}
11818
11819std::pair<SDValue, SDValue>
11821 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
11822 "unaligned indexed loads not implemented!");
11823 SDValue Chain = LD->getChain();
11824 SDValue Ptr = LD->getBasePtr();
11825 EVT VT = LD->getValueType(0);
11826 EVT LoadedVT = LD->getMemoryVT();
11827 SDLoc dl(LD);
11828 auto &MF = DAG.getMachineFunction();
11829
11830 if (VT.isFloatingPoint() || VT.isVector()) {
11831 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
11832 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
11833 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
11834 LoadedVT.isVector()) {
11835 // Scalarize the load and let the individual components be handled.
11836 return scalarizeVectorLoad(LD, DAG);
11837 }
11838
11839 // Expand to a (misaligned) integer load of the same size,
11840 // then bitconvert to floating point or vector.
11841 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
11842 LD->getMemOperand());
11843 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
11844 if (LoadedVT != VT)
11845 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
11846 ISD::ANY_EXTEND, dl, VT, Result);
11847
11848 return std::make_pair(Result, newLoad.getValue(1));
11849 }
11850
11851 // Copy the value to a (aligned) stack slot using (unaligned) integer
11852 // loads and stores, then do a (aligned) load from the stack slot.
11853 MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
11854 unsigned LoadedBytes = LoadedVT.getStoreSize();
11855 unsigned RegBytes = RegVT.getSizeInBits() / 8;
11856 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
11857
11858 // Make sure the stack slot is also aligned for the register type.
11859 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
11860 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
11862 SDValue StackPtr = StackBase;
11863 unsigned Offset = 0;
11864
11865 EVT PtrVT = Ptr.getValueType();
11866 EVT StackPtrVT = StackPtr.getValueType();
11867
11868 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
11869 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
11870
11871 // Do all but one copies using the full register width.
11872 for (unsigned i = 1; i < NumRegs; i++) {
11873 // Load one integer register's worth from the original location.
11874 SDValue Load = DAG.getLoad(
11875 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
11876 LD->getBaseAlign(), LD->getMemOperand()->getFlags(), LD->getAAInfo());
11877 // Follow the load with a store to the stack slot. Remember the store.
11878 Stores.push_back(DAG.getStore(
11879 Load.getValue(1), dl, Load, StackPtr,
11880 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
11881 // Increment the pointers.
11882 Offset += RegBytes;
11883
11884 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
11885 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
11886 }
11887
11888 // The last copy may be partial. Do an extending load.
11889 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
11890 8 * (LoadedBytes - Offset));
11891 SDValue Load = DAG.getExtLoad(
11892 ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
11893 LD->getPointerInfo().getWithOffset(Offset), MemVT, LD->getBaseAlign(),
11894 LD->getMemOperand()->getFlags(), LD->getAAInfo());
11895 // Follow the load with a store to the stack slot. Remember the store.
11896 // On big-endian machines this requires a truncating store to ensure
11897 // that the bits end up in the right place.
11898 Stores.push_back(DAG.getTruncStore(
11899 Load.getValue(1), dl, Load, StackPtr,
11900 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
11901
11902 // The order of the stores doesn't matter - say it with a TokenFactor.
11903 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
11904
11905 // Finally, perform the original load only redirected to the stack slot.
11906 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
11907 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
11908 LoadedVT);
11909
11910 // Callers expect a MERGE_VALUES node.
11911 return std::make_pair(Load, TF);
11912 }
11913
11914 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
11915 "Unaligned load of unsupported type.");
11916
11917 // Compute the new VT that is half the size of the old one. This is an
11918 // integer MVT.
11919 unsigned NumBits = LoadedVT.getSizeInBits();
11920 EVT NewLoadedVT;
11921 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
11922 NumBits >>= 1;
11923
11924 Align Alignment = LD->getBaseAlign();
11925 unsigned IncrementSize = NumBits / 8;
11926 ISD::LoadExtType HiExtType = LD->getExtensionType();
11927
11928 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
11929 if (HiExtType == ISD::NON_EXTLOAD)
11930 HiExtType = ISD::ZEXTLOAD;
11931
11932 // Load the value in two parts
11933 SDValue Lo, Hi;
11934 if (DAG.getDataLayout().isLittleEndian()) {
11935 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
11936 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
11937 LD->getAAInfo());
11938
11939 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
11940 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
11941 LD->getPointerInfo().getWithOffset(IncrementSize),
11942 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
11943 LD->getAAInfo());
11944 } else {
11945 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
11946 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
11947 LD->getAAInfo());
11948
11949 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
11950 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
11951 LD->getPointerInfo().getWithOffset(IncrementSize),
11952 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
11953 LD->getAAInfo());
11954 }
11955
11956 // aggregate the two parts
11957 SDValue ShiftAmount = DAG.getShiftAmountConstant(NumBits, VT, dl);
11958 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
11959 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
11960
11961 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
11962 Hi.getValue(1));
11963
11964 return std::make_pair(Result, TF);
11965}
11966
11968 SelectionDAG &DAG) const {
11969 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
11970 "unaligned indexed stores not implemented!");
11971 SDValue Chain = ST->getChain();
11972 SDValue Ptr = ST->getBasePtr();
11973 SDValue Val = ST->getValue();
11974 EVT VT = Val.getValueType();
11975 Align Alignment = ST->getBaseAlign();
11976 auto &MF = DAG.getMachineFunction();
11977 EVT StoreMemVT = ST->getMemoryVT();
11978
11979 SDLoc dl(ST);
11980 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
11981 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
11982 if (isTypeLegal(intVT)) {
11983 if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
11984 StoreMemVT.isVector()) {
11985 // Scalarize the store and let the individual components be handled.
11986 SDValue Result = scalarizeVectorStore(ST, DAG);
11987 return Result;
11988 }
11989 // Expand to a bitconvert of the value to the integer type of the
11990 // same size, then a (misaligned) int store.
11991 // FIXME: Does not handle truncating floating point stores!
11992 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
11993 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
11994 Alignment, ST->getMemOperand()->getFlags());
11995 return Result;
11996 }
11997 // Do a (aligned) store to a stack slot, then copy from the stack slot
11998 // to the final destination using (unaligned) integer loads and stores.
11999 MVT RegVT = getRegisterType(
12000 *DAG.getContext(),
12001 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
12002 EVT PtrVT = Ptr.getValueType();
12003 unsigned StoredBytes = StoreMemVT.getStoreSize();
12004 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12005 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
12006
12007 // Make sure the stack slot is also aligned for the register type.
12008 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
12009 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
12010
12011 // Perform the original store, only redirected to the stack slot.
12013 Chain, dl, Val, StackPtr,
12014 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
12015
12016 EVT StackPtrVT = StackPtr.getValueType();
12017
12018 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12019 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12021 unsigned Offset = 0;
12022
12023 // Do all but one copies using the full register width.
12024 for (unsigned i = 1; i < NumRegs; i++) {
12025 // Load one integer register's worth from the stack slot.
12026 SDValue Load = DAG.getLoad(
12027 RegVT, dl, Store, StackPtr,
12028 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
12029 // Store it to the final location. Remember the store.
12030 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
12031 ST->getPointerInfo().getWithOffset(Offset),
12032 ST->getBaseAlign(),
12033 ST->getMemOperand()->getFlags()));
12034 // Increment the pointers.
12035 Offset += RegBytes;
12036 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12037 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12038 }
12039
12040 // The last store may be partial. Do a truncating store. On big-endian
12041 // machines this requires an extending load from the stack slot to ensure
12042 // that the bits are in the right place.
12043 EVT LoadMemVT =
12044 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
12045
12046 // Load from the stack slot.
12047 SDValue Load = DAG.getExtLoad(
12048 ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
12049 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
12050
12051 Stores.push_back(DAG.getTruncStore(
12052 Load.getValue(1), dl, Load, Ptr,
12053 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
12054 ST->getBaseAlign(), ST->getMemOperand()->getFlags(), ST->getAAInfo()));
12055 // The order of the stores doesn't matter - say it with a TokenFactor.
12056 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12057 return Result;
12058 }
12059
12060 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
12061 "Unaligned store of unknown type.");
12062 // Get the half-size VT
12063 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
12064 unsigned NumBits = NewStoredVT.getFixedSizeInBits();
12065 unsigned IncrementSize = NumBits / 8;
12066
12067 // Divide the stored value in two parts.
12068 SDValue ShiftAmount =
12069 DAG.getShiftAmountConstant(NumBits, Val.getValueType(), dl);
12070 SDValue Lo = Val;
12071 // If Val is a constant, replace the upper bits with 0. The SRL will constant
12072 // fold and not use the upper bits. A smaller constant may be easier to
12073 // materialize.
12074 if (auto *C = dyn_cast<ConstantSDNode>(Lo); C && !C->isOpaque())
12075 Lo = DAG.getNode(
12076 ISD::AND, dl, VT, Lo,
12077 DAG.getConstant(APInt::getLowBitsSet(VT.getSizeInBits(), NumBits), dl,
12078 VT));
12079 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
12080
12081 // Store the two parts
12082 SDValue Store1, Store2;
12083 Store1 = DAG.getTruncStore(Chain, dl,
12084 DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
12085 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
12086 ST->getMemOperand()->getFlags());
12087
12088 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12089 Store2 = DAG.getTruncStore(
12090 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
12091 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
12092 ST->getMemOperand()->getFlags(), ST->getAAInfo());
12093
12094 SDValue Result =
12095 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
12096 return Result;
12097}
12098
12099SDValue
12101 const SDLoc &DL, EVT DataVT,
12102 SelectionDAG &DAG,
12103 bool IsCompressedMemory) const {
12105 EVT AddrVT = Addr.getValueType();
12106 EVT MaskVT = Mask.getValueType();
12107 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
12108 "Incompatible types of Data and Mask");
12109 if (IsCompressedMemory) {
12110 // Incrementing the pointer according to number of '1's in the mask.
12111 if (DataVT.isScalableVector()) {
12112 EVT MaskExtVT = MaskVT.changeElementType(*DAG.getContext(), MVT::i32);
12113 SDValue MaskExt = DAG.getNode(ISD::ZERO_EXTEND, DL, MaskExtVT, Mask);
12114 Increment = DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i32, MaskExt);
12115 } else {
12116 EVT MaskIntVT =
12117 EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
12118 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
12119 if (MaskIntVT.getSizeInBits() < 32) {
12120 MaskInIntReg =
12121 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
12122 MaskIntVT = MVT::i32;
12123 }
12124 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
12125 }
12126 // Scale is an element size in bytes.
12127 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
12128 AddrVT);
12129 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
12130 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
12131 } else
12132 Increment = DAG.getTypeSize(DL, AddrVT, DataVT.getStoreSize());
12133
12134 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
12135}
12136
12138 EVT VecVT, const SDLoc &dl,
12139 ElementCount SubEC) {
12140 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
12141 "Cannot index a scalable vector within a fixed-width vector");
12142
12143 unsigned NElts = VecVT.getVectorMinNumElements();
12144 unsigned NumSubElts = SubEC.getKnownMinValue();
12145 EVT IdxVT = Idx.getValueType();
12146
12147 if (VecVT.isScalableVector() && !SubEC.isScalable()) {
12148 // If this is a constant index and we know the value plus the number of the
12149 // elements in the subvector minus one is less than the minimum number of
12150 // elements then it's safe to return Idx.
12151 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx))
12152 if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts)
12153 return Idx;
12154 SDValue VS =
12155 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts));
12156 unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT;
12157 SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS,
12158 DAG.getConstant(NumSubElts, dl, IdxVT));
12159 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub);
12160 }
12161 if (isPowerOf2_32(NElts) && NumSubElts == 1) {
12163 return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
12164 DAG.getConstant(Imm, dl, IdxVT));
12165 }
12166 unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0;
12167 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
12168 DAG.getConstant(MaxIndex, dl, IdxVT));
12169}
12170
12171SDValue
12173 EVT VecVT, SDValue Index,
12174 const SDNodeFlags PtrArithFlags) const {
12176 DAG, VecPtr, VecVT,
12178 Index, PtrArithFlags);
12179}
12180
12181SDValue
12183 EVT VecVT, EVT SubVecVT, SDValue Index,
12184 const SDNodeFlags PtrArithFlags) const {
12185 SDLoc dl(Index);
12186 // Make sure the index type is big enough to compute in.
12187 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
12188
12189 EVT EltVT = VecVT.getVectorElementType();
12190
12191 // Calculate the element offset and add it to the pointer.
12192 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
12193 assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
12194 "Converting bits to bytes lost precision");
12195 assert(SubVecVT.getVectorElementType() == EltVT &&
12196 "Sub-vector must be a vector with matching element type");
12197 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
12198 SubVecVT.getVectorElementCount());
12199
12200 EVT IdxVT = Index.getValueType();
12201 if (SubVecVT.isScalableVector())
12202 Index =
12203 DAG.getNode(ISD::MUL, dl, IdxVT, Index,
12204 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1)));
12205
12206 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
12207 DAG.getConstant(EltSize, dl, IdxVT));
12208 return DAG.getMemBasePlusOffset(VecPtr, Index, dl, PtrArithFlags);
12209}
12210
12211//===----------------------------------------------------------------------===//
12212// Implementation of Emulated TLS Model
12213//===----------------------------------------------------------------------===//
12214
12216 SelectionDAG &DAG) const {
12217 // Access to address of TLS varialbe xyz is lowered to a function call:
12218 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
12219 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12220 PointerType *VoidPtrType = PointerType::get(*DAG.getContext(), 0);
12221 SDLoc dl(GA);
12222
12223 ArgListTy Args;
12224 const GlobalValue *GV =
12226 SmallString<32> NameString("__emutls_v.");
12227 NameString += GV->getName();
12228 StringRef EmuTlsVarName(NameString);
12229 const GlobalVariable *EmuTlsVar =
12230 GV->getParent()->getNamedGlobal(EmuTlsVarName);
12231 assert(EmuTlsVar && "Cannot find EmuTlsVar ");
12232 Args.emplace_back(DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT), VoidPtrType);
12233
12234 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
12235
12237 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
12238 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
12239 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12240
12241 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12242 // At last for X86 targets, maybe good for other targets too?
12244 MFI.setAdjustsStack(true); // Is this only for X86 target?
12245 MFI.setHasCalls(true);
12246
12247 assert((GA->getOffset() == 0) &&
12248 "Emulated TLS must have zero offset in GlobalAddressSDNode");
12249 return CallResult.first;
12250}
12251
12253 SelectionDAG &DAG) const {
12254 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
12255 if (!isCtlzFast())
12256 return SDValue();
12257 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12258 SDLoc dl(Op);
12259 if (isNullConstant(Op.getOperand(1)) && CC == ISD::SETEQ) {
12260 EVT VT = Op.getOperand(0).getValueType();
12261 SDValue Zext = Op.getOperand(0);
12262 if (VT.bitsLT(MVT::i32)) {
12263 VT = MVT::i32;
12264 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
12265 }
12266 unsigned Log2b = Log2_32(VT.getSizeInBits());
12267 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
12268 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
12269 DAG.getConstant(Log2b, dl, MVT::i32));
12270 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
12271 }
12272 return SDValue();
12273}
12274
12276 SDValue Op0 = Node->getOperand(0);
12277 SDValue Op1 = Node->getOperand(1);
12278 EVT VT = Op0.getValueType();
12279 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12280 unsigned Opcode = Node->getOpcode();
12281 SDLoc DL(Node);
12282
12283 // If both sign bits are zero, flip UMIN/UMAX <-> SMIN/SMAX if legal.
12284 unsigned AltOpcode = ISD::getOppositeSignednessMinMaxOpcode(Opcode);
12285 if (isOperationLegal(AltOpcode, VT) && DAG.SignBitIsZero(Op0) &&
12286 DAG.SignBitIsZero(Op1))
12287 return DAG.getNode(AltOpcode, DL, VT, Op0, Op1);
12288
12289 // umax(x,1) --> sub(x,cmpeq(x,0)) iff cmp result is allbits
12290 if (Opcode == ISD::UMAX && llvm::isOneOrOneSplat(Op1, true) && BoolVT == VT &&
12292 Op0 = DAG.getFreeze(Op0);
12293 SDValue Zero = DAG.getConstant(0, DL, VT);
12294 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12295 DAG.getSetCC(DL, VT, Op0, Zero, ISD::SETEQ));
12296 }
12297
12298 // umin(x,y) -> sub(x,usubsat(x,y))
12299 // TODO: Missing freeze(Op0)?
12300 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
12302 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12303 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
12304 }
12305
12306 // umax(x,y) -> add(x,usubsat(y,x))
12307 // TODO: Missing freeze(Op0)?
12308 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
12310 return DAG.getNode(ISD::ADD, DL, VT, Op0,
12311 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
12312 }
12313
12314 // FIXME: Should really try to split the vector in case it's legal on a
12315 // subvector.
12317 return DAG.UnrollVectorOp(Node);
12318
12319 // Attempt to find an existing SETCC node that we can reuse.
12320 // TODO: Do we need a generic doesSETCCNodeExist?
12321 // TODO: Missing freeze(Op0)/freeze(Op1)?
12322 auto buildMinMax = [&](ISD::CondCode PrefCC, ISD::CondCode AltCC,
12323 ISD::CondCode PrefCommuteCC,
12324 ISD::CondCode AltCommuteCC) {
12325 SDVTList BoolVTList = DAG.getVTList(BoolVT);
12326 for (ISD::CondCode CC : {PrefCC, AltCC}) {
12327 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12328 {Op0, Op1, DAG.getCondCode(CC)})) {
12329 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12330 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12331 }
12332 }
12333 for (ISD::CondCode CC : {PrefCommuteCC, AltCommuteCC}) {
12334 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12335 {Op0, Op1, DAG.getCondCode(CC)})) {
12336 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12337 return DAG.getSelect(DL, VT, Cond, Op1, Op0);
12338 }
12339 }
12340 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, PrefCC);
12341 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12342 };
12343
12344 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
12345 // -> Y = (A < B) ? B : A
12346 // -> Y = (A >= B) ? A : B
12347 // -> Y = (A <= B) ? B : A
12348 switch (Opcode) {
12349 case ISD::SMAX:
12350 return buildMinMax(ISD::SETGT, ISD::SETGE, ISD::SETLT, ISD::SETLE);
12351 case ISD::SMIN:
12352 return buildMinMax(ISD::SETLT, ISD::SETLE, ISD::SETGT, ISD::SETGE);
12353 case ISD::UMAX:
12354 return buildMinMax(ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE);
12355 case ISD::UMIN:
12356 return buildMinMax(ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE);
12357 }
12358
12359 llvm_unreachable("How did we get here?");
12360}
12361
12363 unsigned Opcode = Node->getOpcode();
12364 SDValue LHS = Node->getOperand(0);
12365 SDValue RHS = Node->getOperand(1);
12366 EVT VT = LHS.getValueType();
12367 SDLoc dl(Node);
12368
12369 assert(VT == RHS.getValueType() && "Expected operands to be the same type");
12370 assert(VT.isInteger() && "Expected operands to be integers");
12371
12372 // usub.sat(a, b) -> umax(a, b) - b
12373 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
12374 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
12375 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
12376 }
12377
12378 // usub.sat(a, 1) -> sub(a, zext(a != 0))
12379 // Prefer this on targets without legal/cost-effective overflow-carry nodes.
12380 if (Opcode == ISD::USUBSAT && isOneOrOneSplat(RHS) &&
12382 LHS = DAG.getFreeze(LHS);
12383 SDValue Zero = DAG.getConstant(0, dl, VT);
12384 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12385 SDValue IsNonZero = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETNE);
12386 SDValue Subtrahend = DAG.getBoolExtOrTrunc(IsNonZero, dl, VT, BoolVT);
12387 Subtrahend =
12388 DAG.getNode(ISD::AND, dl, VT, Subtrahend, DAG.getConstant(1, dl, VT));
12389 return DAG.getNode(ISD::SUB, dl, VT, LHS, Subtrahend);
12390 }
12391
12392 // uadd.sat(a, b) -> umin(a, ~b) + b
12393 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
12394 SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
12395 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
12396 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
12397 }
12398
12399 unsigned OverflowOp;
12400 switch (Opcode) {
12401 case ISD::SADDSAT:
12402 OverflowOp = ISD::SADDO;
12403 break;
12404 case ISD::UADDSAT:
12405 OverflowOp = ISD::UADDO;
12406 break;
12407 case ISD::SSUBSAT:
12408 OverflowOp = ISD::SSUBO;
12409 break;
12410 case ISD::USUBSAT:
12411 OverflowOp = ISD::USUBO;
12412 break;
12413 default:
12414 llvm_unreachable("Expected method to receive signed or unsigned saturation "
12415 "addition or subtraction node.");
12416 }
12417
12418 // FIXME: Should really try to split the vector in case it's legal on a
12419 // subvector.
12421 return DAG.UnrollVectorOp(Node);
12422
12423 unsigned BitWidth = LHS.getScalarValueSizeInBits();
12424 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12425 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12426 SDValue SumDiff = Result.getValue(0);
12427 SDValue Overflow = Result.getValue(1);
12428 SDValue Zero = DAG.getConstant(0, dl, VT);
12429 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
12430
12431 if (Opcode == ISD::UADDSAT) {
12433 // (LHS + RHS) | OverflowMask
12434 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12435 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
12436 }
12437 // Overflow ? 0xffff.... : (LHS + RHS)
12438 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
12439 }
12440
12441 if (Opcode == ISD::USUBSAT) {
12443 // (LHS - RHS) & ~OverflowMask
12444 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12445 SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
12446 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
12447 }
12448 // Overflow ? 0 : (LHS - RHS)
12449 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
12450 }
12451
12452 assert((Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) &&
12453 "Expected signed saturating add/sub opcode");
12454
12455 const APInt MinVal = APInt::getSignedMinValue(BitWidth);
12456 const APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
12457
12458 KnownBits KnownLHS = DAG.computeKnownBits(LHS);
12459 KnownBits KnownRHS = DAG.computeKnownBits(RHS);
12460
12461 // If either of the operand signs are known, then they are guaranteed to
12462 // only saturate in one direction. If non-negative they will saturate
12463 // towards SIGNED_MAX, if negative they will saturate towards SIGNED_MIN.
12464 //
12465 // In the case of ISD::SSUBSAT, 'x - y' is equivalent to 'x + (-y)', so the
12466 // sign of 'y' has to be flipped.
12467
12468 bool LHSIsNonNegative = KnownLHS.isNonNegative();
12469 bool RHSIsNonNegative =
12470 Opcode == ISD::SADDSAT ? KnownRHS.isNonNegative() : KnownRHS.isNegative();
12471 if (LHSIsNonNegative || RHSIsNonNegative) {
12472 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12473 return DAG.getSelect(dl, VT, Overflow, SatMax, SumDiff);
12474 }
12475
12476 bool LHSIsNegative = KnownLHS.isNegative();
12477 bool RHSIsNegative =
12478 Opcode == ISD::SADDSAT ? KnownRHS.isNegative() : KnownRHS.isNonNegative();
12479 if (LHSIsNegative || RHSIsNegative) {
12480 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12481 return DAG.getSelect(dl, VT, Overflow, SatMin, SumDiff);
12482 }
12483
12484 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
12485 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12486 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
12487 DAG.getConstant(BitWidth - 1, dl, VT));
12488 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
12489 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
12490}
12491
12493 unsigned Opcode = Node->getOpcode();
12494 SDValue LHS = Node->getOperand(0);
12495 SDValue RHS = Node->getOperand(1);
12496 EVT VT = LHS.getValueType();
12497 EVT ResVT = Node->getValueType(0);
12498 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12499 SDLoc dl(Node);
12500
12501 auto LTPredicate = (Opcode == ISD::UCMP ? ISD::SETULT : ISD::SETLT);
12502 auto GTPredicate = (Opcode == ISD::UCMP ? ISD::SETUGT : ISD::SETGT);
12503 SDValue IsLT = DAG.getSetCC(dl, BoolVT, LHS, RHS, LTPredicate);
12504 SDValue IsGT = DAG.getSetCC(dl, BoolVT, LHS, RHS, GTPredicate);
12505
12506 // We can't perform arithmetic on i1 values. Extending them would
12507 // probably result in worse codegen, so let's just use two selects instead.
12508 // Some targets are also just better off using selects rather than subtraction
12509 // because one of the conditions can be merged with one of the selects.
12510 // And finally, if we don't know the contents of high bits of a boolean value
12511 // we can't perform any arithmetic either.
12513 BoolVT.getScalarSizeInBits() == 1 ||
12515 SDValue SelectZeroOrOne =
12516 DAG.getSelect(dl, ResVT, IsGT, DAG.getConstant(1, dl, ResVT),
12517 DAG.getConstant(0, dl, ResVT));
12518 return DAG.getSelect(dl, ResVT, IsLT, DAG.getAllOnesConstant(dl, ResVT),
12519 SelectZeroOrOne);
12520 }
12521
12523 std::swap(IsGT, IsLT);
12524 return DAG.getSExtOrTrunc(DAG.getNode(ISD::SUB, dl, BoolVT, IsGT, IsLT), dl,
12525 ResVT);
12526}
12527
12529 unsigned Opcode = Node->getOpcode();
12530 bool IsSigned = Opcode == ISD::SSHLSAT;
12531 SDValue LHS = Node->getOperand(0);
12532 SDValue RHS = Node->getOperand(1);
12533 EVT VT = LHS.getValueType();
12534 SDLoc dl(Node);
12535
12536 assert((Node->getOpcode() == ISD::SSHLSAT ||
12537 Node->getOpcode() == ISD::USHLSAT) &&
12538 "Expected a SHLSAT opcode");
12539 assert(VT.isInteger() && "Expected operands to be integers");
12540
12542 return DAG.UnrollVectorOp(Node);
12543
12544 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
12545
12546 unsigned BW = VT.getScalarSizeInBits();
12547 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12548 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
12549 SDValue Orig =
12550 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
12551
12552 SDValue SatVal;
12553 if (IsSigned) {
12554 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
12555 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
12556 SDValue Cond =
12557 DAG.getSetCC(dl, BoolVT, LHS, DAG.getConstant(0, dl, VT), ISD::SETLT);
12558 SatVal = DAG.getSelect(dl, VT, Cond, SatMin, SatMax);
12559 } else {
12560 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
12561 }
12562 SDValue Cond = DAG.getSetCC(dl, BoolVT, LHS, Orig, ISD::SETNE);
12563 return DAG.getSelect(dl, VT, Cond, SatVal, Result);
12564}
12565
12567 bool Signed, SDValue &Lo, SDValue &Hi,
12568 SDValue LHS, SDValue RHS,
12569 SDValue HiLHS, SDValue HiRHS) const {
12570 EVT VT = LHS.getValueType();
12571 assert(RHS.getValueType() == VT && "Mismatching operand types");
12572
12573 assert((HiLHS && HiRHS) || (!HiLHS && !HiRHS));
12574 assert((!Signed || !HiLHS) &&
12575 "Signed flag should only be set when HiLHS and RiRHS are null");
12576
12577 // We'll expand the multiplication by brute force because we have no other
12578 // options. This is a trivially-generalized version of the code from
12579 // Hacker's Delight (itself derived from Knuth's Algorithm M from section
12580 // 4.3.1). If Signed is set, we can use arithmetic right shifts to propagate
12581 // sign bits while calculating the Hi half.
12582 unsigned Bits = VT.getScalarSizeInBits();
12583 unsigned HalfBits = Bits / 2;
12584 SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(Bits, HalfBits), dl, VT);
12585 SDValue LL = DAG.getNode(ISD::AND, dl, VT, LHS, Mask);
12586 SDValue RL = DAG.getNode(ISD::AND, dl, VT, RHS, Mask);
12587
12588 SDValue T = DAG.getNode(ISD::MUL, dl, VT, LL, RL);
12589 SDValue TL = DAG.getNode(ISD::AND, dl, VT, T, Mask);
12590
12591 SDValue Shift = DAG.getShiftAmountConstant(HalfBits, VT, dl);
12592 // This is always an unsigned shift.
12593 SDValue TH = DAG.getNode(ISD::SRL, dl, VT, T, Shift);
12594
12595 unsigned ShiftOpc = Signed ? ISD::SRA : ISD::SRL;
12596 SDValue LH = DAG.getNode(ShiftOpc, dl, VT, LHS, Shift);
12597 SDValue RH = DAG.getNode(ShiftOpc, dl, VT, RHS, Shift);
12598
12599 SDValue U =
12600 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RL), TH);
12601 SDValue UL = DAG.getNode(ISD::AND, dl, VT, U, Mask);
12602 SDValue UH = DAG.getNode(ShiftOpc, dl, VT, U, Shift);
12603
12604 SDValue V =
12605 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LL, RH), UL);
12606 SDValue VH = DAG.getNode(ShiftOpc, dl, VT, V, Shift);
12607
12608 Lo = DAG.getNode(ISD::ADD, dl, VT, TL,
12609 DAG.getNode(ISD::SHL, dl, VT, V, Shift));
12610
12611 Hi = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RH),
12612 DAG.getNode(ISD::ADD, dl, VT, UH, VH));
12613
12614 // If HiLHS and HiRHS are set, multiply them by the opposite low part and add
12615 // the products to Hi.
12616 if (HiLHS) {
12617 SDValue RHLL = DAG.getNode(ISD::MUL, dl, VT, HiRHS, LHS);
12618 SDValue RLLH = DAG.getNode(ISD::MUL, dl, VT, RHS, HiLHS);
12619 Hi = DAG.getNode(ISD::ADD, dl, VT, Hi,
12620 DAG.getNode(ISD::ADD, dl, VT, RHLL, RLLH));
12621 }
12622}
12623
12625 bool Signed, const SDValue LHS,
12626 const SDValue RHS, SDValue &Lo,
12627 SDValue &Hi) const {
12628 EVT VT = LHS.getValueType();
12629 assert(RHS.getValueType() == VT && "Mismatching operand types");
12630 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
12631 // We can fall back to a libcall with an illegal type for the MUL if we
12632 // have a libcall big enough.
12633 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
12634 if (WideVT == MVT::i16)
12635 LC = RTLIB::MUL_I16;
12636 else if (WideVT == MVT::i32)
12637 LC = RTLIB::MUL_I32;
12638 else if (WideVT == MVT::i64)
12639 LC = RTLIB::MUL_I64;
12640 else if (WideVT == MVT::i128)
12641 LC = RTLIB::MUL_I128;
12642
12643 RTLIB::LibcallImpl LibcallImpl = getLibcallImpl(LC);
12644 if (LibcallImpl == RTLIB::Unsupported) {
12645 forceExpandMultiply(DAG, dl, Signed, Lo, Hi, LHS, RHS);
12646 return;
12647 }
12648
12649 SDValue HiLHS, HiRHS;
12650 if (Signed) {
12651 // The high part is obtained by SRA'ing all but one of the bits of low
12652 // part.
12653 unsigned LoSize = VT.getFixedSizeInBits();
12654 SDValue Shift = DAG.getShiftAmountConstant(LoSize - 1, VT, dl);
12655 HiLHS = DAG.getNode(ISD::SRA, dl, VT, LHS, Shift);
12656 HiRHS = DAG.getNode(ISD::SRA, dl, VT, RHS, Shift);
12657 } else {
12658 HiLHS = DAG.getConstant(0, dl, VT);
12659 HiRHS = DAG.getConstant(0, dl, VT);
12660 }
12661
12662 // Attempt a libcall.
12663 SDValue Ret;
12665 CallOptions.setIsSigned(Signed);
12666 CallOptions.setIsPostTypeLegalization(true);
12668 // Halves of WideVT are packed into registers in different order
12669 // depending on platform endianness. This is usually handled by
12670 // the C calling convention, but we can't defer to it in
12671 // the legalizer.
12672 SDValue Args[] = {LHS, HiLHS, RHS, HiRHS};
12673 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
12674 } else {
12675 SDValue Args[] = {HiLHS, LHS, HiRHS, RHS};
12676 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
12677 }
12679 "Ret value is a collection of constituent nodes holding result.");
12680 if (DAG.getDataLayout().isLittleEndian()) {
12681 // Same as above.
12682 Lo = Ret.getOperand(0);
12683 Hi = Ret.getOperand(1);
12684 } else {
12685 Lo = Ret.getOperand(1);
12686 Hi = Ret.getOperand(0);
12687 }
12688}
12689
12690SDValue
12692 assert((Node->getOpcode() == ISD::SMULFIX ||
12693 Node->getOpcode() == ISD::UMULFIX ||
12694 Node->getOpcode() == ISD::SMULFIXSAT ||
12695 Node->getOpcode() == ISD::UMULFIXSAT) &&
12696 "Expected a fixed point multiplication opcode");
12697
12698 SDLoc dl(Node);
12699 SDValue LHS = Node->getOperand(0);
12700 SDValue RHS = Node->getOperand(1);
12701 EVT VT = LHS.getValueType();
12702 unsigned Scale = Node->getConstantOperandVal(2);
12703 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
12704 Node->getOpcode() == ISD::UMULFIXSAT);
12705 bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
12706 Node->getOpcode() == ISD::SMULFIXSAT);
12707 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12708 unsigned VTSize = VT.getScalarSizeInBits();
12709
12710 if (!Scale) {
12711 // [us]mul.fix(a, b, 0) -> mul(a, b)
12712 if (!Saturating) {
12714 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
12715 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
12716 SDValue Result =
12717 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12718 SDValue Product = Result.getValue(0);
12719 SDValue Overflow = Result.getValue(1);
12720 SDValue Zero = DAG.getConstant(0, dl, VT);
12721
12722 APInt MinVal = APInt::getSignedMinValue(VTSize);
12723 APInt MaxVal = APInt::getSignedMaxValue(VTSize);
12724 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12725 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12726 // Xor the inputs, if resulting sign bit is 0 the product will be
12727 // positive, else negative.
12728 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
12729 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
12730 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
12731 return DAG.getSelect(dl, VT, Overflow, Result, Product);
12732 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
12733 SDValue Result =
12734 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12735 SDValue Product = Result.getValue(0);
12736 SDValue Overflow = Result.getValue(1);
12737
12738 APInt MaxVal = APInt::getMaxValue(VTSize);
12739 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12740 return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
12741 }
12742 }
12743
12744 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
12745 "Expected scale to be less than the number of bits if signed or at "
12746 "most the number of bits if unsigned.");
12747 assert(LHS.getValueType() == RHS.getValueType() &&
12748 "Expected both operands to be the same type");
12749
12750 // Select the saturated value when Cond0 <CC> Cond1, keeping it vectorized:
12751 // SELECT_CC is scalarized for vector types, so build SETCC + VSELECT there.
12752 auto getSaturatingSelect = [&](SDValue Cond0, SDValue Cond1, SDValue Sat,
12753 SDValue Val, ISD::CondCode CC) {
12754 if (VT.isVector())
12755 return DAG.getSelect(dl, VT, DAG.getSetCC(dl, BoolVT, Cond0, Cond1, CC),
12756 Sat, Val);
12757 return DAG.getSelectCC(dl, Cond0, Cond1, Sat, Val, CC);
12758 };
12759
12760 // Get the upper and lower bits of the result.
12761 SDValue Lo, Hi;
12762 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
12763 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
12764 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
12765 if (isOperationLegalOrCustom(LoHiOp, VT)) {
12766 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
12767 Lo = Result.getValue(0);
12768 Hi = Result.getValue(1);
12769 } else if (isOperationLegalOrCustom(HiOp, VT)) {
12770 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
12771 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
12772 } else if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
12773 // Try for a multiplication using a wider type.
12774 unsigned Ext = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
12775 SDValue LHSExt = DAG.getNode(Ext, dl, WideVT, LHS);
12776 SDValue RHSExt = DAG.getNode(Ext, dl, WideVT, RHS);
12777 SDValue Res = DAG.getNode(ISD::MUL, dl, WideVT, LHSExt, RHSExt);
12778 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
12779 SDValue Shifted =
12780 DAG.getNode(ISD::SRA, dl, WideVT, Res,
12781 DAG.getShiftAmountConstant(VTSize, WideVT, dl));
12782 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT, Shifted);
12783 } else if (VT.isVector()) {
12784 return SDValue();
12785 } else {
12786 forceExpandWideMUL(DAG, dl, Signed, LHS, RHS, Lo, Hi);
12787 }
12788
12789 if (Scale == VTSize)
12790 // Result is just the top half since we'd be shifting by the width of the
12791 // operand. Overflow impossible so this works for both UMULFIX and
12792 // UMULFIXSAT.
12793 return Hi;
12794
12795 // The result will need to be shifted right by the scale since both operands
12796 // are scaled. The result is given to us in 2 halves, so we only want part of
12797 // both in the result.
12798 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
12799 DAG.getShiftAmountConstant(Scale, VT, dl));
12800 if (!Saturating)
12801 return Result;
12802
12803 if (!Signed) {
12804 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
12805 // widened multiplication) aren't all zeroes.
12806
12807 // Saturate to max if ((Hi >> Scale) != 0),
12808 // which is the same as if (Hi > ((1 << Scale) - 1))
12809 APInt MaxVal = APInt::getMaxValue(VTSize);
12810 SDValue LowMask =
12811 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), dl, VT);
12812 return getSaturatingSelect(Hi, LowMask, DAG.getConstant(MaxVal, dl, VT),
12813 Result, ISD::SETUGT);
12814 }
12815
12816 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
12817 // widened multiplication) aren't all ones or all zeroes.
12818
12819 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
12820 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
12821
12822 if (Scale == 0) {
12823 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
12824 DAG.getShiftAmountConstant(VTSize - 1, VT, dl));
12825 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
12826 // Saturated to SatMin if wide product is negative, and SatMax if wide
12827 // product is positive ...
12828 SDValue Zero = DAG.getConstant(0, dl, VT);
12829 SDValue ResultIfOverflow =
12830 getSaturatingSelect(Hi, Zero, SatMin, SatMax, ISD::SETLT);
12831 // ... but only if we overflowed.
12832 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
12833 }
12834
12835 // We handled Scale==0 above so all the bits to examine is in Hi.
12836
12837 // Saturate to max if ((Hi >> (Scale - 1)) > 0),
12838 // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
12839 SDValue LowMask =
12840 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), dl, VT);
12841 // Saturate to min if (Hi >> (Scale - 1)) < -1),
12842 // which is the same as if (HI < (-1 << (Scale - 1))
12843 SDValue HighMask = DAG.getConstant(
12844 APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), dl, VT);
12845 Result = getSaturatingSelect(Hi, LowMask, SatMax, Result, ISD::SETGT);
12846 Result = getSaturatingSelect(Hi, HighMask, SatMin, Result, ISD::SETLT);
12847 return Result;
12848}
12849
12850SDValue
12852 SDValue LHS, SDValue RHS,
12853 unsigned Scale, SelectionDAG &DAG) const {
12854 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
12855 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
12856 "Expected a fixed point division opcode");
12857
12858 EVT VT = LHS.getValueType();
12859 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
12860 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
12861 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12862
12863 // If there is enough room in the type to upscale the LHS or downscale the
12864 // RHS before the division, we can perform it in this type without having to
12865 // resize. For signed operations, the LHS headroom is the number of
12866 // redundant sign bits, and for unsigned ones it is the number of zeroes.
12867 // The headroom for the RHS is the number of trailing zeroes.
12868 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
12870 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
12871
12872 // For signed saturating operations, we need to be able to detect true integer
12873 // division overflow; that is, when you have MIN / -EPS. However, this
12874 // is undefined behavior and if we emit divisions that could take such
12875 // values it may cause undesired behavior (arithmetic exceptions on x86, for
12876 // example).
12877 // Avoid this by requiring an extra bit so that we never get this case.
12878 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
12879 // signed saturating division, we need to emit a whopping 32-bit division.
12880 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
12881 return SDValue();
12882
12883 unsigned LHSShift = std::min(LHSLead, Scale);
12884 unsigned RHSShift = Scale - LHSShift;
12885
12886 // At this point, we know that if we shift the LHS up by LHSShift and the
12887 // RHS down by RHSShift, we can emit a regular division with a final scaling
12888 // factor of Scale.
12889
12890 if (LHSShift)
12891 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
12892 DAG.getShiftAmountConstant(LHSShift, VT, dl));
12893 if (RHSShift)
12894 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
12895 DAG.getShiftAmountConstant(RHSShift, VT, dl));
12896
12897 SDValue Quot;
12898 if (Signed) {
12899 // For signed operations, if the resulting quotient is negative and the
12900 // remainder is nonzero, subtract 1 from the quotient to round towards
12901 // negative infinity.
12902 SDValue Rem;
12903 // FIXME: Ideally we would always produce an SDIVREM here, but if the
12904 // type isn't legal, SDIVREM cannot be expanded. There is no reason why
12905 // we couldn't just form a libcall, but the type legalizer doesn't do it.
12906 if (isTypeLegal(VT) &&
12908 Quot = DAG.getNode(ISD::SDIVREM, dl,
12909 DAG.getVTList(VT, VT),
12910 LHS, RHS);
12911 Rem = Quot.getValue(1);
12912 Quot = Quot.getValue(0);
12913 } else {
12914 Quot = DAG.getNode(ISD::SDIV, dl, VT,
12915 LHS, RHS);
12916 Rem = DAG.getNode(ISD::SREM, dl, VT,
12917 LHS, RHS);
12918 }
12919 SDValue Zero = DAG.getConstant(0, dl, VT);
12920 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
12921 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
12922 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
12923 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
12924 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
12925 DAG.getConstant(1, dl, VT));
12926 Quot = DAG.getSelect(dl, VT,
12927 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
12928 Sub1, Quot);
12929 } else
12930 Quot = DAG.getNode(ISD::UDIV, dl, VT,
12931 LHS, RHS);
12932
12933 return Quot;
12934}
12935
12937 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
12938 SDLoc dl(Node);
12939 SDValue LHS = Node->getOperand(0);
12940 SDValue RHS = Node->getOperand(1);
12941 bool IsAdd = Node->getOpcode() == ISD::UADDO;
12942
12943 // If UADDO_CARRY/SUBO_CARRY is legal, use that instead.
12944 unsigned OpcCarry = IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
12945 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
12946 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
12947 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
12948 { LHS, RHS, CarryIn });
12949 Result = SDValue(NodeCarry.getNode(), 0);
12950 Overflow = SDValue(NodeCarry.getNode(), 1);
12951 return;
12952 }
12953
12954 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
12955 LHS.getValueType(), LHS, RHS);
12956
12957 EVT ResultType = Node->getValueType(1);
12958 EVT SetCCType = getSetCCResultType(
12959 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
12960 SDValue SetCC;
12961 if (IsAdd && isOneConstant(RHS)) {
12962 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces
12963 // the live range of X. We assume comparing with 0 is cheap.
12964 // The general case (X + C) < C is not necessarily beneficial. Although we
12965 // reduce the live range of X, we may introduce the materialization of
12966 // constant C.
12967 SetCC =
12968 DAG.getSetCC(dl, SetCCType, Result,
12969 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ);
12970 } else if (IsAdd && isAllOnesConstant(RHS)) {
12971 // Special case: uaddo X, -1 overflows if X != 0.
12972 SetCC =
12973 DAG.getSetCC(dl, SetCCType, LHS,
12974 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETNE);
12975 } else {
12976 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
12977 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
12978 }
12979 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
12980}
12981
12983 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
12984 SDLoc dl(Node);
12985 SDValue LHS = Node->getOperand(0);
12986 SDValue RHS = Node->getOperand(1);
12987 bool IsAdd = Node->getOpcode() == ISD::SADDO;
12988
12989 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
12990 LHS.getValueType(), LHS, RHS);
12991
12992 EVT ResultType = Node->getValueType(1);
12993 EVT OType = getSetCCResultType(
12994 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
12995
12996 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
12997 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
12998 if (isOperationLegal(OpcSat, LHS.getValueType())) {
12999 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
13000 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
13001 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13002 return;
13003 }
13004
13005 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
13006
13007 if (IsAdd) {
13008 // For an addition, the result should be less than one of the operands (LHS)
13009 // if and only if the other operand (RHS) is negative, otherwise there will
13010 // be overflow.
13011 SDValue ResultLowerThanLHS =
13012 DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
13013 SDValue RHSNegative = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETLT);
13014 Overflow = DAG.getBoolExtOrTrunc(
13015 DAG.getNode(ISD::XOR, dl, OType, RHSNegative, ResultLowerThanLHS), dl,
13016 ResultType, ResultType);
13017 } else {
13018 // For subtraction, overflow occurs when the signed comparison of operands
13019 // doesn't match the sign of the result.
13020 SDValue LHSLessThanRHS = DAG.getSetCC(dl, OType, LHS, RHS, ISD::SETLT);
13021 SDValue ResultNegative = DAG.getSetCC(dl, OType, Result, Zero, ISD::SETLT);
13022 Overflow = DAG.getBoolExtOrTrunc(
13023 DAG.getNode(ISD::XOR, dl, OType, LHSLessThanRHS, ResultNegative), dl,
13024 ResultType, ResultType);
13025 }
13026}
13027
13029 SDValue &Overflow, SelectionDAG &DAG) const {
13030 SDLoc dl(Node);
13031 EVT VT = Node->getValueType(0);
13032 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13033 SDValue LHS = Node->getOperand(0);
13034 SDValue RHS = Node->getOperand(1);
13035 bool isSigned = Node->getOpcode() == ISD::SMULO;
13036
13037 // For power-of-two multiplications we can use a simpler shift expansion.
13038 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
13039 const APInt &C = RHSC->getAPIntValue();
13040 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
13041 if (C.isPowerOf2()) {
13042 // smulo(x, signed_min) is same as umulo(x, signed_min).
13043 bool UseArithShift = isSigned && !C.isMinSignedValue();
13044 SDValue ShiftAmt = DAG.getShiftAmountConstant(C.logBase2(), VT, dl);
13045 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
13046 Overflow = DAG.getSetCC(dl, SetCCVT,
13047 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
13048 dl, VT, Result, ShiftAmt),
13049 LHS, ISD::SETNE);
13050 return true;
13051 }
13052 }
13053
13054 SDValue BottomHalf;
13055 SDValue TopHalf;
13056 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13057
13058 static const unsigned Ops[2][3] =
13061 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
13062 BottomHalf = DAG.getNode(Ops[isSigned][0], dl, DAG.getVTList(VT, VT), LHS,
13063 RHS);
13064 TopHalf = BottomHalf.getValue(1);
13065 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
13066 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13067 TopHalf = DAG.getNode(Ops[isSigned][1], dl, VT, LHS, RHS);
13068 } else if (isTypeLegal(WideVT)) {
13069 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
13070 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
13071 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
13072 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
13073 SDValue ShiftAmt =
13074 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
13075 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
13076 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
13077 } else {
13078 if (VT.isVector())
13079 return false;
13080
13081 forceExpandWideMUL(DAG, dl, isSigned, LHS, RHS, BottomHalf, TopHalf);
13082 }
13083
13084 Result = BottomHalf;
13085 if (isSigned) {
13086 SDValue ShiftAmt = DAG.getShiftAmountConstant(
13087 VT.getScalarSizeInBits() - 1, BottomHalf.getValueType(), dl);
13088 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
13089 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
13090 } else {
13091 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
13092 DAG.getConstant(0, dl, VT), ISD::SETNE);
13093 }
13094
13095 // Truncate the result if SetCC returns a larger type than needed.
13096 EVT RType = Node->getValueType(1);
13097 if (RType.bitsLT(Overflow.getValueType()))
13098 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
13099
13100 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
13101 "Unexpected result type for S/UMULO legalization");
13102 return true;
13103}
13104
13106 SDLoc dl(Node);
13107 EVT VT = Node->getValueType(0);
13108 SDValue LHS = Node->getOperand(0);
13109 SDValue RHS = Node->getOperand(1);
13110 bool IsSigned = Node->getOpcode() == ISD::MULHS;
13111
13112 // Use MUL_LOHI if legal/custom for the original type.
13113 unsigned LoHiOp = IsSigned ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
13114 if (isOperationLegalOrCustom(LoHiOp, VT))
13115 return DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS).getValue(1);
13116
13117 // Use a wide multiply if available.
13118 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13119 if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
13120 unsigned BW = VT.getScalarSizeInBits();
13121 LHS = DAG.getExtOrTrunc(IsSigned, LHS, dl, WideVT);
13122 RHS = DAG.getExtOrTrunc(IsSigned, RHS, dl, WideVT);
13123 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13124 DAG.getNode(ISD::SRL, dl, WideVT,
13125 DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS),
13126 DAG.getShiftAmountConstant(BW, WideVT, dl)));
13127 }
13128
13129 // Let fixed-length vectors be scalarised by the caller.
13130 // Expand everything else with a wide multiply.
13131 if (!VT.isFixedLengthVector()) {
13132 SDValue Lo, Hi;
13133 forceExpandWideMUL(DAG, dl, IsSigned, LHS, RHS, Lo, Hi);
13134 return Hi;
13135 }
13136
13137 return SDValue();
13138}
13139
13141 SDLoc dl(Node);
13142 ISD::NodeType BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13143 SDValue Op = Node->getOperand(0);
13144 SDNodeFlags Flags = Node->getFlags();
13145 EVT VT = Op.getValueType();
13146
13147 // Try to use a shuffle reduction for power of two vectors.
13148 if (VT.isPow2VectorType()) {
13149 // See if the reduction opcode is safe to use with widened types.
13150 bool WidenSrc = false;
13151 switch (Node->getOpcode()) {
13154 case ISD::VECREDUCE_ADD:
13155 case ISD::VECREDUCE_MUL:
13156 case ISD::VECREDUCE_AND:
13157 case ISD::VECREDUCE_OR:
13158 case ISD::VECREDUCE_XOR:
13163 WidenSrc = VT.isFixedLengthVector();
13164 break;
13165 }
13166
13168 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
13169 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) {
13170 if (WidenSrc && Op.getOpcode() != ISD::BUILD_VECTOR) {
13171 // Attempt to widen the source vectors to a legal op.
13172 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), HalfVT);
13173 if (WideVT.isVector() &&
13174 WideVT.getScalarType() == HalfVT.getScalarType() &&
13175 WideVT.getVectorNumElements() >= HalfVT.getVectorNumElements() &&
13176 isOperationLegalOrCustom(BaseOpcode, WideVT)) {
13177 SDValue Lo, Hi;
13178 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13179 Lo = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Lo, 0);
13180 Hi = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Hi, 0);
13181 Op = DAG.getNode(BaseOpcode, dl, WideVT, Lo, Hi, Flags);
13182 Op = DAG.getExtractSubvector(dl, HalfVT, Op, 0);
13183 VT = HalfVT;
13184 continue;
13185 }
13186 }
13187 break;
13188 }
13189
13190 SDValue Lo, Hi;
13191 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13192 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi, Flags);
13193 VT = HalfVT;
13194
13195 // Stop if splitting is enough to make the reduction legal.
13196 if (isOperationLegalOrCustom(Node->getOpcode(), HalfVT))
13197 return DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Op,
13198 Flags);
13199 }
13200 }
13201
13202 if (VT.isScalableVector())
13204 "Expanding reductions for scalable vectors is undefined.");
13205
13206 EVT EltVT = VT.getVectorElementType();
13207 unsigned NumElts = VT.getVectorNumElements();
13208
13210 DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
13211
13212 SDValue Res = Ops[0];
13213 for (unsigned i = 1; i < NumElts; i++)
13214 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13215
13216 // Result type may be wider than element type.
13217 if (EltVT != Node->getValueType(0))
13218 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
13219 return Res;
13220}
13221
13223 SDLoc dl(Node);
13224 SDValue AccOp = Node->getOperand(0);
13225 SDValue VecOp = Node->getOperand(1);
13226 SDNodeFlags Flags = Node->getFlags();
13227
13228 EVT VT = VecOp.getValueType();
13229 EVT EltVT = VT.getVectorElementType();
13230
13231 if (VT.isScalableVector())
13233 "Expanding reductions for scalable vectors is undefined.");
13234
13235 unsigned NumElts = VT.getVectorNumElements();
13236
13238 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
13239
13240 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13241
13242 SDValue Res = AccOp;
13243 for (unsigned i = 0; i < NumElts; i++)
13244 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13245
13246 return Res;
13247}
13248
13250 SelectionDAG &DAG) const {
13251 EVT VT = Node->getValueType(0);
13252 SDLoc dl(Node);
13253 bool isSigned = Node->getOpcode() == ISD::SREM;
13254 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
13255 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
13256 SDValue Dividend = Node->getOperand(0);
13257 SDValue Divisor = Node->getOperand(1);
13258 if (isOperationLegalOrCustom(DivRemOpc, VT)) {
13259 SDVTList VTs = DAG.getVTList(VT, VT);
13260 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
13261 return true;
13262 }
13263 if (isOperationLegalOrCustom(DivOpc, VT)) {
13264 // X % Y -> X-X/Y*Y
13265 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
13266 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
13267 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13268 return true;
13269 }
13270 return false;
13271}
13272
13274 SelectionDAG &DAG) const {
13275 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
13276 SDLoc dl(SDValue(Node, 0));
13277 SDValue Src = Node->getOperand(0);
13278
13279 // DstVT is the result type, while SatVT is the size to which we saturate
13280 EVT SrcVT = Src.getValueType();
13281 EVT DstVT = Node->getValueType(0);
13282
13283 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
13284 unsigned SatWidth = SatVT.getScalarSizeInBits();
13285 unsigned DstWidth = DstVT.getScalarSizeInBits();
13286 assert(SatWidth <= DstWidth &&
13287 "Expected saturation width smaller than result width");
13288
13289 // Determine minimum and maximum integer values and their corresponding
13290 // floating-point values.
13291 APInt MinInt, MaxInt;
13292 if (IsSigned) {
13293 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
13294 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
13295 } else {
13296 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
13297 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
13298 }
13299
13300 // We cannot risk emitting FP_TO_XINT nodes with a source VT of [b]f16, as
13301 // libcall emission cannot handle this. Large result types will fail.
13302 if (SrcVT == MVT::f16 || SrcVT == MVT::bf16) {
13303 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
13304 SrcVT = Src.getValueType();
13305 }
13306
13307 const fltSemantics &Sem = SrcVT.getFltSemantics();
13308 APFloat MinFloat(Sem);
13309 APFloat MaxFloat(Sem);
13310
13311 APFloat::opStatus MinStatus =
13312 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
13313 APFloat::opStatus MaxStatus =
13314 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
13315 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
13316 !(MaxStatus & APFloat::opStatus::opInexact);
13317
13318 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
13319 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
13320
13321 // If the integer bounds are exactly representable as floats and min/max are
13322 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
13323 // of comparisons and selects.
13324 auto EmitMinMax = [&](unsigned MinOpcode, unsigned MaxOpcode,
13325 bool MayPropagateNaN) {
13326 bool MinMaxLegal = isOperationLegalOrCustom(MinOpcode, SrcVT) &&
13327 isOperationLegalOrCustom(MaxOpcode, SrcVT);
13328 if (!MinMaxLegal)
13329 return SDValue();
13330
13331 SDValue Clamped = Src;
13332
13333 // Clamp Src by MinFloat from below. If !MayPropagateNaN and Src is NaN
13334 // then the result is MinFloat.
13335 Clamped = DAG.getNode(MaxOpcode, dl, SrcVT, Clamped, MinFloatNode);
13336 // Clamp by MaxFloat from above. If !MayPropagateNaN then NaN cannot occur.
13337 Clamped = DAG.getNode(MinOpcode, dl, SrcVT, Clamped, MaxFloatNode);
13338 // Convert clamped value to integer.
13339 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
13340 dl, DstVT, Clamped);
13341
13342 // If !MayPropagateNan and the conversion is unsigned case we're done,
13343 // because we mapped NaN to MinFloat, which will cast to zero.
13344 if (!MayPropagateNaN && !IsSigned)
13345 return FpToInt;
13346
13347 // Otherwise, select 0 if Src is NaN.
13348 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13349 EVT SetCCVT =
13350 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13351 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13352 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, FpToInt);
13353 };
13354 if (AreExactFloatBounds) {
13355 if (SDValue Res = EmitMinMax(ISD::FMINIMUMNUM, ISD::FMAXIMUMNUM,
13356 /*MayPropagateNaN=*/false))
13357 return Res;
13358 // These may propagate NaN for sNaN operands.
13359 if (SDValue Res =
13360 EmitMinMax(ISD::FMINNUM, ISD::FMAXNUM, /*MayPropagateNaN=*/true))
13361 return Res;
13362 // These always propagate NaN.
13363 if (SDValue Res =
13364 EmitMinMax(ISD::FMINIMUM, ISD::FMAXIMUM, /*MayPropagateNaN=*/true))
13365 return Res;
13366 }
13367
13368 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
13369 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
13370
13371 // Result of direct conversion. The assumption here is that the operation is
13372 // non-trapping and it's fine to apply it to an out-of-range value if we
13373 // select it away later.
13374 SDValue FpToInt =
13375 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
13376
13377 SDValue Select = FpToInt;
13378
13379 EVT SetCCVT =
13380 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13381
13382 // If Src ULT MinFloat, select MinInt. In particular, this also selects
13383 // MinInt if Src is NaN.
13384 SDValue ULT = DAG.getSetCC(dl, SetCCVT, Src, MinFloatNode, ISD::SETULT);
13385 Select = DAG.getSelect(dl, DstVT, ULT, MinIntNode, Select);
13386 // If Src OGT MaxFloat, select MaxInt.
13387 SDValue OGT = DAG.getSetCC(dl, SetCCVT, Src, MaxFloatNode, ISD::SETOGT);
13388 Select = DAG.getSelect(dl, DstVT, OGT, MaxIntNode, Select);
13389
13390 // In the unsigned case we are done, because we mapped NaN to MinInt, which
13391 // is already zero.
13392 if (!IsSigned)
13393 return Select;
13394
13395 // Otherwise, select 0 if Src is NaN.
13396 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13397 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13398 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, Select);
13399}
13400
13402 const SDLoc &dl,
13403 SelectionDAG &DAG) const {
13404 EVT OperandVT = Op.getValueType();
13405 if (OperandVT.getScalarType() == ResultVT.getScalarType())
13406 return Op;
13407 EVT ResultIntVT = ResultVT.changeTypeToInteger();
13408 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13409 // can induce double-rounding which may alter the results. We can
13410 // correct for this using a trick explained in: Boldo, Sylvie, and
13411 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13412 // World Congress. 2005.
13413 SDValue Narrow = DAG.getFPExtendOrRound(Op, dl, ResultVT);
13414 SDValue NarrowAsWide = DAG.getFPExtendOrRound(Narrow, dl, OperandVT);
13415
13416 // We can keep the narrow value as-is if narrowing was exact (no
13417 // rounding error), the wide value was NaN (the narrow value is also
13418 // NaN and should be preserved) or if we rounded to the odd value.
13419 SDValue NarrowBits = DAG.getNode(ISD::BITCAST, dl, ResultIntVT, Narrow);
13420 SDValue One = DAG.getConstant(1, dl, ResultIntVT);
13421 SDValue NegativeOne = DAG.getAllOnesConstant(dl, ResultIntVT);
13422 SDValue And = DAG.getNode(ISD::AND, dl, ResultIntVT, NarrowBits, One);
13423 EVT ResultIntVTCCVT = getSetCCResultType(
13424 DAG.getDataLayout(), *DAG.getContext(), And.getValueType());
13425 SDValue Zero = DAG.getConstant(0, dl, ResultIntVT);
13426 // The result is already odd so we don't need to do anything.
13427 SDValue AlreadyOdd = DAG.getSetCC(dl, ResultIntVTCCVT, And, Zero, ISD::SETNE);
13428
13429 EVT WideSetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
13430 Op.getValueType());
13431 // We keep results which are exact, odd or NaN.
13432 SDValue KeepNarrow =
13433 DAG.getSetCC(dl, WideSetCCVT, Op, NarrowAsWide, ISD::SETUEQ);
13434 KeepNarrow = DAG.getNode(ISD::OR, dl, WideSetCCVT, KeepNarrow, AlreadyOdd);
13435 // We morally performed a round-down if AbsNarrow is smaller than
13436 // AbsWide.
13437 SDValue AbsWide = DAG.getNode(ISD::FABS, dl, OperandVT, Op);
13438 SDValue AbsNarrowAsWide = DAG.getNode(ISD::FABS, dl, OperandVT, NarrowAsWide);
13439 SDValue NarrowIsRd =
13440 DAG.getSetCC(dl, WideSetCCVT, AbsWide, AbsNarrowAsWide, ISD::SETOGT);
13441 // If the narrow value is odd or exact, pick it.
13442 // Otherwise, narrow is even and corresponds to either the rounded-up
13443 // or rounded-down value. If narrow is the rounded-down value, we want
13444 // the rounded-up value as it will be odd.
13445 SDValue Adjust = DAG.getSelect(dl, ResultIntVT, NarrowIsRd, One, NegativeOne);
13446 SDValue Adjusted = DAG.getNode(ISD::ADD, dl, ResultIntVT, NarrowBits, Adjust);
13447 Op = DAG.getSelect(dl, ResultIntVT, KeepNarrow, NarrowBits, Adjusted);
13448 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Op);
13449}
13450
13452 assert(Node->getOpcode() == ISD::FP_ROUND && "Unexpected opcode!");
13453 SDValue Op = Node->getOperand(0);
13454 EVT VT = Node->getValueType(0);
13455 SDLoc dl(Node);
13456 if (VT.getScalarType() == MVT::bf16) {
13457 if (Node->getConstantOperandVal(1) == 1) {
13458 return DAG.getNode(ISD::FP_TO_BF16, dl, VT, Node->getOperand(0));
13459 }
13460 EVT OperandVT = Op.getValueType();
13461 SDValue IsNaN = DAG.getSetCC(
13462 dl,
13463 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), OperandVT),
13464 Op, Op, ISD::SETUO);
13465
13466 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13467 // can induce double-rounding which may alter the results. We can
13468 // correct for this using a trick explained in: Boldo, Sylvie, and
13469 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13470 // World Congress. 2005.
13471 EVT F32 = VT.changeElementType(*DAG.getContext(), MVT::f32);
13472 EVT I32 = F32.changeTypeToInteger();
13473 Op = expandRoundInexactToOdd(F32, Op, dl, DAG);
13474 Op = DAG.getNode(ISD::BITCAST, dl, I32, Op);
13475
13476 // Conversions should set NaN's quiet bit. This also prevents NaNs from
13477 // turning into infinities.
13478 SDValue NaN =
13479 DAG.getNode(ISD::OR, dl, I32, Op, DAG.getConstant(0x400000, dl, I32));
13480
13481 // Factor in the contribution of the low 16 bits.
13482 SDValue One = DAG.getConstant(1, dl, I32);
13483 SDValue Lsb = DAG.getNode(ISD::SRL, dl, I32, Op,
13484 DAG.getShiftAmountConstant(16, I32, dl));
13485 Lsb = DAG.getNode(ISD::AND, dl, I32, Lsb, One);
13486 SDValue RoundingBias =
13487 DAG.getNode(ISD::ADD, dl, I32, Lsb, DAG.getConstant(0x7fff, dl, I32));
13488 SDValue Add = DAG.getNode(ISD::ADD, dl, I32, Op, RoundingBias);
13489
13490 // Don't round if we had a NaN, we don't want to turn 0x7fffffff into
13491 // 0x80000000.
13492 Op = DAG.getSelect(dl, I32, IsNaN, NaN, Add);
13493
13494 // Now that we have rounded, shift the bits into position.
13495 Op = DAG.getNode(ISD::SRL, dl, I32, Op,
13496 DAG.getShiftAmountConstant(16, I32, dl));
13497 EVT I16 = I32.changeElementType(*DAG.getContext(), MVT::i16);
13498 Op = DAG.getNode(ISD::TRUNCATE, dl, I16, Op);
13499 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13500 }
13501 return SDValue();
13502}
13503
13505 SelectionDAG &DAG) const {
13506 assert((Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT ||
13507 Node->getOpcode() == ISD::VECTOR_SPLICE_RIGHT) &&
13508 "Unexpected opcode!");
13509 assert((Node->getValueType(0).isScalableVector() ||
13510 !isa<ConstantSDNode>(Node->getOperand(2))) &&
13511 "Fixed length vector types with constant offsets expected to use "
13512 "SHUFFLE_VECTOR!");
13513
13514 EVT VT = Node->getValueType(0);
13515 SDValue V1 = Node->getOperand(0);
13516 SDValue V2 = Node->getOperand(1);
13517 SDValue Offset = Node->getOperand(2);
13518 SDLoc DL(Node);
13519
13520 // Expand through memory thusly:
13521 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
13522 // Store V1, Ptr
13523 // Store V2, Ptr + sizeof(V1)
13524 // if (VECTOR_SPLICE_LEFT)
13525 // Ptr = Ptr + (Offset * sizeof(VT.Elt))
13526 // else
13527 // Ptr = Ptr + sizeof(V1) - (Offset * size(VT.Elt))
13528 // Res = Load Ptr
13529
13530 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
13531
13533 VT.getVectorElementCount() * 2);
13534 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
13535 EVT PtrVT = StackPtr.getValueType();
13536 auto &MF = DAG.getMachineFunction();
13537 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
13538 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
13539
13540 // Store the lo part of CONCAT_VECTORS(V1, V2)
13541 SDValue StoreV1 =
13542 DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo, Alignment);
13543 // Store the hi part of CONCAT_VECTORS(V1, V2)
13544 SDValue VTBytes = DAG.getTypeSize(DL, PtrVT, VT.getStoreSize());
13545 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, VTBytes);
13546 SDValue StoreV2 =
13547 DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo, Alignment);
13548
13549 // NOTE: TrailingBytes must be clamped so as not to read outside of V1:V2.
13550 SDValue EltByteSize =
13551 DAG.getTypeSize(DL, PtrVT, VT.getVectorElementType().getStoreSize());
13552 Offset = DAG.getZExtOrTrunc(Offset, DL, PtrVT);
13553 SDValue TrailingBytes = DAG.getNode(ISD::MUL, DL, PtrVT, Offset, EltByteSize);
13554
13555 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VTBytes);
13556
13557 if (Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT)
13558 StackPtr = DAG.getMemBasePlusOffset(StackPtr, TrailingBytes, DL);
13559 else
13560 StackPtr = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
13561
13562 // Load the spliced result
13563 return DAG.getLoad(VT, DL, StoreV2, StackPtr,
13565}
13566
13568 SelectionDAG &DAG) const {
13569 SDLoc DL(Node);
13570 SDValue Vec = Node->getOperand(0);
13571 SDValue Mask = Node->getOperand(1);
13572 SDValue Passthru = Node->getOperand(2);
13573
13574 EVT VecVT = Vec.getValueType();
13575 EVT ScalarVT = VecVT.getScalarType();
13576 EVT MaskVT = Mask.getValueType();
13577 EVT MaskScalarVT = MaskVT.getScalarType();
13578
13579 // Needs to be handled by targets that have scalable vector types.
13580 if (VecVT.isScalableVector())
13581 report_fatal_error("Cannot expand masked_compress for scalable vectors.");
13582
13583 Align Alignment = DAG.getReducedAlign(VecVT, /*UseABI=*/false);
13584 SDValue StackPtr = DAG.CreateStackTemporary(VecVT.getStoreSize(), Alignment);
13585 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
13586 MachinePointerInfo PtrInfo =
13588
13589 MVT PositionVT = getVectorIdxTy(DAG.getDataLayout());
13590 SDValue Chain = DAG.getEntryNode();
13591 SDValue OutPos = DAG.getConstant(0, DL, PositionVT);
13592
13593 bool HasPassthru = !Passthru.isUndef();
13594
13595 // If we have a passthru vector, store it on the stack, overwrite the matching
13596 // positions and then re-write the last element that was potentially
13597 // overwritten even though mask[i] = false.
13598 if (HasPassthru)
13599 Chain = DAG.getStore(Chain, DL, Passthru, StackPtr, PtrInfo, Alignment);
13600
13601 SDValue LastWriteVal;
13602 APInt PassthruSplatVal;
13603 bool IsSplatPassthru =
13604 ISD::isConstantSplatVector(Passthru.getNode(), PassthruSplatVal);
13605
13606 if (IsSplatPassthru) {
13607 // As we do not know which position we wrote to last, we cannot simply
13608 // access that index from the passthru vector. So we first check if passthru
13609 // is a splat vector, to use any element ...
13610 LastWriteVal = DAG.getConstant(PassthruSplatVal, DL, ScalarVT);
13611 } else if (HasPassthru) {
13612 // ... if it is not a splat vector, we need to get the passthru value at
13613 // position = popcount(mask) and re-load it from the stack before it is
13614 // overwritten in the loop below.
13615 EVT PopcountVT = ScalarVT.changeTypeToInteger();
13616 SDValue Popcount = DAG.getNode(
13618 MaskVT.changeVectorElementType(*DAG.getContext(), MVT::i1), Mask);
13619 Popcount = DAG.getNode(
13621 MaskVT.changeVectorElementType(*DAG.getContext(), PopcountVT),
13622 Popcount);
13623 Popcount = DAG.getNode(ISD::VECREDUCE_ADD, DL, PopcountVT, Popcount);
13624 SDValue LastElmtPtr =
13625 getVectorElementPointer(DAG, StackPtr, VecVT, Popcount);
13626 LastWriteVal = DAG.getLoad(
13627 ScalarVT, DL, Chain, LastElmtPtr,
13629 Chain = LastWriteVal.getValue(1);
13630 }
13631
13632 unsigned NumElms = VecVT.getVectorNumElements();
13633 for (unsigned I = 0; I < NumElms; I++) {
13634 SDValue ValI = DAG.getExtractVectorElt(DL, ScalarVT, Vec, I);
13635 SDValue OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
13636 Chain = DAG.getStore(
13637 Chain, DL, ValI, OutPtr,
13639
13640 // Get the mask value and add it to the current output position. This
13641 // either increments by 1 if MaskI is true or adds 0 otherwise.
13642 // Freeze in case we have poison/undef mask entries.
13643 SDValue MaskI = DAG.getExtractVectorElt(DL, MaskScalarVT, Mask, I);
13644 MaskI = DAG.getFreeze(MaskI);
13645 MaskI = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, MaskI);
13646 MaskI = DAG.getNode(ISD::ZERO_EXTEND, DL, PositionVT, MaskI);
13647 OutPos = DAG.getNode(ISD::ADD, DL, PositionVT, OutPos, MaskI);
13648
13649 if (HasPassthru && I == NumElms - 1) {
13650 SDValue EndOfVector =
13651 DAG.getConstant(VecVT.getVectorNumElements() - 1, DL, PositionVT);
13652 SDValue AllLanesSelected =
13653 DAG.getSetCC(DL, MVT::i1, OutPos, EndOfVector, ISD::CondCode::SETUGT);
13654 OutPos = DAG.getNode(ISD::UMIN, DL, PositionVT, OutPos, EndOfVector);
13655 OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
13656
13657 // Re-write the last ValI if all lanes were selected. Otherwise,
13658 // overwrite the last write it with the passthru value.
13659 LastWriteVal = DAG.getSelect(DL, ScalarVT, AllLanesSelected, ValI,
13660 LastWriteVal, SDNodeFlags::Unpredictable);
13661 Chain = DAG.getStore(
13662 Chain, DL, LastWriteVal, OutPtr,
13664 }
13665 }
13666
13667 return DAG.getLoad(VecVT, DL, Chain, StackPtr, PtrInfo, Alignment);
13668}
13669
13671 SDLoc DL(Node);
13672 EVT VT = Node->getValueType(0);
13673 SDValue Op = Node->getOperand(0);
13674 ElementCount EC = Op.getValueType().getVectorElementCount();
13675
13676 bool ZeroIsPoison = Node->getOpcode() == ISD::CTTZ_ELTS_ZERO_POISON;
13677 auto [Mask, StepVec] = getLegalMaskAndStepVector(Op, ZeroIsPoison, DL, DAG);
13678
13679 // No legal step vector: split mask in half and recombine results.
13680 // LoNumElts uses the non-poison CTTZ_ELTS so its result is well-defined
13681 // (== LoNumElts when no active lane), allowing the SETNE comparison.
13682 // Result: (ResLo != LoNumElts) ? ResLo : (LoNumElts + ResHi)
13683 if (!StepVec) {
13684 EVT ResVT = Node->getValueType(0);
13685 auto [MaskLo, MaskHi] = DAG.SplitVector(Op, DL);
13686 SDValue LoNumElts = DAG.getElementCount(
13687 DL, ResVT, MaskLo.getValueType().getVectorElementCount());
13688 SDValue ResLo = DAG.getNode(ISD::CTTZ_ELTS, DL, ResVT, MaskLo);
13689 SDValue ResHi = DAG.getNode(Node->getOpcode(), DL, ResVT, MaskHi);
13690 SDValue ResLoNotNumElts = DAG.getSetCC(
13691 DL, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ResVT),
13692 ResLo, LoNumElts, ISD::SETNE);
13693 // Per LangRef, ResVT must be wide enough to hold the total element count,
13694 // so the sum cannot wrap as an unsigned add. NSW is not guaranteed since
13695 // the count is only required to fit unsigned.
13696 SDValue Sum = DAG.getNode(ISD::ADD, DL, ResVT, LoNumElts, ResHi,
13698 return DAG.getSelect(DL, ResVT, ResLoNotNumElts, ResLo, Sum);
13699 }
13700
13701 EVT StepVecVT = StepVec.getValueType();
13702 EVT StepVT = StepVecVT.getVectorElementType();
13703
13704 // Promote the scalar result type early to avoid redundant zexts.
13706 StepVT = getTypeToTransformTo(*DAG.getContext(), StepVT);
13707
13708 SDValue VL = DAG.getElementCount(DL, StepVT, EC);
13709 SDValue SplatVL = DAG.getSplat(StepVecVT, DL, VL);
13710 StepVec = DAG.getNode(ISD::SUB, DL, StepVecVT, SplatVL, StepVec);
13711 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
13712 SDValue Select = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
13714 StepVecVT.getVectorElementType(), Select);
13715 SDValue Sub = DAG.getNode(ISD::SUB, DL, StepVT, VL,
13716 DAG.getZExtOrTrunc(Max, DL, StepVT));
13717
13718 return DAG.getZExtOrTrunc(Sub, DL, VT);
13719}
13720
13722 SDLoc DL(N);
13723 SDValue Source = N->getOperand(0);
13724 SDValue Needle = N->getOperand(1);
13725 SDValue Mask = N->getOperand(2);
13726 EVT SourceVT = Source.getValueType();
13727 EVT NeedleVT = Needle.getValueType();
13728 EVT ResVT = N->getValueType(0);
13729 EVT CmpVT =
13730 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SourceVT);
13731
13732 assert(NeedleVT.isFixedLengthVector() && "Needle must be a fixed vector");
13733
13734 SDValue Ret = DAG.getConstant(0, DL, CmpVT);
13735 EVT NeedleEltVT = NeedleVT.getVectorElementType();
13736 for (unsigned I = 0, E = NeedleVT.getVectorNumElements(); I != E; ++I) {
13737 SDValue Splat;
13738 if (NeedleVT == SourceVT) {
13739 // Prefer a shuffle over scalar extracts + splat for fixed vectors.
13740 Splat = DAG.getVectorShuffle(
13741 SourceVT, DL, Needle, DAG.getUNDEF(SourceVT),
13743 } else {
13744 SDValue NeedleElt = DAG.getExtractVectorElt(DL, NeedleEltVT, Needle, I);
13745 Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, SourceVT, NeedleElt);
13746 }
13747 SDValue Cmp = DAG.getSetCC(DL, CmpVT, Source, Splat, ISD::SETEQ);
13748 Ret = DAG.getNode(ISD::OR, DL, CmpVT, Ret, Cmp);
13749 }
13750
13751 EVT UseVT = ResVT;
13752 // If the result is immediately truncated, only extend to that type (to avoid
13753 // unnecessary sign/zero extends).
13754 if (N->hasOneUse() && N->user_begin()->getOpcode() == ISD::TRUNCATE)
13755 UseVT = N->user_begin()->getValueType(0);
13756
13757 Mask = DAG.getBoolExtOrTrunc(Mask, DL, UseVT, Mask.getValueType());
13758 Ret = DAG.getBoolExtOrTrunc(Ret, DL, UseVT, Ret.getValueType());
13759
13760 Ret = DAG.getNode(ISD::AND, DL, UseVT, Ret, Mask);
13761 if (UseVT != ResVT)
13762 Ret = DAG.getNode(ISD::ANY_EXTEND, DL, ResVT, Ret);
13763 return Ret;
13764}
13765
13767 SelectionDAG &DAG) const {
13768 SDLoc DL(N);
13769 SDValue Acc = N->getOperand(0);
13770 SDValue MulLHS = N->getOperand(1);
13771 SDValue MulRHS = N->getOperand(2);
13772 EVT AccVT = Acc.getValueType();
13773 EVT MulOpVT = MulLHS.getValueType();
13774
13775 EVT ExtMulOpVT =
13777 MulOpVT.getVectorElementCount());
13778
13779 unsigned ExtOpcLHS, ExtOpcRHS;
13780 switch (N->getOpcode()) {
13781 default:
13782 llvm_unreachable("Unexpected opcode");
13784 ExtOpcLHS = ExtOpcRHS = ISD::ZERO_EXTEND;
13785 break;
13787 ExtOpcLHS = ExtOpcRHS = ISD::SIGN_EXTEND;
13788 break;
13790 ExtOpcLHS = ISD::SIGN_EXTEND;
13791 ExtOpcRHS = ISD::ZERO_EXTEND;
13792 break;
13794 ExtOpcLHS = ExtOpcRHS = ISD::FP_EXTEND;
13795 break;
13796 }
13797
13798 // A wide partial reduction is built from a ladder of narrower ones, a rung
13799 // at a time, each halving the element count and doubling the width.
13800 unsigned Opc = N->getOpcode();
13801 ElementCount MulEC = MulOpVT.getVectorElementCount();
13802 ElementCount AccEC = AccVT.getVectorElementCount();
13803 unsigned CountRatio =
13804 MulEC.hasKnownScalarFactor(AccEC) ? MulEC.getKnownScalarFactor(AccEC) : 0;
13805 unsigned WidthRatio =
13806 AccVT.getScalarSizeInBits() / MulOpVT.getScalarSizeInBits();
13807 if (Opc != ISD::PARTIAL_REDUCE_FMLA && CountRatio > 2 && WidthRatio >= 2) {
13808 LLVMContext &Ctx = *DAG.getContext();
13809 EVT ProdVT = MulOpVT.widenIntegerVectorElementType(Ctx);
13810
13811 // A pure reduction peels one rung and re-enters.
13812 if (llvm::isOneOrOneSplat(MulRHS)) {
13813 EVT RungVT = ProdVT.getHalfNumVectorElementsVT(Ctx);
13814 return DAG.getNode(Opc, DL, AccVT, Acc,
13815 DAG.getNode(Opc, DL, RungVT,
13816 DAG.getConstant(0, DL, RungVT), MulLHS,
13817 MulRHS),
13818 DAG.getConstant(1, DL, RungVT));
13819 }
13820
13821 // A multiply widens the products by one rung, which legalizes back into a
13822 // widening multiply per half, and the ladder re-enters as a plain sum.
13823 SDValue Prod = DAG.getNode(ISD::MUL, DL, ProdVT,
13824 DAG.getNode(ExtOpcLHS, DL, ProdVT, MulLHS),
13825 DAG.getNode(ExtOpcRHS, DL, ProdVT, MulRHS));
13826 auto [Lo, Hi] = DAG.SplitVector(Prod, DL);
13827 SDValue One = DAG.getConstant(1, DL, Lo.getValueType());
13828
13829 // The halves meet at the narrowest rung, so the accumulator is added once.
13830 EVT MidVT = Lo.getValueType()
13831 .widenIntegerVectorElementType(Ctx)
13832 .getHalfNumVectorElementsVT(Ctx);
13834 return DAG.getNode(Opc, DL, AccVT,
13835 DAG.getNode(Opc, DL, AccVT, Acc, Lo, One), Hi, One);
13836 SDValue Mid =
13837 DAG.getNode(Opc, DL, MidVT, DAG.getConstant(0, DL, MidVT), Lo, One);
13838 Mid = DAG.getNode(Opc, DL, MidVT, Mid, Hi, One);
13839 return DAG.getNode(Opc, DL, AccVT, Acc, Mid, DAG.getConstant(1, DL, MidVT));
13840 }
13841
13842 if (ExtMulOpVT != MulOpVT) {
13843 MulLHS = DAG.getNode(ExtOpcLHS, DL, ExtMulOpVT, MulLHS);
13844 MulRHS = DAG.getNode(ExtOpcRHS, DL, ExtMulOpVT, MulRHS);
13845 }
13846 SDValue Input = MulLHS;
13847 if (N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA) {
13848 if (!llvm::isOneOrOneSplatFP(MulRHS))
13849 Input = DAG.getNode(ISD::FMUL, DL, ExtMulOpVT, MulLHS, MulRHS);
13850 } else if (!llvm::isOneOrOneSplat(MulRHS)) {
13851 Input = DAG.getNode(ISD::MUL, DL, ExtMulOpVT, MulLHS, MulRHS);
13852 }
13853
13854 unsigned Stride = AccVT.getVectorMinNumElements();
13855 unsigned ScaleFactor = MulOpVT.getVectorMinNumElements() / Stride;
13856
13857 // Collect all of the subvectors
13858 std::deque<SDValue> Subvectors = {Acc};
13859 for (unsigned I = 0; I < ScaleFactor; I++)
13860 Subvectors.push_back(DAG.getExtractSubvector(DL, AccVT, Input, I * Stride));
13861
13862 unsigned FlatNode =
13863 N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA ? ISD::FADD : ISD::ADD;
13864
13865 // Flatten the subvector tree
13866 while (Subvectors.size() > 1) {
13867 Subvectors.push_back(
13868 DAG.getNode(FlatNode, DL, AccVT, {Subvectors[0], Subvectors[1]}));
13869 Subvectors.pop_front();
13870 Subvectors.pop_front();
13871 }
13872
13873 assert(Subvectors.size() == 1 &&
13874 "There should only be one subvector after tree flattening");
13875
13876 return Subvectors[0];
13877}
13878
13879/// Given a store node \p StoreNode, return true if it is safe to fold that node
13880/// into \p FPNode, which expands to a library call with output pointers.
13882 SDNode *FPNode) {
13884 SmallVector<const SDNode *, 8> DeferredNodes;
13886
13887 // Skip FPNode use by StoreNode (that's the use we want to fold into FPNode).
13888 for (SDValue Op : StoreNode->ops())
13889 if (Op.getNode() != FPNode)
13890 Worklist.push_back(Op.getNode());
13891
13893 while (!Worklist.empty()) {
13894 const SDNode *Node = Worklist.pop_back_val();
13895 auto [_, Inserted] = Visited.insert(Node);
13896 if (!Inserted)
13897 continue;
13898
13899 if (MaxSteps > 0 && Visited.size() >= MaxSteps)
13900 return false;
13901
13902 // Reached the FPNode (would result in a cycle).
13903 // OR Reached CALLSEQ_START (would result in nested call sequences).
13904 if (Node == FPNode || Node->getOpcode() == ISD::CALLSEQ_START)
13905 return false;
13906
13907 if (Node->getOpcode() == ISD::CALLSEQ_END) {
13908 // Defer looking into call sequences (so we can check we're outside one).
13909 // We still need to look through these for the predecessor check.
13910 DeferredNodes.push_back(Node);
13911 continue;
13912 }
13913
13914 for (SDValue Op : Node->ops())
13915 Worklist.push_back(Op.getNode());
13916 }
13917
13918 // True if we're outside a call sequence and don't have the FPNode as a
13919 // predecessor. No cycles or nested call sequences possible.
13920 return !SDNode::hasPredecessorHelper(FPNode, Visited, DeferredNodes,
13921 MaxSteps);
13922}
13923
13925 SelectionDAG &DAG, RTLIB::Libcall LC, SDNode *Node,
13927 std::optional<unsigned> CallRetResNo) const {
13928 if (LC == RTLIB::UNKNOWN_LIBCALL)
13929 return false;
13930
13931 RTLIB::LibcallImpl LibcallImpl = getLibcallImpl(LC);
13932 if (LibcallImpl == RTLIB::Unsupported)
13933 return false;
13934
13935 LLVMContext &Ctx = *DAG.getContext();
13936 EVT VT = Node->getValueType(0);
13937 unsigned NumResults = Node->getNumValues();
13938
13939 // Find users of the node that store the results (and share input chains). The
13940 // destination pointers can be used instead of creating stack allocations.
13941 SDValue StoresInChain;
13942 SmallVector<StoreSDNode *, 2> ResultStores(NumResults);
13943 for (SDNode *User : Node->users()) {
13945 continue;
13946 auto *ST = cast<StoreSDNode>(User);
13947 SDValue StoreValue = ST->getValue();
13948 unsigned ResNo = StoreValue.getResNo();
13949 // Ensure the store corresponds to an output pointer.
13950 if (CallRetResNo == ResNo)
13951 continue;
13952 // Ensure the store to the default address space and not atomic or volatile.
13953 if (!ST->isSimple() || ST->getAddressSpace() != 0)
13954 continue;
13955 // Ensure all store chains are the same (so they don't alias).
13956 if (StoresInChain && ST->getChain() != StoresInChain)
13957 continue;
13958 // Ensure the store is properly aligned.
13959 Type *StoreType = StoreValue.getValueType().getTypeForEVT(Ctx);
13960 if (ST->getAlign() <
13961 DAG.getDataLayout().getABITypeAlign(StoreType->getScalarType()))
13962 continue;
13963 // Avoid:
13964 // 1. Creating cyclic dependencies.
13965 // 2. Expanding the node to a call within a call sequence.
13967 continue;
13968 ResultStores[ResNo] = ST;
13969 StoresInChain = ST->getChain();
13970 }
13971
13972 ArgListTy Args;
13973
13974 // Pass the arguments.
13975 for (const SDValue &Op : Node->op_values()) {
13976 EVT ArgVT = Op.getValueType();
13977 Type *ArgTy = ArgVT.getTypeForEVT(Ctx);
13978 Args.emplace_back(Op, ArgTy);
13979 }
13980
13981 // Pass the output pointers.
13982 SmallVector<SDValue, 2> ResultPtrs(NumResults);
13984 for (auto [ResNo, ST] : llvm::enumerate(ResultStores)) {
13985 if (ResNo == CallRetResNo)
13986 continue;
13987 EVT ResVT = Node->getValueType(ResNo);
13988 SDValue ResultPtr = ST ? ST->getBasePtr() : DAG.CreateStackTemporary(ResVT);
13989 ResultPtrs[ResNo] = ResultPtr;
13990 Args.emplace_back(ResultPtr, PointerTy);
13991 }
13992
13993 SDLoc DL(Node);
13994
13996 // Pass the vector mask (if required).
13997 EVT MaskVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
13998 SDValue Mask = DAG.getBoolConstant(true, DL, MaskVT, VT);
13999 Args.emplace_back(Mask, MaskVT.getTypeForEVT(Ctx));
14000 }
14001
14002 Type *RetType = CallRetResNo.has_value()
14003 ? Node->getValueType(*CallRetResNo).getTypeForEVT(Ctx)
14004 : Type::getVoidTy(Ctx);
14005 SDValue InChain = StoresInChain ? StoresInChain : DAG.getEntryNode();
14006 SDValue Callee =
14007 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
14009 CLI.setDebugLoc(DL).setChain(InChain).setLibCallee(
14010 getLibcallImplCallingConv(LibcallImpl), RetType, Callee, std::move(Args));
14011
14012 auto [Call, CallChain] = LowerCallTo(CLI);
14013
14014 for (auto [ResNo, ResultPtr] : llvm::enumerate(ResultPtrs)) {
14015 if (ResNo == CallRetResNo) {
14016 Results.push_back(Call);
14017 continue;
14018 }
14019 MachinePointerInfo PtrInfo;
14020 SDValue LoadResult = DAG.getLoad(Node->getValueType(ResNo), DL, CallChain,
14021 ResultPtr, PtrInfo);
14022 SDValue OutChain = LoadResult.getValue(1);
14023
14024 if (StoreSDNode *ST = ResultStores[ResNo]) {
14025 // Replace store with the library call.
14026 DAG.ReplaceAllUsesOfValueWith(SDValue(ST, 0), OutChain);
14027 PtrInfo = ST->getPointerInfo();
14028 } else {
14030 DAG.getMachineFunction(),
14031 cast<FrameIndexSDNode>(ResultPtr)->getIndex());
14032 }
14033
14034 Results.push_back(LoadResult);
14035 }
14036
14037 return true;
14038}
14039
14041 SDValue &LHS, SDValue &RHS,
14042 SDValue &CC, bool &NeedInvert,
14043 const SDLoc &dl, SDValue &Chain,
14044 bool IsSignaling) const {
14045 MVT OpVT = LHS.getSimpleValueType();
14046 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
14047 NeedInvert = false;
14048 switch (getCondCodeAction(CCCode, OpVT)) {
14049 default:
14050 llvm_unreachable("Unknown condition code action!");
14052 // Nothing to do.
14053 break;
14056 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14057 std::swap(LHS, RHS);
14058 CC = DAG.getCondCode(InvCC);
14059 return true;
14060 }
14061 // Swapping operands didn't work. Try inverting the condition.
14062 bool NeedSwap = false;
14063 InvCC = getSetCCInverse(CCCode, OpVT);
14064 if (!isCondCodeLegalOrCustom(InvCC, OpVT)) {
14065 // If inverting the condition is not enough, try swapping operands
14066 // on top of it.
14067 InvCC = ISD::getSetCCSwappedOperands(InvCC);
14068 NeedSwap = true;
14069 }
14070 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14071 CC = DAG.getCondCode(InvCC);
14072 NeedInvert = true;
14073 if (NeedSwap)
14074 std::swap(LHS, RHS);
14075 return true;
14076 }
14077
14078 // Special case: expand i1 comparisons using logical operations.
14079 if (OpVT == MVT::i1) {
14080 SDValue Ret;
14081 switch (CCCode) {
14082 default:
14083 llvm_unreachable("Unknown integer setcc!");
14084 case ISD::SETEQ: // X == Y --> ~(X ^ Y)
14085 Ret = DAG.getNOT(dl, DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS),
14086 MVT::i1);
14087 break;
14088 case ISD::SETNE: // X != Y --> (X ^ Y)
14089 Ret = DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS);
14090 break;
14091 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
14092 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
14093 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, RHS,
14094 DAG.getNOT(dl, LHS, MVT::i1));
14095 break;
14096 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
14097 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
14098 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, LHS,
14099 DAG.getNOT(dl, RHS, MVT::i1));
14100 break;
14101 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
14102 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
14103 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, RHS,
14104 DAG.getNOT(dl, LHS, MVT::i1));
14105 break;
14106 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
14107 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
14108 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, LHS,
14109 DAG.getNOT(dl, RHS, MVT::i1));
14110 break;
14111 }
14112
14113 LHS = DAG.getZExtOrTrunc(Ret, dl, VT);
14114 RHS = SDValue();
14115 CC = SDValue();
14116 return true;
14117 }
14118
14120 unsigned Opc = 0;
14121 switch (CCCode) {
14122 default:
14123 llvm_unreachable("Don't know how to expand this condition!");
14124 case ISD::SETUO:
14125 if (isCondCodeLegal(ISD::SETUNE, OpVT)) {
14126 CC1 = ISD::SETUNE;
14127 CC2 = ISD::SETUNE;
14128 Opc = ISD::OR;
14129 break;
14130 }
14132 "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
14133 NeedInvert = true;
14134 [[fallthrough]];
14135 case ISD::SETO:
14137 "If SETO is expanded, SETOEQ must be legal!");
14138 CC1 = ISD::SETOEQ;
14139 CC2 = ISD::SETOEQ;
14140 Opc = ISD::AND;
14141 break;
14142 case ISD::SETONE:
14143 case ISD::SETUEQ:
14144 // If the SETUO or SETO CC isn't legal, we might be able to use
14145 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
14146 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
14147 // the operands.
14148 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14149 if (!isCondCodeLegal(CC2, OpVT) && (isCondCodeLegal(ISD::SETOGT, OpVT) ||
14150 isCondCodeLegal(ISD::SETOLT, OpVT))) {
14151 CC1 = ISD::SETOGT;
14152 CC2 = ISD::SETOLT;
14153 Opc = ISD::OR;
14154 NeedInvert = ((unsigned)CCCode & 0x8U);
14155 break;
14156 }
14157 [[fallthrough]];
14158 case ISD::SETOEQ:
14159 case ISD::SETOGT:
14160 case ISD::SETOGE:
14161 case ISD::SETOLT:
14162 case ISD::SETOLE:
14163 case ISD::SETUNE:
14164 case ISD::SETUGT:
14165 case ISD::SETUGE:
14166 case ISD::SETULT:
14167 case ISD::SETULE:
14168 // If we are floating point, assign and break, otherwise fall through.
14169 if (!OpVT.isInteger()) {
14170 // We can use the 4th bit to tell if we are the unordered
14171 // or ordered version of the opcode.
14172 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14173 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
14174 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
14175 break;
14176 }
14177 // Fallthrough if we are unsigned integer.
14178 [[fallthrough]];
14179 case ISD::SETLE:
14180 case ISD::SETGT:
14181 case ISD::SETGE:
14182 case ISD::SETLT:
14183 case ISD::SETNE:
14184 case ISD::SETEQ:
14185 // If all combinations of inverting the condition and swapping operands
14186 // didn't work then we have no means to expand the condition.
14187 llvm_unreachable("Don't know how to expand this condition!");
14188 }
14189
14190 SDValue SetCC1, SetCC2;
14191 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
14192 // If we aren't the ordered or unorder operation,
14193 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
14194 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
14195 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
14196 } else {
14197 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
14198 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
14199 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
14200 }
14201 if (Chain)
14202 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
14203 SetCC2.getValue(1));
14204 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
14205 RHS = SDValue();
14206 CC = SDValue();
14207 return true;
14208 }
14209 }
14210 return false;
14211}
14212
14214 SelectionDAG &DAG) const {
14215 EVT VT = Node->getValueType(0);
14216 // Despite its documentation, GetSplitDestVTs will assert if VT cannot be
14217 // split into two equal parts.
14218 if (!VT.isVector() || !VT.getVectorElementCount().isKnownMultipleOf(2))
14219 return SDValue();
14220
14221 // Restrict expansion to cases where both parts can be concatenated.
14222 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
14223 if (LoVT != HiVT || !isTypeLegal(LoVT))
14224 return SDValue();
14225
14226 SDLoc DL(Node);
14227 unsigned Opcode = Node->getOpcode();
14228
14229 // Don't expand if the result is likely to be unrolled anyway.
14230 if (!isOperationLegalOrCustomOrPromote(Opcode, LoVT))
14231 return SDValue();
14232
14233 SmallVector<SDValue, 4> LoOps, HiOps;
14234 for (const SDValue &V : Node->op_values()) {
14235 if (!V.getValueType().isVector()) {
14236 // Scalar operands pass through to both halves unchanged.
14237 LoOps.push_back(V);
14238 HiOps.push_back(V);
14239 continue;
14240 }
14241 auto [Lo, Hi] = DAG.SplitVector(V, DL, LoVT, HiVT);
14242 LoOps.push_back(Lo);
14243 HiOps.push_back(Hi);
14244 }
14245
14246 SDValue SplitOpLo = DAG.getNode(Opcode, DL, LoVT, LoOps, Node->getFlags());
14247 SDValue SplitOpHi = DAG.getNode(Opcode, DL, HiVT, HiOps, Node->getFlags());
14248 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SplitOpLo, SplitOpHi);
14249}
14250
14252 const SDLoc &DL,
14253 EVT InVecVT, SDValue EltNo,
14254 LoadSDNode *OriginalLoad,
14255 SelectionDAG &DAG) const {
14256 assert(OriginalLoad->isSimple());
14257
14258 EVT VecEltVT = InVecVT.getVectorElementType();
14259
14260 // If the vector element type is not a multiple of a byte then we are unable
14261 // to correctly compute an address to load only the extracted element as a
14262 // scalar.
14263 if (!VecEltVT.isByteSized())
14264 return SDValue();
14265
14266 ISD::LoadExtType ExtTy =
14267 ResultVT.bitsGT(VecEltVT) ? ISD::EXTLOAD : ISD::NON_EXTLOAD;
14268 if (!isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14269 return SDValue();
14270
14271 std::optional<unsigned> ByteOffset;
14272 Align Alignment = OriginalLoad->getAlign();
14274 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14275 int Elt = ConstEltNo->getZExtValue();
14276 ByteOffset = VecEltVT.getSizeInBits() * Elt / 8;
14277 MPI = OriginalLoad->getPointerInfo().getWithOffset(*ByteOffset);
14278 Alignment = commonAlignment(Alignment, *ByteOffset);
14279 } else {
14280 // Discard the pointer info except the address space because the memory
14281 // operand can't represent this new access since the offset is variable.
14282 MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace());
14283 Alignment = commonAlignment(Alignment, VecEltVT.getSizeInBits() / 8);
14284 }
14285
14286 if (!shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT, ByteOffset))
14287 return SDValue();
14288
14289 unsigned IsFast = 0;
14290 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VecEltVT,
14291 OriginalLoad->getAddressSpace(), Alignment,
14292 OriginalLoad->getMemOperand()->getFlags(), &IsFast) ||
14293 !IsFast)
14294 return SDValue();
14295
14296 // The original DAG loaded the entire vector from memory, so arithmetic
14297 // within it must be inbounds.
14299 DAG, OriginalLoad->getBasePtr(), InVecVT, EltNo);
14300
14301 // We are replacing a vector load with a scalar load. The new load must have
14302 // identical memory op ordering to the original.
14303 SDValue Load;
14304 if (ResultVT.bitsGT(VecEltVT)) {
14305 // If the result type of vextract is wider than the load, then issue an
14306 // extending load instead.
14307 ISD::LoadExtType ExtType =
14308 isLoadLegal(ResultVT, VecEltVT, Alignment,
14309 OriginalLoad->getAddressSpace(), ISD::ZEXTLOAD, false)
14311 : ISD::EXTLOAD;
14312 Load = DAG.getExtLoad(ExtType, DL, ResultVT, OriginalLoad->getChain(),
14313 NewPtr, MPI, VecEltVT, Alignment,
14314 OriginalLoad->getMemOperand()->getFlags(),
14315 OriginalLoad->getAAInfo());
14316 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14317 } else {
14318 // The result type is narrower or the same width as the vector element
14319 Load = DAG.getLoad(VecEltVT, DL, OriginalLoad->getChain(), NewPtr, MPI,
14320 Alignment, OriginalLoad->getMemOperand()->getFlags(),
14321 OriginalLoad->getAAInfo());
14322 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14323 if (ResultVT.bitsLT(VecEltVT))
14324 Load = DAG.getNode(ISD::TRUNCATE, DL, ResultVT, Load);
14325 else
14326 Load = DAG.getBitcast(ResultVT, Load);
14327 }
14328
14329 return Load;
14330}
14331
14332// Set type id for call site info and metadata 'call_target'.
14333// We are filtering for:
14334// a) The call-graph-section use case that wants to know about indirect
14335// calls, or
14336// b) We want to annotate indirect calls.
14338 const CallBase *CB, MachineFunction &MF,
14339 MachineFunction::CallSiteInfo &CSInfo) const {
14340 if (CB && CB->isIndirectCall() &&
14343 CSInfo = MachineFunction::CallSiteInfo(*CB);
14344}
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 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 bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT)
static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, const SDLoc &dl, SelectionDAG &DAG)
static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, const SDLoc &dl, SelectionDAG &DAG, SmallVectorImpl< SDNode * > &Created)
Given an exact SDIV by a constant, create a multiplication with the multiplicative inverse of the con...
static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT, SDValue N0, const APInt &C1, ISD::CondCode Cond, const SDLoc &dl, SelectionDAG &DAG)
static SDValue combineShiftToAVG(SDValue Op, TargetLowering::TargetLoweringOpt &TLO, const TargetLowering &TLI, const APInt &DemandedBits, const APInt &DemandedElts, unsigned Depth)
This file describes how to lower LLVM code to machine code.
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
static SDValue scalarizeVectorStore(StoreSDNode *Store, MVT StoreVT, SelectionDAG &DAG)
Scalarize a vector store, bitcasting to TargetVT to determine the scalar type.
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
static LLVM_ABI const llvm::fltSemantics & EnumToSemantics(Semantics S)
Definition APFloat.cpp:136
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:337
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:358
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:393
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:329
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:370
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
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
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
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:68
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
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.
This class is used to represent ISD::LOAD nodes.
const SDValue & getBasePtr() const
Context object for machine code objects.
Definition MCContext.h:83
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
iterator_range< regclass_iterator > regclasses() const
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:213
Machine Value Type.
SimpleValueType SimpleTy
bool isInteger() const
Return true if this is an integer or a vector integer type.
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
static MVT getIntegerVT(unsigned BitWidth)
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
DenormalMode getDenormalMode(const fltSemantics &FPType) const
Returns the denormal handling type for the default rounding mode of the function.
MCSymbol * getJTISymbol(unsigned JTI, MCContext &Ctx, bool isLinkerPrivate=false) const
getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
Function & getFunction()
Return the LLVM function that this machine code represents.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
@ EK_LabelDifference32
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table.
@ EK_BlockAddress
EK_BlockAddress - Each entry is a plain address of block, e.g.: .word LBB123.
Flags getFlags() const
Return the raw flags of the source value,.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI MCRegister getLiveInPhysReg(Register VReg) const
getLiveInPhysReg - If VReg is a live-in virtual register, return the corresponding live-in physical r...
unsigned getAddressSpace() const
Return the address space for the associated pointer.
Align getAlign() const
AAMDNodes getAAInfo() const
Returns the AA info that describes the dereference.
bool isSimple() const
Returns true if the memory operation is neither atomic or volatile.
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const MachinePointerInfo & getPointerInfo() const
const SDValue & getChain() const
const GlobalVariable * getNamedGlobal(StringRef Name) const
Return the global variable in the module with the specified name, of arbitrary type.
Definition Module.h: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
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)
Set CallLoweringInfo attribute flags based on a call instruction and called function attributes.
bool isOperationExpand(unsigned Op, EVT VT) const
Return true if the specified operation is illegal on this target or unlikely to be made legal with cu...
unsigned getBitWidthForCttzElements(EVT RetVT, ElementCount EC, bool ZeroIsPoison, const ConstantRange *VScaleRange) const
Return the minimum number of bits required to hold the maximum possible number of trailing zero vecto...
virtual bool isShuffleMaskLegal(ArrayRef< int >, EVT) const
Targets can use this to indicate that they only support some VECTOR_SHUFFLE operations,...
virtual bool shouldRemoveRedundantExtend(SDValue Op) const
Return true (the default) if it is profitable to remove a sext_inreg(x) where the sext is redundant,...
virtual bool shouldReduceLoadWidth(SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT, std::optional< unsigned > ByteOffset=std::nullopt) const
Return true if it is profitable to reduce a load to a smaller type.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
virtual bool preferSelectsOverBooleanArithmetic(EVT VT) const
Should we prefer selects to doing arithmetic on boolean types.
virtual bool isLegalICmpImmediate(int64_t) const
Return true if the specified immediate is legal icmp immediate, that is the target has icmp instructi...
virtual MVT::SimpleValueType getCmpLibcallReturnType() const
Return the ValueType for comparison libcalls.
virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension.
MVT getVectorIdxTy(const DataLayout &DL) const
Returns the type to be used for the index operand of: ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT...
virtual bool isSafeMemOpType(MVT) const
Returns true if it's safe to use load / store of the specified type to expand memcpy / memset inline.
const TargetMachine & getTargetMachine() const
virtual bool isCtpopFast(EVT VT) const
Return true if ctpop instruction is fast.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
bool isPaddedAtMostSignificantBitsWhenStored(EVT VT) const
Indicates if any padding is guaranteed to go at the most significant bits when storing the type to me...
LegalizeTypeAction
This enum indicates whether a types are legal for a target, and if not, what action should be used to...
virtual bool hasBitTest(SDValue X, SDValue Y) const
Return true if the target has a bit-test instruction: (X & (1 << Y)) ==/!= 0 This knowledge can be us...
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.
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.
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 forceExpandMultiply(SelectionDAG &DAG, const SDLoc &dl, bool Signed, SDValue &Lo, SDValue &Hi, SDValue LHS, SDValue RHS, SDValue HiLHS=SDValue(), SDValue HiRHS=SDValue()) const
Calculate the product twice the width of LHS and RHS.
virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, SelectionDAG &DAG) const
Lower TLS global address SDNode for target independent emulated TLS model.
virtual bool isTypeDesirableForOp(unsigned, EVT VT) const
Return true if the target has native support for the specified value type and it is 'desirable' to us...
SDValue expandVectorSplice(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::VECTOR_SPLICE.
SDValue getVectorSubVecPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT, EVT SubVecVT, SDValue Index, const SDNodeFlags PtrArithFlags=SDNodeFlags()) const
Get a pointer to a sub-vector of type SubVecVT at index Idx located in memory for a vector of type Ve...
SDValue expandLoopDependenceMask(SDNode *N, SelectionDAG &DAG) const
Expand LOOP_DEPENDENCE_MASK nodes.
virtual const char * LowerXConstraint(EVT ConstraintVT) const
Try to replace an X constraint, which matches anything, with another that has more specific requireme...
SDValue expandCTPOP(SDNode *N, SelectionDAG &DAG) const
Expand CTPOP nodes.
virtual void computeKnownBitsForTargetInstr(GISelValueTracking &Analysis, Register R, KnownBits &Known, const APInt &DemandedElts, const MachineRegisterInfo &MRI, unsigned Depth=0) const
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization, bool IsAfterLegalTypes, SmallVectorImpl< SDNode * > &Created) const
Given an ISD::UDIV node expressing a divide by constant, return a DAG expression to select that will ...
SDValue expandVectorNaryOpBySplitting(SDNode *Node, SelectionDAG &DAG) const
~TargetLowering() override
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
SDValue expandBSWAP(SDNode *N, SelectionDAG &DAG) const
Expand BSWAP nodes.
SDValue expandFMINIMUM_FMAXIMUM(SDNode *N, SelectionDAG &DAG) const
Expand fminimum/fmaximum into multiple comparison with selects.
SDValue CTTZTableLookup(SDNode *N, SelectionDAG &DAG, const SDLoc &DL, EVT VT, SDValue Op, unsigned NumBitsPerElt) const
Expand CTTZ via Table Lookup.
bool expandDIVREMByConstant(SDNode *N, SmallVectorImpl< SDValue > &Result, EVT HiLoVT, SelectionDAG &DAG, SDValue LL=SDValue(), SDValue LH=SDValue()) const
Attempt to expand an n-bit div/rem/divrem by constant using an n/2-bit algorithm.
virtual void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
bool isPositionIndependent() const
std::pair< StringRef, TargetLowering::ConstraintType > ConstraintPair
virtual SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, NegatibleCost &Cost, unsigned Depth=0) const
Return the newly negated expression if the cost is not expensive and set the cost in Cost to indicate...
virtual ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const
Examine constraint string and operand type and determine a weight value.
ConstraintGroup getConstraintPreferences(AsmOperandInfo &OpInfo) const
Given an OpInfo with list of constraints codes as strings, return a sorted Vector of pairs of constra...
bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const
Expand float(f32) to SINT(i64) conversion.
virtual SDValue SimplifyMultipleUseDemandedBitsForTargetNode(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, SelectionDAG &DAG, unsigned Depth) const
More limited version of SimplifyDemandedBits that can be used to "lookthrough" ops that don't contrib...
virtual SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Glue, const SDLoc &DL, const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const
SDValue buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, SDValue N1, MutableArrayRef< int > Mask, SelectionDAG &DAG) const
Tries to build a legal vector shuffle using the provided parameters or equivalent variations.
virtual void computeKnownBitsForStackObjectPointer(KnownBits &Known, const MachineFunction &MF, Align Alignment) const
Determine known bits of a pointer to a known valid stack object.
virtual SDValue getPICJumpTableRelocBase(SDValue Table, SelectionDAG &DAG) const
Returns relocation base for the given PIC jumptable.
std::pair< SDValue, SDValue > scalarizeVectorLoad(LoadSDNode *LD, SelectionDAG &DAG) const
Turn load of vector type into a load of the individual elements.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth=0, bool AssumeSingleUse=false) const
Look at Op.
virtual bool SimplifyDemandedBitsForTargetNode(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth=0) const
Attempt to simplify any target nodes based on the demanded bits/elts, returning true on success.
virtual bool isDesirableToCommuteXorWithShift(const SDNode *N) const
Return true if it is profitable to combine an XOR of a logical shift to create a logical shift of NOT...
TargetLowering(const TargetLowering &)=delete
virtual bool shouldSimplifyDemandedVectorElts(SDValue Op, const TargetLoweringOpt &TLO) const
Return true if the target supports simplifying demanded vector elements by converting them to undefs.
bool isConstFalseVal(SDValue N) const
Return if the N is a constant or constant vector equal to the false value from getBooleanContents().
SDValue IncrementMemoryAddress(SDValue Addr, SDValue Mask, const SDLoc &DL, EVT DataVT, SelectionDAG &DAG, bool IsCompressedMemory) const
Increments memory address Addr according to the type of the value DataVT that should be stored.
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:869
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:717
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
constexpr bool isKnownMultipleOf(ScalarTy RHS) const
This function tells the caller whether the element count is known at compile time to be a multiple of...
Definition TypeSize.h:180
constexpr 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:41
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:830
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:261
@ PTRADD
PTRADD represents pointer arithmetic semantics, for targets that opt in using shouldPreservePtrArith(...
@ PARTIAL_REDUCE_SMLA
PARTIAL_REDUCE_[U|S]MLA(Accumulator, Input1, Input2) The partial reduction nodes sign or zero extend ...
@ LOOP_DEPENDENCE_RAW_MASK
@ FGETSIGN
INT = FGETSIGN(FP) - Return the sign bit of the specified floating point value as an integer 0/1 valu...
Definition ISDOpcodes.h:541
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:275
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:603
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:790
@ SMULFIX
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
Definition ISDOpcodes.h:395
@ ADDC
Carry-setting nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:294
@ FMAD
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations.
Definition ISDOpcodes.h:525
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:264
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ SMULFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:401
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:864
@ 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:521
@ VECTOR_FIND_LAST_ACTIVE
Finds the index of the last active mask element Operands: Mask.
@ PSEUDO_FMIN
PSEUDO_FMIN is strictly equivalent to op0 olt op1 ?
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:220
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:891
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:587
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:418
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:750
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:921
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:280
@ FMULADD
FMULADD - Performs a * b + c, with, or without, intermediate rounding.
Definition ISDOpcodes.h:531
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:254
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:781
@ SDIVFIX
RESULT = [US]DIVFIX(LHS, RHS, SCALE) - Perform fixed point division on 2 integers with the same width...
Definition ISDOpcodes.h:408
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:799
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:855
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:718
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:668
@ 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:353
@ BRIND
BRIND - Indirect branch.
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:544
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:551
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:375
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:807
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:247
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:675
@ GET_ACTIVE_LANE_MASK
GET_ACTIVE_LANE_MASK - this corrosponds to the llvm.get.active.lane.mask intrinsic.
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:230
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:349
@ 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:707
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:772
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:652
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:617
@ 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:579
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:861
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:822
@ 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:387
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:357
@ VECTOR_SPLICE_LEFT
VECTOR_SPLICE_LEFT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1, VEC2) left by OFFSET elements an...
Definition ISDOpcodes.h:656
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:910
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:899
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:730
@ SDIVFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:414
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:989
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:816
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:329
@ PEXT
Parallel bit extract (compress) and parallel bit deposit (expand).
Definition ISDOpcodes.h:786
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:480
@ 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:937
@ TargetConstant
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification,...
Definition ISDOpcodes.h:179
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:742
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:205
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:713
@ VECTOR_SPLICE_RIGHT
VECTOR_SPLICE_RIGHT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1,VEC2) right by OFFSET elements a...
Definition ISDOpcodes.h:660
@ ADDE
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:304
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:241
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:568
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:53
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:798
@ 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:970
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:932
@ 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:956
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:867
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:844
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:537
@ PARTIAL_REDUCE_SUMLA
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:366
@ CALLSEQ_START
CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end of a call sequence,...
@ CTTZ_ELTS_ZERO_POISON
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - minimumnum/maximumnum that is same with FMINNUM_IEEE and FMAXNUM_IEEE besid...
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:725
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:213
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:754
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:559
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.
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(SDNode *N, const SelectionDAG *DAG, Pattern &&P)
NUses_match< 1, Value_match > m_OneUse()
This is an optimization pass for GlobalISel generic memory operations.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h: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:1557
@ 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:1539
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.
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:144
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
@ 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.
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isZeroOrZeroSplat(SDValue N, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
LLVM_ABI bool isNullFPConstant(SDValue V)
Returns true if V is an FP constant with a value of positive zero.
APFloat neg(APFloat X)
Returns the negated value of the argument.
Definition APFloat.h:1727
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h: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
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h: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
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
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.
static LLVM_ABI bool hasVectorMaskArgument(RTLIB::LibcallImpl Impl)
Returns true if the function has a vector mask argument, which is assumed to be the last argument.
These are IR-level optimization flags that may be propagated to SDNodes.
bool hasNoUnsignedWrap() const
bool hasNoSignedWrap() const
void setNoSignedWrap(bool b)
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
Magic data for optimising signed division by a constant.
static LLVM_ABI SignedDivisionByConstantInfo get(const APInt &D)
Calculate the magic numbers required to implement a signed integer division by a constant as a sequen...
This contains information for each constraint that we are lowering.
std::string ConstraintCode
This contains the actual string for the code, like "m".
LLVM_ABI unsigned getMatchedOperand() const
If this is an input matching constraint, this method returns the output operand it matches.
LLVM_ABI bool isMatchingInputConstraint() const
Return true of this is an input operand that is a matching constraint like "4".
This structure contains all information that is necessary for lowering calls.
CallLoweringInfo & setIsPostTypeLegalization(bool Value=true)
CallLoweringInfo & setLibCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList)
CallLoweringInfo & setDiscardResult(bool Value=true)
CallLoweringInfo & setZExtResult(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setSExtResult(bool Value=true)
CallLoweringInfo & setNoReturn(bool Value=true)
CallLoweringInfo & setChain(SDValue InChain)
LLVM_ABI void AddToWorklist(SDNode *N)
LLVM_ABI void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO)
This structure is used to pass arguments to makeLibCall function.
MakeLibCallOptions & setIsPostTypeLegalization(bool Value=true)
MakeLibCallOptions & setTypeListBeforeSoften(ArrayRef< EVT > OpsVT, EVT RetVT)
MakeLibCallOptions & setIsSigned(bool Value=true)
A convenience struct that encapsulates a DAG, and two SDValues for returning information from TargetL...
Magic data for optimising unsigned division by a constant.
static LLVM_ABI UnsignedDivisionByConstantInfo get(const APInt &D, unsigned LeadingZeros=0, bool AllowEvenDivisorOptimization=true, bool AllowWidenOptimization=false)
Calculate the magic numbers required to implement an unsigned integer division by a constant as a seq...
fltNonfiniteBehavior nonFiniteBehavior
Definition APFloat.h:1039
fltNanEncoding nanEncoding
Definition APFloat.h:1041