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 13 #include "llvm/CodeGen/TargetLowering.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/Analysis/VectorUtils.h" 16 #include "llvm/CodeGen/CallingConvLower.h" 17 #include "llvm/CodeGen/CodeGenCommonISel.h" 18 #include "llvm/CodeGen/MachineFrameInfo.h" 19 #include "llvm/CodeGen/MachineFunction.h" 20 #include "llvm/CodeGen/MachineJumpTableInfo.h" 21 #include "llvm/CodeGen/MachineModuleInfoImpls.h" 22 #include "llvm/CodeGen/MachineRegisterInfo.h" 23 #include "llvm/CodeGen/SelectionDAG.h" 24 #include "llvm/CodeGen/TargetRegisterInfo.h" 25 #include "llvm/IR/DataLayout.h" 26 #include "llvm/IR/DerivedTypes.h" 27 #include "llvm/IR/GlobalVariable.h" 28 #include "llvm/IR/LLVMContext.h" 29 #include "llvm/MC/MCAsmInfo.h" 30 #include "llvm/MC/MCExpr.h" 31 #include "llvm/Support/DivisionByConstantInfo.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/KnownBits.h" 34 #include "llvm/Support/MathExtras.h" 35 #include "llvm/Target/TargetMachine.h" 36 #include <cctype> 37 using namespace llvm; 38 39 /// NOTE: The TargetMachine owns TLOF. 40 TargetLowering::TargetLowering(const TargetMachine &tm) 41 : TargetLoweringBase(tm) {} 42 43 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const { 44 return nullptr; 45 } 46 47 bool TargetLowering::isPositionIndependent() const { 48 return getTargetMachine().isPositionIndependent(); 49 } 50 51 /// Check whether a given call node is in tail position within its function. If 52 /// so, it sets Chain to the input chain of the tail call. 53 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node, 54 SDValue &Chain) const { 55 const Function &F = DAG.getMachineFunction().getFunction(); 56 57 // First, check if tail calls have been disabled in this function. 58 if (F.getFnAttribute("disable-tail-calls").getValueAsBool()) 59 return false; 60 61 // Conservatively require the attributes of the call to match those of 62 // the return. Ignore following attributes because they don't affect the 63 // call sequence. 64 AttrBuilder CallerAttrs(F.getContext(), F.getAttributes().getRetAttrs()); 65 for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable, 66 Attribute::DereferenceableOrNull, Attribute::NoAlias, 67 Attribute::NonNull, Attribute::NoUndef}) 68 CallerAttrs.removeAttribute(Attr); 69 70 if (CallerAttrs.hasAttributes()) 71 return false; 72 73 // It's not safe to eliminate the sign / zero extension of the return value. 74 if (CallerAttrs.contains(Attribute::ZExt) || 75 CallerAttrs.contains(Attribute::SExt)) 76 return false; 77 78 // Check if the only use is a function return node. 79 return isUsedByReturnOnly(Node, Chain); 80 } 81 82 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI, 83 const uint32_t *CallerPreservedMask, 84 const SmallVectorImpl<CCValAssign> &ArgLocs, 85 const SmallVectorImpl<SDValue> &OutVals) const { 86 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 87 const CCValAssign &ArgLoc = ArgLocs[I]; 88 if (!ArgLoc.isRegLoc()) 89 continue; 90 MCRegister Reg = ArgLoc.getLocReg(); 91 // Only look at callee saved registers. 92 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg)) 93 continue; 94 // Check that we pass the value used for the caller. 95 // (We look for a CopyFromReg reading a virtual register that is used 96 // for the function live-in value of register Reg) 97 SDValue Value = OutVals[I]; 98 if (Value->getOpcode() == ISD::AssertZext) 99 Value = Value.getOperand(0); 100 if (Value->getOpcode() != ISD::CopyFromReg) 101 return false; 102 Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg(); 103 if (MRI.getLiveInPhysReg(ArgReg) != Reg) 104 return false; 105 } 106 return true; 107 } 108 109 /// Set CallLoweringInfo attribute flags based on a call instruction 110 /// and called function attributes. 111 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call, 112 unsigned ArgIdx) { 113 IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt); 114 IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt); 115 IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg); 116 IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet); 117 IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest); 118 IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal); 119 IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated); 120 IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca); 121 IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned); 122 IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf); 123 IsSwiftAsync = Call->paramHasAttr(ArgIdx, Attribute::SwiftAsync); 124 IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError); 125 Alignment = Call->getParamStackAlign(ArgIdx); 126 IndirectType = nullptr; 127 assert(IsByVal + IsPreallocated + IsInAlloca + IsSRet <= 1 && 128 "multiple ABI attributes?"); 129 if (IsByVal) { 130 IndirectType = Call->getParamByValType(ArgIdx); 131 if (!Alignment) 132 Alignment = Call->getParamAlign(ArgIdx); 133 } 134 if (IsPreallocated) 135 IndirectType = Call->getParamPreallocatedType(ArgIdx); 136 if (IsInAlloca) 137 IndirectType = Call->getParamInAllocaType(ArgIdx); 138 if (IsSRet) 139 IndirectType = Call->getParamStructRetType(ArgIdx); 140 } 141 142 /// Generate a libcall taking the given operands as arguments and returning a 143 /// result of type RetVT. 144 std::pair<SDValue, SDValue> 145 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, 146 ArrayRef<SDValue> Ops, 147 MakeLibCallOptions CallOptions, 148 const SDLoc &dl, 149 SDValue InChain) const { 150 if (!InChain) 151 InChain = DAG.getEntryNode(); 152 153 TargetLowering::ArgListTy Args; 154 Args.reserve(Ops.size()); 155 156 TargetLowering::ArgListEntry Entry; 157 for (unsigned i = 0; i < Ops.size(); ++i) { 158 SDValue NewOp = Ops[i]; 159 Entry.Node = NewOp; 160 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 161 Entry.IsSExt = shouldSignExtendTypeInLibCall(NewOp.getValueType(), 162 CallOptions.IsSExt); 163 Entry.IsZExt = !Entry.IsSExt; 164 165 if (CallOptions.IsSoften && 166 !shouldExtendTypeInLibCall(CallOptions.OpsVTBeforeSoften[i])) { 167 Entry.IsSExt = Entry.IsZExt = false; 168 } 169 Args.push_back(Entry); 170 } 171 172 if (LC == RTLIB::UNKNOWN_LIBCALL) 173 report_fatal_error("Unsupported library call operation!"); 174 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 175 getPointerTy(DAG.getDataLayout())); 176 177 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 178 TargetLowering::CallLoweringInfo CLI(DAG); 179 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, CallOptions.IsSExt); 180 bool zeroExtend = !signExtend; 181 182 if (CallOptions.IsSoften && 183 !shouldExtendTypeInLibCall(CallOptions.RetVTBeforeSoften)) { 184 signExtend = zeroExtend = false; 185 } 186 187 CLI.setDebugLoc(dl) 188 .setChain(InChain) 189 .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 190 .setNoReturn(CallOptions.DoesNotReturn) 191 .setDiscardResult(!CallOptions.IsReturnValueUsed) 192 .setIsPostTypeLegalization(CallOptions.IsPostTypeLegalization) 193 .setSExtResult(signExtend) 194 .setZExtResult(zeroExtend); 195 return LowerCallTo(CLI); 196 } 197 198 bool TargetLowering::findOptimalMemOpLowering( 199 std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, 200 unsigned SrcAS, const AttributeList &FuncAttributes) const { 201 if (Limit != ~unsigned(0) && Op.isMemcpyWithFixedDstAlign() && 202 Op.getSrcAlign() < Op.getDstAlign()) 203 return false; 204 205 EVT VT = getOptimalMemOpType(Op, FuncAttributes); 206 207 if (VT == MVT::Other) { 208 // Use the largest integer type whose alignment constraints are satisfied. 209 // We only need to check DstAlign here as SrcAlign is always greater or 210 // equal to DstAlign (or zero). 211 VT = MVT::i64; 212 if (Op.isFixedDstAlign()) 213 while (Op.getDstAlign() < (VT.getSizeInBits() / 8) && 214 !allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign())) 215 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1); 216 assert(VT.isInteger()); 217 218 // Find the largest legal integer type. 219 MVT LVT = MVT::i64; 220 while (!isTypeLegal(LVT)) 221 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1); 222 assert(LVT.isInteger()); 223 224 // If the type we've chosen is larger than the largest legal integer type 225 // then use that instead. 226 if (VT.bitsGT(LVT)) 227 VT = LVT; 228 } 229 230 unsigned NumMemOps = 0; 231 uint64_t Size = Op.size(); 232 while (Size) { 233 unsigned VTSize = VT.getSizeInBits() / 8; 234 while (VTSize > Size) { 235 // For now, only use non-vector load / store's for the left-over pieces. 236 EVT NewVT = VT; 237 unsigned NewVTSize; 238 239 bool Found = false; 240 if (VT.isVector() || VT.isFloatingPoint()) { 241 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32; 242 if (isOperationLegalOrCustom(ISD::STORE, NewVT) && 243 isSafeMemOpType(NewVT.getSimpleVT())) 244 Found = true; 245 else if (NewVT == MVT::i64 && 246 isOperationLegalOrCustom(ISD::STORE, MVT::f64) && 247 isSafeMemOpType(MVT::f64)) { 248 // i64 is usually not legal on 32-bit targets, but f64 may be. 249 NewVT = MVT::f64; 250 Found = true; 251 } 252 } 253 254 if (!Found) { 255 do { 256 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1); 257 if (NewVT == MVT::i8) 258 break; 259 } while (!isSafeMemOpType(NewVT.getSimpleVT())); 260 } 261 NewVTSize = NewVT.getSizeInBits() / 8; 262 263 // If the new VT cannot cover all of the remaining bits, then consider 264 // issuing a (or a pair of) unaligned and overlapping load / store. 265 unsigned Fast; 266 if (NumMemOps && Op.allowOverlap() && NewVTSize < Size && 267 allowsMisalignedMemoryAccesses( 268 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1), 269 MachineMemOperand::MONone, &Fast) && 270 Fast) 271 VTSize = Size; 272 else { 273 VT = NewVT; 274 VTSize = NewVTSize; 275 } 276 } 277 278 if (++NumMemOps > Limit) 279 return false; 280 281 MemOps.push_back(VT); 282 Size -= VTSize; 283 } 284 285 return true; 286 } 287 288 /// Soften the operands of a comparison. This code is shared among BR_CC, 289 /// SELECT_CC, and SETCC handlers. 290 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 291 SDValue &NewLHS, SDValue &NewRHS, 292 ISD::CondCode &CCCode, 293 const SDLoc &dl, const SDValue OldLHS, 294 const SDValue OldRHS) const { 295 SDValue Chain; 296 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS, 297 OldRHS, Chain); 298 } 299 300 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 301 SDValue &NewLHS, SDValue &NewRHS, 302 ISD::CondCode &CCCode, 303 const SDLoc &dl, const SDValue OldLHS, 304 const SDValue OldRHS, 305 SDValue &Chain, 306 bool IsSignaling) const { 307 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc 308 // not supporting it. We can update this code when libgcc provides such 309 // functions. 310 311 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128) 312 && "Unsupported setcc type!"); 313 314 // Expand into one or more soft-fp libcall(s). 315 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL; 316 bool ShouldInvertCC = false; 317 switch (CCCode) { 318 case ISD::SETEQ: 319 case ISD::SETOEQ: 320 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 321 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 322 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 323 break; 324 case ISD::SETNE: 325 case ISD::SETUNE: 326 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : 327 (VT == MVT::f64) ? RTLIB::UNE_F64 : 328 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128; 329 break; 330 case ISD::SETGE: 331 case ISD::SETOGE: 332 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 333 (VT == MVT::f64) ? RTLIB::OGE_F64 : 334 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 335 break; 336 case ISD::SETLT: 337 case ISD::SETOLT: 338 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 339 (VT == MVT::f64) ? RTLIB::OLT_F64 : 340 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 341 break; 342 case ISD::SETLE: 343 case ISD::SETOLE: 344 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 345 (VT == MVT::f64) ? RTLIB::OLE_F64 : 346 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 347 break; 348 case ISD::SETGT: 349 case ISD::SETOGT: 350 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 351 (VT == MVT::f64) ? RTLIB::OGT_F64 : 352 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 353 break; 354 case ISD::SETO: 355 ShouldInvertCC = true; 356 [[fallthrough]]; 357 case ISD::SETUO: 358 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 359 (VT == MVT::f64) ? RTLIB::UO_F64 : 360 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 361 break; 362 case ISD::SETONE: 363 // SETONE = O && UNE 364 ShouldInvertCC = true; 365 [[fallthrough]]; 366 case ISD::SETUEQ: 367 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 368 (VT == MVT::f64) ? RTLIB::UO_F64 : 369 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 370 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 371 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 372 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 373 break; 374 default: 375 // Invert CC for unordered comparisons 376 ShouldInvertCC = true; 377 switch (CCCode) { 378 case ISD::SETULT: 379 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 380 (VT == MVT::f64) ? RTLIB::OGE_F64 : 381 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 382 break; 383 case ISD::SETULE: 384 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 385 (VT == MVT::f64) ? RTLIB::OGT_F64 : 386 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 387 break; 388 case ISD::SETUGT: 389 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 390 (VT == MVT::f64) ? RTLIB::OLE_F64 : 391 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 392 break; 393 case ISD::SETUGE: 394 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 395 (VT == MVT::f64) ? RTLIB::OLT_F64 : 396 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 397 break; 398 default: llvm_unreachable("Do not know how to soften this setcc!"); 399 } 400 } 401 402 // Use the target specific return value for comparison lib calls. 403 EVT RetVT = getCmpLibcallReturnType(); 404 SDValue Ops[2] = {NewLHS, NewRHS}; 405 TargetLowering::MakeLibCallOptions CallOptions; 406 EVT OpsVT[2] = { OldLHS.getValueType(), 407 OldRHS.getValueType() }; 408 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT, true); 409 auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain); 410 NewLHS = Call.first; 411 NewRHS = DAG.getConstant(0, dl, RetVT); 412 413 CCCode = getCmpLibcallCC(LC1); 414 if (ShouldInvertCC) { 415 assert(RetVT.isInteger()); 416 CCCode = getSetCCInverse(CCCode, RetVT); 417 } 418 419 if (LC2 == RTLIB::UNKNOWN_LIBCALL) { 420 // Update Chain. 421 Chain = Call.second; 422 } else { 423 EVT SetCCVT = 424 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT); 425 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode); 426 auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain); 427 CCCode = getCmpLibcallCC(LC2); 428 if (ShouldInvertCC) 429 CCCode = getSetCCInverse(CCCode, RetVT); 430 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode); 431 if (Chain) 432 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second, 433 Call2.second); 434 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl, 435 Tmp.getValueType(), Tmp, NewLHS); 436 NewRHS = SDValue(); 437 } 438 } 439 440 /// Return the entry encoding for a jump table in the current function. The 441 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum. 442 unsigned TargetLowering::getJumpTableEncoding() const { 443 // In non-pic modes, just use the address of a block. 444 if (!isPositionIndependent()) 445 return MachineJumpTableInfo::EK_BlockAddress; 446 447 // In PIC mode, if the target supports a GPRel32 directive, use it. 448 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr) 449 return MachineJumpTableInfo::EK_GPRel32BlockAddress; 450 451 // Otherwise, use a label difference. 452 return MachineJumpTableInfo::EK_LabelDifference32; 453 } 454 455 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table, 456 SelectionDAG &DAG) const { 457 // If our PIC model is GP relative, use the global offset table as the base. 458 unsigned JTEncoding = getJumpTableEncoding(); 459 460 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) || 461 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress)) 462 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout())); 463 464 return Table; 465 } 466 467 /// This returns the relocation base for the given PIC jumptable, the same as 468 /// getPICJumpTableRelocBase, but as an MCExpr. 469 const MCExpr * 470 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 471 unsigned JTI,MCContext &Ctx) const{ 472 // The normal PIC reloc base is the label at the start of the jump table. 473 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx); 474 } 475 476 SDValue TargetLowering::expandIndirectJTBranch(const SDLoc &dl, SDValue Value, 477 SDValue Addr, int JTI, 478 SelectionDAG &DAG) const { 479 SDValue Chain = Value; 480 // Jump table debug info is only needed if CodeView is enabled. 481 if (DAG.getTarget().getTargetTriple().isOSBinFormatCOFF()) { 482 Chain = DAG.getJumpTableDebugInfo(JTI, Chain, dl); 483 } 484 return DAG.getNode(ISD::BRIND, dl, MVT::Other, Chain, Addr); 485 } 486 487 bool 488 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 489 const TargetMachine &TM = getTargetMachine(); 490 const GlobalValue *GV = GA->getGlobal(); 491 492 // If the address is not even local to this DSO we will have to load it from 493 // a got and then add the offset. 494 if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 495 return false; 496 497 // If the code is position independent we will have to add a base register. 498 if (isPositionIndependent()) 499 return false; 500 501 // Otherwise we can do it. 502 return true; 503 } 504 505 //===----------------------------------------------------------------------===// 506 // Optimization Methods 507 //===----------------------------------------------------------------------===// 508 509 /// If the specified instruction has a constant integer operand and there are 510 /// bits set in that constant that are not demanded, then clear those bits and 511 /// return true. 512 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 513 const APInt &DemandedBits, 514 const APInt &DemandedElts, 515 TargetLoweringOpt &TLO) const { 516 SDLoc DL(Op); 517 unsigned Opcode = Op.getOpcode(); 518 519 // Early-out if we've ended up calling an undemanded node, leave this to 520 // constant folding. 521 if (DemandedBits.isZero() || DemandedElts.isZero()) 522 return false; 523 524 // Do target-specific constant optimization. 525 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 526 return TLO.New.getNode(); 527 528 // FIXME: ISD::SELECT, ISD::SELECT_CC 529 switch (Opcode) { 530 default: 531 break; 532 case ISD::XOR: 533 case ISD::AND: 534 case ISD::OR: { 535 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 536 if (!Op1C || Op1C->isOpaque()) 537 return false; 538 539 // If this is a 'not' op, don't touch it because that's a canonical form. 540 const APInt &C = Op1C->getAPIntValue(); 541 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C)) 542 return false; 543 544 if (!C.isSubsetOf(DemandedBits)) { 545 EVT VT = Op.getValueType(); 546 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT); 547 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC); 548 return TLO.CombineTo(Op, NewOp); 549 } 550 551 break; 552 } 553 } 554 555 return false; 556 } 557 558 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 559 const APInt &DemandedBits, 560 TargetLoweringOpt &TLO) const { 561 EVT VT = Op.getValueType(); 562 APInt DemandedElts = VT.isVector() 563 ? APInt::getAllOnes(VT.getVectorNumElements()) 564 : APInt(1, 1); 565 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO); 566 } 567 568 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. 569 /// This uses isTruncateFree/isZExtFree and ANY_EXTEND for the widening cast, 570 /// but it could be generalized for targets with other types of implicit 571 /// widening casts. 572 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth, 573 const APInt &DemandedBits, 574 TargetLoweringOpt &TLO) const { 575 assert(Op.getNumOperands() == 2 && 576 "ShrinkDemandedOp only supports binary operators!"); 577 assert(Op.getNode()->getNumValues() == 1 && 578 "ShrinkDemandedOp only supports nodes with one result!"); 579 580 EVT VT = Op.getValueType(); 581 SelectionDAG &DAG = TLO.DAG; 582 SDLoc dl(Op); 583 584 // Early return, as this function cannot handle vector types. 585 if (VT.isVector()) 586 return false; 587 588 // Don't do this if the node has another user, which may require the 589 // full value. 590 if (!Op.getNode()->hasOneUse()) 591 return false; 592 593 // Search for the smallest integer type with free casts to and from 594 // Op's type. For expedience, just check power-of-2 integer types. 595 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 596 unsigned DemandedSize = DemandedBits.getActiveBits(); 597 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize); 598 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) { 599 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits); 600 if (TLI.isTruncateFree(VT, SmallVT) && TLI.isZExtFree(SmallVT, VT)) { 601 // We found a type with free casts. 602 SDValue X = DAG.getNode( 603 Op.getOpcode(), dl, SmallVT, 604 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)), 605 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1))); 606 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?"); 607 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, VT, X); 608 return TLO.CombineTo(Op, Z); 609 } 610 } 611 return false; 612 } 613 614 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 615 DAGCombinerInfo &DCI) const { 616 SelectionDAG &DAG = DCI.DAG; 617 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 618 !DCI.isBeforeLegalizeOps()); 619 KnownBits Known; 620 621 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO); 622 if (Simplified) { 623 DCI.AddToWorklist(Op.getNode()); 624 DCI.CommitTargetLoweringOpt(TLO); 625 } 626 return Simplified; 627 } 628 629 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 630 const APInt &DemandedElts, 631 DAGCombinerInfo &DCI) const { 632 SelectionDAG &DAG = DCI.DAG; 633 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 634 !DCI.isBeforeLegalizeOps()); 635 KnownBits Known; 636 637 bool Simplified = 638 SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO); 639 if (Simplified) { 640 DCI.AddToWorklist(Op.getNode()); 641 DCI.CommitTargetLoweringOpt(TLO); 642 } 643 return Simplified; 644 } 645 646 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 647 KnownBits &Known, 648 TargetLoweringOpt &TLO, 649 unsigned Depth, 650 bool AssumeSingleUse) const { 651 EVT VT = Op.getValueType(); 652 653 // Since the number of lanes in a scalable vector is unknown at compile time, 654 // we track one bit which is implicitly broadcast to all lanes. This means 655 // that all lanes in a scalable vector are considered demanded. 656 APInt DemandedElts = VT.isFixedLengthVector() 657 ? APInt::getAllOnes(VT.getVectorNumElements()) 658 : APInt(1, 1); 659 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth, 660 AssumeSingleUse); 661 } 662 663 // TODO: Under what circumstances can we create nodes? Constant folding? 664 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 665 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 666 SelectionDAG &DAG, unsigned Depth) const { 667 EVT VT = Op.getValueType(); 668 669 // Limit search depth. 670 if (Depth >= SelectionDAG::MaxRecursionDepth) 671 return SDValue(); 672 673 // Ignore UNDEFs. 674 if (Op.isUndef()) 675 return SDValue(); 676 677 // Not demanding any bits/elts from Op. 678 if (DemandedBits == 0 || DemandedElts == 0) 679 return DAG.getUNDEF(VT); 680 681 bool IsLE = DAG.getDataLayout().isLittleEndian(); 682 unsigned NumElts = DemandedElts.getBitWidth(); 683 unsigned BitWidth = DemandedBits.getBitWidth(); 684 KnownBits LHSKnown, RHSKnown; 685 switch (Op.getOpcode()) { 686 case ISD::BITCAST: { 687 if (VT.isScalableVector()) 688 return SDValue(); 689 690 SDValue Src = peekThroughBitcasts(Op.getOperand(0)); 691 EVT SrcVT = Src.getValueType(); 692 EVT DstVT = Op.getValueType(); 693 if (SrcVT == DstVT) 694 return Src; 695 696 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 697 unsigned NumDstEltBits = DstVT.getScalarSizeInBits(); 698 if (NumSrcEltBits == NumDstEltBits) 699 if (SDValue V = SimplifyMultipleUseDemandedBits( 700 Src, DemandedBits, DemandedElts, DAG, Depth + 1)) 701 return DAG.getBitcast(DstVT, V); 702 703 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) { 704 unsigned Scale = NumDstEltBits / NumSrcEltBits; 705 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 706 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 707 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 708 for (unsigned i = 0; i != Scale; ++i) { 709 unsigned EltOffset = IsLE ? i : (Scale - 1 - i); 710 unsigned BitOffset = EltOffset * NumSrcEltBits; 711 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset); 712 if (!Sub.isZero()) { 713 DemandedSrcBits |= Sub; 714 for (unsigned j = 0; j != NumElts; ++j) 715 if (DemandedElts[j]) 716 DemandedSrcElts.setBit((j * Scale) + i); 717 } 718 } 719 720 if (SDValue V = SimplifyMultipleUseDemandedBits( 721 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 722 return DAG.getBitcast(DstVT, V); 723 } 724 725 // TODO - bigendian once we have test coverage. 726 if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) { 727 unsigned Scale = NumSrcEltBits / NumDstEltBits; 728 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 729 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 730 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 731 for (unsigned i = 0; i != NumElts; ++i) 732 if (DemandedElts[i]) { 733 unsigned Offset = (i % Scale) * NumDstEltBits; 734 DemandedSrcBits.insertBits(DemandedBits, Offset); 735 DemandedSrcElts.setBit(i / Scale); 736 } 737 738 if (SDValue V = SimplifyMultipleUseDemandedBits( 739 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 740 return DAG.getBitcast(DstVT, V); 741 } 742 743 break; 744 } 745 case ISD::AND: { 746 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 747 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 748 749 // If all of the demanded bits are known 1 on one side, return the other. 750 // These bits cannot contribute to the result of the 'and' in this 751 // context. 752 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) 753 return Op.getOperand(0); 754 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One)) 755 return Op.getOperand(1); 756 break; 757 } 758 case ISD::OR: { 759 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 760 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 761 762 // If all of the demanded bits are known zero on one side, return the 763 // other. These bits cannot contribute to the result of the 'or' in this 764 // context. 765 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero)) 766 return Op.getOperand(0); 767 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero)) 768 return Op.getOperand(1); 769 break; 770 } 771 case ISD::XOR: { 772 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 773 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 774 775 // If all of the demanded bits are known zero on one side, return the 776 // other. 777 if (DemandedBits.isSubsetOf(RHSKnown.Zero)) 778 return Op.getOperand(0); 779 if (DemandedBits.isSubsetOf(LHSKnown.Zero)) 780 return Op.getOperand(1); 781 break; 782 } 783 case ISD::SHL: { 784 // If we are only demanding sign bits then we can use the shift source 785 // directly. 786 if (const APInt *MaxSA = 787 DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 788 SDValue Op0 = Op.getOperand(0); 789 unsigned ShAmt = MaxSA->getZExtValue(); 790 unsigned NumSignBits = 791 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 792 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero(); 793 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 794 return Op0; 795 } 796 break; 797 } 798 case ISD::SETCC: { 799 SDValue Op0 = Op.getOperand(0); 800 SDValue Op1 = Op.getOperand(1); 801 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 802 // If (1) we only need the sign-bit, (2) the setcc operands are the same 803 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 804 // -1, we may be able to bypass the setcc. 805 if (DemandedBits.isSignMask() && 806 Op0.getScalarValueSizeInBits() == BitWidth && 807 getBooleanContents(Op0.getValueType()) == 808 BooleanContent::ZeroOrNegativeOneBooleanContent) { 809 // If we're testing X < 0, then this compare isn't needed - just use X! 810 // FIXME: We're limiting to integer types here, but this should also work 811 // if we don't care about FP signed-zero. The use of SETLT with FP means 812 // that we don't care about NaNs. 813 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 814 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 815 return Op0; 816 } 817 break; 818 } 819 case ISD::SIGN_EXTEND_INREG: { 820 // If none of the extended bits are demanded, eliminate the sextinreg. 821 SDValue Op0 = Op.getOperand(0); 822 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 823 unsigned ExBits = ExVT.getScalarSizeInBits(); 824 if (DemandedBits.getActiveBits() <= ExBits && 825 shouldRemoveRedundantExtend(Op)) 826 return Op0; 827 // If the input is already sign extended, just drop the extension. 828 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 829 if (NumSignBits >= (BitWidth - ExBits + 1)) 830 return Op0; 831 break; 832 } 833 case ISD::ANY_EXTEND_VECTOR_INREG: 834 case ISD::SIGN_EXTEND_VECTOR_INREG: 835 case ISD::ZERO_EXTEND_VECTOR_INREG: { 836 if (VT.isScalableVector()) 837 return SDValue(); 838 839 // If we only want the lowest element and none of extended bits, then we can 840 // return the bitcasted source vector. 841 SDValue Src = Op.getOperand(0); 842 EVT SrcVT = Src.getValueType(); 843 EVT DstVT = Op.getValueType(); 844 if (IsLE && DemandedElts == 1 && 845 DstVT.getSizeInBits() == SrcVT.getSizeInBits() && 846 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) { 847 return DAG.getBitcast(DstVT, Src); 848 } 849 break; 850 } 851 case ISD::INSERT_VECTOR_ELT: { 852 if (VT.isScalableVector()) 853 return SDValue(); 854 855 // If we don't demand the inserted element, return the base vector. 856 SDValue Vec = Op.getOperand(0); 857 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 858 EVT VecVT = Vec.getValueType(); 859 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) && 860 !DemandedElts[CIdx->getZExtValue()]) 861 return Vec; 862 break; 863 } 864 case ISD::INSERT_SUBVECTOR: { 865 if (VT.isScalableVector()) 866 return SDValue(); 867 868 SDValue Vec = Op.getOperand(0); 869 SDValue Sub = Op.getOperand(1); 870 uint64_t Idx = Op.getConstantOperandVal(2); 871 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 872 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 873 // If we don't demand the inserted subvector, return the base vector. 874 if (DemandedSubElts == 0) 875 return Vec; 876 break; 877 } 878 case ISD::VECTOR_SHUFFLE: { 879 assert(!VT.isScalableVector()); 880 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 881 882 // If all the demanded elts are from one operand and are inline, 883 // then we can use the operand directly. 884 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true; 885 for (unsigned i = 0; i != NumElts; ++i) { 886 int M = ShuffleMask[i]; 887 if (M < 0 || !DemandedElts[i]) 888 continue; 889 AllUndef = false; 890 IdentityLHS &= (M == (int)i); 891 IdentityRHS &= ((M - NumElts) == i); 892 } 893 894 if (AllUndef) 895 return DAG.getUNDEF(Op.getValueType()); 896 if (IdentityLHS) 897 return Op.getOperand(0); 898 if (IdentityRHS) 899 return Op.getOperand(1); 900 break; 901 } 902 default: 903 // TODO: Probably okay to remove after audit; here to reduce change size 904 // in initial enablement patch for scalable vectors 905 if (VT.isScalableVector()) 906 return SDValue(); 907 908 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) 909 if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode( 910 Op, DemandedBits, DemandedElts, DAG, Depth)) 911 return V; 912 break; 913 } 914 return SDValue(); 915 } 916 917 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 918 SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG, 919 unsigned Depth) const { 920 EVT VT = Op.getValueType(); 921 // Since the number of lanes in a scalable vector is unknown at compile time, 922 // we track one bit which is implicitly broadcast to all lanes. This means 923 // that all lanes in a scalable vector are considered demanded. 924 APInt DemandedElts = VT.isFixedLengthVector() 925 ? APInt::getAllOnes(VT.getVectorNumElements()) 926 : APInt(1, 1); 927 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 928 Depth); 929 } 930 931 SDValue TargetLowering::SimplifyMultipleUseDemandedVectorElts( 932 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG, 933 unsigned Depth) const { 934 APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits()); 935 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 936 Depth); 937 } 938 939 // Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1). 940 // or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1). 941 static SDValue combineShiftToAVG(SDValue Op, SelectionDAG &DAG, 942 const TargetLowering &TLI, 943 const APInt &DemandedBits, 944 const APInt &DemandedElts, 945 unsigned Depth) { 946 assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) && 947 "SRL or SRA node is required here!"); 948 // Is the right shift using an immediate value of 1? 949 ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts); 950 if (!N1C || !N1C->isOne()) 951 return SDValue(); 952 953 // We are looking for an avgfloor 954 // add(ext, ext) 955 // or one of these as a avgceil 956 // add(add(ext, ext), 1) 957 // add(add(ext, 1), ext) 958 // add(ext, add(ext, 1)) 959 SDValue Add = Op.getOperand(0); 960 if (Add.getOpcode() != ISD::ADD) 961 return SDValue(); 962 963 SDValue ExtOpA = Add.getOperand(0); 964 SDValue ExtOpB = Add.getOperand(1); 965 SDValue Add2; 966 auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3, SDValue A) { 967 ConstantSDNode *ConstOp; 968 if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) && 969 ConstOp->isOne()) { 970 ExtOpA = Op1; 971 ExtOpB = Op3; 972 Add2 = A; 973 return true; 974 } 975 if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) && 976 ConstOp->isOne()) { 977 ExtOpA = Op1; 978 ExtOpB = Op2; 979 Add2 = A; 980 return true; 981 } 982 return false; 983 }; 984 bool IsCeil = 985 (ExtOpA.getOpcode() == ISD::ADD && 986 MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB, ExtOpA)) || 987 (ExtOpB.getOpcode() == ISD::ADD && 988 MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA, ExtOpB)); 989 990 // If the shift is signed (sra): 991 // - Needs >= 2 sign bit for both operands. 992 // - Needs >= 2 zero bits. 993 // If the shift is unsigned (srl): 994 // - Needs >= 1 zero bit for both operands. 995 // - Needs 1 demanded bit zero and >= 2 sign bits. 996 unsigned ShiftOpc = Op.getOpcode(); 997 bool IsSigned = false; 998 unsigned KnownBits; 999 unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth); 1000 unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth); 1001 unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1; 1002 unsigned NumZeroA = 1003 DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros(); 1004 unsigned NumZeroB = 1005 DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros(); 1006 unsigned NumZero = std::min(NumZeroA, NumZeroB); 1007 1008 switch (ShiftOpc) { 1009 default: 1010 llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG"); 1011 case ISD::SRA: { 1012 if (NumZero >= 2 && NumSigned < NumZero) { 1013 IsSigned = false; 1014 KnownBits = NumZero; 1015 break; 1016 } 1017 if (NumSigned >= 1) { 1018 IsSigned = true; 1019 KnownBits = NumSigned; 1020 break; 1021 } 1022 return SDValue(); 1023 } 1024 case ISD::SRL: { 1025 if (NumZero >= 1 && NumSigned < NumZero) { 1026 IsSigned = false; 1027 KnownBits = NumZero; 1028 break; 1029 } 1030 if (NumSigned >= 1 && DemandedBits.isSignBitClear()) { 1031 IsSigned = true; 1032 KnownBits = NumSigned; 1033 break; 1034 } 1035 return SDValue(); 1036 } 1037 } 1038 1039 unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU) 1040 : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU); 1041 1042 // Find the smallest power-2 type that is legal for this vector size and 1043 // operation, given the original type size and the number of known sign/zero 1044 // bits. 1045 EVT VT = Op.getValueType(); 1046 unsigned MinWidth = 1047 std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8); 1048 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), llvm::bit_ceil(MinWidth)); 1049 if (VT.isVector()) 1050 NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount()); 1051 if (!TLI.isOperationLegalOrCustom(AVGOpc, NVT)) { 1052 // If we could not transform, and (both) adds are nuw/nsw, we can use the 1053 // larger type size to do the transform. 1054 if (!TLI.isOperationLegalOrCustom(AVGOpc, VT)) 1055 return SDValue(); 1056 if (DAG.willNotOverflowAdd(IsSigned, Add.getOperand(0), 1057 Add.getOperand(1)) && 1058 (!Add2 || DAG.willNotOverflowAdd(IsSigned, Add2.getOperand(0), 1059 Add2.getOperand(1)))) 1060 NVT = VT; 1061 else 1062 return SDValue(); 1063 } 1064 1065 SDLoc DL(Op); 1066 SDValue ResultAVG = 1067 DAG.getNode(AVGOpc, DL, NVT, DAG.getExtOrTrunc(IsSigned, ExtOpA, DL, NVT), 1068 DAG.getExtOrTrunc(IsSigned, ExtOpB, DL, NVT)); 1069 return DAG.getExtOrTrunc(IsSigned, ResultAVG, DL, VT); 1070 } 1071 1072 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the 1073 /// result of Op are ever used downstream. If we can use this information to 1074 /// simplify Op, create a new simplified DAG node and return true, returning the 1075 /// original and new nodes in Old and New. Otherwise, analyze the expression and 1076 /// return a mask of Known bits for the expression (used to simplify the 1077 /// caller). The Known bits may only be accurate for those bits in the 1078 /// OriginalDemandedBits and OriginalDemandedElts. 1079 bool TargetLowering::SimplifyDemandedBits( 1080 SDValue Op, const APInt &OriginalDemandedBits, 1081 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 1082 unsigned Depth, bool AssumeSingleUse) const { 1083 unsigned BitWidth = OriginalDemandedBits.getBitWidth(); 1084 assert(Op.getScalarValueSizeInBits() == BitWidth && 1085 "Mask size mismatches value type size!"); 1086 1087 // Don't know anything. 1088 Known = KnownBits(BitWidth); 1089 1090 EVT VT = Op.getValueType(); 1091 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 1092 unsigned NumElts = OriginalDemandedElts.getBitWidth(); 1093 assert((!VT.isFixedLengthVector() || NumElts == VT.getVectorNumElements()) && 1094 "Unexpected vector size"); 1095 1096 APInt DemandedBits = OriginalDemandedBits; 1097 APInt DemandedElts = OriginalDemandedElts; 1098 SDLoc dl(Op); 1099 auto &DL = TLO.DAG.getDataLayout(); 1100 1101 // Undef operand. 1102 if (Op.isUndef()) 1103 return false; 1104 1105 // We can't simplify target constants. 1106 if (Op.getOpcode() == ISD::TargetConstant) 1107 return false; 1108 1109 if (Op.getOpcode() == ISD::Constant) { 1110 // We know all of the bits for a constant! 1111 Known = KnownBits::makeConstant(cast<ConstantSDNode>(Op)->getAPIntValue()); 1112 return false; 1113 } 1114 1115 if (Op.getOpcode() == ISD::ConstantFP) { 1116 // We know all of the bits for a floating point constant! 1117 Known = KnownBits::makeConstant( 1118 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()); 1119 return false; 1120 } 1121 1122 // Other users may use these bits. 1123 bool HasMultiUse = false; 1124 if (!AssumeSingleUse && !Op.getNode()->hasOneUse()) { 1125 if (Depth >= SelectionDAG::MaxRecursionDepth) { 1126 // Limit search depth. 1127 return false; 1128 } 1129 // Allow multiple uses, just set the DemandedBits/Elts to all bits. 1130 DemandedBits = APInt::getAllOnes(BitWidth); 1131 DemandedElts = APInt::getAllOnes(NumElts); 1132 HasMultiUse = true; 1133 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) { 1134 // Not demanding any bits/elts from Op. 1135 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1136 } else if (Depth >= SelectionDAG::MaxRecursionDepth) { 1137 // Limit search depth. 1138 return false; 1139 } 1140 1141 KnownBits Known2; 1142 switch (Op.getOpcode()) { 1143 case ISD::SCALAR_TO_VECTOR: { 1144 if (VT.isScalableVector()) 1145 return false; 1146 if (!DemandedElts[0]) 1147 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1148 1149 KnownBits SrcKnown; 1150 SDValue Src = Op.getOperand(0); 1151 unsigned SrcBitWidth = Src.getScalarValueSizeInBits(); 1152 APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth); 1153 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1)) 1154 return true; 1155 1156 // Upper elements are undef, so only get the knownbits if we just demand 1157 // the bottom element. 1158 if (DemandedElts == 1) 1159 Known = SrcKnown.anyextOrTrunc(BitWidth); 1160 break; 1161 } 1162 case ISD::BUILD_VECTOR: 1163 // Collect the known bits that are shared by every demanded element. 1164 // TODO: Call SimplifyDemandedBits for non-constant demanded elements. 1165 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1166 return false; // Don't fall through, will infinitely loop. 1167 case ISD::SPLAT_VECTOR: { 1168 SDValue Scl = Op.getOperand(0); 1169 APInt DemandedSclBits = DemandedBits.zextOrTrunc(Scl.getValueSizeInBits()); 1170 KnownBits KnownScl; 1171 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1)) 1172 return true; 1173 1174 // Implicitly truncate the bits to match the official semantics of 1175 // SPLAT_VECTOR. 1176 Known = KnownScl.trunc(BitWidth); 1177 break; 1178 } 1179 case ISD::LOAD: { 1180 auto *LD = cast<LoadSDNode>(Op); 1181 if (getTargetConstantFromLoad(LD)) { 1182 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1183 return false; // Don't fall through, will infinitely loop. 1184 } 1185 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 1186 // If this is a ZEXTLoad and we are looking at the loaded value. 1187 EVT MemVT = LD->getMemoryVT(); 1188 unsigned MemBits = MemVT.getScalarSizeInBits(); 1189 Known.Zero.setBitsFrom(MemBits); 1190 return false; // Don't fall through, will infinitely loop. 1191 } 1192 break; 1193 } 1194 case ISD::INSERT_VECTOR_ELT: { 1195 if (VT.isScalableVector()) 1196 return false; 1197 SDValue Vec = Op.getOperand(0); 1198 SDValue Scl = Op.getOperand(1); 1199 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 1200 EVT VecVT = Vec.getValueType(); 1201 1202 // If index isn't constant, assume we need all vector elements AND the 1203 // inserted element. 1204 APInt DemandedVecElts(DemandedElts); 1205 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) { 1206 unsigned Idx = CIdx->getZExtValue(); 1207 DemandedVecElts.clearBit(Idx); 1208 1209 // Inserted element is not required. 1210 if (!DemandedElts[Idx]) 1211 return TLO.CombineTo(Op, Vec); 1212 } 1213 1214 KnownBits KnownScl; 1215 unsigned NumSclBits = Scl.getScalarValueSizeInBits(); 1216 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits); 1217 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1)) 1218 return true; 1219 1220 Known = KnownScl.anyextOrTrunc(BitWidth); 1221 1222 KnownBits KnownVec; 1223 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO, 1224 Depth + 1)) 1225 return true; 1226 1227 if (!!DemandedVecElts) 1228 Known = Known.intersectWith(KnownVec); 1229 1230 return false; 1231 } 1232 case ISD::INSERT_SUBVECTOR: { 1233 if (VT.isScalableVector()) 1234 return false; 1235 // Demand any elements from the subvector and the remainder from the src its 1236 // inserted into. 1237 SDValue Src = Op.getOperand(0); 1238 SDValue Sub = Op.getOperand(1); 1239 uint64_t Idx = Op.getConstantOperandVal(2); 1240 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 1241 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 1242 APInt DemandedSrcElts = DemandedElts; 1243 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 1244 1245 KnownBits KnownSub, KnownSrc; 1246 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO, 1247 Depth + 1)) 1248 return true; 1249 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO, 1250 Depth + 1)) 1251 return true; 1252 1253 Known.Zero.setAllBits(); 1254 Known.One.setAllBits(); 1255 if (!!DemandedSubElts) 1256 Known = Known.intersectWith(KnownSub); 1257 if (!!DemandedSrcElts) 1258 Known = Known.intersectWith(KnownSrc); 1259 1260 // Attempt to avoid multi-use src if we don't need anything from it. 1261 if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() || 1262 !DemandedSrcElts.isAllOnes()) { 1263 SDValue NewSub = SimplifyMultipleUseDemandedBits( 1264 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1); 1265 SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1266 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1267 if (NewSub || NewSrc) { 1268 NewSub = NewSub ? NewSub : Sub; 1269 NewSrc = NewSrc ? NewSrc : Src; 1270 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub, 1271 Op.getOperand(2)); 1272 return TLO.CombineTo(Op, NewOp); 1273 } 1274 } 1275 break; 1276 } 1277 case ISD::EXTRACT_SUBVECTOR: { 1278 if (VT.isScalableVector()) 1279 return false; 1280 // Offset the demanded elts by the subvector index. 1281 SDValue Src = Op.getOperand(0); 1282 if (Src.getValueType().isScalableVector()) 1283 break; 1284 uint64_t Idx = Op.getConstantOperandVal(1); 1285 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 1286 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 1287 1288 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO, 1289 Depth + 1)) 1290 return true; 1291 1292 // Attempt to avoid multi-use src if we don't need anything from it. 1293 if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 1294 SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 1295 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1296 if (DemandedSrc) { 1297 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, 1298 Op.getOperand(1)); 1299 return TLO.CombineTo(Op, NewOp); 1300 } 1301 } 1302 break; 1303 } 1304 case ISD::CONCAT_VECTORS: { 1305 if (VT.isScalableVector()) 1306 return false; 1307 Known.Zero.setAllBits(); 1308 Known.One.setAllBits(); 1309 EVT SubVT = Op.getOperand(0).getValueType(); 1310 unsigned NumSubVecs = Op.getNumOperands(); 1311 unsigned NumSubElts = SubVT.getVectorNumElements(); 1312 for (unsigned i = 0; i != NumSubVecs; ++i) { 1313 APInt DemandedSubElts = 1314 DemandedElts.extractBits(NumSubElts, i * NumSubElts); 1315 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts, 1316 Known2, TLO, Depth + 1)) 1317 return true; 1318 // Known bits are shared by every demanded subvector element. 1319 if (!!DemandedSubElts) 1320 Known = Known.intersectWith(Known2); 1321 } 1322 break; 1323 } 1324 case ISD::VECTOR_SHUFFLE: { 1325 assert(!VT.isScalableVector()); 1326 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 1327 1328 // Collect demanded elements from shuffle operands.. 1329 APInt DemandedLHS, DemandedRHS; 1330 if (!getShuffleDemandedElts(NumElts, ShuffleMask, DemandedElts, DemandedLHS, 1331 DemandedRHS)) 1332 break; 1333 1334 if (!!DemandedLHS || !!DemandedRHS) { 1335 SDValue Op0 = Op.getOperand(0); 1336 SDValue Op1 = Op.getOperand(1); 1337 1338 Known.Zero.setAllBits(); 1339 Known.One.setAllBits(); 1340 if (!!DemandedLHS) { 1341 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO, 1342 Depth + 1)) 1343 return true; 1344 Known = Known.intersectWith(Known2); 1345 } 1346 if (!!DemandedRHS) { 1347 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO, 1348 Depth + 1)) 1349 return true; 1350 Known = Known.intersectWith(Known2); 1351 } 1352 1353 // Attempt to avoid multi-use ops if we don't need anything from them. 1354 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1355 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1); 1356 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1357 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1); 1358 if (DemandedOp0 || DemandedOp1) { 1359 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1360 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1361 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask); 1362 return TLO.CombineTo(Op, NewOp); 1363 } 1364 } 1365 break; 1366 } 1367 case ISD::AND: { 1368 SDValue Op0 = Op.getOperand(0); 1369 SDValue Op1 = Op.getOperand(1); 1370 1371 // If the RHS is a constant, check to see if the LHS would be zero without 1372 // using the bits from the RHS. Below, we use knowledge about the RHS to 1373 // simplify the LHS, here we're using information from the LHS to simplify 1374 // the RHS. 1375 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) { 1376 // Do not increment Depth here; that can cause an infinite loop. 1377 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth); 1378 // If the LHS already has zeros where RHSC does, this 'and' is dead. 1379 if ((LHSKnown.Zero & DemandedBits) == 1380 (~RHSC->getAPIntValue() & DemandedBits)) 1381 return TLO.CombineTo(Op, Op0); 1382 1383 // If any of the set bits in the RHS are known zero on the LHS, shrink 1384 // the constant. 1385 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits, 1386 DemandedElts, TLO)) 1387 return true; 1388 1389 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its 1390 // constant, but if this 'and' is only clearing bits that were just set by 1391 // the xor, then this 'and' can be eliminated by shrinking the mask of 1392 // the xor. For example, for a 32-bit X: 1393 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1 1394 if (isBitwiseNot(Op0) && Op0.hasOneUse() && 1395 LHSKnown.One == ~RHSC->getAPIntValue()) { 1396 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1); 1397 return TLO.CombineTo(Op, Xor); 1398 } 1399 } 1400 1401 // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I) 1402 // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits). 1403 if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR && !VT.isScalableVector() && 1404 (Op0.getOperand(0).isUndef() || 1405 ISD::isBuildVectorOfConstantSDNodes(Op0.getOperand(0).getNode())) && 1406 Op0->hasOneUse()) { 1407 unsigned NumSubElts = 1408 Op0.getOperand(1).getValueType().getVectorNumElements(); 1409 unsigned SubIdx = Op0.getConstantOperandVal(2); 1410 APInt DemandedSub = 1411 APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts); 1412 KnownBits KnownSubMask = 1413 TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1); 1414 if (DemandedBits.isSubsetOf(KnownSubMask.One)) { 1415 SDValue NewAnd = 1416 TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1); 1417 SDValue NewInsert = 1418 TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd, 1419 Op0.getOperand(1), Op0.getOperand(2)); 1420 return TLO.CombineTo(Op, NewInsert); 1421 } 1422 } 1423 1424 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1425 Depth + 1)) 1426 return true; 1427 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1428 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts, 1429 Known2, TLO, Depth + 1)) 1430 return true; 1431 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1432 1433 // If all of the demanded bits are known one on one side, return the other. 1434 // These bits cannot contribute to the result of the 'and'. 1435 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) 1436 return TLO.CombineTo(Op, Op0); 1437 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One)) 1438 return TLO.CombineTo(Op, Op1); 1439 // If all of the demanded bits in the inputs are known zeros, return zero. 1440 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1441 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT)); 1442 // If the RHS is a constant, see if we can simplify it. 1443 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts, 1444 TLO)) 1445 return true; 1446 // If the operation can be done in a smaller type, do so. 1447 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1448 return true; 1449 1450 // Attempt to avoid multi-use ops if we don't need anything from them. 1451 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1452 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1453 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1454 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1455 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1456 if (DemandedOp0 || DemandedOp1) { 1457 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1458 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1459 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1460 return TLO.CombineTo(Op, NewOp); 1461 } 1462 } 1463 1464 Known &= Known2; 1465 break; 1466 } 1467 case ISD::OR: { 1468 SDValue Op0 = Op.getOperand(0); 1469 SDValue Op1 = Op.getOperand(1); 1470 SDNodeFlags Flags = Op.getNode()->getFlags(); 1471 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1472 Depth + 1)) { 1473 if (Flags.hasDisjoint()) { 1474 Flags.setDisjoint(false); 1475 Op->setFlags(Flags); 1476 } 1477 return true; 1478 } 1479 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1480 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts, 1481 Known2, TLO, Depth + 1)) { 1482 if (Flags.hasDisjoint()) { 1483 Flags.setDisjoint(false); 1484 Op->setFlags(Flags); 1485 } 1486 return true; 1487 } 1488 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1489 1490 // If all of the demanded bits are known zero on one side, return the other. 1491 // These bits cannot contribute to the result of the 'or'. 1492 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) 1493 return TLO.CombineTo(Op, Op0); 1494 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero)) 1495 return TLO.CombineTo(Op, Op1); 1496 // If the RHS is a constant, see if we can simplify it. 1497 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1498 return true; 1499 // If the operation can be done in a smaller type, do so. 1500 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1501 return true; 1502 1503 // Attempt to avoid multi-use ops if we don't need anything from them. 1504 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1505 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1506 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1507 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1508 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1509 if (DemandedOp0 || DemandedOp1) { 1510 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1511 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1512 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1513 return TLO.CombineTo(Op, NewOp); 1514 } 1515 } 1516 1517 // (or (and X, C1), (and (or X, Y), C2)) -> (or (and X, C1|C2), (and Y, C2)) 1518 // TODO: Use SimplifyMultipleUseDemandedBits to peek through masks. 1519 if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::AND && 1520 Op0->hasOneUse() && Op1->hasOneUse()) { 1521 // Attempt to match all commutations - m_c_Or would've been useful! 1522 for (int I = 0; I != 2; ++I) { 1523 SDValue X = Op.getOperand(I).getOperand(0); 1524 SDValue C1 = Op.getOperand(I).getOperand(1); 1525 SDValue Alt = Op.getOperand(1 - I).getOperand(0); 1526 SDValue C2 = Op.getOperand(1 - I).getOperand(1); 1527 if (Alt.getOpcode() == ISD::OR) { 1528 for (int J = 0; J != 2; ++J) { 1529 if (X == Alt.getOperand(J)) { 1530 SDValue Y = Alt.getOperand(1 - J); 1531 if (SDValue C12 = TLO.DAG.FoldConstantArithmetic(ISD::OR, dl, VT, 1532 {C1, C2})) { 1533 SDValue MaskX = TLO.DAG.getNode(ISD::AND, dl, VT, X, C12); 1534 SDValue MaskY = TLO.DAG.getNode(ISD::AND, dl, VT, Y, C2); 1535 return TLO.CombineTo( 1536 Op, TLO.DAG.getNode(ISD::OR, dl, VT, MaskX, MaskY)); 1537 } 1538 } 1539 } 1540 } 1541 } 1542 } 1543 1544 Known |= Known2; 1545 break; 1546 } 1547 case ISD::XOR: { 1548 SDValue Op0 = Op.getOperand(0); 1549 SDValue Op1 = Op.getOperand(1); 1550 1551 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1552 Depth + 1)) 1553 return true; 1554 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1555 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO, 1556 Depth + 1)) 1557 return true; 1558 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1559 1560 // If all of the demanded bits are known zero on one side, return the other. 1561 // These bits cannot contribute to the result of the 'xor'. 1562 if (DemandedBits.isSubsetOf(Known.Zero)) 1563 return TLO.CombineTo(Op, Op0); 1564 if (DemandedBits.isSubsetOf(Known2.Zero)) 1565 return TLO.CombineTo(Op, Op1); 1566 // If the operation can be done in a smaller type, do so. 1567 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1568 return true; 1569 1570 // If all of the unknown bits are known to be zero on one side or the other 1571 // turn this into an *inclusive* or. 1572 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 1573 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1574 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1)); 1575 1576 ConstantSDNode *C = isConstOrConstSplat(Op1, DemandedElts); 1577 if (C) { 1578 // If one side is a constant, and all of the set bits in the constant are 1579 // also known set on the other side, turn this into an AND, as we know 1580 // the bits will be cleared. 1581 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 1582 // NB: it is okay if more bits are known than are requested 1583 if (C->getAPIntValue() == Known2.One) { 1584 SDValue ANDC = 1585 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT); 1586 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC)); 1587 } 1588 1589 // If the RHS is a constant, see if we can change it. Don't alter a -1 1590 // constant because that's a 'not' op, and that is better for combining 1591 // and codegen. 1592 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) { 1593 // We're flipping all demanded bits. Flip the undemanded bits too. 1594 SDValue New = TLO.DAG.getNOT(dl, Op0, VT); 1595 return TLO.CombineTo(Op, New); 1596 } 1597 1598 unsigned Op0Opcode = Op0.getOpcode(); 1599 if ((Op0Opcode == ISD::SRL || Op0Opcode == ISD::SHL) && Op0.hasOneUse()) { 1600 if (ConstantSDNode *ShiftC = 1601 isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) { 1602 // Don't crash on an oversized shift. We can not guarantee that a 1603 // bogus shift has been simplified to undef. 1604 if (ShiftC->getAPIntValue().ult(BitWidth)) { 1605 uint64_t ShiftAmt = ShiftC->getZExtValue(); 1606 APInt Ones = APInt::getAllOnes(BitWidth); 1607 Ones = Op0Opcode == ISD::SHL ? Ones.shl(ShiftAmt) 1608 : Ones.lshr(ShiftAmt); 1609 const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo(); 1610 if ((DemandedBits & C->getAPIntValue()) == (DemandedBits & Ones) && 1611 TLI.isDesirableToCommuteXorWithShift(Op.getNode())) { 1612 // If the xor constant is a demanded mask, do a 'not' before the 1613 // shift: 1614 // xor (X << ShiftC), XorC --> (not X) << ShiftC 1615 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC 1616 SDValue Not = TLO.DAG.getNOT(dl, Op0.getOperand(0), VT); 1617 return TLO.CombineTo(Op, TLO.DAG.getNode(Op0Opcode, dl, VT, Not, 1618 Op0.getOperand(1))); 1619 } 1620 } 1621 } 1622 } 1623 } 1624 1625 // If we can't turn this into a 'not', try to shrink the constant. 1626 if (!C || !C->isAllOnes()) 1627 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1628 return true; 1629 1630 // Attempt to avoid multi-use ops if we don't need anything from them. 1631 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1632 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1633 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1634 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1635 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1636 if (DemandedOp0 || DemandedOp1) { 1637 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1638 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1639 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1640 return TLO.CombineTo(Op, NewOp); 1641 } 1642 } 1643 1644 Known ^= Known2; 1645 break; 1646 } 1647 case ISD::SELECT: 1648 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts, 1649 Known, TLO, Depth + 1)) 1650 return true; 1651 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts, 1652 Known2, TLO, Depth + 1)) 1653 return true; 1654 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1655 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1656 1657 // If the operands are constants, see if we can simplify them. 1658 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1659 return true; 1660 1661 // Only known if known in both the LHS and RHS. 1662 Known = Known.intersectWith(Known2); 1663 break; 1664 case ISD::VSELECT: 1665 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts, 1666 Known, TLO, Depth + 1)) 1667 return true; 1668 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts, 1669 Known2, TLO, Depth + 1)) 1670 return true; 1671 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1672 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1673 1674 // Only known if known in both the LHS and RHS. 1675 Known = Known.intersectWith(Known2); 1676 break; 1677 case ISD::SELECT_CC: 1678 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, DemandedElts, 1679 Known, TLO, Depth + 1)) 1680 return true; 1681 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts, 1682 Known2, TLO, Depth + 1)) 1683 return true; 1684 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1685 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1686 1687 // If the operands are constants, see if we can simplify them. 1688 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1689 return true; 1690 1691 // Only known if known in both the LHS and RHS. 1692 Known = Known.intersectWith(Known2); 1693 break; 1694 case ISD::SETCC: { 1695 SDValue Op0 = Op.getOperand(0); 1696 SDValue Op1 = Op.getOperand(1); 1697 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 1698 // If (1) we only need the sign-bit, (2) the setcc operands are the same 1699 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 1700 // -1, we may be able to bypass the setcc. 1701 if (DemandedBits.isSignMask() && 1702 Op0.getScalarValueSizeInBits() == BitWidth && 1703 getBooleanContents(Op0.getValueType()) == 1704 BooleanContent::ZeroOrNegativeOneBooleanContent) { 1705 // If we're testing X < 0, then this compare isn't needed - just use X! 1706 // FIXME: We're limiting to integer types here, but this should also work 1707 // if we don't care about FP signed-zero. The use of SETLT with FP means 1708 // that we don't care about NaNs. 1709 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 1710 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 1711 return TLO.CombineTo(Op, Op0); 1712 1713 // TODO: Should we check for other forms of sign-bit comparisons? 1714 // Examples: X <= -1, X >= 0 1715 } 1716 if (getBooleanContents(Op0.getValueType()) == 1717 TargetLowering::ZeroOrOneBooleanContent && 1718 BitWidth > 1) 1719 Known.Zero.setBitsFrom(1); 1720 break; 1721 } 1722 case ISD::SHL: { 1723 SDValue Op0 = Op.getOperand(0); 1724 SDValue Op1 = Op.getOperand(1); 1725 EVT ShiftVT = Op1.getValueType(); 1726 1727 if (const APInt *SA = 1728 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1729 unsigned ShAmt = SA->getZExtValue(); 1730 if (ShAmt == 0) 1731 return TLO.CombineTo(Op, Op0); 1732 1733 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 1734 // single shift. We can do this if the bottom bits (which are shifted 1735 // out) are never demanded. 1736 // TODO - support non-uniform vector amounts. 1737 if (Op0.getOpcode() == ISD::SRL) { 1738 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) { 1739 if (const APInt *SA2 = 1740 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1741 unsigned C1 = SA2->getZExtValue(); 1742 unsigned Opc = ISD::SHL; 1743 int Diff = ShAmt - C1; 1744 if (Diff < 0) { 1745 Diff = -Diff; 1746 Opc = ISD::SRL; 1747 } 1748 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1749 return TLO.CombineTo( 1750 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1751 } 1752 } 1753 } 1754 1755 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 1756 // are not demanded. This will likely allow the anyext to be folded away. 1757 // TODO - support non-uniform vector amounts. 1758 if (Op0.getOpcode() == ISD::ANY_EXTEND) { 1759 SDValue InnerOp = Op0.getOperand(0); 1760 EVT InnerVT = InnerOp.getValueType(); 1761 unsigned InnerBits = InnerVT.getScalarSizeInBits(); 1762 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits && 1763 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 1764 SDValue NarrowShl = TLO.DAG.getNode( 1765 ISD::SHL, dl, InnerVT, InnerOp, 1766 TLO.DAG.getShiftAmountConstant(ShAmt, InnerVT, dl)); 1767 return TLO.CombineTo( 1768 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl)); 1769 } 1770 1771 // Repeat the SHL optimization above in cases where an extension 1772 // intervenes: (shl (anyext (shr x, c1)), c2) to 1773 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 1774 // aren't demanded (as above) and that the shifted upper c1 bits of 1775 // x aren't demanded. 1776 // TODO - support non-uniform vector amounts. 1777 if (InnerOp.getOpcode() == ISD::SRL && Op0.hasOneUse() && 1778 InnerOp.hasOneUse()) { 1779 if (const APInt *SA2 = 1780 TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) { 1781 unsigned InnerShAmt = SA2->getZExtValue(); 1782 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits && 1783 DemandedBits.getActiveBits() <= 1784 (InnerBits - InnerShAmt + ShAmt) && 1785 DemandedBits.countr_zero() >= ShAmt) { 1786 SDValue NewSA = 1787 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT); 1788 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 1789 InnerOp.getOperand(0)); 1790 return TLO.CombineTo( 1791 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA)); 1792 } 1793 } 1794 } 1795 } 1796 1797 APInt InDemandedMask = DemandedBits.lshr(ShAmt); 1798 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1799 Depth + 1)) { 1800 SDNodeFlags Flags = Op.getNode()->getFlags(); 1801 if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) { 1802 // Disable the nsw and nuw flags. We can no longer guarantee that we 1803 // won't wrap after simplification. 1804 Flags.setNoSignedWrap(false); 1805 Flags.setNoUnsignedWrap(false); 1806 Op->setFlags(Flags); 1807 } 1808 return true; 1809 } 1810 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1811 Known.Zero <<= ShAmt; 1812 Known.One <<= ShAmt; 1813 // low bits known zero. 1814 Known.Zero.setLowBits(ShAmt); 1815 1816 // Attempt to avoid multi-use ops if we don't need anything from them. 1817 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) { 1818 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1819 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1820 if (DemandedOp0) { 1821 SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1); 1822 return TLO.CombineTo(Op, NewOp); 1823 } 1824 } 1825 1826 // Try shrinking the operation as long as the shift amount will still be 1827 // in range. 1828 if ((ShAmt < DemandedBits.getActiveBits()) && 1829 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1830 return true; 1831 1832 // Narrow shift to lower half - similar to ShrinkDemandedOp. 1833 // (shl i64:x, K) -> (i64 zero_extend (shl (i32 (trunc i64:x)), K)) 1834 // Only do this if we demand the upper half so the knownbits are correct. 1835 unsigned HalfWidth = BitWidth / 2; 1836 if ((BitWidth % 2) == 0 && !VT.isVector() && ShAmt < HalfWidth && 1837 DemandedBits.countLeadingOnes() >= HalfWidth) { 1838 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), HalfWidth); 1839 if (isNarrowingProfitable(VT, HalfVT) && 1840 isTypeDesirableForOp(ISD::SHL, HalfVT) && 1841 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) && 1842 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, HalfVT))) { 1843 // If we're demanding the upper bits at all, we must ensure 1844 // that the upper bits of the shift result are known to be zero, 1845 // which is equivalent to the narrow shift being NUW. 1846 if (bool IsNUW = (Known.countMinLeadingZeros() >= HalfWidth)) { 1847 bool IsNSW = Known.countMinSignBits() > HalfWidth; 1848 SDNodeFlags Flags; 1849 Flags.setNoSignedWrap(IsNSW); 1850 Flags.setNoUnsignedWrap(IsNUW); 1851 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0); 1852 SDValue NewShiftAmt = TLO.DAG.getShiftAmountConstant( 1853 ShAmt, HalfVT, dl, TLO.LegalTypes()); 1854 SDValue NewShift = TLO.DAG.getNode(ISD::SHL, dl, HalfVT, NewOp, 1855 NewShiftAmt, Flags); 1856 SDValue NewExt = 1857 TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift); 1858 return TLO.CombineTo(Op, NewExt); 1859 } 1860 } 1861 } 1862 } else { 1863 // This is a variable shift, so we can't shift the demand mask by a known 1864 // amount. But if we are not demanding high bits, then we are not 1865 // demanding those bits from the pre-shifted operand either. 1866 if (unsigned CTLZ = DemandedBits.countl_zero()) { 1867 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ)); 1868 if (SimplifyDemandedBits(Op0, DemandedFromOp, DemandedElts, Known, TLO, 1869 Depth + 1)) { 1870 SDNodeFlags Flags = Op.getNode()->getFlags(); 1871 if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) { 1872 // Disable the nsw and nuw flags. We can no longer guarantee that we 1873 // won't wrap after simplification. 1874 Flags.setNoSignedWrap(false); 1875 Flags.setNoUnsignedWrap(false); 1876 Op->setFlags(Flags); 1877 } 1878 return true; 1879 } 1880 Known.resetAll(); 1881 } 1882 } 1883 1884 // If we are only demanding sign bits then we can use the shift source 1885 // directly. 1886 if (const APInt *MaxSA = 1887 TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 1888 unsigned ShAmt = MaxSA->getZExtValue(); 1889 unsigned NumSignBits = 1890 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1891 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero(); 1892 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 1893 return TLO.CombineTo(Op, Op0); 1894 } 1895 break; 1896 } 1897 case ISD::SRL: { 1898 SDValue Op0 = Op.getOperand(0); 1899 SDValue Op1 = Op.getOperand(1); 1900 EVT ShiftVT = Op1.getValueType(); 1901 1902 // Try to match AVG patterns. 1903 if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits, 1904 DemandedElts, Depth + 1)) 1905 return TLO.CombineTo(Op, AVG); 1906 1907 if (const APInt *SA = 1908 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1909 unsigned ShAmt = SA->getZExtValue(); 1910 if (ShAmt == 0) 1911 return TLO.CombineTo(Op, Op0); 1912 1913 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 1914 // single shift. We can do this if the top bits (which are shifted out) 1915 // are never demanded. 1916 // TODO - support non-uniform vector amounts. 1917 if (Op0.getOpcode() == ISD::SHL) { 1918 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) { 1919 if (const APInt *SA2 = 1920 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1921 unsigned C1 = SA2->getZExtValue(); 1922 unsigned Opc = ISD::SRL; 1923 int Diff = ShAmt - C1; 1924 if (Diff < 0) { 1925 Diff = -Diff; 1926 Opc = ISD::SHL; 1927 } 1928 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1929 return TLO.CombineTo( 1930 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1931 } 1932 } 1933 } 1934 1935 APInt InDemandedMask = (DemandedBits << ShAmt); 1936 1937 // If the shift is exact, then it does demand the low bits (and knows that 1938 // they are zero). 1939 if (Op->getFlags().hasExact()) 1940 InDemandedMask.setLowBits(ShAmt); 1941 1942 // Narrow shift to lower half - similar to ShrinkDemandedOp. 1943 // (srl i64:x, K) -> (i64 zero_extend (srl (i32 (trunc i64:x)), K)) 1944 if ((BitWidth % 2) == 0 && !VT.isVector()) { 1945 APInt HiBits = APInt::getHighBitsSet(BitWidth, BitWidth / 2); 1946 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), BitWidth / 2); 1947 if (isNarrowingProfitable(VT, HalfVT) && 1948 isTypeDesirableForOp(ISD::SRL, HalfVT) && 1949 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) && 1950 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, HalfVT)) && 1951 ((InDemandedMask.countLeadingZeros() >= (BitWidth / 2)) || 1952 TLO.DAG.MaskedValueIsZero(Op0, HiBits))) { 1953 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0); 1954 SDValue NewShiftAmt = TLO.DAG.getShiftAmountConstant( 1955 ShAmt, HalfVT, dl, TLO.LegalTypes()); 1956 SDValue NewShift = 1957 TLO.DAG.getNode(ISD::SRL, dl, HalfVT, NewOp, NewShiftAmt); 1958 return TLO.CombineTo( 1959 Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift)); 1960 } 1961 } 1962 1963 // Compute the new bits that are at the top now. 1964 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1965 Depth + 1)) 1966 return true; 1967 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1968 Known.Zero.lshrInPlace(ShAmt); 1969 Known.One.lshrInPlace(ShAmt); 1970 // High bits known zero. 1971 Known.Zero.setHighBits(ShAmt); 1972 1973 // Attempt to avoid multi-use ops if we don't need anything from them. 1974 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) { 1975 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1976 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1977 if (DemandedOp0) { 1978 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, DemandedOp0, Op1); 1979 return TLO.CombineTo(Op, NewOp); 1980 } 1981 } 1982 } else { 1983 // Use generic knownbits computation as it has support for non-uniform 1984 // shift amounts. 1985 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1986 } 1987 break; 1988 } 1989 case ISD::SRA: { 1990 SDValue Op0 = Op.getOperand(0); 1991 SDValue Op1 = Op.getOperand(1); 1992 EVT ShiftVT = Op1.getValueType(); 1993 1994 // If we only want bits that already match the signbit then we don't need 1995 // to shift. 1996 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countr_zero(); 1997 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >= 1998 NumHiDemandedBits) 1999 return TLO.CombineTo(Op, Op0); 2000 2001 // If this is an arithmetic shift right and only the low-bit is set, we can 2002 // always convert this into a logical shr, even if the shift amount is 2003 // variable. The low bit of the shift cannot be an input sign bit unless 2004 // the shift amount is >= the size of the datatype, which is undefined. 2005 if (DemandedBits.isOne()) 2006 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 2007 2008 // Try to match AVG patterns. 2009 if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits, 2010 DemandedElts, Depth + 1)) 2011 return TLO.CombineTo(Op, AVG); 2012 2013 if (const APInt *SA = 2014 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 2015 unsigned ShAmt = SA->getZExtValue(); 2016 if (ShAmt == 0) 2017 return TLO.CombineTo(Op, Op0); 2018 2019 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target 2020 // supports sext_inreg. 2021 if (Op0.getOpcode() == ISD::SHL) { 2022 if (const APInt *InnerSA = 2023 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 2024 unsigned LowBits = BitWidth - ShAmt; 2025 EVT ExtVT = EVT::getIntegerVT(*TLO.DAG.getContext(), LowBits); 2026 if (VT.isVector()) 2027 ExtVT = EVT::getVectorVT(*TLO.DAG.getContext(), ExtVT, 2028 VT.getVectorElementCount()); 2029 2030 if (*InnerSA == ShAmt) { 2031 if (!TLO.LegalOperations() || 2032 getOperationAction(ISD::SIGN_EXTEND_INREG, ExtVT) == Legal) 2033 return TLO.CombineTo( 2034 Op, TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, 2035 Op0.getOperand(0), 2036 TLO.DAG.getValueType(ExtVT))); 2037 2038 // Even if we can't convert to sext_inreg, we might be able to 2039 // remove this shift pair if the input is already sign extended. 2040 unsigned NumSignBits = 2041 TLO.DAG.ComputeNumSignBits(Op0.getOperand(0), DemandedElts); 2042 if (NumSignBits > ShAmt) 2043 return TLO.CombineTo(Op, Op0.getOperand(0)); 2044 } 2045 } 2046 } 2047 2048 APInt InDemandedMask = (DemandedBits << ShAmt); 2049 2050 // If the shift is exact, then it does demand the low bits (and knows that 2051 // they are zero). 2052 if (Op->getFlags().hasExact()) 2053 InDemandedMask.setLowBits(ShAmt); 2054 2055 // If any of the demanded bits are produced by the sign extension, we also 2056 // demand the input sign bit. 2057 if (DemandedBits.countl_zero() < ShAmt) 2058 InDemandedMask.setSignBit(); 2059 2060 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 2061 Depth + 1)) 2062 return true; 2063 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2064 Known.Zero.lshrInPlace(ShAmt); 2065 Known.One.lshrInPlace(ShAmt); 2066 2067 // If the input sign bit is known to be zero, or if none of the top bits 2068 // are demanded, turn this into an unsigned shift right. 2069 if (Known.Zero[BitWidth - ShAmt - 1] || 2070 DemandedBits.countl_zero() >= ShAmt) { 2071 SDNodeFlags Flags; 2072 Flags.setExact(Op->getFlags().hasExact()); 2073 return TLO.CombineTo( 2074 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags)); 2075 } 2076 2077 int Log2 = DemandedBits.exactLogBase2(); 2078 if (Log2 >= 0) { 2079 // The bit must come from the sign. 2080 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT); 2081 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA)); 2082 } 2083 2084 if (Known.One[BitWidth - ShAmt - 1]) 2085 // New bits are known one. 2086 Known.One.setHighBits(ShAmt); 2087 2088 // Attempt to avoid multi-use ops if we don't need anything from them. 2089 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) { 2090 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2091 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 2092 if (DemandedOp0) { 2093 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1); 2094 return TLO.CombineTo(Op, NewOp); 2095 } 2096 } 2097 } 2098 break; 2099 } 2100 case ISD::FSHL: 2101 case ISD::FSHR: { 2102 SDValue Op0 = Op.getOperand(0); 2103 SDValue Op1 = Op.getOperand(1); 2104 SDValue Op2 = Op.getOperand(2); 2105 bool IsFSHL = (Op.getOpcode() == ISD::FSHL); 2106 2107 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) { 2108 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 2109 2110 // For fshl, 0-shift returns the 1st arg. 2111 // For fshr, 0-shift returns the 2nd arg. 2112 if (Amt == 0) { 2113 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts, 2114 Known, TLO, Depth + 1)) 2115 return true; 2116 break; 2117 } 2118 2119 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt)) 2120 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt) 2121 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt)); 2122 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt); 2123 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 2124 Depth + 1)) 2125 return true; 2126 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO, 2127 Depth + 1)) 2128 return true; 2129 2130 Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt)); 2131 Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt)); 2132 Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 2133 Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 2134 Known = Known.unionWith(Known2); 2135 2136 // Attempt to avoid multi-use ops if we don't need anything from them. 2137 if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() || 2138 !DemandedElts.isAllOnes()) { 2139 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2140 Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1); 2141 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 2142 Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1); 2143 if (DemandedOp0 || DemandedOp1) { 2144 DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0; 2145 DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1; 2146 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0, 2147 DemandedOp1, Op2); 2148 return TLO.CombineTo(Op, NewOp); 2149 } 2150 } 2151 } 2152 2153 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 2154 if (isPowerOf2_32(BitWidth)) { 2155 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1); 2156 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, 2157 Known2, TLO, Depth + 1)) 2158 return true; 2159 } 2160 break; 2161 } 2162 case ISD::ROTL: 2163 case ISD::ROTR: { 2164 SDValue Op0 = Op.getOperand(0); 2165 SDValue Op1 = Op.getOperand(1); 2166 bool IsROTL = (Op.getOpcode() == ISD::ROTL); 2167 2168 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 2169 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1)) 2170 return TLO.CombineTo(Op, Op0); 2171 2172 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) { 2173 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 2174 unsigned RevAmt = BitWidth - Amt; 2175 2176 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt)) 2177 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt) 2178 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt); 2179 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 2180 Depth + 1)) 2181 return true; 2182 2183 // rot*(x, 0) --> x 2184 if (Amt == 0) 2185 return TLO.CombineTo(Op, Op0); 2186 2187 // See if we don't demand either half of the rotated bits. 2188 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) && 2189 DemandedBits.countr_zero() >= (IsROTL ? Amt : RevAmt)) { 2190 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType()); 2191 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1)); 2192 } 2193 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) && 2194 DemandedBits.countl_zero() >= (IsROTL ? RevAmt : Amt)) { 2195 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType()); 2196 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 2197 } 2198 } 2199 2200 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 2201 if (isPowerOf2_32(BitWidth)) { 2202 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1); 2203 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO, 2204 Depth + 1)) 2205 return true; 2206 } 2207 break; 2208 } 2209 case ISD::SMIN: 2210 case ISD::SMAX: 2211 case ISD::UMIN: 2212 case ISD::UMAX: { 2213 unsigned Opc = Op.getOpcode(); 2214 SDValue Op0 = Op.getOperand(0); 2215 SDValue Op1 = Op.getOperand(1); 2216 2217 // If we're only demanding signbits, then we can simplify to OR/AND node. 2218 unsigned BitOp = 2219 (Opc == ISD::SMIN || Opc == ISD::UMAX) ? ISD::OR : ISD::AND; 2220 unsigned NumSignBits = 2221 std::min(TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1), 2222 TLO.DAG.ComputeNumSignBits(Op1, DemandedElts, Depth + 1)); 2223 unsigned NumDemandedUpperBits = BitWidth - DemandedBits.countr_zero(); 2224 if (NumSignBits >= NumDemandedUpperBits) 2225 return TLO.CombineTo(Op, TLO.DAG.getNode(BitOp, SDLoc(Op), VT, Op0, Op1)); 2226 2227 // Check if one arg is always less/greater than (or equal) to the other arg. 2228 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 2229 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 2230 switch (Opc) { 2231 case ISD::SMIN: 2232 if (std::optional<bool> IsSLE = KnownBits::sle(Known0, Known1)) 2233 return TLO.CombineTo(Op, *IsSLE ? Op0 : Op1); 2234 if (std::optional<bool> IsSLT = KnownBits::slt(Known0, Known1)) 2235 return TLO.CombineTo(Op, *IsSLT ? Op0 : Op1); 2236 Known = KnownBits::smin(Known0, Known1); 2237 break; 2238 case ISD::SMAX: 2239 if (std::optional<bool> IsSGE = KnownBits::sge(Known0, Known1)) 2240 return TLO.CombineTo(Op, *IsSGE ? Op0 : Op1); 2241 if (std::optional<bool> IsSGT = KnownBits::sgt(Known0, Known1)) 2242 return TLO.CombineTo(Op, *IsSGT ? Op0 : Op1); 2243 Known = KnownBits::smax(Known0, Known1); 2244 break; 2245 case ISD::UMIN: 2246 if (std::optional<bool> IsULE = KnownBits::ule(Known0, Known1)) 2247 return TLO.CombineTo(Op, *IsULE ? Op0 : Op1); 2248 if (std::optional<bool> IsULT = KnownBits::ult(Known0, Known1)) 2249 return TLO.CombineTo(Op, *IsULT ? Op0 : Op1); 2250 Known = KnownBits::umin(Known0, Known1); 2251 break; 2252 case ISD::UMAX: 2253 if (std::optional<bool> IsUGE = KnownBits::uge(Known0, Known1)) 2254 return TLO.CombineTo(Op, *IsUGE ? Op0 : Op1); 2255 if (std::optional<bool> IsUGT = KnownBits::ugt(Known0, Known1)) 2256 return TLO.CombineTo(Op, *IsUGT ? Op0 : Op1); 2257 Known = KnownBits::umax(Known0, Known1); 2258 break; 2259 } 2260 break; 2261 } 2262 case ISD::BITREVERSE: { 2263 SDValue Src = Op.getOperand(0); 2264 APInt DemandedSrcBits = DemandedBits.reverseBits(); 2265 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 2266 Depth + 1)) 2267 return true; 2268 Known.One = Known2.One.reverseBits(); 2269 Known.Zero = Known2.Zero.reverseBits(); 2270 break; 2271 } 2272 case ISD::BSWAP: { 2273 SDValue Src = Op.getOperand(0); 2274 2275 // If the only bits demanded come from one byte of the bswap result, 2276 // just shift the input byte into position to eliminate the bswap. 2277 unsigned NLZ = DemandedBits.countl_zero(); 2278 unsigned NTZ = DemandedBits.countr_zero(); 2279 2280 // Round NTZ down to the next byte. If we have 11 trailing zeros, then 2281 // we need all the bits down to bit 8. Likewise, round NLZ. If we 2282 // have 14 leading zeros, round to 8. 2283 NLZ = alignDown(NLZ, 8); 2284 NTZ = alignDown(NTZ, 8); 2285 // If we need exactly one byte, we can do this transformation. 2286 if (BitWidth - NLZ - NTZ == 8) { 2287 // Replace this with either a left or right shift to get the byte into 2288 // the right place. 2289 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL; 2290 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) { 2291 EVT ShiftAmtTy = getShiftAmountTy(VT, DL); 2292 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ; 2293 SDValue ShAmt = TLO.DAG.getConstant(ShiftAmount, dl, ShiftAmtTy); 2294 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt); 2295 return TLO.CombineTo(Op, NewOp); 2296 } 2297 } 2298 2299 APInt DemandedSrcBits = DemandedBits.byteSwap(); 2300 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 2301 Depth + 1)) 2302 return true; 2303 Known.One = Known2.One.byteSwap(); 2304 Known.Zero = Known2.Zero.byteSwap(); 2305 break; 2306 } 2307 case ISD::CTPOP: { 2308 // If only 1 bit is demanded, replace with PARITY as long as we're before 2309 // op legalization. 2310 // FIXME: Limit to scalars for now. 2311 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector()) 2312 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT, 2313 Op.getOperand(0))); 2314 2315 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2316 break; 2317 } 2318 case ISD::SIGN_EXTEND_INREG: { 2319 SDValue Op0 = Op.getOperand(0); 2320 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2321 unsigned ExVTBits = ExVT.getScalarSizeInBits(); 2322 2323 // If we only care about the highest bit, don't bother shifting right. 2324 if (DemandedBits.isSignMask()) { 2325 unsigned MinSignedBits = 2326 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1); 2327 bool AlreadySignExtended = ExVTBits >= MinSignedBits; 2328 // However if the input is already sign extended we expect the sign 2329 // extension to be dropped altogether later and do not simplify. 2330 if (!AlreadySignExtended) { 2331 // Compute the correct shift amount type, which must be getShiftAmountTy 2332 // for scalar types after legalization. 2333 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ExVTBits, dl, 2334 getShiftAmountTy(VT, DL)); 2335 return TLO.CombineTo(Op, 2336 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt)); 2337 } 2338 } 2339 2340 // If none of the extended bits are demanded, eliminate the sextinreg. 2341 if (DemandedBits.getActiveBits() <= ExVTBits) 2342 return TLO.CombineTo(Op, Op0); 2343 2344 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits); 2345 2346 // Since the sign extended bits are demanded, we know that the sign 2347 // bit is demanded. 2348 InputDemandedBits.setBit(ExVTBits - 1); 2349 2350 if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO, 2351 Depth + 1)) 2352 return true; 2353 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2354 2355 // If the sign bit of the input is known set or clear, then we know the 2356 // top bits of the result. 2357 2358 // If the input sign bit is known zero, convert this into a zero extension. 2359 if (Known.Zero[ExVTBits - 1]) 2360 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT)); 2361 2362 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits); 2363 if (Known.One[ExVTBits - 1]) { // Input sign bit known set 2364 Known.One.setBitsFrom(ExVTBits); 2365 Known.Zero &= Mask; 2366 } else { // Input sign bit unknown 2367 Known.Zero &= Mask; 2368 Known.One &= Mask; 2369 } 2370 break; 2371 } 2372 case ISD::BUILD_PAIR: { 2373 EVT HalfVT = Op.getOperand(0).getValueType(); 2374 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 2375 2376 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 2377 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 2378 2379 KnownBits KnownLo, KnownHi; 2380 2381 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1)) 2382 return true; 2383 2384 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1)) 2385 return true; 2386 2387 Known = KnownHi.concat(KnownLo); 2388 break; 2389 } 2390 case ISD::ZERO_EXTEND_VECTOR_INREG: 2391 if (VT.isScalableVector()) 2392 return false; 2393 [[fallthrough]]; 2394 case ISD::ZERO_EXTEND: { 2395 SDValue Src = Op.getOperand(0); 2396 EVT SrcVT = Src.getValueType(); 2397 unsigned InBits = SrcVT.getScalarSizeInBits(); 2398 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1; 2399 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG; 2400 2401 // If none of the top bits are demanded, convert this into an any_extend. 2402 if (DemandedBits.getActiveBits() <= InBits) { 2403 // If we only need the non-extended bits of the bottom element 2404 // then we can just bitcast to the result. 2405 if (IsLE && IsVecInReg && DemandedElts == 1 && 2406 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2407 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2408 2409 unsigned Opc = 2410 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2411 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2412 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2413 } 2414 2415 SDNodeFlags Flags = Op->getFlags(); 2416 APInt InDemandedBits = DemandedBits.trunc(InBits); 2417 APInt InDemandedElts = DemandedElts.zext(InElts); 2418 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2419 Depth + 1)) { 2420 if (Flags.hasNonNeg()) { 2421 Flags.setNonNeg(false); 2422 Op->setFlags(Flags); 2423 } 2424 return true; 2425 } 2426 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2427 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2428 Known = Known.zext(BitWidth); 2429 2430 // Attempt to avoid multi-use ops if we don't need anything from them. 2431 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2432 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2433 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2434 break; 2435 } 2436 case ISD::SIGN_EXTEND_VECTOR_INREG: 2437 if (VT.isScalableVector()) 2438 return false; 2439 [[fallthrough]]; 2440 case ISD::SIGN_EXTEND: { 2441 SDValue Src = Op.getOperand(0); 2442 EVT SrcVT = Src.getValueType(); 2443 unsigned InBits = SrcVT.getScalarSizeInBits(); 2444 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1; 2445 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG; 2446 2447 APInt InDemandedElts = DemandedElts.zext(InElts); 2448 APInt InDemandedBits = DemandedBits.trunc(InBits); 2449 2450 // Since some of the sign extended bits are demanded, we know that the sign 2451 // bit is demanded. 2452 InDemandedBits.setBit(InBits - 1); 2453 2454 // If none of the top bits are demanded, convert this into an any_extend. 2455 if (DemandedBits.getActiveBits() <= InBits) { 2456 // If we only need the non-extended bits of the bottom element 2457 // then we can just bitcast to the result. 2458 if (IsLE && IsVecInReg && DemandedElts == 1 && 2459 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2460 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2461 2462 // Don't lose an all signbits 0/-1 splat on targets with 0/-1 booleans. 2463 if (getBooleanContents(VT) != ZeroOrNegativeOneBooleanContent || 2464 TLO.DAG.ComputeNumSignBits(Src, InDemandedElts, Depth + 1) != 2465 InBits) { 2466 unsigned Opc = 2467 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2468 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2469 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2470 } 2471 } 2472 2473 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2474 Depth + 1)) 2475 return true; 2476 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2477 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2478 2479 // If the sign bit is known one, the top bits match. 2480 Known = Known.sext(BitWidth); 2481 2482 // If the sign bit is known zero, convert this to a zero extend. 2483 if (Known.isNonNegative()) { 2484 unsigned Opc = 2485 IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND; 2486 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2487 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2488 } 2489 2490 // Attempt to avoid multi-use ops if we don't need anything from them. 2491 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2492 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2493 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2494 break; 2495 } 2496 case ISD::ANY_EXTEND_VECTOR_INREG: 2497 if (VT.isScalableVector()) 2498 return false; 2499 [[fallthrough]]; 2500 case ISD::ANY_EXTEND: { 2501 SDValue Src = Op.getOperand(0); 2502 EVT SrcVT = Src.getValueType(); 2503 unsigned InBits = SrcVT.getScalarSizeInBits(); 2504 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1; 2505 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG; 2506 2507 // If we only need the bottom element then we can just bitcast. 2508 // TODO: Handle ANY_EXTEND? 2509 if (IsLE && IsVecInReg && DemandedElts == 1 && 2510 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2511 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2512 2513 APInt InDemandedBits = DemandedBits.trunc(InBits); 2514 APInt InDemandedElts = DemandedElts.zext(InElts); 2515 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2516 Depth + 1)) 2517 return true; 2518 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2519 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2520 Known = Known.anyext(BitWidth); 2521 2522 // Attempt to avoid multi-use ops if we don't need anything from them. 2523 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2524 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2525 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2526 break; 2527 } 2528 case ISD::TRUNCATE: { 2529 SDValue Src = Op.getOperand(0); 2530 2531 // Simplify the input, using demanded bit information, and compute the known 2532 // zero/one bits live out. 2533 unsigned OperandBitWidth = Src.getScalarValueSizeInBits(); 2534 APInt TruncMask = DemandedBits.zext(OperandBitWidth); 2535 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO, 2536 Depth + 1)) 2537 return true; 2538 Known = Known.trunc(BitWidth); 2539 2540 // Attempt to avoid multi-use ops if we don't need anything from them. 2541 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2542 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1)) 2543 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc)); 2544 2545 // If the input is only used by this truncate, see if we can shrink it based 2546 // on the known demanded bits. 2547 switch (Src.getOpcode()) { 2548 default: 2549 break; 2550 case ISD::SRL: 2551 // Shrink SRL by a constant if none of the high bits shifted in are 2552 // demanded. 2553 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT)) 2554 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 2555 // undesirable. 2556 break; 2557 2558 if (Src.getNode()->hasOneUse()) { 2559 const APInt *ShAmtC = 2560 TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts); 2561 if (!ShAmtC || ShAmtC->uge(BitWidth)) 2562 break; 2563 uint64_t ShVal = ShAmtC->getZExtValue(); 2564 2565 APInt HighBits = 2566 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth); 2567 HighBits.lshrInPlace(ShVal); 2568 HighBits = HighBits.trunc(BitWidth); 2569 2570 if (!(HighBits & DemandedBits)) { 2571 // None of the shifted in bits are needed. Add a truncate of the 2572 // shift input, then shift it. 2573 SDValue NewShAmt = TLO.DAG.getConstant( 2574 ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes())); 2575 SDValue NewTrunc = 2576 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0)); 2577 return TLO.CombineTo( 2578 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt)); 2579 } 2580 } 2581 break; 2582 } 2583 2584 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2585 break; 2586 } 2587 case ISD::AssertZext: { 2588 // AssertZext demands all of the high bits, plus any of the low bits 2589 // demanded by its users. 2590 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2591 APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits()); 2592 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known, 2593 TLO, Depth + 1)) 2594 return true; 2595 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2596 2597 Known.Zero |= ~InMask; 2598 Known.One &= (~Known.Zero); 2599 break; 2600 } 2601 case ISD::EXTRACT_VECTOR_ELT: { 2602 SDValue Src = Op.getOperand(0); 2603 SDValue Idx = Op.getOperand(1); 2604 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount(); 2605 unsigned EltBitWidth = Src.getScalarValueSizeInBits(); 2606 2607 if (SrcEltCnt.isScalable()) 2608 return false; 2609 2610 // Demand the bits from every vector element without a constant index. 2611 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2612 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 2613 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx)) 2614 if (CIdx->getAPIntValue().ult(NumSrcElts)) 2615 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue()); 2616 2617 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 2618 // anything about the extended bits. 2619 APInt DemandedSrcBits = DemandedBits; 2620 if (BitWidth > EltBitWidth) 2621 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth); 2622 2623 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO, 2624 Depth + 1)) 2625 return true; 2626 2627 // Attempt to avoid multi-use ops if we don't need anything from them. 2628 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 2629 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 2630 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) { 2631 SDValue NewOp = 2632 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx); 2633 return TLO.CombineTo(Op, NewOp); 2634 } 2635 } 2636 2637 Known = Known2; 2638 if (BitWidth > EltBitWidth) 2639 Known = Known.anyext(BitWidth); 2640 break; 2641 } 2642 case ISD::BITCAST: { 2643 if (VT.isScalableVector()) 2644 return false; 2645 SDValue Src = Op.getOperand(0); 2646 EVT SrcVT = Src.getValueType(); 2647 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 2648 2649 // If this is an FP->Int bitcast and if the sign bit is the only 2650 // thing demanded, turn this into a FGETSIGN. 2651 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() && 2652 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) && 2653 SrcVT.isFloatingPoint()) { 2654 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT); 2655 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 2656 if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 && 2657 SrcVT != MVT::f128) { 2658 // Cannot eliminate/lower SHL for f128 yet. 2659 EVT Ty = OpVTLegal ? VT : MVT::i32; 2660 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 2661 // place. We expect the SHL to be eliminated by other optimizations. 2662 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src); 2663 unsigned OpVTSizeInBits = Op.getValueSizeInBits(); 2664 if (!OpVTLegal && OpVTSizeInBits > 32) 2665 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign); 2666 unsigned ShVal = Op.getValueSizeInBits() - 1; 2667 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT); 2668 return TLO.CombineTo(Op, 2669 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt)); 2670 } 2671 } 2672 2673 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts. 2674 // Demand the elt/bit if any of the original elts/bits are demanded. 2675 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) { 2676 unsigned Scale = BitWidth / NumSrcEltBits; 2677 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2678 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2679 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2680 for (unsigned i = 0; i != Scale; ++i) { 2681 unsigned EltOffset = IsLE ? i : (Scale - 1 - i); 2682 unsigned BitOffset = EltOffset * NumSrcEltBits; 2683 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset); 2684 if (!Sub.isZero()) { 2685 DemandedSrcBits |= Sub; 2686 for (unsigned j = 0; j != NumElts; ++j) 2687 if (DemandedElts[j]) 2688 DemandedSrcElts.setBit((j * Scale) + i); 2689 } 2690 } 2691 2692 APInt KnownSrcUndef, KnownSrcZero; 2693 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2694 KnownSrcZero, TLO, Depth + 1)) 2695 return true; 2696 2697 KnownBits KnownSrcBits; 2698 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2699 KnownSrcBits, TLO, Depth + 1)) 2700 return true; 2701 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) { 2702 // TODO - bigendian once we have test coverage. 2703 unsigned Scale = NumSrcEltBits / BitWidth; 2704 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2705 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2706 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2707 for (unsigned i = 0; i != NumElts; ++i) 2708 if (DemandedElts[i]) { 2709 unsigned Offset = (i % Scale) * BitWidth; 2710 DemandedSrcBits.insertBits(DemandedBits, Offset); 2711 DemandedSrcElts.setBit(i / Scale); 2712 } 2713 2714 if (SrcVT.isVector()) { 2715 APInt KnownSrcUndef, KnownSrcZero; 2716 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2717 KnownSrcZero, TLO, Depth + 1)) 2718 return true; 2719 } 2720 2721 KnownBits KnownSrcBits; 2722 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2723 KnownSrcBits, TLO, Depth + 1)) 2724 return true; 2725 2726 // Attempt to avoid multi-use ops if we don't need anything from them. 2727 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 2728 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 2729 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) { 2730 SDValue NewOp = TLO.DAG.getBitcast(VT, DemandedSrc); 2731 return TLO.CombineTo(Op, NewOp); 2732 } 2733 } 2734 } 2735 2736 // If this is a bitcast, let computeKnownBits handle it. Only do this on a 2737 // recursive call where Known may be useful to the caller. 2738 if (Depth > 0) { 2739 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2740 return false; 2741 } 2742 break; 2743 } 2744 case ISD::MUL: 2745 if (DemandedBits.isPowerOf2()) { 2746 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1. 2747 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is 2748 // odd (has LSB set), then the left-shifted low bit of X is the answer. 2749 unsigned CTZ = DemandedBits.countr_zero(); 2750 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts); 2751 if (C && C->getAPIntValue().countr_zero() == CTZ) { 2752 EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout()); 2753 SDValue AmtC = TLO.DAG.getConstant(CTZ, dl, ShiftAmtTy); 2754 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC); 2755 return TLO.CombineTo(Op, Shl); 2756 } 2757 } 2758 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because: 2759 // X * X is odd iff X is odd. 2760 // 'Quadratic Reciprocity': X * X -> 0 for bit[1] 2761 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) { 2762 SDValue One = TLO.DAG.getConstant(1, dl, VT); 2763 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One); 2764 return TLO.CombineTo(Op, And1); 2765 } 2766 [[fallthrough]]; 2767 case ISD::ADD: 2768 case ISD::SUB: { 2769 // Add, Sub, and Mul don't demand any bits in positions beyond that 2770 // of the highest bit demanded of them. 2771 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1); 2772 SDNodeFlags Flags = Op.getNode()->getFlags(); 2773 unsigned DemandedBitsLZ = DemandedBits.countl_zero(); 2774 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ); 2775 KnownBits KnownOp0, KnownOp1; 2776 if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, KnownOp0, TLO, 2777 Depth + 1) || 2778 SimplifyDemandedBits(Op1, LoMask, DemandedElts, KnownOp1, TLO, 2779 Depth + 1) || 2780 // See if the operation should be performed at a smaller bit width. 2781 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) { 2782 if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) { 2783 // Disable the nsw and nuw flags. We can no longer guarantee that we 2784 // won't wrap after simplification. 2785 Flags.setNoSignedWrap(false); 2786 Flags.setNoUnsignedWrap(false); 2787 Op->setFlags(Flags); 2788 } 2789 return true; 2790 } 2791 2792 // neg x with only low bit demanded is simply x. 2793 if (Op.getOpcode() == ISD::SUB && DemandedBits.isOne() && 2794 isNullConstant(Op0)) 2795 return TLO.CombineTo(Op, Op1); 2796 2797 // Attempt to avoid multi-use ops if we don't need anything from them. 2798 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) { 2799 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2800 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2801 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 2802 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2803 if (DemandedOp0 || DemandedOp1) { 2804 Flags.setNoSignedWrap(false); 2805 Flags.setNoUnsignedWrap(false); 2806 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 2807 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 2808 SDValue NewOp = 2809 TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags); 2810 return TLO.CombineTo(Op, NewOp); 2811 } 2812 } 2813 2814 // If we have a constant operand, we may be able to turn it into -1 if we 2815 // do not demand the high bits. This can make the constant smaller to 2816 // encode, allow more general folding, or match specialized instruction 2817 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that 2818 // is probably not useful (and could be detrimental). 2819 ConstantSDNode *C = isConstOrConstSplat(Op1); 2820 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ); 2821 if (C && !C->isAllOnes() && !C->isOne() && 2822 (C->getAPIntValue() | HighMask).isAllOnes()) { 2823 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT); 2824 // Disable the nsw and nuw flags. We can no longer guarantee that we 2825 // won't wrap after simplification. 2826 Flags.setNoSignedWrap(false); 2827 Flags.setNoUnsignedWrap(false); 2828 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags); 2829 return TLO.CombineTo(Op, NewOp); 2830 } 2831 2832 // Match a multiply with a disguised negated-power-of-2 and convert to a 2833 // an equivalent shift-left amount. 2834 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2835 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned { 2836 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse()) 2837 return 0; 2838 2839 // Don't touch opaque constants. Also, ignore zero and power-of-2 2840 // multiplies. Those will get folded later. 2841 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1)); 2842 if (MulC && !MulC->isOpaque() && !MulC->isZero() && 2843 !MulC->getAPIntValue().isPowerOf2()) { 2844 APInt UnmaskedC = MulC->getAPIntValue() | HighMask; 2845 if (UnmaskedC.isNegatedPowerOf2()) 2846 return (-UnmaskedC).logBase2(); 2847 } 2848 return 0; 2849 }; 2850 2851 auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y, unsigned ShlAmt) { 2852 EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout()); 2853 SDValue ShlAmtC = TLO.DAG.getConstant(ShlAmt, dl, ShiftAmtTy); 2854 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC); 2855 SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl); 2856 return TLO.CombineTo(Op, Res); 2857 }; 2858 2859 if (isOperationLegalOrCustom(ISD::SHL, VT)) { 2860 if (Op.getOpcode() == ISD::ADD) { 2861 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2862 if (unsigned ShAmt = getShiftLeftAmt(Op0)) 2863 return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt); 2864 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC)) 2865 if (unsigned ShAmt = getShiftLeftAmt(Op1)) 2866 return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt); 2867 } 2868 if (Op.getOpcode() == ISD::SUB) { 2869 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC)) 2870 if (unsigned ShAmt = getShiftLeftAmt(Op1)) 2871 return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt); 2872 } 2873 } 2874 2875 if (Op.getOpcode() == ISD::MUL) { 2876 Known = KnownBits::mul(KnownOp0, KnownOp1); 2877 } else { // Op.getOpcode() is either ISD::ADD or ISD::SUB. 2878 Known = KnownBits::computeForAddSub(Op.getOpcode() == ISD::ADD, 2879 Flags.hasNoSignedWrap(), KnownOp0, 2880 KnownOp1); 2881 } 2882 break; 2883 } 2884 default: 2885 // We also ask the target about intrinsics (which could be specific to it). 2886 if (Op.getOpcode() >= ISD::BUILTIN_OP_END || 2887 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN) { 2888 // TODO: Probably okay to remove after audit; here to reduce change size 2889 // in initial enablement patch for scalable vectors 2890 if (Op.getValueType().isScalableVector()) 2891 break; 2892 if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts, 2893 Known, TLO, Depth)) 2894 return true; 2895 break; 2896 } 2897 2898 // Just use computeKnownBits to compute output bits. 2899 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2900 break; 2901 } 2902 2903 // If we know the value of all of the demanded bits, return this as a 2904 // constant. 2905 if (!isTargetCanonicalConstantNode(Op) && 2906 DemandedBits.isSubsetOf(Known.Zero | Known.One)) { 2907 // Avoid folding to a constant if any OpaqueConstant is involved. 2908 const SDNode *N = Op.getNode(); 2909 for (SDNode *Op : 2910 llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) { 2911 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 2912 if (C->isOpaque()) 2913 return false; 2914 } 2915 if (VT.isInteger()) 2916 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT)); 2917 if (VT.isFloatingPoint()) 2918 return TLO.CombineTo( 2919 Op, 2920 TLO.DAG.getConstantFP( 2921 APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT)); 2922 } 2923 2924 // A multi use 'all demanded elts' simplify failed to find any knownbits. 2925 // Try again just for the original demanded elts. 2926 // Ensure we do this AFTER constant folding above. 2927 if (HasMultiUse && Known.isUnknown() && !OriginalDemandedElts.isAllOnes()) 2928 Known = TLO.DAG.computeKnownBits(Op, OriginalDemandedElts, Depth); 2929 2930 return false; 2931 } 2932 2933 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op, 2934 const APInt &DemandedElts, 2935 DAGCombinerInfo &DCI) const { 2936 SelectionDAG &DAG = DCI.DAG; 2937 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 2938 !DCI.isBeforeLegalizeOps()); 2939 2940 APInt KnownUndef, KnownZero; 2941 bool Simplified = 2942 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO); 2943 if (Simplified) { 2944 DCI.AddToWorklist(Op.getNode()); 2945 DCI.CommitTargetLoweringOpt(TLO); 2946 } 2947 2948 return Simplified; 2949 } 2950 2951 /// Given a vector binary operation and known undefined elements for each input 2952 /// operand, compute whether each element of the output is undefined. 2953 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG, 2954 const APInt &UndefOp0, 2955 const APInt &UndefOp1) { 2956 EVT VT = BO.getValueType(); 2957 assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() && 2958 "Vector binop only"); 2959 2960 EVT EltVT = VT.getVectorElementType(); 2961 unsigned NumElts = VT.isFixedLengthVector() ? VT.getVectorNumElements() : 1; 2962 assert(UndefOp0.getBitWidth() == NumElts && 2963 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis"); 2964 2965 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index, 2966 const APInt &UndefVals) { 2967 if (UndefVals[Index]) 2968 return DAG.getUNDEF(EltVT); 2969 2970 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 2971 // Try hard to make sure that the getNode() call is not creating temporary 2972 // nodes. Ignore opaque integers because they do not constant fold. 2973 SDValue Elt = BV->getOperand(Index); 2974 auto *C = dyn_cast<ConstantSDNode>(Elt); 2975 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque())) 2976 return Elt; 2977 } 2978 2979 return SDValue(); 2980 }; 2981 2982 APInt KnownUndef = APInt::getZero(NumElts); 2983 for (unsigned i = 0; i != NumElts; ++i) { 2984 // If both inputs for this element are either constant or undef and match 2985 // the element type, compute the constant/undef result for this element of 2986 // the vector. 2987 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does 2988 // not handle FP constants. The code within getNode() should be refactored 2989 // to avoid the danger of creating a bogus temporary node here. 2990 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0); 2991 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1); 2992 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT) 2993 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef()) 2994 KnownUndef.setBit(i); 2995 } 2996 return KnownUndef; 2997 } 2998 2999 bool TargetLowering::SimplifyDemandedVectorElts( 3000 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef, 3001 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth, 3002 bool AssumeSingleUse) const { 3003 EVT VT = Op.getValueType(); 3004 unsigned Opcode = Op.getOpcode(); 3005 APInt DemandedElts = OriginalDemandedElts; 3006 unsigned NumElts = DemandedElts.getBitWidth(); 3007 assert(VT.isVector() && "Expected vector op"); 3008 3009 KnownUndef = KnownZero = APInt::getZero(NumElts); 3010 3011 const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo(); 3012 if (!TLI.shouldSimplifyDemandedVectorElts(Op, TLO)) 3013 return false; 3014 3015 // TODO: For now we assume we know nothing about scalable vectors. 3016 if (VT.isScalableVector()) 3017 return false; 3018 3019 assert(VT.getVectorNumElements() == NumElts && 3020 "Mask size mismatches value type element count!"); 3021 3022 // Undef operand. 3023 if (Op.isUndef()) { 3024 KnownUndef.setAllBits(); 3025 return false; 3026 } 3027 3028 // If Op has other users, assume that all elements are needed. 3029 if (!AssumeSingleUse && !Op.getNode()->hasOneUse()) 3030 DemandedElts.setAllBits(); 3031 3032 // Not demanding any elements from Op. 3033 if (DemandedElts == 0) { 3034 KnownUndef.setAllBits(); 3035 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 3036 } 3037 3038 // Limit search depth. 3039 if (Depth >= SelectionDAG::MaxRecursionDepth) 3040 return false; 3041 3042 SDLoc DL(Op); 3043 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 3044 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 3045 3046 // Helper for demanding the specified elements and all the bits of both binary 3047 // operands. 3048 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) { 3049 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts, 3050 TLO.DAG, Depth + 1); 3051 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts, 3052 TLO.DAG, Depth + 1); 3053 if (NewOp0 || NewOp1) { 3054 SDValue NewOp = 3055 TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, 3056 NewOp1 ? NewOp1 : Op1, Op->getFlags()); 3057 return TLO.CombineTo(Op, NewOp); 3058 } 3059 return false; 3060 }; 3061 3062 switch (Opcode) { 3063 case ISD::SCALAR_TO_VECTOR: { 3064 if (!DemandedElts[0]) { 3065 KnownUndef.setAllBits(); 3066 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 3067 } 3068 SDValue ScalarSrc = Op.getOperand(0); 3069 if (ScalarSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 3070 SDValue Src = ScalarSrc.getOperand(0); 3071 SDValue Idx = ScalarSrc.getOperand(1); 3072 EVT SrcVT = Src.getValueType(); 3073 3074 ElementCount SrcEltCnt = SrcVT.getVectorElementCount(); 3075 3076 if (SrcEltCnt.isScalable()) 3077 return false; 3078 3079 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 3080 if (isNullConstant(Idx)) { 3081 APInt SrcDemandedElts = APInt::getOneBitSet(NumSrcElts, 0); 3082 APInt SrcUndef = KnownUndef.zextOrTrunc(NumSrcElts); 3083 APInt SrcZero = KnownZero.zextOrTrunc(NumSrcElts); 3084 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 3085 TLO, Depth + 1)) 3086 return true; 3087 } 3088 } 3089 KnownUndef.setHighBits(NumElts - 1); 3090 break; 3091 } 3092 case ISD::BITCAST: { 3093 SDValue Src = Op.getOperand(0); 3094 EVT SrcVT = Src.getValueType(); 3095 3096 // We only handle vectors here. 3097 // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits? 3098 if (!SrcVT.isVector()) 3099 break; 3100 3101 // Fast handling of 'identity' bitcasts. 3102 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 3103 if (NumSrcElts == NumElts) 3104 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, 3105 KnownZero, TLO, Depth + 1); 3106 3107 APInt SrcDemandedElts, SrcZero, SrcUndef; 3108 3109 // Bitcast from 'large element' src vector to 'small element' vector, we 3110 // must demand a source element if any DemandedElt maps to it. 3111 if ((NumElts % NumSrcElts) == 0) { 3112 unsigned Scale = NumElts / NumSrcElts; 3113 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 3114 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 3115 TLO, Depth + 1)) 3116 return true; 3117 3118 // Try calling SimplifyDemandedBits, converting demanded elts to the bits 3119 // of the large element. 3120 // TODO - bigendian once we have test coverage. 3121 if (IsLE) { 3122 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits(); 3123 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits); 3124 for (unsigned i = 0; i != NumElts; ++i) 3125 if (DemandedElts[i]) { 3126 unsigned Ofs = (i % Scale) * EltSizeInBits; 3127 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits); 3128 } 3129 3130 KnownBits Known; 3131 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known, 3132 TLO, Depth + 1)) 3133 return true; 3134 3135 // The bitcast has split each wide element into a number of 3136 // narrow subelements. We have just computed the Known bits 3137 // for wide elements. See if element splitting results in 3138 // some subelements being zero. Only for demanded elements! 3139 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) { 3140 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits) 3141 .isAllOnes()) 3142 continue; 3143 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) { 3144 unsigned Elt = Scale * SrcElt + SubElt; 3145 if (DemandedElts[Elt]) 3146 KnownZero.setBit(Elt); 3147 } 3148 } 3149 } 3150 3151 // If the src element is zero/undef then all the output elements will be - 3152 // only demanded elements are guaranteed to be correct. 3153 for (unsigned i = 0; i != NumSrcElts; ++i) { 3154 if (SrcDemandedElts[i]) { 3155 if (SrcZero[i]) 3156 KnownZero.setBits(i * Scale, (i + 1) * Scale); 3157 if (SrcUndef[i]) 3158 KnownUndef.setBits(i * Scale, (i + 1) * Scale); 3159 } 3160 } 3161 } 3162 3163 // Bitcast from 'small element' src vector to 'large element' vector, we 3164 // demand all smaller source elements covered by the larger demanded element 3165 // of this vector. 3166 if ((NumSrcElts % NumElts) == 0) { 3167 unsigned Scale = NumSrcElts / NumElts; 3168 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 3169 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 3170 TLO, Depth + 1)) 3171 return true; 3172 3173 // If all the src elements covering an output element are zero/undef, then 3174 // the output element will be as well, assuming it was demanded. 3175 for (unsigned i = 0; i != NumElts; ++i) { 3176 if (DemandedElts[i]) { 3177 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes()) 3178 KnownZero.setBit(i); 3179 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes()) 3180 KnownUndef.setBit(i); 3181 } 3182 } 3183 } 3184 break; 3185 } 3186 case ISD::BUILD_VECTOR: { 3187 // Check all elements and simplify any unused elements with UNDEF. 3188 if (!DemandedElts.isAllOnes()) { 3189 // Don't simplify BROADCASTS. 3190 if (llvm::any_of(Op->op_values(), 3191 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) { 3192 SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end()); 3193 bool Updated = false; 3194 for (unsigned i = 0; i != NumElts; ++i) { 3195 if (!DemandedElts[i] && !Ops[i].isUndef()) { 3196 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType()); 3197 KnownUndef.setBit(i); 3198 Updated = true; 3199 } 3200 } 3201 if (Updated) 3202 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops)); 3203 } 3204 } 3205 for (unsigned i = 0; i != NumElts; ++i) { 3206 SDValue SrcOp = Op.getOperand(i); 3207 if (SrcOp.isUndef()) { 3208 KnownUndef.setBit(i); 3209 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() && 3210 (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) { 3211 KnownZero.setBit(i); 3212 } 3213 } 3214 break; 3215 } 3216 case ISD::CONCAT_VECTORS: { 3217 EVT SubVT = Op.getOperand(0).getValueType(); 3218 unsigned NumSubVecs = Op.getNumOperands(); 3219 unsigned NumSubElts = SubVT.getVectorNumElements(); 3220 for (unsigned i = 0; i != NumSubVecs; ++i) { 3221 SDValue SubOp = Op.getOperand(i); 3222 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 3223 APInt SubUndef, SubZero; 3224 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO, 3225 Depth + 1)) 3226 return true; 3227 KnownUndef.insertBits(SubUndef, i * NumSubElts); 3228 KnownZero.insertBits(SubZero, i * NumSubElts); 3229 } 3230 3231 // Attempt to avoid multi-use ops if we don't need anything from them. 3232 if (!DemandedElts.isAllOnes()) { 3233 bool FoundNewSub = false; 3234 SmallVector<SDValue, 2> DemandedSubOps; 3235 for (unsigned i = 0; i != NumSubVecs; ++i) { 3236 SDValue SubOp = Op.getOperand(i); 3237 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 3238 SDValue NewSubOp = SimplifyMultipleUseDemandedVectorElts( 3239 SubOp, SubElts, TLO.DAG, Depth + 1); 3240 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp); 3241 FoundNewSub = NewSubOp ? true : FoundNewSub; 3242 } 3243 if (FoundNewSub) { 3244 SDValue NewOp = 3245 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps); 3246 return TLO.CombineTo(Op, NewOp); 3247 } 3248 } 3249 break; 3250 } 3251 case ISD::INSERT_SUBVECTOR: { 3252 // Demand any elements from the subvector and the remainder from the src its 3253 // inserted into. 3254 SDValue Src = Op.getOperand(0); 3255 SDValue Sub = Op.getOperand(1); 3256 uint64_t Idx = Op.getConstantOperandVal(2); 3257 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3258 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3259 APInt DemandedSrcElts = DemandedElts; 3260 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 3261 3262 APInt SubUndef, SubZero; 3263 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO, 3264 Depth + 1)) 3265 return true; 3266 3267 // If none of the src operand elements are demanded, replace it with undef. 3268 if (!DemandedSrcElts && !Src.isUndef()) 3269 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 3270 TLO.DAG.getUNDEF(VT), Sub, 3271 Op.getOperand(2))); 3272 3273 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero, 3274 TLO, Depth + 1)) 3275 return true; 3276 KnownUndef.insertBits(SubUndef, Idx); 3277 KnownZero.insertBits(SubZero, Idx); 3278 3279 // Attempt to avoid multi-use ops if we don't need anything from them. 3280 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) { 3281 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 3282 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 3283 SDValue NewSub = SimplifyMultipleUseDemandedVectorElts( 3284 Sub, DemandedSubElts, TLO.DAG, Depth + 1); 3285 if (NewSrc || NewSub) { 3286 NewSrc = NewSrc ? NewSrc : Src; 3287 NewSub = NewSub ? NewSub : Sub; 3288 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 3289 NewSub, Op.getOperand(2)); 3290 return TLO.CombineTo(Op, NewOp); 3291 } 3292 } 3293 break; 3294 } 3295 case ISD::EXTRACT_SUBVECTOR: { 3296 // Offset the demanded elts by the subvector index. 3297 SDValue Src = Op.getOperand(0); 3298 if (Src.getValueType().isScalableVector()) 3299 break; 3300 uint64_t Idx = Op.getConstantOperandVal(1); 3301 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3302 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 3303 3304 APInt SrcUndef, SrcZero; 3305 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 3306 Depth + 1)) 3307 return true; 3308 KnownUndef = SrcUndef.extractBits(NumElts, Idx); 3309 KnownZero = SrcZero.extractBits(NumElts, Idx); 3310 3311 // Attempt to avoid multi-use ops if we don't need anything from them. 3312 if (!DemandedElts.isAllOnes()) { 3313 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 3314 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 3315 if (NewSrc) { 3316 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 3317 Op.getOperand(1)); 3318 return TLO.CombineTo(Op, NewOp); 3319 } 3320 } 3321 break; 3322 } 3323 case ISD::INSERT_VECTOR_ELT: { 3324 SDValue Vec = Op.getOperand(0); 3325 SDValue Scl = Op.getOperand(1); 3326 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 3327 3328 // For a legal, constant insertion index, if we don't need this insertion 3329 // then strip it, else remove it from the demanded elts. 3330 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) { 3331 unsigned Idx = CIdx->getZExtValue(); 3332 if (!DemandedElts[Idx]) 3333 return TLO.CombineTo(Op, Vec); 3334 3335 APInt DemandedVecElts(DemandedElts); 3336 DemandedVecElts.clearBit(Idx); 3337 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef, 3338 KnownZero, TLO, Depth + 1)) 3339 return true; 3340 3341 KnownUndef.setBitVal(Idx, Scl.isUndef()); 3342 3343 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl)); 3344 break; 3345 } 3346 3347 APInt VecUndef, VecZero; 3348 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO, 3349 Depth + 1)) 3350 return true; 3351 // Without knowing the insertion index we can't set KnownUndef/KnownZero. 3352 break; 3353 } 3354 case ISD::VSELECT: { 3355 SDValue Sel = Op.getOperand(0); 3356 SDValue LHS = Op.getOperand(1); 3357 SDValue RHS = Op.getOperand(2); 3358 3359 // Try to transform the select condition based on the current demanded 3360 // elements. 3361 APInt UndefSel, ZeroSel; 3362 if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, ZeroSel, TLO, 3363 Depth + 1)) 3364 return true; 3365 3366 // See if we can simplify either vselect operand. 3367 APInt DemandedLHS(DemandedElts); 3368 APInt DemandedRHS(DemandedElts); 3369 APInt UndefLHS, ZeroLHS; 3370 APInt UndefRHS, ZeroRHS; 3371 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO, 3372 Depth + 1)) 3373 return true; 3374 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO, 3375 Depth + 1)) 3376 return true; 3377 3378 KnownUndef = UndefLHS & UndefRHS; 3379 KnownZero = ZeroLHS & ZeroRHS; 3380 3381 // If we know that the selected element is always zero, we don't need the 3382 // select value element. 3383 APInt DemandedSel = DemandedElts & ~KnownZero; 3384 if (DemandedSel != DemandedElts) 3385 if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, ZeroSel, TLO, 3386 Depth + 1)) 3387 return true; 3388 3389 break; 3390 } 3391 case ISD::VECTOR_SHUFFLE: { 3392 SDValue LHS = Op.getOperand(0); 3393 SDValue RHS = Op.getOperand(1); 3394 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 3395 3396 // Collect demanded elements from shuffle operands.. 3397 APInt DemandedLHS(NumElts, 0); 3398 APInt DemandedRHS(NumElts, 0); 3399 for (unsigned i = 0; i != NumElts; ++i) { 3400 int M = ShuffleMask[i]; 3401 if (M < 0 || !DemandedElts[i]) 3402 continue; 3403 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 3404 if (M < (int)NumElts) 3405 DemandedLHS.setBit(M); 3406 else 3407 DemandedRHS.setBit(M - NumElts); 3408 } 3409 3410 // See if we can simplify either shuffle operand. 3411 APInt UndefLHS, ZeroLHS; 3412 APInt UndefRHS, ZeroRHS; 3413 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO, 3414 Depth + 1)) 3415 return true; 3416 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO, 3417 Depth + 1)) 3418 return true; 3419 3420 // Simplify mask using undef elements from LHS/RHS. 3421 bool Updated = false; 3422 bool IdentityLHS = true, IdentityRHS = true; 3423 SmallVector<int, 32> NewMask(ShuffleMask); 3424 for (unsigned i = 0; i != NumElts; ++i) { 3425 int &M = NewMask[i]; 3426 if (M < 0) 3427 continue; 3428 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) || 3429 (M >= (int)NumElts && UndefRHS[M - NumElts])) { 3430 Updated = true; 3431 M = -1; 3432 } 3433 IdentityLHS &= (M < 0) || (M == (int)i); 3434 IdentityRHS &= (M < 0) || ((M - NumElts) == i); 3435 } 3436 3437 // Update legal shuffle masks based on demanded elements if it won't reduce 3438 // to Identity which can cause premature removal of the shuffle mask. 3439 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) { 3440 SDValue LegalShuffle = 3441 buildLegalVectorShuffle(VT, DL, LHS, RHS, NewMask, TLO.DAG); 3442 if (LegalShuffle) 3443 return TLO.CombineTo(Op, LegalShuffle); 3444 } 3445 3446 // Propagate undef/zero elements from LHS/RHS. 3447 for (unsigned i = 0; i != NumElts; ++i) { 3448 int M = ShuffleMask[i]; 3449 if (M < 0) { 3450 KnownUndef.setBit(i); 3451 } else if (M < (int)NumElts) { 3452 if (UndefLHS[M]) 3453 KnownUndef.setBit(i); 3454 if (ZeroLHS[M]) 3455 KnownZero.setBit(i); 3456 } else { 3457 if (UndefRHS[M - NumElts]) 3458 KnownUndef.setBit(i); 3459 if (ZeroRHS[M - NumElts]) 3460 KnownZero.setBit(i); 3461 } 3462 } 3463 break; 3464 } 3465 case ISD::ANY_EXTEND_VECTOR_INREG: 3466 case ISD::SIGN_EXTEND_VECTOR_INREG: 3467 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3468 APInt SrcUndef, SrcZero; 3469 SDValue Src = Op.getOperand(0); 3470 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3471 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts); 3472 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 3473 Depth + 1)) 3474 return true; 3475 KnownZero = SrcZero.zextOrTrunc(NumElts); 3476 KnownUndef = SrcUndef.zextOrTrunc(NumElts); 3477 3478 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG && 3479 Op.getValueSizeInBits() == Src.getValueSizeInBits() && 3480 DemandedSrcElts == 1) { 3481 // aext - if we just need the bottom element then we can bitcast. 3482 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 3483 } 3484 3485 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { 3486 // zext(undef) upper bits are guaranteed to be zero. 3487 if (DemandedElts.isSubsetOf(KnownUndef)) 3488 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3489 KnownUndef.clearAllBits(); 3490 3491 // zext - if we just need the bottom element then we can mask: 3492 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and. 3493 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND && 3494 Op->isOnlyUserOf(Src.getNode()) && 3495 Op.getValueSizeInBits() == Src.getValueSizeInBits()) { 3496 SDLoc DL(Op); 3497 EVT SrcVT = Src.getValueType(); 3498 EVT SrcSVT = SrcVT.getScalarType(); 3499 SmallVector<SDValue> MaskElts; 3500 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT)); 3501 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT)); 3502 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts); 3503 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic( 3504 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) { 3505 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold); 3506 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold)); 3507 } 3508 } 3509 } 3510 break; 3511 } 3512 3513 // TODO: There are more binop opcodes that could be handled here - MIN, 3514 // MAX, saturated math, etc. 3515 case ISD::ADD: { 3516 SDValue Op0 = Op.getOperand(0); 3517 SDValue Op1 = Op.getOperand(1); 3518 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) { 3519 APInt UndefLHS, ZeroLHS; 3520 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3521 Depth + 1, /*AssumeSingleUse*/ true)) 3522 return true; 3523 } 3524 [[fallthrough]]; 3525 } 3526 case ISD::OR: 3527 case ISD::XOR: 3528 case ISD::SUB: 3529 case ISD::FADD: 3530 case ISD::FSUB: 3531 case ISD::FMUL: 3532 case ISD::FDIV: 3533 case ISD::FREM: { 3534 SDValue Op0 = Op.getOperand(0); 3535 SDValue Op1 = Op.getOperand(1); 3536 3537 APInt UndefRHS, ZeroRHS; 3538 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3539 Depth + 1)) 3540 return true; 3541 APInt UndefLHS, ZeroLHS; 3542 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3543 Depth + 1)) 3544 return true; 3545 3546 KnownZero = ZeroLHS & ZeroRHS; 3547 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS); 3548 3549 // Attempt to avoid multi-use ops if we don't need anything from them. 3550 // TODO - use KnownUndef to relax the demandedelts? 3551 if (!DemandedElts.isAllOnes()) 3552 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3553 return true; 3554 break; 3555 } 3556 case ISD::SHL: 3557 case ISD::SRL: 3558 case ISD::SRA: 3559 case ISD::ROTL: 3560 case ISD::ROTR: { 3561 SDValue Op0 = Op.getOperand(0); 3562 SDValue Op1 = Op.getOperand(1); 3563 3564 APInt UndefRHS, ZeroRHS; 3565 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3566 Depth + 1)) 3567 return true; 3568 APInt UndefLHS, ZeroLHS; 3569 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3570 Depth + 1)) 3571 return true; 3572 3573 KnownZero = ZeroLHS; 3574 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop? 3575 3576 // Attempt to avoid multi-use ops if we don't need anything from them. 3577 // TODO - use KnownUndef to relax the demandedelts? 3578 if (!DemandedElts.isAllOnes()) 3579 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3580 return true; 3581 break; 3582 } 3583 case ISD::MUL: 3584 case ISD::MULHU: 3585 case ISD::MULHS: 3586 case ISD::AND: { 3587 SDValue Op0 = Op.getOperand(0); 3588 SDValue Op1 = Op.getOperand(1); 3589 3590 APInt SrcUndef, SrcZero; 3591 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO, 3592 Depth + 1)) 3593 return true; 3594 // If we know that a demanded element was zero in Op1 we don't need to 3595 // demand it in Op0 - its guaranteed to be zero. 3596 APInt DemandedElts0 = DemandedElts & ~SrcZero; 3597 if (SimplifyDemandedVectorElts(Op0, DemandedElts0, KnownUndef, KnownZero, 3598 TLO, Depth + 1)) 3599 return true; 3600 3601 KnownUndef &= DemandedElts0; 3602 KnownZero &= DemandedElts0; 3603 3604 // If every element pair has a zero/undef then just fold to zero. 3605 // fold (and x, undef) -> 0 / (and x, 0) -> 0 3606 // fold (mul x, undef) -> 0 / (mul x, 0) -> 0 3607 if (DemandedElts.isSubsetOf(SrcZero | KnownZero | SrcUndef | KnownUndef)) 3608 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3609 3610 // If either side has a zero element, then the result element is zero, even 3611 // if the other is an UNDEF. 3612 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros 3613 // and then handle 'and' nodes with the rest of the binop opcodes. 3614 KnownZero |= SrcZero; 3615 KnownUndef &= SrcUndef; 3616 KnownUndef &= ~KnownZero; 3617 3618 // Attempt to avoid multi-use ops if we don't need anything from them. 3619 if (!DemandedElts.isAllOnes()) 3620 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3621 return true; 3622 break; 3623 } 3624 case ISD::TRUNCATE: 3625 case ISD::SIGN_EXTEND: 3626 case ISD::ZERO_EXTEND: 3627 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 3628 KnownZero, TLO, Depth + 1)) 3629 return true; 3630 3631 if (Op.getOpcode() == ISD::ZERO_EXTEND) { 3632 // zext(undef) upper bits are guaranteed to be zero. 3633 if (DemandedElts.isSubsetOf(KnownUndef)) 3634 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3635 KnownUndef.clearAllBits(); 3636 } 3637 break; 3638 default: { 3639 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 3640 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef, 3641 KnownZero, TLO, Depth)) 3642 return true; 3643 } else { 3644 KnownBits Known; 3645 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits); 3646 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known, 3647 TLO, Depth, AssumeSingleUse)) 3648 return true; 3649 } 3650 break; 3651 } 3652 } 3653 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero"); 3654 3655 // Constant fold all undef cases. 3656 // TODO: Handle zero cases as well. 3657 if (DemandedElts.isSubsetOf(KnownUndef)) 3658 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 3659 3660 return false; 3661 } 3662 3663 /// Determine which of the bits specified in Mask are known to be either zero or 3664 /// one and return them in the Known. 3665 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 3666 KnownBits &Known, 3667 const APInt &DemandedElts, 3668 const SelectionDAG &DAG, 3669 unsigned Depth) const { 3670 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3671 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3672 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3673 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3674 "Should use MaskedValueIsZero if you don't know whether Op" 3675 " is a target node!"); 3676 Known.resetAll(); 3677 } 3678 3679 void TargetLowering::computeKnownBitsForTargetInstr( 3680 GISelKnownBits &Analysis, Register R, KnownBits &Known, 3681 const APInt &DemandedElts, const MachineRegisterInfo &MRI, 3682 unsigned Depth) const { 3683 Known.resetAll(); 3684 } 3685 3686 void TargetLowering::computeKnownBitsForFrameIndex( 3687 const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const { 3688 // The low bits are known zero if the pointer is aligned. 3689 Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx))); 3690 } 3691 3692 Align TargetLowering::computeKnownAlignForTargetInstr( 3693 GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI, 3694 unsigned Depth) const { 3695 return Align(1); 3696 } 3697 3698 /// This method can be implemented by targets that want to expose additional 3699 /// information about sign bits to the DAG Combiner. 3700 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 3701 const APInt &, 3702 const SelectionDAG &, 3703 unsigned Depth) const { 3704 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3705 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3706 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3707 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3708 "Should use ComputeNumSignBits if you don't know whether Op" 3709 " is a target node!"); 3710 return 1; 3711 } 3712 3713 unsigned TargetLowering::computeNumSignBitsForTargetInstr( 3714 GISelKnownBits &Analysis, Register R, const APInt &DemandedElts, 3715 const MachineRegisterInfo &MRI, unsigned Depth) const { 3716 return 1; 3717 } 3718 3719 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode( 3720 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero, 3721 TargetLoweringOpt &TLO, unsigned Depth) const { 3722 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3723 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3724 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3725 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3726 "Should use SimplifyDemandedVectorElts if you don't know whether Op" 3727 " is a target node!"); 3728 return false; 3729 } 3730 3731 bool TargetLowering::SimplifyDemandedBitsForTargetNode( 3732 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3733 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const { 3734 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3735 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3736 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3737 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3738 "Should use SimplifyDemandedBits if you don't know whether Op" 3739 " is a target node!"); 3740 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth); 3741 return false; 3742 } 3743 3744 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode( 3745 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3746 SelectionDAG &DAG, unsigned Depth) const { 3747 assert( 3748 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3749 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3750 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3751 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3752 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op" 3753 " is a target node!"); 3754 return SDValue(); 3755 } 3756 3757 SDValue 3758 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, 3759 SDValue N1, MutableArrayRef<int> Mask, 3760 SelectionDAG &DAG) const { 3761 bool LegalMask = isShuffleMaskLegal(Mask, VT); 3762 if (!LegalMask) { 3763 std::swap(N0, N1); 3764 ShuffleVectorSDNode::commuteMask(Mask); 3765 LegalMask = isShuffleMaskLegal(Mask, VT); 3766 } 3767 3768 if (!LegalMask) 3769 return SDValue(); 3770 3771 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask); 3772 } 3773 3774 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const { 3775 return nullptr; 3776 } 3777 3778 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode( 3779 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 3780 bool PoisonOnly, unsigned Depth) const { 3781 assert( 3782 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3783 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3784 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3785 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3786 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op" 3787 " is a target node!"); 3788 return false; 3789 } 3790 3791 bool TargetLowering::canCreateUndefOrPoisonForTargetNode( 3792 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 3793 bool PoisonOnly, bool ConsiderFlags, unsigned Depth) const { 3794 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3795 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3796 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3797 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3798 "Should use canCreateUndefOrPoison if you don't know whether Op" 3799 " is a target node!"); 3800 // Be conservative and return true. 3801 return true; 3802 } 3803 3804 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 3805 const SelectionDAG &DAG, 3806 bool SNaN, 3807 unsigned Depth) const { 3808 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3809 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3810 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3811 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3812 "Should use isKnownNeverNaN if you don't know whether Op" 3813 " is a target node!"); 3814 return false; 3815 } 3816 3817 bool TargetLowering::isSplatValueForTargetNode(SDValue Op, 3818 const APInt &DemandedElts, 3819 APInt &UndefElts, 3820 const SelectionDAG &DAG, 3821 unsigned Depth) const { 3822 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3823 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3824 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3825 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3826 "Should use isSplatValue if you don't know whether Op" 3827 " is a target node!"); 3828 return false; 3829 } 3830 3831 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must 3832 // work with truncating build vectors and vectors with elements of less than 3833 // 8 bits. 3834 bool TargetLowering::isConstTrueVal(SDValue N) const { 3835 if (!N) 3836 return false; 3837 3838 unsigned EltWidth; 3839 APInt CVal; 3840 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false, 3841 /*AllowTruncation=*/true)) { 3842 CVal = CN->getAPIntValue(); 3843 EltWidth = N.getValueType().getScalarSizeInBits(); 3844 } else 3845 return false; 3846 3847 // If this is a truncating splat, truncate the splat value. 3848 // Otherwise, we may fail to match the expected values below. 3849 if (EltWidth < CVal.getBitWidth()) 3850 CVal = CVal.trunc(EltWidth); 3851 3852 switch (getBooleanContents(N.getValueType())) { 3853 case UndefinedBooleanContent: 3854 return CVal[0]; 3855 case ZeroOrOneBooleanContent: 3856 return CVal.isOne(); 3857 case ZeroOrNegativeOneBooleanContent: 3858 return CVal.isAllOnes(); 3859 } 3860 3861 llvm_unreachable("Invalid boolean contents"); 3862 } 3863 3864 bool TargetLowering::isConstFalseVal(SDValue N) const { 3865 if (!N) 3866 return false; 3867 3868 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 3869 if (!CN) { 3870 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 3871 if (!BV) 3872 return false; 3873 3874 // Only interested in constant splats, we don't care about undef 3875 // elements in identifying boolean constants and getConstantSplatNode 3876 // returns NULL if all ops are undef; 3877 CN = BV->getConstantSplatNode(); 3878 if (!CN) 3879 return false; 3880 } 3881 3882 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 3883 return !CN->getAPIntValue()[0]; 3884 3885 return CN->isZero(); 3886 } 3887 3888 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 3889 bool SExt) const { 3890 if (VT == MVT::i1) 3891 return N->isOne(); 3892 3893 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 3894 switch (Cnt) { 3895 case TargetLowering::ZeroOrOneBooleanContent: 3896 // An extended value of 1 is always true, unless its original type is i1, 3897 // in which case it will be sign extended to -1. 3898 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 3899 case TargetLowering::UndefinedBooleanContent: 3900 case TargetLowering::ZeroOrNegativeOneBooleanContent: 3901 return N->isAllOnes() && SExt; 3902 } 3903 llvm_unreachable("Unexpected enumeration."); 3904 } 3905 3906 /// This helper function of SimplifySetCC tries to optimize the comparison when 3907 /// either operand of the SetCC node is a bitwise-and instruction. 3908 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 3909 ISD::CondCode Cond, const SDLoc &DL, 3910 DAGCombinerInfo &DCI) const { 3911 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 3912 std::swap(N0, N1); 3913 3914 SelectionDAG &DAG = DCI.DAG; 3915 EVT OpVT = N0.getValueType(); 3916 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 3917 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 3918 return SDValue(); 3919 3920 // (X & Y) != 0 --> zextOrTrunc(X & Y) 3921 // iff everything but LSB is known zero: 3922 if (Cond == ISD::SETNE && isNullConstant(N1) && 3923 (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent || 3924 getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) { 3925 unsigned NumEltBits = OpVT.getScalarSizeInBits(); 3926 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1); 3927 if (DAG.MaskedValueIsZero(N0, UpperBits)) 3928 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT); 3929 } 3930 3931 // Try to eliminate a power-of-2 mask constant by converting to a signbit 3932 // test in a narrow type that we can truncate to with no cost. Examples: 3933 // (i32 X & 32768) == 0 --> (trunc X to i16) >= 0 3934 // (i32 X & 32768) != 0 --> (trunc X to i16) < 0 3935 // TODO: This conservatively checks for type legality on the source and 3936 // destination types. That may inhibit optimizations, but it also 3937 // allows setcc->shift transforms that may be more beneficial. 3938 auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3939 if (AndC && isNullConstant(N1) && AndC->getAPIntValue().isPowerOf2() && 3940 isTypeLegal(OpVT) && N0.hasOneUse()) { 3941 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), 3942 AndC->getAPIntValue().getActiveBits()); 3943 if (isTruncateFree(OpVT, NarrowVT) && isTypeLegal(NarrowVT)) { 3944 SDValue Trunc = DAG.getZExtOrTrunc(N0.getOperand(0), DL, NarrowVT); 3945 SDValue Zero = DAG.getConstant(0, DL, NarrowVT); 3946 return DAG.getSetCC(DL, VT, Trunc, Zero, 3947 Cond == ISD::SETEQ ? ISD::SETGE : ISD::SETLT); 3948 } 3949 } 3950 3951 // Match these patterns in any of their permutations: 3952 // (X & Y) == Y 3953 // (X & Y) != Y 3954 SDValue X, Y; 3955 if (N0.getOperand(0) == N1) { 3956 X = N0.getOperand(1); 3957 Y = N0.getOperand(0); 3958 } else if (N0.getOperand(1) == N1) { 3959 X = N0.getOperand(0); 3960 Y = N0.getOperand(1); 3961 } else { 3962 return SDValue(); 3963 } 3964 3965 // TODO: We should invert (X & Y) eq/ne 0 -> (X & Y) ne/eq Y if 3966 // `isXAndYEqZeroPreferableToXAndYEqY` is false. This is a bit difficult as 3967 // its liable to create and infinite loop. 3968 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3969 if (isXAndYEqZeroPreferableToXAndYEqY(Cond, OpVT) && 3970 DAG.isKnownToBeAPowerOfTwo(Y)) { 3971 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 3972 // Note that where Y is variable and is known to have at most one bit set 3973 // (for example, if it is Z & 1) we cannot do this; the expressions are not 3974 // equivalent when Y == 0. 3975 assert(OpVT.isInteger()); 3976 Cond = ISD::getSetCCInverse(Cond, OpVT); 3977 if (DCI.isBeforeLegalizeOps() || 3978 isCondCodeLegal(Cond, N0.getSimpleValueType())) 3979 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 3980 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 3981 // If the target supports an 'and-not' or 'and-complement' logic operation, 3982 // try to use that to make a comparison operation more efficient. 3983 // But don't do this transform if the mask is a single bit because there are 3984 // more efficient ways to deal with that case (for example, 'bt' on x86 or 3985 // 'rlwinm' on PPC). 3986 3987 // Bail out if the compare operand that we want to turn into a zero is 3988 // already a zero (otherwise, infinite loop). 3989 if (isNullConstant(Y)) 3990 return SDValue(); 3991 3992 // Transform this into: ~X & Y == 0. 3993 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 3994 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 3995 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 3996 } 3997 3998 return SDValue(); 3999 } 4000 4001 /// There are multiple IR patterns that could be checking whether certain 4002 /// truncation of a signed number would be lossy or not. The pattern which is 4003 /// best at IR level, may not lower optimally. Thus, we want to unfold it. 4004 /// We are looking for the following pattern: (KeptBits is a constant) 4005 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits) 4006 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false. 4007 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0 4008 /// We will unfold it into the natural trunc+sext pattern: 4009 /// ((%x << C) a>> C) dstcond %x 4010 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x) 4011 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck( 4012 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI, 4013 const SDLoc &DL) const { 4014 // We must be comparing with a constant. 4015 ConstantSDNode *C1; 4016 if (!(C1 = dyn_cast<ConstantSDNode>(N1))) 4017 return SDValue(); 4018 4019 // N0 should be: add %x, (1 << (KeptBits-1)) 4020 if (N0->getOpcode() != ISD::ADD) 4021 return SDValue(); 4022 4023 // And we must be 'add'ing a constant. 4024 ConstantSDNode *C01; 4025 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1)))) 4026 return SDValue(); 4027 4028 SDValue X = N0->getOperand(0); 4029 EVT XVT = X.getValueType(); 4030 4031 // Validate constants ... 4032 4033 APInt I1 = C1->getAPIntValue(); 4034 4035 ISD::CondCode NewCond; 4036 if (Cond == ISD::CondCode::SETULT) { 4037 NewCond = ISD::CondCode::SETEQ; 4038 } else if (Cond == ISD::CondCode::SETULE) { 4039 NewCond = ISD::CondCode::SETEQ; 4040 // But need to 'canonicalize' the constant. 4041 I1 += 1; 4042 } else if (Cond == ISD::CondCode::SETUGT) { 4043 NewCond = ISD::CondCode::SETNE; 4044 // But need to 'canonicalize' the constant. 4045 I1 += 1; 4046 } else if (Cond == ISD::CondCode::SETUGE) { 4047 NewCond = ISD::CondCode::SETNE; 4048 } else 4049 return SDValue(); 4050 4051 APInt I01 = C01->getAPIntValue(); 4052 4053 auto checkConstants = [&I1, &I01]() -> bool { 4054 // Both of them must be power-of-two, and the constant from setcc is bigger. 4055 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2(); 4056 }; 4057 4058 if (checkConstants()) { 4059 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256 4060 } else { 4061 // What if we invert constants? (and the target predicate) 4062 I1.negate(); 4063 I01.negate(); 4064 assert(XVT.isInteger()); 4065 NewCond = getSetCCInverse(NewCond, XVT); 4066 if (!checkConstants()) 4067 return SDValue(); 4068 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256 4069 } 4070 4071 // They are power-of-two, so which bit is set? 4072 const unsigned KeptBits = I1.logBase2(); 4073 const unsigned KeptBitsMinusOne = I01.logBase2(); 4074 4075 // Magic! 4076 if (KeptBits != (KeptBitsMinusOne + 1)) 4077 return SDValue(); 4078 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable"); 4079 4080 // We don't want to do this in every single case. 4081 SelectionDAG &DAG = DCI.DAG; 4082 if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck( 4083 XVT, KeptBits)) 4084 return SDValue(); 4085 4086 const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits; 4087 assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable"); 4088 4089 // Unfold into: ((%x << C) a>> C) cond %x 4090 // Where 'cond' will be either 'eq' or 'ne'. 4091 SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT); 4092 SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt); 4093 SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt); 4094 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond); 4095 4096 return T2; 4097 } 4098 4099 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 4100 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift( 4101 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond, 4102 DAGCombinerInfo &DCI, const SDLoc &DL) const { 4103 assert(isConstOrConstSplat(N1C) && isConstOrConstSplat(N1C)->isZero() && 4104 "Should be a comparison with 0."); 4105 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4106 "Valid only for [in]equality comparisons."); 4107 4108 unsigned NewShiftOpcode; 4109 SDValue X, C, Y; 4110 4111 SelectionDAG &DAG = DCI.DAG; 4112 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4113 4114 // Look for '(C l>>/<< Y)'. 4115 auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) { 4116 // The shift should be one-use. 4117 if (!V.hasOneUse()) 4118 return false; 4119 unsigned OldShiftOpcode = V.getOpcode(); 4120 switch (OldShiftOpcode) { 4121 case ISD::SHL: 4122 NewShiftOpcode = ISD::SRL; 4123 break; 4124 case ISD::SRL: 4125 NewShiftOpcode = ISD::SHL; 4126 break; 4127 default: 4128 return false; // must be a logical shift. 4129 } 4130 // We should be shifting a constant. 4131 // FIXME: best to use isConstantOrConstantVector(). 4132 C = V.getOperand(0); 4133 ConstantSDNode *CC = 4134 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 4135 if (!CC) 4136 return false; 4137 Y = V.getOperand(1); 4138 4139 ConstantSDNode *XC = 4140 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 4141 return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 4142 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG); 4143 }; 4144 4145 // LHS of comparison should be an one-use 'and'. 4146 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 4147 return SDValue(); 4148 4149 X = N0.getOperand(0); 4150 SDValue Mask = N0.getOperand(1); 4151 4152 // 'and' is commutative! 4153 if (!Match(Mask)) { 4154 std::swap(X, Mask); 4155 if (!Match(Mask)) 4156 return SDValue(); 4157 } 4158 4159 EVT VT = X.getValueType(); 4160 4161 // Produce: 4162 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0 4163 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y); 4164 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C); 4165 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond); 4166 return T2; 4167 } 4168 4169 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as 4170 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to 4171 /// handle the commuted versions of these patterns. 4172 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, 4173 ISD::CondCode Cond, const SDLoc &DL, 4174 DAGCombinerInfo &DCI) const { 4175 unsigned BOpcode = N0.getOpcode(); 4176 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) && 4177 "Unexpected binop"); 4178 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode"); 4179 4180 // (X + Y) == X --> Y == 0 4181 // (X - Y) == X --> Y == 0 4182 // (X ^ Y) == X --> Y == 0 4183 SelectionDAG &DAG = DCI.DAG; 4184 EVT OpVT = N0.getValueType(); 4185 SDValue X = N0.getOperand(0); 4186 SDValue Y = N0.getOperand(1); 4187 if (X == N1) 4188 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond); 4189 4190 if (Y != N1) 4191 return SDValue(); 4192 4193 // (X + Y) == Y --> X == 0 4194 // (X ^ Y) == Y --> X == 0 4195 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR) 4196 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond); 4197 4198 // The shift would not be valid if the operands are boolean (i1). 4199 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1) 4200 return SDValue(); 4201 4202 // (X - Y) == Y --> X == Y << 1 4203 EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(), 4204 !DCI.isBeforeLegalize()); 4205 SDValue One = DAG.getConstant(1, DL, ShiftVT); 4206 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One); 4207 if (!DCI.isCalledByLegalizer()) 4208 DCI.AddToWorklist(YShl1.getNode()); 4209 return DAG.getSetCC(DL, VT, X, YShl1, Cond); 4210 } 4211 4212 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT, 4213 SDValue N0, const APInt &C1, 4214 ISD::CondCode Cond, const SDLoc &dl, 4215 SelectionDAG &DAG) { 4216 // Look through truncs that don't change the value of a ctpop. 4217 // FIXME: Add vector support? Need to be careful with setcc result type below. 4218 SDValue CTPOP = N0; 4219 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() && 4220 N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits())) 4221 CTPOP = N0.getOperand(0); 4222 4223 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse()) 4224 return SDValue(); 4225 4226 EVT CTVT = CTPOP.getValueType(); 4227 SDValue CTOp = CTPOP.getOperand(0); 4228 4229 // Expand a power-of-2-or-zero comparison based on ctpop: 4230 // (ctpop x) u< 2 -> (x & x-1) == 0 4231 // (ctpop x) u> 1 -> (x & x-1) != 0 4232 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) { 4233 // Keep the CTPOP if it is a cheap vector op. 4234 if (CTVT.isVector() && TLI.isCtpopFast(CTVT)) 4235 return SDValue(); 4236 4237 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond); 4238 if (C1.ugt(CostLimit + (Cond == ISD::SETULT))) 4239 return SDValue(); 4240 if (C1 == 0 && (Cond == ISD::SETULT)) 4241 return SDValue(); // This is handled elsewhere. 4242 4243 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT); 4244 4245 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 4246 SDValue Result = CTOp; 4247 for (unsigned i = 0; i < Passes; i++) { 4248 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne); 4249 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add); 4250 } 4251 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 4252 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC); 4253 } 4254 4255 // Expand a power-of-2 comparison based on ctpop 4256 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) { 4257 // Keep the CTPOP if it is cheap. 4258 if (TLI.isCtpopFast(CTVT)) 4259 return SDValue(); 4260 4261 SDValue Zero = DAG.getConstant(0, dl, CTVT); 4262 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 4263 assert(CTVT.isInteger()); 4264 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne); 4265 4266 // Its not uncommon for known-never-zero X to exist in (ctpop X) eq/ne 1, so 4267 // check before emitting a potentially unnecessary op. 4268 if (DAG.isKnownNeverZero(CTOp)) { 4269 // (ctpop x) == 1 --> (x & x-1) == 0 4270 // (ctpop x) != 1 --> (x & x-1) != 0 4271 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add); 4272 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond); 4273 return RHS; 4274 } 4275 4276 // (ctpop x) == 1 --> (x ^ x-1) > x-1 4277 // (ctpop x) != 1 --> (x ^ x-1) <= x-1 4278 SDValue Xor = DAG.getNode(ISD::XOR, dl, CTVT, CTOp, Add); 4279 ISD::CondCode CmpCond = Cond == ISD::SETEQ ? ISD::SETUGT : ISD::SETULE; 4280 return DAG.getSetCC(dl, VT, Xor, Add, CmpCond); 4281 } 4282 4283 return SDValue(); 4284 } 4285 4286 static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1, 4287 ISD::CondCode Cond, const SDLoc &dl, 4288 SelectionDAG &DAG) { 4289 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 4290 return SDValue(); 4291 4292 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 4293 if (!C1 || !(C1->isZero() || C1->isAllOnes())) 4294 return SDValue(); 4295 4296 auto getRotateSource = [](SDValue X) { 4297 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR) 4298 return X.getOperand(0); 4299 return SDValue(); 4300 }; 4301 4302 // Peek through a rotated value compared against 0 or -1: 4303 // (rot X, Y) == 0/-1 --> X == 0/-1 4304 // (rot X, Y) != 0/-1 --> X != 0/-1 4305 if (SDValue R = getRotateSource(N0)) 4306 return DAG.getSetCC(dl, VT, R, N1, Cond); 4307 4308 // Peek through an 'or' of a rotated value compared against 0: 4309 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0 4310 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0 4311 // 4312 // TODO: Add the 'and' with -1 sibling. 4313 // TODO: Recurse through a series of 'or' ops to find the rotate. 4314 EVT OpVT = N0.getValueType(); 4315 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) { 4316 if (SDValue R = getRotateSource(N0.getOperand(0))) { 4317 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1)); 4318 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4319 } 4320 if (SDValue R = getRotateSource(N0.getOperand(1))) { 4321 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0)); 4322 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4323 } 4324 } 4325 4326 return SDValue(); 4327 } 4328 4329 static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1, 4330 ISD::CondCode Cond, const SDLoc &dl, 4331 SelectionDAG &DAG) { 4332 // If we are testing for all-bits-clear, we might be able to do that with 4333 // less shifting since bit-order does not matter. 4334 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 4335 return SDValue(); 4336 4337 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 4338 if (!C1 || !C1->isZero()) 4339 return SDValue(); 4340 4341 if (!N0.hasOneUse() || 4342 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR)) 4343 return SDValue(); 4344 4345 unsigned BitWidth = N0.getScalarValueSizeInBits(); 4346 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2)); 4347 if (!ShAmtC || ShAmtC->getAPIntValue().uge(BitWidth)) 4348 return SDValue(); 4349 4350 // Canonicalize fshr as fshl to reduce pattern-matching. 4351 unsigned ShAmt = ShAmtC->getZExtValue(); 4352 if (N0.getOpcode() == ISD::FSHR) 4353 ShAmt = BitWidth - ShAmt; 4354 4355 // Match an 'or' with a specific operand 'Other' in either commuted variant. 4356 SDValue X, Y; 4357 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) { 4358 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse()) 4359 return false; 4360 if (Or.getOperand(0) == Other) { 4361 X = Or.getOperand(0); 4362 Y = Or.getOperand(1); 4363 return true; 4364 } 4365 if (Or.getOperand(1) == Other) { 4366 X = Or.getOperand(1); 4367 Y = Or.getOperand(0); 4368 return true; 4369 } 4370 return false; 4371 }; 4372 4373 EVT OpVT = N0.getValueType(); 4374 EVT ShAmtVT = N0.getOperand(2).getValueType(); 4375 SDValue F0 = N0.getOperand(0); 4376 SDValue F1 = N0.getOperand(1); 4377 if (matchOr(F0, F1)) { 4378 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0 4379 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT); 4380 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt); 4381 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 4382 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4383 } 4384 if (matchOr(F1, F0)) { 4385 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0 4386 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT); 4387 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt); 4388 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 4389 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4390 } 4391 4392 return SDValue(); 4393 } 4394 4395 /// Try to simplify a setcc built with the specified operands and cc. If it is 4396 /// unable to simplify it, return a null SDValue. 4397 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 4398 ISD::CondCode Cond, bool foldBooleans, 4399 DAGCombinerInfo &DCI, 4400 const SDLoc &dl) const { 4401 SelectionDAG &DAG = DCI.DAG; 4402 const DataLayout &Layout = DAG.getDataLayout(); 4403 EVT OpVT = N0.getValueType(); 4404 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4405 4406 // Constant fold or commute setcc. 4407 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl)) 4408 return Fold; 4409 4410 bool N0ConstOrSplat = 4411 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 4412 bool N1ConstOrSplat = 4413 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 4414 4415 // Canonicalize toward having the constant on the RHS. 4416 // TODO: Handle non-splat vector constants. All undef causes trouble. 4417 // FIXME: We can't yet fold constant scalable vector splats, so avoid an 4418 // infinite loop here when we encounter one. 4419 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 4420 if (N0ConstOrSplat && !N1ConstOrSplat && 4421 (DCI.isBeforeLegalizeOps() || 4422 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 4423 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4424 4425 // If we have a subtract with the same 2 non-constant operands as this setcc 4426 // -- but in reverse order -- then try to commute the operands of this setcc 4427 // to match. A matching pair of setcc (cmp) and sub may be combined into 1 4428 // instruction on some targets. 4429 if (!N0ConstOrSplat && !N1ConstOrSplat && 4430 (DCI.isBeforeLegalizeOps() || 4431 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) && 4432 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) && 4433 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1})) 4434 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4435 4436 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG)) 4437 return V; 4438 4439 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG)) 4440 return V; 4441 4442 if (auto *N1C = isConstOrConstSplat(N1)) { 4443 const APInt &C1 = N1C->getAPIntValue(); 4444 4445 // Optimize some CTPOP cases. 4446 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG)) 4447 return V; 4448 4449 // For equality to 0 of a no-wrap multiply, decompose and test each op: 4450 // X * Y == 0 --> (X == 0) || (Y == 0) 4451 // X * Y != 0 --> (X != 0) && (Y != 0) 4452 // TODO: This bails out if minsize is set, but if the target doesn't have a 4453 // single instruction multiply for this type, it would likely be 4454 // smaller to decompose. 4455 if (C1.isZero() && (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4456 N0.getOpcode() == ISD::MUL && N0.hasOneUse() && 4457 (N0->getFlags().hasNoUnsignedWrap() || 4458 N0->getFlags().hasNoSignedWrap()) && 4459 !Attr.hasFnAttr(Attribute::MinSize)) { 4460 SDValue IsXZero = DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 4461 SDValue IsYZero = DAG.getSetCC(dl, VT, N0.getOperand(1), N1, Cond); 4462 unsigned LogicOp = Cond == ISD::SETEQ ? ISD::OR : ISD::AND; 4463 return DAG.getNode(LogicOp, dl, VT, IsXZero, IsYZero); 4464 } 4465 4466 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 4467 // equality comparison, then we're just comparing whether X itself is 4468 // zero. 4469 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) && 4470 N0.getOperand(0).getOpcode() == ISD::CTLZ && 4471 llvm::has_single_bit<uint32_t>(N0.getScalarValueSizeInBits())) { 4472 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) { 4473 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4474 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) { 4475 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 4476 // (srl (ctlz x), 5) == 0 -> X != 0 4477 // (srl (ctlz x), 5) != 1 -> X != 0 4478 Cond = ISD::SETNE; 4479 } else { 4480 // (srl (ctlz x), 5) != 0 -> X == 0 4481 // (srl (ctlz x), 5) == 1 -> X == 0 4482 Cond = ISD::SETEQ; 4483 } 4484 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 4485 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero, 4486 Cond); 4487 } 4488 } 4489 } 4490 } 4491 4492 // FIXME: Support vectors. 4493 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4494 const APInt &C1 = N1C->getAPIntValue(); 4495 4496 // (zext x) == C --> x == (trunc C) 4497 // (sext x) == C --> x == (trunc C) 4498 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4499 DCI.isBeforeLegalize() && N0->hasOneUse()) { 4500 unsigned MinBits = N0.getValueSizeInBits(); 4501 SDValue PreExt; 4502 bool Signed = false; 4503 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 4504 // ZExt 4505 MinBits = N0->getOperand(0).getValueSizeInBits(); 4506 PreExt = N0->getOperand(0); 4507 } else if (N0->getOpcode() == ISD::AND) { 4508 // DAGCombine turns costly ZExts into ANDs 4509 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 4510 if ((C->getAPIntValue()+1).isPowerOf2()) { 4511 MinBits = C->getAPIntValue().countr_one(); 4512 PreExt = N0->getOperand(0); 4513 } 4514 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 4515 // SExt 4516 MinBits = N0->getOperand(0).getValueSizeInBits(); 4517 PreExt = N0->getOperand(0); 4518 Signed = true; 4519 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 4520 // ZEXTLOAD / SEXTLOAD 4521 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 4522 MinBits = LN0->getMemoryVT().getSizeInBits(); 4523 PreExt = N0; 4524 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 4525 Signed = true; 4526 MinBits = LN0->getMemoryVT().getSizeInBits(); 4527 PreExt = N0; 4528 } 4529 } 4530 4531 // Figure out how many bits we need to preserve this constant. 4532 unsigned ReqdBits = Signed ? C1.getSignificantBits() : C1.getActiveBits(); 4533 4534 // Make sure we're not losing bits from the constant. 4535 if (MinBits > 0 && 4536 MinBits < C1.getBitWidth() && 4537 MinBits >= ReqdBits) { 4538 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 4539 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 4540 // Will get folded away. 4541 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 4542 if (MinBits == 1 && C1 == 1) 4543 // Invert the condition. 4544 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 4545 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4546 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 4547 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 4548 } 4549 4550 // If truncating the setcc operands is not desirable, we can still 4551 // simplify the expression in some cases: 4552 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 4553 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 4554 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 4555 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 4556 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 4557 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 4558 SDValue TopSetCC = N0->getOperand(0); 4559 unsigned N0Opc = N0->getOpcode(); 4560 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 4561 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 4562 TopSetCC.getOpcode() == ISD::SETCC && 4563 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 4564 (isConstFalseVal(N1) || 4565 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 4566 4567 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) || 4568 (!N1C->isZero() && Cond == ISD::SETNE); 4569 4570 if (!Inverse) 4571 return TopSetCC; 4572 4573 ISD::CondCode InvCond = ISD::getSetCCInverse( 4574 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 4575 TopSetCC.getOperand(0).getValueType()); 4576 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 4577 TopSetCC.getOperand(1), 4578 InvCond); 4579 } 4580 } 4581 } 4582 4583 // If the LHS is '(and load, const)', the RHS is 0, the test is for 4584 // equality or unsigned, and all 1 bits of the const are in the same 4585 // partial word, see if we can shorten the load. 4586 if (DCI.isBeforeLegalize() && 4587 !ISD::isSignedIntSetCC(Cond) && 4588 N0.getOpcode() == ISD::AND && C1 == 0 && 4589 N0.getNode()->hasOneUse() && 4590 isa<LoadSDNode>(N0.getOperand(0)) && 4591 N0.getOperand(0).getNode()->hasOneUse() && 4592 isa<ConstantSDNode>(N0.getOperand(1))) { 4593 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 4594 APInt bestMask; 4595 unsigned bestWidth = 0, bestOffset = 0; 4596 if (Lod->isSimple() && Lod->isUnindexed()) { 4597 unsigned origWidth = N0.getValueSizeInBits(); 4598 unsigned maskWidth = origWidth; 4599 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 4600 // 8 bits, but have to be careful... 4601 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 4602 origWidth = Lod->getMemoryVT().getSizeInBits(); 4603 const APInt &Mask = N0.getConstantOperandAPInt(1); 4604 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 4605 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 4606 for (unsigned offset=0; offset<origWidth/width; offset++) { 4607 if (Mask.isSubsetOf(newMask)) { 4608 if (Layout.isLittleEndian()) 4609 bestOffset = (uint64_t)offset * (width/8); 4610 else 4611 bestOffset = (origWidth/width - offset - 1) * (width/8); 4612 bestMask = Mask.lshr(offset * (width/8) * 8); 4613 bestWidth = width; 4614 break; 4615 } 4616 newMask <<= width; 4617 } 4618 } 4619 } 4620 if (bestWidth) { 4621 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 4622 if (newVT.isRound() && 4623 shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) { 4624 SDValue Ptr = Lod->getBasePtr(); 4625 if (bestOffset != 0) 4626 Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::getFixed(bestOffset), 4627 dl); 4628 SDValue NewLoad = 4629 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr, 4630 Lod->getPointerInfo().getWithOffset(bestOffset), 4631 Lod->getOriginalAlign()); 4632 return DAG.getSetCC(dl, VT, 4633 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 4634 DAG.getConstant(bestMask.trunc(bestWidth), 4635 dl, newVT)), 4636 DAG.getConstant(0LL, dl, newVT), Cond); 4637 } 4638 } 4639 } 4640 4641 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 4642 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 4643 unsigned InSize = N0.getOperand(0).getValueSizeInBits(); 4644 4645 // If the comparison constant has bits in the upper part, the 4646 // zero-extended value could never match. 4647 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 4648 C1.getBitWidth() - InSize))) { 4649 switch (Cond) { 4650 case ISD::SETUGT: 4651 case ISD::SETUGE: 4652 case ISD::SETEQ: 4653 return DAG.getConstant(0, dl, VT); 4654 case ISD::SETULT: 4655 case ISD::SETULE: 4656 case ISD::SETNE: 4657 return DAG.getConstant(1, dl, VT); 4658 case ISD::SETGT: 4659 case ISD::SETGE: 4660 // True if the sign bit of C1 is set. 4661 return DAG.getConstant(C1.isNegative(), dl, VT); 4662 case ISD::SETLT: 4663 case ISD::SETLE: 4664 // True if the sign bit of C1 isn't set. 4665 return DAG.getConstant(C1.isNonNegative(), dl, VT); 4666 default: 4667 break; 4668 } 4669 } 4670 4671 // Otherwise, we can perform the comparison with the low bits. 4672 switch (Cond) { 4673 case ISD::SETEQ: 4674 case ISD::SETNE: 4675 case ISD::SETUGT: 4676 case ISD::SETUGE: 4677 case ISD::SETULT: 4678 case ISD::SETULE: { 4679 EVT newVT = N0.getOperand(0).getValueType(); 4680 if (DCI.isBeforeLegalizeOps() || 4681 (isOperationLegal(ISD::SETCC, newVT) && 4682 isCondCodeLegal(Cond, newVT.getSimpleVT()))) { 4683 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT); 4684 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 4685 4686 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 4687 NewConst, Cond); 4688 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 4689 } 4690 break; 4691 } 4692 default: 4693 break; // todo, be more careful with signed comparisons 4694 } 4695 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 4696 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4697 !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(), 4698 OpVT)) { 4699 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 4700 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 4701 EVT ExtDstTy = N0.getValueType(); 4702 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 4703 4704 // If the constant doesn't fit into the number of bits for the source of 4705 // the sign extension, it is impossible for both sides to be equal. 4706 if (C1.getSignificantBits() > ExtSrcTyBits) 4707 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT); 4708 4709 assert(ExtDstTy == N0.getOperand(0).getValueType() && 4710 ExtDstTy != ExtSrcTy && "Unexpected types!"); 4711 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 4712 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0), 4713 DAG.getConstant(Imm, dl, ExtDstTy)); 4714 if (!DCI.isCalledByLegalizer()) 4715 DCI.AddToWorklist(ZextOp.getNode()); 4716 // Otherwise, make this a use of a zext. 4717 return DAG.getSetCC(dl, VT, ZextOp, 4718 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond); 4719 } else if ((N1C->isZero() || N1C->isOne()) && 4720 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4721 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 4722 if (N0.getOpcode() == ISD::SETCC && 4723 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) && 4724 (N0.getValueType() == MVT::i1 || 4725 getBooleanContents(N0.getOperand(0).getValueType()) == 4726 ZeroOrOneBooleanContent)) { 4727 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne()); 4728 if (TrueWhenTrue) 4729 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 4730 // Invert the condition. 4731 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4732 CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType()); 4733 if (DCI.isBeforeLegalizeOps() || 4734 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 4735 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 4736 } 4737 4738 if ((N0.getOpcode() == ISD::XOR || 4739 (N0.getOpcode() == ISD::AND && 4740 N0.getOperand(0).getOpcode() == ISD::XOR && 4741 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 4742 isOneConstant(N0.getOperand(1))) { 4743 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 4744 // can only do this if the top bits are known zero. 4745 unsigned BitWidth = N0.getValueSizeInBits(); 4746 if (DAG.MaskedValueIsZero(N0, 4747 APInt::getHighBitsSet(BitWidth, 4748 BitWidth-1))) { 4749 // Okay, get the un-inverted input value. 4750 SDValue Val; 4751 if (N0.getOpcode() == ISD::XOR) { 4752 Val = N0.getOperand(0); 4753 } else { 4754 assert(N0.getOpcode() == ISD::AND && 4755 N0.getOperand(0).getOpcode() == ISD::XOR); 4756 // ((X^1)&1)^1 -> X & 1 4757 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 4758 N0.getOperand(0).getOperand(0), 4759 N0.getOperand(1)); 4760 } 4761 4762 return DAG.getSetCC(dl, VT, Val, N1, 4763 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4764 } 4765 } else if (N1C->isOne()) { 4766 SDValue Op0 = N0; 4767 if (Op0.getOpcode() == ISD::TRUNCATE) 4768 Op0 = Op0.getOperand(0); 4769 4770 if ((Op0.getOpcode() == ISD::XOR) && 4771 Op0.getOperand(0).getOpcode() == ISD::SETCC && 4772 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 4773 SDValue XorLHS = Op0.getOperand(0); 4774 SDValue XorRHS = Op0.getOperand(1); 4775 // Ensure that the input setccs return an i1 type or 0/1 value. 4776 if (Op0.getValueType() == MVT::i1 || 4777 (getBooleanContents(XorLHS.getOperand(0).getValueType()) == 4778 ZeroOrOneBooleanContent && 4779 getBooleanContents(XorRHS.getOperand(0).getValueType()) == 4780 ZeroOrOneBooleanContent)) { 4781 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 4782 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 4783 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond); 4784 } 4785 } 4786 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) { 4787 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 4788 if (Op0.getValueType().bitsGT(VT)) 4789 Op0 = DAG.getNode(ISD::AND, dl, VT, 4790 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 4791 DAG.getConstant(1, dl, VT)); 4792 else if (Op0.getValueType().bitsLT(VT)) 4793 Op0 = DAG.getNode(ISD::AND, dl, VT, 4794 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 4795 DAG.getConstant(1, dl, VT)); 4796 4797 return DAG.getSetCC(dl, VT, Op0, 4798 DAG.getConstant(0, dl, Op0.getValueType()), 4799 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4800 } 4801 if (Op0.getOpcode() == ISD::AssertZext && 4802 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 4803 return DAG.getSetCC(dl, VT, Op0, 4804 DAG.getConstant(0, dl, Op0.getValueType()), 4805 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4806 } 4807 } 4808 4809 // Given: 4810 // icmp eq/ne (urem %x, %y), 0 4811 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem': 4812 // icmp eq/ne %x, 0 4813 if (N0.getOpcode() == ISD::UREM && N1C->isZero() && 4814 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4815 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0)); 4816 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1)); 4817 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2) 4818 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 4819 } 4820 4821 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0 4822 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0 4823 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4824 N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) && 4825 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 && 4826 N1C && N1C->isAllOnes()) { 4827 return DAG.getSetCC(dl, VT, N0.getOperand(0), 4828 DAG.getConstant(0, dl, OpVT), 4829 Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE); 4830 } 4831 4832 if (SDValue V = 4833 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl)) 4834 return V; 4835 } 4836 4837 // These simplifications apply to splat vectors as well. 4838 // TODO: Handle more splat vector cases. 4839 if (auto *N1C = isConstOrConstSplat(N1)) { 4840 const APInt &C1 = N1C->getAPIntValue(); 4841 4842 APInt MinVal, MaxVal; 4843 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits(); 4844 if (ISD::isSignedIntSetCC(Cond)) { 4845 MinVal = APInt::getSignedMinValue(OperandBitSize); 4846 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 4847 } else { 4848 MinVal = APInt::getMinValue(OperandBitSize); 4849 MaxVal = APInt::getMaxValue(OperandBitSize); 4850 } 4851 4852 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 4853 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 4854 // X >= MIN --> true 4855 if (C1 == MinVal) 4856 return DAG.getBoolConstant(true, dl, VT, OpVT); 4857 4858 if (!VT.isVector()) { // TODO: Support this for vectors. 4859 // X >= C0 --> X > (C0 - 1) 4860 APInt C = C1 - 1; 4861 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 4862 if ((DCI.isBeforeLegalizeOps() || 4863 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4864 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4865 isLegalICmpImmediate(C.getSExtValue())))) { 4866 return DAG.getSetCC(dl, VT, N0, 4867 DAG.getConstant(C, dl, N1.getValueType()), 4868 NewCC); 4869 } 4870 } 4871 } 4872 4873 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 4874 // X <= MAX --> true 4875 if (C1 == MaxVal) 4876 return DAG.getBoolConstant(true, dl, VT, OpVT); 4877 4878 // X <= C0 --> X < (C0 + 1) 4879 if (!VT.isVector()) { // TODO: Support this for vectors. 4880 APInt C = C1 + 1; 4881 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 4882 if ((DCI.isBeforeLegalizeOps() || 4883 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4884 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4885 isLegalICmpImmediate(C.getSExtValue())))) { 4886 return DAG.getSetCC(dl, VT, N0, 4887 DAG.getConstant(C, dl, N1.getValueType()), 4888 NewCC); 4889 } 4890 } 4891 } 4892 4893 if (Cond == ISD::SETLT || Cond == ISD::SETULT) { 4894 if (C1 == MinVal) 4895 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false 4896 4897 // TODO: Support this for vectors after legalize ops. 4898 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4899 // Canonicalize setlt X, Max --> setne X, Max 4900 if (C1 == MaxVal) 4901 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 4902 4903 // If we have setult X, 1, turn it into seteq X, 0 4904 if (C1 == MinVal+1) 4905 return DAG.getSetCC(dl, VT, N0, 4906 DAG.getConstant(MinVal, dl, N0.getValueType()), 4907 ISD::SETEQ); 4908 } 4909 } 4910 4911 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) { 4912 if (C1 == MaxVal) 4913 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false 4914 4915 // TODO: Support this for vectors after legalize ops. 4916 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4917 // Canonicalize setgt X, Min --> setne X, Min 4918 if (C1 == MinVal) 4919 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 4920 4921 // If we have setugt X, Max-1, turn it into seteq X, Max 4922 if (C1 == MaxVal-1) 4923 return DAG.getSetCC(dl, VT, N0, 4924 DAG.getConstant(MaxVal, dl, N0.getValueType()), 4925 ISD::SETEQ); 4926 } 4927 } 4928 4929 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) { 4930 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 4931 if (C1.isZero()) 4932 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift( 4933 VT, N0, N1, Cond, DCI, dl)) 4934 return CC; 4935 4936 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y). 4937 // For example, when high 32-bits of i64 X are known clear: 4938 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0 4939 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1 4940 bool CmpZero = N1C->isZero(); 4941 bool CmpNegOne = N1C->isAllOnes(); 4942 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) { 4943 // Match or(lo,shl(hi,bw/2)) pattern. 4944 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) { 4945 unsigned EltBits = V.getScalarValueSizeInBits(); 4946 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0) 4947 return false; 4948 SDValue LHS = V.getOperand(0); 4949 SDValue RHS = V.getOperand(1); 4950 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2); 4951 // Unshifted element must have zero upperbits. 4952 if (RHS.getOpcode() == ISD::SHL && 4953 isa<ConstantSDNode>(RHS.getOperand(1)) && 4954 RHS.getConstantOperandAPInt(1) == (EltBits / 2) && 4955 DAG.MaskedValueIsZero(LHS, HiBits)) { 4956 Lo = LHS; 4957 Hi = RHS.getOperand(0); 4958 return true; 4959 } 4960 if (LHS.getOpcode() == ISD::SHL && 4961 isa<ConstantSDNode>(LHS.getOperand(1)) && 4962 LHS.getConstantOperandAPInt(1) == (EltBits / 2) && 4963 DAG.MaskedValueIsZero(RHS, HiBits)) { 4964 Lo = RHS; 4965 Hi = LHS.getOperand(0); 4966 return true; 4967 } 4968 return false; 4969 }; 4970 4971 auto MergeConcat = [&](SDValue Lo, SDValue Hi) { 4972 unsigned EltBits = N0.getScalarValueSizeInBits(); 4973 unsigned HalfBits = EltBits / 2; 4974 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits); 4975 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT); 4976 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits); 4977 SDValue NewN0 = 4978 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask); 4979 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits; 4980 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond); 4981 }; 4982 4983 SDValue Lo, Hi; 4984 if (IsConcat(N0, Lo, Hi)) 4985 return MergeConcat(Lo, Hi); 4986 4987 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) { 4988 SDValue Lo0, Lo1, Hi0, Hi1; 4989 if (IsConcat(N0.getOperand(0), Lo0, Hi0) && 4990 IsConcat(N0.getOperand(1), Lo1, Hi1)) { 4991 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1), 4992 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1)); 4993 } 4994 } 4995 } 4996 } 4997 4998 // If we have "setcc X, C0", check to see if we can shrink the immediate 4999 // by changing cc. 5000 // TODO: Support this for vectors after legalize ops. 5001 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 5002 // SETUGT X, SINTMAX -> SETLT X, 0 5003 // SETUGE X, SINTMIN -> SETLT X, 0 5004 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) || 5005 (Cond == ISD::SETUGE && C1.isMinSignedValue())) 5006 return DAG.getSetCC(dl, VT, N0, 5007 DAG.getConstant(0, dl, N1.getValueType()), 5008 ISD::SETLT); 5009 5010 // SETULT X, SINTMIN -> SETGT X, -1 5011 // SETULE X, SINTMAX -> SETGT X, -1 5012 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) || 5013 (Cond == ISD::SETULE && C1.isMaxSignedValue())) 5014 return DAG.getSetCC(dl, VT, N0, 5015 DAG.getAllOnesConstant(dl, N1.getValueType()), 5016 ISD::SETGT); 5017 } 5018 } 5019 5020 // Back to non-vector simplifications. 5021 // TODO: Can we do these for vector splats? 5022 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 5023 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5024 const APInt &C1 = N1C->getAPIntValue(); 5025 EVT ShValTy = N0.getValueType(); 5026 5027 // Fold bit comparisons when we can. This will result in an 5028 // incorrect value when boolean false is negative one, unless 5029 // the bitsize is 1 in which case the false value is the same 5030 // in practice regardless of the representation. 5031 if ((VT.getSizeInBits() == 1 || 5032 getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) && 5033 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5034 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) && 5035 N0.getOpcode() == ISD::AND) { 5036 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5037 EVT ShiftTy = 5038 getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 5039 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 5040 // Perform the xform if the AND RHS is a single bit. 5041 unsigned ShCt = AndRHS->getAPIntValue().logBase2(); 5042 if (AndRHS->getAPIntValue().isPowerOf2() && 5043 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 5044 return DAG.getNode(ISD::TRUNCATE, dl, VT, 5045 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 5046 DAG.getConstant(ShCt, dl, ShiftTy))); 5047 } 5048 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 5049 // (X & 8) == 8 --> (X & 8) >> 3 5050 // Perform the xform if C1 is a single bit. 5051 unsigned ShCt = C1.logBase2(); 5052 if (C1.isPowerOf2() && 5053 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 5054 return DAG.getNode(ISD::TRUNCATE, dl, VT, 5055 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 5056 DAG.getConstant(ShCt, dl, ShiftTy))); 5057 } 5058 } 5059 } 5060 } 5061 5062 if (C1.getSignificantBits() <= 64 && 5063 !isLegalICmpImmediate(C1.getSExtValue())) { 5064 EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 5065 // (X & -256) == 256 -> (X >> 8) == 1 5066 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5067 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 5068 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5069 const APInt &AndRHSC = AndRHS->getAPIntValue(); 5070 if (AndRHSC.isNegatedPowerOf2() && (AndRHSC & C1) == C1) { 5071 unsigned ShiftBits = AndRHSC.countr_zero(); 5072 if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 5073 SDValue Shift = 5074 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0), 5075 DAG.getConstant(ShiftBits, dl, ShiftTy)); 5076 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy); 5077 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 5078 } 5079 } 5080 } 5081 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 5082 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 5083 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 5084 // X < 0x100000000 -> (X >> 32) < 1 5085 // X >= 0x100000000 -> (X >> 32) >= 1 5086 // X <= 0x0ffffffff -> (X >> 32) < 1 5087 // X > 0x0ffffffff -> (X >> 32) >= 1 5088 unsigned ShiftBits; 5089 APInt NewC = C1; 5090 ISD::CondCode NewCond = Cond; 5091 if (AdjOne) { 5092 ShiftBits = C1.countr_one(); 5093 NewC = NewC + 1; 5094 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 5095 } else { 5096 ShiftBits = C1.countr_zero(); 5097 } 5098 NewC.lshrInPlace(ShiftBits); 5099 if (ShiftBits && NewC.getSignificantBits() <= 64 && 5100 isLegalICmpImmediate(NewC.getSExtValue()) && 5101 !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 5102 SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0, 5103 DAG.getConstant(ShiftBits, dl, ShiftTy)); 5104 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy); 5105 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 5106 } 5107 } 5108 } 5109 } 5110 5111 if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) { 5112 auto *CFP = cast<ConstantFPSDNode>(N1); 5113 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value"); 5114 5115 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 5116 // constant if knowing that the operand is non-nan is enough. We prefer to 5117 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 5118 // materialize 0.0. 5119 if (Cond == ISD::SETO || Cond == ISD::SETUO) 5120 return DAG.getSetCC(dl, VT, N0, N0, Cond); 5121 5122 // setcc (fneg x), C -> setcc swap(pred) x, -C 5123 if (N0.getOpcode() == ISD::FNEG) { 5124 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 5125 if (DCI.isBeforeLegalizeOps() || 5126 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 5127 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 5128 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 5129 } 5130 } 5131 5132 // setueq/setoeq X, (fabs Inf) -> is_fpclass X, fcInf 5133 if (isOperationLegalOrCustom(ISD::IS_FPCLASS, N0.getValueType()) && 5134 !isFPImmLegal(CFP->getValueAPF(), CFP->getValueType(0))) { 5135 bool IsFabs = N0.getOpcode() == ISD::FABS; 5136 SDValue Op = IsFabs ? N0.getOperand(0) : N0; 5137 if ((Cond == ISD::SETOEQ || Cond == ISD::SETUEQ) && CFP->isInfinity()) { 5138 FPClassTest Flag = CFP->isNegative() ? (IsFabs ? fcNone : fcNegInf) 5139 : (IsFabs ? fcInf : fcPosInf); 5140 if (Cond == ISD::SETUEQ) 5141 Flag |= fcNan; 5142 return DAG.getNode(ISD::IS_FPCLASS, dl, VT, Op, 5143 DAG.getTargetConstant(Flag, dl, MVT::i32)); 5144 } 5145 } 5146 5147 // If the condition is not legal, see if we can find an equivalent one 5148 // which is legal. 5149 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 5150 // If the comparison was an awkward floating-point == or != and one of 5151 // the comparison operands is infinity or negative infinity, convert the 5152 // condition to a less-awkward <= or >=. 5153 if (CFP->getValueAPF().isInfinity()) { 5154 bool IsNegInf = CFP->getValueAPF().isNegative(); 5155 ISD::CondCode NewCond = ISD::SETCC_INVALID; 5156 switch (Cond) { 5157 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break; 5158 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break; 5159 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break; 5160 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break; 5161 default: break; 5162 } 5163 if (NewCond != ISD::SETCC_INVALID && 5164 isCondCodeLegal(NewCond, N0.getSimpleValueType())) 5165 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 5166 } 5167 } 5168 } 5169 5170 if (N0 == N1) { 5171 // The sext(setcc()) => setcc() optimization relies on the appropriate 5172 // constant being emitted. 5173 assert(!N0.getValueType().isInteger() && 5174 "Integer types should be handled by FoldSetCC"); 5175 5176 bool EqTrue = ISD::isTrueWhenEqual(Cond); 5177 unsigned UOF = ISD::getUnorderedFlavor(Cond); 5178 if (UOF == 2) // FP operators that are undefined on NaNs. 5179 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 5180 if (UOF == unsigned(EqTrue)) 5181 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 5182 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 5183 // if it is not already. 5184 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 5185 if (NewCond != Cond && 5186 (DCI.isBeforeLegalizeOps() || 5187 isCondCodeLegal(NewCond, N0.getSimpleValueType()))) 5188 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 5189 } 5190 5191 // ~X > ~Y --> Y > X 5192 // ~X < ~Y --> Y < X 5193 // ~X < C --> X > ~C 5194 // ~X > C --> X < ~C 5195 if ((isSignedIntSetCC(Cond) || isUnsignedIntSetCC(Cond)) && 5196 N0.getValueType().isInteger()) { 5197 if (isBitwiseNot(N0)) { 5198 if (isBitwiseNot(N1)) 5199 return DAG.getSetCC(dl, VT, N1.getOperand(0), N0.getOperand(0), Cond); 5200 5201 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 5202 !DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(0))) { 5203 SDValue Not = DAG.getNOT(dl, N1, OpVT); 5204 return DAG.getSetCC(dl, VT, Not, N0.getOperand(0), Cond); 5205 } 5206 } 5207 } 5208 5209 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5210 N0.getValueType().isInteger()) { 5211 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 5212 N0.getOpcode() == ISD::XOR) { 5213 // Simplify (X+Y) == (X+Z) --> Y == Z 5214 if (N0.getOpcode() == N1.getOpcode()) { 5215 if (N0.getOperand(0) == N1.getOperand(0)) 5216 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 5217 if (N0.getOperand(1) == N1.getOperand(1)) 5218 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 5219 if (isCommutativeBinOp(N0.getOpcode())) { 5220 // If X op Y == Y op X, try other combinations. 5221 if (N0.getOperand(0) == N1.getOperand(1)) 5222 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 5223 Cond); 5224 if (N0.getOperand(1) == N1.getOperand(0)) 5225 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 5226 Cond); 5227 } 5228 } 5229 5230 // If RHS is a legal immediate value for a compare instruction, we need 5231 // to be careful about increasing register pressure needlessly. 5232 bool LegalRHSImm = false; 5233 5234 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 5235 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5236 // Turn (X+C1) == C2 --> X == C2-C1 5237 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) 5238 return DAG.getSetCC( 5239 dl, VT, N0.getOperand(0), 5240 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(), 5241 dl, N0.getValueType()), 5242 Cond); 5243 5244 // Turn (X^C1) == C2 --> X == C1^C2 5245 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse()) 5246 return DAG.getSetCC( 5247 dl, VT, N0.getOperand(0), 5248 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(), 5249 dl, N0.getValueType()), 5250 Cond); 5251 } 5252 5253 // Turn (C1-X) == C2 --> X == C1-C2 5254 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 5255 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) 5256 return DAG.getSetCC( 5257 dl, VT, N0.getOperand(1), 5258 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(), 5259 dl, N0.getValueType()), 5260 Cond); 5261 5262 // Could RHSC fold directly into a compare? 5263 if (RHSC->getValueType(0).getSizeInBits() <= 64) 5264 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 5265 } 5266 5267 // (X+Y) == X --> Y == 0 and similar folds. 5268 // Don't do this if X is an immediate that can fold into a cmp 5269 // instruction and X+Y has other uses. It could be an induction variable 5270 // chain, and the transform would increase register pressure. 5271 if (!LegalRHSImm || N0.hasOneUse()) 5272 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI)) 5273 return V; 5274 } 5275 5276 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 5277 N1.getOpcode() == ISD::XOR) 5278 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI)) 5279 return V; 5280 5281 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI)) 5282 return V; 5283 } 5284 5285 // Fold remainder of division by a constant. 5286 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) && 5287 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 5288 // When division is cheap or optimizing for minimum size, 5289 // fall through to DIVREM creation by skipping this fold. 5290 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) { 5291 if (N0.getOpcode() == ISD::UREM) { 5292 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl)) 5293 return Folded; 5294 } else if (N0.getOpcode() == ISD::SREM) { 5295 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl)) 5296 return Folded; 5297 } 5298 } 5299 } 5300 5301 // Fold away ALL boolean setcc's. 5302 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) { 5303 SDValue Temp; 5304 switch (Cond) { 5305 default: llvm_unreachable("Unknown integer setcc!"); 5306 case ISD::SETEQ: // X == Y -> ~(X^Y) 5307 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 5308 N0 = DAG.getNOT(dl, Temp, OpVT); 5309 if (!DCI.isCalledByLegalizer()) 5310 DCI.AddToWorklist(Temp.getNode()); 5311 break; 5312 case ISD::SETNE: // X != Y --> (X^Y) 5313 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 5314 break; 5315 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 5316 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 5317 Temp = DAG.getNOT(dl, N0, OpVT); 5318 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp); 5319 if (!DCI.isCalledByLegalizer()) 5320 DCI.AddToWorklist(Temp.getNode()); 5321 break; 5322 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 5323 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 5324 Temp = DAG.getNOT(dl, N1, OpVT); 5325 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp); 5326 if (!DCI.isCalledByLegalizer()) 5327 DCI.AddToWorklist(Temp.getNode()); 5328 break; 5329 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 5330 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 5331 Temp = DAG.getNOT(dl, N0, OpVT); 5332 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp); 5333 if (!DCI.isCalledByLegalizer()) 5334 DCI.AddToWorklist(Temp.getNode()); 5335 break; 5336 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 5337 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 5338 Temp = DAG.getNOT(dl, N1, OpVT); 5339 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp); 5340 break; 5341 } 5342 if (VT.getScalarType() != MVT::i1) { 5343 if (!DCI.isCalledByLegalizer()) 5344 DCI.AddToWorklist(N0.getNode()); 5345 // FIXME: If running after legalize, we probably can't do this. 5346 ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT)); 5347 N0 = DAG.getNode(ExtendCode, dl, VT, N0); 5348 } 5349 return N0; 5350 } 5351 5352 // Could not fold it. 5353 return SDValue(); 5354 } 5355 5356 /// Returns true (and the GlobalValue and the offset) if the node is a 5357 /// GlobalAddress + offset. 5358 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA, 5359 int64_t &Offset) const { 5360 5361 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode(); 5362 5363 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 5364 GA = GASD->getGlobal(); 5365 Offset += GASD->getOffset(); 5366 return true; 5367 } 5368 5369 if (N->getOpcode() == ISD::ADD) { 5370 SDValue N1 = N->getOperand(0); 5371 SDValue N2 = N->getOperand(1); 5372 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 5373 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 5374 Offset += V->getSExtValue(); 5375 return true; 5376 } 5377 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 5378 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 5379 Offset += V->getSExtValue(); 5380 return true; 5381 } 5382 } 5383 } 5384 5385 return false; 5386 } 5387 5388 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 5389 DAGCombinerInfo &DCI) const { 5390 // Default implementation: no optimization. 5391 return SDValue(); 5392 } 5393 5394 //===----------------------------------------------------------------------===// 5395 // Inline Assembler Implementation Methods 5396 //===----------------------------------------------------------------------===// 5397 5398 TargetLowering::ConstraintType 5399 TargetLowering::getConstraintType(StringRef Constraint) const { 5400 unsigned S = Constraint.size(); 5401 5402 if (S == 1) { 5403 switch (Constraint[0]) { 5404 default: break; 5405 case 'r': 5406 return C_RegisterClass; 5407 case 'm': // memory 5408 case 'o': // offsetable 5409 case 'V': // not offsetable 5410 return C_Memory; 5411 case 'p': // Address. 5412 return C_Address; 5413 case 'n': // Simple Integer 5414 case 'E': // Floating Point Constant 5415 case 'F': // Floating Point Constant 5416 return C_Immediate; 5417 case 'i': // Simple Integer or Relocatable Constant 5418 case 's': // Relocatable Constant 5419 case 'X': // Allow ANY value. 5420 case 'I': // Target registers. 5421 case 'J': 5422 case 'K': 5423 case 'L': 5424 case 'M': 5425 case 'N': 5426 case 'O': 5427 case 'P': 5428 case '<': 5429 case '>': 5430 return C_Other; 5431 } 5432 } 5433 5434 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') { 5435 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 5436 return C_Memory; 5437 return C_Register; 5438 } 5439 return C_Unknown; 5440 } 5441 5442 /// Try to replace an X constraint, which matches anything, with another that 5443 /// has more specific requirements based on the type of the corresponding 5444 /// operand. 5445 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 5446 if (ConstraintVT.isInteger()) 5447 return "r"; 5448 if (ConstraintVT.isFloatingPoint()) 5449 return "f"; // works for many targets 5450 return nullptr; 5451 } 5452 5453 SDValue TargetLowering::LowerAsmOutputForConstraint( 5454 SDValue &Chain, SDValue &Glue, const SDLoc &DL, 5455 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const { 5456 return SDValue(); 5457 } 5458 5459 /// Lower the specified operand into the Ops vector. 5460 /// If it is invalid, don't add anything to Ops. 5461 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 5462 StringRef Constraint, 5463 std::vector<SDValue> &Ops, 5464 SelectionDAG &DAG) const { 5465 5466 if (Constraint.size() > 1) 5467 return; 5468 5469 char ConstraintLetter = Constraint[0]; 5470 switch (ConstraintLetter) { 5471 default: break; 5472 case 'X': // Allows any operand 5473 case 'i': // Simple Integer or Relocatable Constant 5474 case 'n': // Simple Integer 5475 case 's': { // Relocatable Constant 5476 5477 ConstantSDNode *C; 5478 uint64_t Offset = 0; 5479 5480 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C), 5481 // etc., since getelementpointer is variadic. We can't use 5482 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible 5483 // while in this case the GA may be furthest from the root node which is 5484 // likely an ISD::ADD. 5485 while (true) { 5486 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') { 5487 // gcc prints these as sign extended. Sign extend value to 64 bits 5488 // now; without this it would get ZExt'd later in 5489 // ScheduleDAGSDNodes::EmitNode, which is very generic. 5490 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1; 5491 BooleanContent BCont = getBooleanContents(MVT::i64); 5492 ISD::NodeType ExtOpc = 5493 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND; 5494 int64_t ExtVal = 5495 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue(); 5496 Ops.push_back( 5497 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64)); 5498 return; 5499 } 5500 if (ConstraintLetter != 'n') { 5501 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 5502 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 5503 GA->getValueType(0), 5504 Offset + GA->getOffset())); 5505 return; 5506 } 5507 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 5508 Ops.push_back(DAG.getTargetBlockAddress( 5509 BA->getBlockAddress(), BA->getValueType(0), 5510 Offset + BA->getOffset(), BA->getTargetFlags())); 5511 return; 5512 } 5513 if (isa<BasicBlockSDNode>(Op)) { 5514 Ops.push_back(Op); 5515 return; 5516 } 5517 } 5518 const unsigned OpCode = Op.getOpcode(); 5519 if (OpCode == ISD::ADD || OpCode == ISD::SUB) { 5520 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0)))) 5521 Op = Op.getOperand(1); 5522 // Subtraction is not commutative. 5523 else if (OpCode == ISD::ADD && 5524 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))) 5525 Op = Op.getOperand(0); 5526 else 5527 return; 5528 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue(); 5529 continue; 5530 } 5531 return; 5532 } 5533 break; 5534 } 5535 } 5536 } 5537 5538 void TargetLowering::CollectTargetIntrinsicOperands( 5539 const CallInst &I, SmallVectorImpl<SDValue> &Ops, SelectionDAG &DAG) const { 5540 } 5541 5542 std::pair<unsigned, const TargetRegisterClass *> 5543 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 5544 StringRef Constraint, 5545 MVT VT) const { 5546 if (Constraint.empty() || Constraint[0] != '{') 5547 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr)); 5548 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?"); 5549 5550 // Remove the braces from around the name. 5551 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 5552 5553 std::pair<unsigned, const TargetRegisterClass *> R = 5554 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr)); 5555 5556 // Figure out which register class contains this reg. 5557 for (const TargetRegisterClass *RC : RI->regclasses()) { 5558 // If none of the value types for this register class are valid, we 5559 // can't use it. For example, 64-bit reg classes on 32-bit targets. 5560 if (!isLegalRC(*RI, *RC)) 5561 continue; 5562 5563 for (const MCPhysReg &PR : *RC) { 5564 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) { 5565 std::pair<unsigned, const TargetRegisterClass *> S = 5566 std::make_pair(PR, RC); 5567 5568 // If this register class has the requested value type, return it, 5569 // otherwise keep searching and return the first class found 5570 // if no other is found which explicitly has the requested type. 5571 if (RI->isTypeLegalForClass(*RC, VT)) 5572 return S; 5573 if (!R.second) 5574 R = S; 5575 } 5576 } 5577 } 5578 5579 return R; 5580 } 5581 5582 //===----------------------------------------------------------------------===// 5583 // Constraint Selection. 5584 5585 /// Return true of this is an input operand that is a matching constraint like 5586 /// "4". 5587 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 5588 assert(!ConstraintCode.empty() && "No known constraint!"); 5589 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 5590 } 5591 5592 /// If this is an input matching constraint, this method returns the output 5593 /// operand it matches. 5594 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 5595 assert(!ConstraintCode.empty() && "No known constraint!"); 5596 return atoi(ConstraintCode.c_str()); 5597 } 5598 5599 /// Split up the constraint string from the inline assembly value into the 5600 /// specific constraints and their prefixes, and also tie in the associated 5601 /// operand values. 5602 /// If this returns an empty vector, and if the constraint string itself 5603 /// isn't empty, there was an error parsing. 5604 TargetLowering::AsmOperandInfoVector 5605 TargetLowering::ParseConstraints(const DataLayout &DL, 5606 const TargetRegisterInfo *TRI, 5607 const CallBase &Call) const { 5608 /// Information about all of the constraints. 5609 AsmOperandInfoVector ConstraintOperands; 5610 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 5611 unsigned maCount = 0; // Largest number of multiple alternative constraints. 5612 5613 // Do a prepass over the constraints, canonicalizing them, and building up the 5614 // ConstraintOperands list. 5615 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 5616 unsigned ResNo = 0; // ResNo - The result number of the next output. 5617 unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number. 5618 5619 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 5620 ConstraintOperands.emplace_back(std::move(CI)); 5621 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 5622 5623 // Update multiple alternative constraint count. 5624 if (OpInfo.multipleAlternatives.size() > maCount) 5625 maCount = OpInfo.multipleAlternatives.size(); 5626 5627 OpInfo.ConstraintVT = MVT::Other; 5628 5629 // Compute the value type for each operand. 5630 switch (OpInfo.Type) { 5631 case InlineAsm::isOutput: 5632 // Indirect outputs just consume an argument. 5633 if (OpInfo.isIndirect) { 5634 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5635 break; 5636 } 5637 5638 // The return value of the call is this value. As such, there is no 5639 // corresponding argument. 5640 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 5641 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 5642 OpInfo.ConstraintVT = 5643 getSimpleValueType(DL, STy->getElementType(ResNo)); 5644 } else { 5645 assert(ResNo == 0 && "Asm only has one result!"); 5646 OpInfo.ConstraintVT = 5647 getAsmOperandValueType(DL, Call.getType()).getSimpleVT(); 5648 } 5649 ++ResNo; 5650 break; 5651 case InlineAsm::isInput: 5652 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5653 break; 5654 case InlineAsm::isLabel: 5655 OpInfo.CallOperandVal = cast<CallBrInst>(&Call)->getIndirectDest(LabelNo); 5656 ++LabelNo; 5657 continue; 5658 case InlineAsm::isClobber: 5659 // Nothing to do. 5660 break; 5661 } 5662 5663 if (OpInfo.CallOperandVal) { 5664 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 5665 if (OpInfo.isIndirect) { 5666 OpTy = Call.getParamElementType(ArgNo); 5667 assert(OpTy && "Indirect operand must have elementtype attribute"); 5668 } 5669 5670 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 5671 if (StructType *STy = dyn_cast<StructType>(OpTy)) 5672 if (STy->getNumElements() == 1) 5673 OpTy = STy->getElementType(0); 5674 5675 // If OpTy is not a single value, it may be a struct/union that we 5676 // can tile with integers. 5677 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 5678 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 5679 switch (BitSize) { 5680 default: break; 5681 case 1: 5682 case 8: 5683 case 16: 5684 case 32: 5685 case 64: 5686 case 128: 5687 OpTy = IntegerType::get(OpTy->getContext(), BitSize); 5688 break; 5689 } 5690 } 5691 5692 EVT VT = getAsmOperandValueType(DL, OpTy, true); 5693 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 5694 ArgNo++; 5695 } 5696 } 5697 5698 // If we have multiple alternative constraints, select the best alternative. 5699 if (!ConstraintOperands.empty()) { 5700 if (maCount) { 5701 unsigned bestMAIndex = 0; 5702 int bestWeight = -1; 5703 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 5704 int weight = -1; 5705 unsigned maIndex; 5706 // Compute the sums of the weights for each alternative, keeping track 5707 // of the best (highest weight) one so far. 5708 for (maIndex = 0; maIndex < maCount; ++maIndex) { 5709 int weightSum = 0; 5710 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5711 cIndex != eIndex; ++cIndex) { 5712 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5713 if (OpInfo.Type == InlineAsm::isClobber) 5714 continue; 5715 5716 // If this is an output operand with a matching input operand, 5717 // look up the matching input. If their types mismatch, e.g. one 5718 // is an integer, the other is floating point, or their sizes are 5719 // different, flag it as an maCantMatch. 5720 if (OpInfo.hasMatchingInput()) { 5721 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5722 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5723 if ((OpInfo.ConstraintVT.isInteger() != 5724 Input.ConstraintVT.isInteger()) || 5725 (OpInfo.ConstraintVT.getSizeInBits() != 5726 Input.ConstraintVT.getSizeInBits())) { 5727 weightSum = -1; // Can't match. 5728 break; 5729 } 5730 } 5731 } 5732 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 5733 if (weight == -1) { 5734 weightSum = -1; 5735 break; 5736 } 5737 weightSum += weight; 5738 } 5739 // Update best. 5740 if (weightSum > bestWeight) { 5741 bestWeight = weightSum; 5742 bestMAIndex = maIndex; 5743 } 5744 } 5745 5746 // Now select chosen alternative in each constraint. 5747 for (AsmOperandInfo &cInfo : ConstraintOperands) 5748 if (cInfo.Type != InlineAsm::isClobber) 5749 cInfo.selectAlternative(bestMAIndex); 5750 } 5751 } 5752 5753 // Check and hook up tied operands, choose constraint code to use. 5754 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5755 cIndex != eIndex; ++cIndex) { 5756 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5757 5758 // If this is an output operand with a matching input operand, look up the 5759 // matching input. If their types mismatch, e.g. one is an integer, the 5760 // other is floating point, or their sizes are different, flag it as an 5761 // error. 5762 if (OpInfo.hasMatchingInput()) { 5763 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5764 5765 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5766 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 5767 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 5768 OpInfo.ConstraintVT); 5769 std::pair<unsigned, const TargetRegisterClass *> InputRC = 5770 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 5771 Input.ConstraintVT); 5772 if ((OpInfo.ConstraintVT.isInteger() != 5773 Input.ConstraintVT.isInteger()) || 5774 (MatchRC.second != InputRC.second)) { 5775 report_fatal_error("Unsupported asm: input constraint" 5776 " with a matching output constraint of" 5777 " incompatible type!"); 5778 } 5779 } 5780 } 5781 } 5782 5783 return ConstraintOperands; 5784 } 5785 5786 /// Return a number indicating our preference for chosing a type of constraint 5787 /// over another, for the purpose of sorting them. Immediates are almost always 5788 /// preferrable (when they can be emitted). A higher return value means a 5789 /// stronger preference for one constraint type relative to another. 5790 /// FIXME: We should prefer registers over memory but doing so may lead to 5791 /// unrecoverable register exhaustion later. 5792 /// https://github.com/llvm/llvm-project/issues/20571 5793 static unsigned getConstraintPiority(TargetLowering::ConstraintType CT) { 5794 switch (CT) { 5795 case TargetLowering::C_Immediate: 5796 case TargetLowering::C_Other: 5797 return 4; 5798 case TargetLowering::C_Memory: 5799 case TargetLowering::C_Address: 5800 return 3; 5801 case TargetLowering::C_RegisterClass: 5802 return 2; 5803 case TargetLowering::C_Register: 5804 return 1; 5805 case TargetLowering::C_Unknown: 5806 return 0; 5807 } 5808 llvm_unreachable("Invalid constraint type"); 5809 } 5810 5811 /// Examine constraint type and operand type and determine a weight value. 5812 /// This object must already have been set up with the operand type 5813 /// and the current alternative constraint selected. 5814 TargetLowering::ConstraintWeight 5815 TargetLowering::getMultipleConstraintMatchWeight( 5816 AsmOperandInfo &info, int maIndex) const { 5817 InlineAsm::ConstraintCodeVector *rCodes; 5818 if (maIndex >= (int)info.multipleAlternatives.size()) 5819 rCodes = &info.Codes; 5820 else 5821 rCodes = &info.multipleAlternatives[maIndex].Codes; 5822 ConstraintWeight BestWeight = CW_Invalid; 5823 5824 // Loop over the options, keeping track of the most general one. 5825 for (const std::string &rCode : *rCodes) { 5826 ConstraintWeight weight = 5827 getSingleConstraintMatchWeight(info, rCode.c_str()); 5828 if (weight > BestWeight) 5829 BestWeight = weight; 5830 } 5831 5832 return BestWeight; 5833 } 5834 5835 /// Examine constraint type and operand type and determine a weight value. 5836 /// This object must already have been set up with the operand type 5837 /// and the current alternative constraint selected. 5838 TargetLowering::ConstraintWeight 5839 TargetLowering::getSingleConstraintMatchWeight( 5840 AsmOperandInfo &info, const char *constraint) const { 5841 ConstraintWeight weight = CW_Invalid; 5842 Value *CallOperandVal = info.CallOperandVal; 5843 // If we don't have a value, we can't do a match, 5844 // but allow it at the lowest weight. 5845 if (!CallOperandVal) 5846 return CW_Default; 5847 // Look at the constraint type. 5848 switch (*constraint) { 5849 case 'i': // immediate integer. 5850 case 'n': // immediate integer with a known value. 5851 if (isa<ConstantInt>(CallOperandVal)) 5852 weight = CW_Constant; 5853 break; 5854 case 's': // non-explicit intregal immediate. 5855 if (isa<GlobalValue>(CallOperandVal)) 5856 weight = CW_Constant; 5857 break; 5858 case 'E': // immediate float if host format. 5859 case 'F': // immediate float. 5860 if (isa<ConstantFP>(CallOperandVal)) 5861 weight = CW_Constant; 5862 break; 5863 case '<': // memory operand with autodecrement. 5864 case '>': // memory operand with autoincrement. 5865 case 'm': // memory operand. 5866 case 'o': // offsettable memory operand 5867 case 'V': // non-offsettable memory operand 5868 weight = CW_Memory; 5869 break; 5870 case 'r': // general register. 5871 case 'g': // general register, memory operand or immediate integer. 5872 // note: Clang converts "g" to "imr". 5873 if (CallOperandVal->getType()->isIntegerTy()) 5874 weight = CW_Register; 5875 break; 5876 case 'X': // any operand. 5877 default: 5878 weight = CW_Default; 5879 break; 5880 } 5881 return weight; 5882 } 5883 5884 /// If there are multiple different constraints that we could pick for this 5885 /// operand (e.g. "imr") try to pick the 'best' one. 5886 /// This is somewhat tricky: constraints (TargetLowering::ConstraintType) fall 5887 /// into seven classes: 5888 /// Register -> one specific register 5889 /// RegisterClass -> a group of regs 5890 /// Memory -> memory 5891 /// Address -> a symbolic memory reference 5892 /// Immediate -> immediate values 5893 /// Other -> magic values (such as "Flag Output Operands") 5894 /// Unknown -> something we don't recognize yet and can't handle 5895 /// Ideally, we would pick the most specific constraint possible: if we have 5896 /// something that fits into a register, we would pick it. The problem here 5897 /// is that if we have something that could either be in a register or in 5898 /// memory that use of the register could cause selection of *other* 5899 /// operands to fail: they might only succeed if we pick memory. Because of 5900 /// this the heuristic we use is: 5901 /// 5902 /// 1) If there is an 'other' constraint, and if the operand is valid for 5903 /// that constraint, use it. This makes us take advantage of 'i' 5904 /// constraints when available. 5905 /// 2) Otherwise, pick the most general constraint present. This prefers 5906 /// 'm' over 'r', for example. 5907 /// 5908 TargetLowering::ConstraintGroup TargetLowering::getConstraintPreferences( 5909 TargetLowering::AsmOperandInfo &OpInfo) const { 5910 ConstraintGroup Ret; 5911 5912 Ret.reserve(OpInfo.Codes.size()); 5913 for (StringRef Code : OpInfo.Codes) { 5914 TargetLowering::ConstraintType CType = getConstraintType(Code); 5915 5916 // Indirect 'other' or 'immediate' constraints are not allowed. 5917 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory || 5918 CType == TargetLowering::C_Register || 5919 CType == TargetLowering::C_RegisterClass)) 5920 continue; 5921 5922 // Things with matching constraints can only be registers, per gcc 5923 // documentation. This mainly affects "g" constraints. 5924 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 5925 continue; 5926 5927 Ret.emplace_back(Code, CType); 5928 } 5929 5930 std::stable_sort( 5931 Ret.begin(), Ret.end(), [](ConstraintPair a, ConstraintPair b) { 5932 return getConstraintPiority(a.second) > getConstraintPiority(b.second); 5933 }); 5934 5935 return Ret; 5936 } 5937 5938 /// If we have an immediate, see if we can lower it. Return true if we can, 5939 /// false otherwise. 5940 static bool lowerImmediateIfPossible(TargetLowering::ConstraintPair &P, 5941 SDValue Op, SelectionDAG *DAG, 5942 const TargetLowering &TLI) { 5943 5944 assert((P.second == TargetLowering::C_Other || 5945 P.second == TargetLowering::C_Immediate) && 5946 "need immediate or other"); 5947 5948 if (!Op.getNode()) 5949 return false; 5950 5951 std::vector<SDValue> ResultOps; 5952 TLI.LowerAsmOperandForConstraint(Op, P.first, ResultOps, *DAG); 5953 return !ResultOps.empty(); 5954 } 5955 5956 /// Determines the constraint code and constraint type to use for the specific 5957 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 5958 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 5959 SDValue Op, 5960 SelectionDAG *DAG) const { 5961 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 5962 5963 // Single-letter constraints ('r') are very common. 5964 if (OpInfo.Codes.size() == 1) { 5965 OpInfo.ConstraintCode = OpInfo.Codes[0]; 5966 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 5967 } else { 5968 ConstraintGroup G = getConstraintPreferences(OpInfo); 5969 if (G.empty()) 5970 return; 5971 5972 unsigned BestIdx = 0; 5973 for (const unsigned E = G.size(); 5974 BestIdx < E && (G[BestIdx].second == TargetLowering::C_Other || 5975 G[BestIdx].second == TargetLowering::C_Immediate); 5976 ++BestIdx) { 5977 if (lowerImmediateIfPossible(G[BestIdx], Op, DAG, *this)) 5978 break; 5979 // If we're out of constraints, just pick the first one. 5980 if (BestIdx + 1 == E) { 5981 BestIdx = 0; 5982 break; 5983 } 5984 } 5985 5986 OpInfo.ConstraintCode = G[BestIdx].first; 5987 OpInfo.ConstraintType = G[BestIdx].second; 5988 } 5989 5990 // 'X' matches anything. 5991 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 5992 // Constants are handled elsewhere. For Functions, the type here is the 5993 // type of the result, which is not what we want to look at; leave them 5994 // alone. 5995 Value *v = OpInfo.CallOperandVal; 5996 if (isa<ConstantInt>(v) || isa<Function>(v)) { 5997 return; 5998 } 5999 6000 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) { 6001 OpInfo.ConstraintCode = "i"; 6002 return; 6003 } 6004 6005 // Otherwise, try to resolve it to something we know about by looking at 6006 // the actual operand type. 6007 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 6008 OpInfo.ConstraintCode = Repl; 6009 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 6010 } 6011 } 6012 } 6013 6014 /// Given an exact SDIV by a constant, create a multiplication 6015 /// with the multiplicative inverse of the constant. 6016 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, 6017 const SDLoc &dl, SelectionDAG &DAG, 6018 SmallVectorImpl<SDNode *> &Created) { 6019 SDValue Op0 = N->getOperand(0); 6020 SDValue Op1 = N->getOperand(1); 6021 EVT VT = N->getValueType(0); 6022 EVT SVT = VT.getScalarType(); 6023 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 6024 EVT ShSVT = ShVT.getScalarType(); 6025 6026 bool UseSRA = false; 6027 SmallVector<SDValue, 16> Shifts, Factors; 6028 6029 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 6030 if (C->isZero()) 6031 return false; 6032 APInt Divisor = C->getAPIntValue(); 6033 unsigned Shift = Divisor.countr_zero(); 6034 if (Shift) { 6035 Divisor.ashrInPlace(Shift); 6036 UseSRA = true; 6037 } 6038 // Calculate the multiplicative inverse, using Newton's method. 6039 APInt t; 6040 APInt Factor = Divisor; 6041 while ((t = Divisor * Factor) != 1) 6042 Factor *= APInt(Divisor.getBitWidth(), 2) - t; 6043 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 6044 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 6045 return true; 6046 }; 6047 6048 // Collect all magic values from the build vector. 6049 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern)) 6050 return SDValue(); 6051 6052 SDValue Shift, Factor; 6053 if (Op1.getOpcode() == ISD::BUILD_VECTOR) { 6054 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 6055 Factor = DAG.getBuildVector(VT, dl, Factors); 6056 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) { 6057 assert(Shifts.size() == 1 && Factors.size() == 1 && 6058 "Expected matchUnaryPredicate to return one element for scalable " 6059 "vectors"); 6060 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 6061 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 6062 } else { 6063 assert(isa<ConstantSDNode>(Op1) && "Expected a constant"); 6064 Shift = Shifts[0]; 6065 Factor = Factors[0]; 6066 } 6067 6068 SDValue Res = Op0; 6069 6070 // Shift the value upfront if it is even, so the LSB is one. 6071 if (UseSRA) { 6072 // TODO: For UDIV use SRL instead of SRA. 6073 SDNodeFlags Flags; 6074 Flags.setExact(true); 6075 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags); 6076 Created.push_back(Res.getNode()); 6077 } 6078 6079 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 6080 } 6081 6082 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 6083 SelectionDAG &DAG, 6084 SmallVectorImpl<SDNode *> &Created) const { 6085 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 6086 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6087 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 6088 return SDValue(N, 0); // Lower SDIV as SDIV 6089 return SDValue(); 6090 } 6091 6092 SDValue 6093 TargetLowering::BuildSREMPow2(SDNode *N, const APInt &Divisor, 6094 SelectionDAG &DAG, 6095 SmallVectorImpl<SDNode *> &Created) const { 6096 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 6097 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6098 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 6099 return SDValue(N, 0); // Lower SREM as SREM 6100 return SDValue(); 6101 } 6102 6103 /// Build sdiv by power-of-2 with conditional move instructions 6104 /// Ref: "Hacker's Delight" by Henry Warren 10-1 6105 /// If conditional move/branch is preferred, we lower sdiv x, +/-2**k into: 6106 /// bgez x, label 6107 /// add x, x, 2**k-1 6108 /// label: 6109 /// sra res, x, k 6110 /// neg res, res (when the divisor is negative) 6111 SDValue TargetLowering::buildSDIVPow2WithCMov( 6112 SDNode *N, const APInt &Divisor, SelectionDAG &DAG, 6113 SmallVectorImpl<SDNode *> &Created) const { 6114 unsigned Lg2 = Divisor.countr_zero(); 6115 EVT VT = N->getValueType(0); 6116 6117 SDLoc DL(N); 6118 SDValue N0 = N->getOperand(0); 6119 SDValue Zero = DAG.getConstant(0, DL, VT); 6120 APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2); 6121 SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT); 6122 6123 // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right. 6124 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6125 SDValue Cmp = DAG.getSetCC(DL, CCVT, N0, Zero, ISD::SETLT); 6126 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 6127 SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 6128 6129 Created.push_back(Cmp.getNode()); 6130 Created.push_back(Add.getNode()); 6131 Created.push_back(CMov.getNode()); 6132 6133 // Divide by pow2. 6134 SDValue SRA = 6135 DAG.getNode(ISD::SRA, DL, VT, CMov, DAG.getConstant(Lg2, DL, VT)); 6136 6137 // If we're dividing by a positive value, we're done. Otherwise, we must 6138 // negate the result. 6139 if (Divisor.isNonNegative()) 6140 return SRA; 6141 6142 Created.push_back(SRA.getNode()); 6143 return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA); 6144 } 6145 6146 /// Given an ISD::SDIV node expressing a divide by constant, 6147 /// return a DAG expression to select that will generate the same value by 6148 /// multiplying by a magic number. 6149 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 6150 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 6151 bool IsAfterLegalization, 6152 SmallVectorImpl<SDNode *> &Created) const { 6153 SDLoc dl(N); 6154 EVT VT = N->getValueType(0); 6155 EVT SVT = VT.getScalarType(); 6156 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6157 EVT ShSVT = ShVT.getScalarType(); 6158 unsigned EltBits = VT.getScalarSizeInBits(); 6159 EVT MulVT; 6160 6161 // Check to see if we can do this. 6162 // FIXME: We should be more aggressive here. 6163 if (!isTypeLegal(VT)) { 6164 // Limit this to simple scalars for now. 6165 if (VT.isVector() || !VT.isSimple()) 6166 return SDValue(); 6167 6168 // If this type will be promoted to a large enough type with a legal 6169 // multiply operation, we can go ahead and do this transform. 6170 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 6171 return SDValue(); 6172 6173 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 6174 if (MulVT.getSizeInBits() < (2 * EltBits) || 6175 !isOperationLegal(ISD::MUL, MulVT)) 6176 return SDValue(); 6177 } 6178 6179 // If the sdiv has an 'exact' bit we can use a simpler lowering. 6180 if (N->getFlags().hasExact()) 6181 return BuildExactSDIV(*this, N, dl, DAG, Created); 6182 6183 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks; 6184 6185 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 6186 if (C->isZero()) 6187 return false; 6188 6189 const APInt &Divisor = C->getAPIntValue(); 6190 SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor); 6191 int NumeratorFactor = 0; 6192 int ShiftMask = -1; 6193 6194 if (Divisor.isOne() || Divisor.isAllOnes()) { 6195 // If d is +1/-1, we just multiply the numerator by +1/-1. 6196 NumeratorFactor = Divisor.getSExtValue(); 6197 magics.Magic = 0; 6198 magics.ShiftAmount = 0; 6199 ShiftMask = 0; 6200 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) { 6201 // If d > 0 and m < 0, add the numerator. 6202 NumeratorFactor = 1; 6203 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) { 6204 // If d < 0 and m > 0, subtract the numerator. 6205 NumeratorFactor = -1; 6206 } 6207 6208 MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT)); 6209 Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT)); 6210 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT)); 6211 ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT)); 6212 return true; 6213 }; 6214 6215 SDValue N0 = N->getOperand(0); 6216 SDValue N1 = N->getOperand(1); 6217 6218 // Collect the shifts / magic values from each element. 6219 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern)) 6220 return SDValue(); 6221 6222 SDValue MagicFactor, Factor, Shift, ShiftMask; 6223 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 6224 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 6225 Factor = DAG.getBuildVector(VT, dl, Factors); 6226 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 6227 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks); 6228 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 6229 assert(MagicFactors.size() == 1 && Factors.size() == 1 && 6230 Shifts.size() == 1 && ShiftMasks.size() == 1 && 6231 "Expected matchUnaryPredicate to return one element for scalable " 6232 "vectors"); 6233 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 6234 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 6235 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 6236 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]); 6237 } else { 6238 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 6239 MagicFactor = MagicFactors[0]; 6240 Factor = Factors[0]; 6241 Shift = Shifts[0]; 6242 ShiftMask = ShiftMasks[0]; 6243 } 6244 6245 // Multiply the numerator (operand 0) by the magic value. 6246 // FIXME: We should support doing a MUL in a wider type. 6247 auto GetMULHS = [&](SDValue X, SDValue Y) { 6248 // If the type isn't legal, use a wider mul of the type calculated 6249 // earlier. 6250 if (!isTypeLegal(VT)) { 6251 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X); 6252 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y); 6253 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 6254 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 6255 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 6256 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 6257 } 6258 6259 if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization)) 6260 return DAG.getNode(ISD::MULHS, dl, VT, X, Y); 6261 if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) { 6262 SDValue LoHi = 6263 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 6264 return SDValue(LoHi.getNode(), 1); 6265 } 6266 // If type twice as wide legal, widen and use a mul plus a shift. 6267 unsigned Size = VT.getScalarSizeInBits(); 6268 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), Size * 2); 6269 if (VT.isVector()) 6270 WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT, 6271 VT.getVectorElementCount()); 6272 if (isOperationLegalOrCustom(ISD::MUL, WideVT)) { 6273 X = DAG.getNode(ISD::SIGN_EXTEND, dl, WideVT, X); 6274 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, WideVT, Y); 6275 Y = DAG.getNode(ISD::MUL, dl, WideVT, X, Y); 6276 Y = DAG.getNode(ISD::SRL, dl, WideVT, Y, 6277 DAG.getShiftAmountConstant(EltBits, WideVT, dl)); 6278 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 6279 } 6280 return SDValue(); 6281 }; 6282 6283 SDValue Q = GetMULHS(N0, MagicFactor); 6284 if (!Q) 6285 return SDValue(); 6286 6287 Created.push_back(Q.getNode()); 6288 6289 // (Optionally) Add/subtract the numerator using Factor. 6290 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor); 6291 Created.push_back(Factor.getNode()); 6292 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor); 6293 Created.push_back(Q.getNode()); 6294 6295 // Shift right algebraic by shift value. 6296 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift); 6297 Created.push_back(Q.getNode()); 6298 6299 // Extract the sign bit, mask it and add it to the quotient. 6300 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT); 6301 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift); 6302 Created.push_back(T.getNode()); 6303 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask); 6304 Created.push_back(T.getNode()); 6305 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 6306 } 6307 6308 /// Given an ISD::UDIV node expressing a divide by constant, 6309 /// return a DAG expression to select that will generate the same value by 6310 /// multiplying by a magic number. 6311 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 6312 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG, 6313 bool IsAfterLegalization, 6314 SmallVectorImpl<SDNode *> &Created) const { 6315 SDLoc dl(N); 6316 EVT VT = N->getValueType(0); 6317 EVT SVT = VT.getScalarType(); 6318 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6319 EVT ShSVT = ShVT.getScalarType(); 6320 unsigned EltBits = VT.getScalarSizeInBits(); 6321 EVT MulVT; 6322 6323 // Check to see if we can do this. 6324 // FIXME: We should be more aggressive here. 6325 if (!isTypeLegal(VT)) { 6326 // Limit this to simple scalars for now. 6327 if (VT.isVector() || !VT.isSimple()) 6328 return SDValue(); 6329 6330 // If this type will be promoted to a large enough type with a legal 6331 // multiply operation, we can go ahead and do this transform. 6332 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 6333 return SDValue(); 6334 6335 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 6336 if (MulVT.getSizeInBits() < (2 * EltBits) || 6337 !isOperationLegal(ISD::MUL, MulVT)) 6338 return SDValue(); 6339 } 6340 6341 SDValue N0 = N->getOperand(0); 6342 SDValue N1 = N->getOperand(1); 6343 6344 // Try to use leading zeros of the dividend to reduce the multiplier and 6345 // avoid expensive fixups. 6346 // TODO: Support vectors. 6347 unsigned LeadingZeros = 0; 6348 if (!VT.isVector() && isa<ConstantSDNode>(N1)) { 6349 assert(!isOneConstant(N1) && "Unexpected divisor"); 6350 LeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros(); 6351 // UnsignedDivisionByConstantInfo doesn't work correctly if leading zeros in 6352 // the dividend exceeds the leading zeros for the divisor. 6353 LeadingZeros = std::min( 6354 LeadingZeros, cast<ConstantSDNode>(N1)->getAPIntValue().countl_zero()); 6355 } 6356 6357 bool UseNPQ = false, UsePreShift = false, UsePostShift = false; 6358 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors; 6359 6360 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 6361 if (C->isZero()) 6362 return false; 6363 const APInt& Divisor = C->getAPIntValue(); 6364 6365 SDValue PreShift, MagicFactor, NPQFactor, PostShift; 6366 6367 // Magic algorithm doesn't work for division by 1. We need to emit a select 6368 // at the end. 6369 if (Divisor.isOne()) { 6370 PreShift = PostShift = DAG.getUNDEF(ShSVT); 6371 MagicFactor = NPQFactor = DAG.getUNDEF(SVT); 6372 } else { 6373 UnsignedDivisionByConstantInfo magics = 6374 UnsignedDivisionByConstantInfo::get(Divisor, LeadingZeros); 6375 6376 MagicFactor = DAG.getConstant(magics.Magic, dl, SVT); 6377 6378 assert(magics.PreShift < Divisor.getBitWidth() && 6379 "We shouldn't generate an undefined shift!"); 6380 assert(magics.PostShift < Divisor.getBitWidth() && 6381 "We shouldn't generate an undefined shift!"); 6382 assert((!magics.IsAdd || magics.PreShift == 0) && 6383 "Unexpected pre-shift"); 6384 PreShift = DAG.getConstant(magics.PreShift, dl, ShSVT); 6385 PostShift = DAG.getConstant(magics.PostShift, dl, ShSVT); 6386 NPQFactor = DAG.getConstant( 6387 magics.IsAdd ? APInt::getOneBitSet(EltBits, EltBits - 1) 6388 : APInt::getZero(EltBits), 6389 dl, SVT); 6390 UseNPQ |= magics.IsAdd; 6391 UsePreShift |= magics.PreShift != 0; 6392 UsePostShift |= magics.PostShift != 0; 6393 } 6394 6395 PreShifts.push_back(PreShift); 6396 MagicFactors.push_back(MagicFactor); 6397 NPQFactors.push_back(NPQFactor); 6398 PostShifts.push_back(PostShift); 6399 return true; 6400 }; 6401 6402 // Collect the shifts/magic values from each element. 6403 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern)) 6404 return SDValue(); 6405 6406 SDValue PreShift, PostShift, MagicFactor, NPQFactor; 6407 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 6408 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts); 6409 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 6410 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors); 6411 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts); 6412 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 6413 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 && 6414 NPQFactors.size() == 1 && PostShifts.size() == 1 && 6415 "Expected matchUnaryPredicate to return one for scalable vectors"); 6416 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]); 6417 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 6418 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]); 6419 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]); 6420 } else { 6421 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 6422 PreShift = PreShifts[0]; 6423 MagicFactor = MagicFactors[0]; 6424 PostShift = PostShifts[0]; 6425 } 6426 6427 SDValue Q = N0; 6428 if (UsePreShift) { 6429 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift); 6430 Created.push_back(Q.getNode()); 6431 } 6432 6433 // FIXME: We should support doing a MUL in a wider type. 6434 auto GetMULHU = [&](SDValue X, SDValue Y) { 6435 // If the type isn't legal, use a wider mul of the type calculated 6436 // earlier. 6437 if (!isTypeLegal(VT)) { 6438 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X); 6439 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y); 6440 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 6441 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 6442 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 6443 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 6444 } 6445 6446 if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization)) 6447 return DAG.getNode(ISD::MULHU, dl, VT, X, Y); 6448 if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) { 6449 SDValue LoHi = 6450 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 6451 return SDValue(LoHi.getNode(), 1); 6452 } 6453 // If type twice as wide legal, widen and use a mul plus a shift. 6454 unsigned Size = VT.getScalarSizeInBits(); 6455 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), Size * 2); 6456 if (VT.isVector()) 6457 WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT, 6458 VT.getVectorElementCount()); 6459 if (isOperationLegalOrCustom(ISD::MUL, WideVT)) { 6460 X = DAG.getNode(ISD::ZERO_EXTEND, dl, WideVT, X); 6461 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, WideVT, Y); 6462 Y = DAG.getNode(ISD::MUL, dl, WideVT, X, Y); 6463 Y = DAG.getNode(ISD::SRL, dl, WideVT, Y, 6464 DAG.getShiftAmountConstant(EltBits, WideVT, dl)); 6465 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 6466 } 6467 return SDValue(); // No mulhu or equivalent 6468 }; 6469 6470 // Multiply the numerator (operand 0) by the magic value. 6471 Q = GetMULHU(Q, MagicFactor); 6472 if (!Q) 6473 return SDValue(); 6474 6475 Created.push_back(Q.getNode()); 6476 6477 if (UseNPQ) { 6478 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q); 6479 Created.push_back(NPQ.getNode()); 6480 6481 // For vectors we might have a mix of non-NPQ/NPQ paths, so use 6482 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero. 6483 if (VT.isVector()) 6484 NPQ = GetMULHU(NPQ, NPQFactor); 6485 else 6486 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT)); 6487 6488 Created.push_back(NPQ.getNode()); 6489 6490 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 6491 Created.push_back(Q.getNode()); 6492 } 6493 6494 if (UsePostShift) { 6495 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift); 6496 Created.push_back(Q.getNode()); 6497 } 6498 6499 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6500 6501 SDValue One = DAG.getConstant(1, dl, VT); 6502 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ); 6503 return DAG.getSelect(dl, VT, IsOne, N0, Q); 6504 } 6505 6506 /// If all values in Values that *don't* match the predicate are same 'splat' 6507 /// value, then replace all values with that splat value. 6508 /// Else, if AlternativeReplacement was provided, then replace all values that 6509 /// do match predicate with AlternativeReplacement value. 6510 static void 6511 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values, 6512 std::function<bool(SDValue)> Predicate, 6513 SDValue AlternativeReplacement = SDValue()) { 6514 SDValue Replacement; 6515 // Is there a value for which the Predicate does *NOT* match? What is it? 6516 auto SplatValue = llvm::find_if_not(Values, Predicate); 6517 if (SplatValue != Values.end()) { 6518 // Does Values consist only of SplatValue's and values matching Predicate? 6519 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) { 6520 return Value == *SplatValue || Predicate(Value); 6521 })) // Then we shall replace values matching predicate with SplatValue. 6522 Replacement = *SplatValue; 6523 } 6524 if (!Replacement) { 6525 // Oops, we did not find the "baseline" splat value. 6526 if (!AlternativeReplacement) 6527 return; // Nothing to do. 6528 // Let's replace with provided value then. 6529 Replacement = AlternativeReplacement; 6530 } 6531 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement); 6532 } 6533 6534 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE 6535 /// where the divisor is constant and the comparison target is zero, 6536 /// return a DAG expression that will generate the same comparison result 6537 /// using only multiplications, additions and shifts/rotations. 6538 /// Ref: "Hacker's Delight" 10-17. 6539 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode, 6540 SDValue CompTargetNode, 6541 ISD::CondCode Cond, 6542 DAGCombinerInfo &DCI, 6543 const SDLoc &DL) const { 6544 SmallVector<SDNode *, 5> Built; 6545 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 6546 DCI, DL, Built)) { 6547 for (SDNode *N : Built) 6548 DCI.AddToWorklist(N); 6549 return Folded; 6550 } 6551 6552 return SDValue(); 6553 } 6554 6555 SDValue 6556 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode, 6557 SDValue CompTargetNode, ISD::CondCode Cond, 6558 DAGCombinerInfo &DCI, const SDLoc &DL, 6559 SmallVectorImpl<SDNode *> &Created) const { 6560 // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q) 6561 // - D must be constant, with D = D0 * 2^K where D0 is odd 6562 // - P is the multiplicative inverse of D0 modulo 2^W 6563 // - Q = floor(((2^W) - 1) / D) 6564 // where W is the width of the common type of N and D. 6565 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 6566 "Only applicable for (in)equality comparisons."); 6567 6568 SelectionDAG &DAG = DCI.DAG; 6569 6570 EVT VT = REMNode.getValueType(); 6571 EVT SVT = VT.getScalarType(); 6572 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize()); 6573 EVT ShSVT = ShVT.getScalarType(); 6574 6575 // If MUL is unavailable, we cannot proceed in any case. 6576 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 6577 return SDValue(); 6578 6579 bool ComparingWithAllZeros = true; 6580 bool AllComparisonsWithNonZerosAreTautological = true; 6581 bool HadTautologicalLanes = false; 6582 bool AllLanesAreTautological = true; 6583 bool HadEvenDivisor = false; 6584 bool AllDivisorsArePowerOfTwo = true; 6585 bool HadTautologicalInvertedLanes = false; 6586 SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts; 6587 6588 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) { 6589 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6590 if (CDiv->isZero()) 6591 return false; 6592 6593 const APInt &D = CDiv->getAPIntValue(); 6594 const APInt &Cmp = CCmp->getAPIntValue(); 6595 6596 ComparingWithAllZeros &= Cmp.isZero(); 6597 6598 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6599 // if C2 is not less than C1, the comparison is always false. 6600 // But we will only be able to produce the comparison that will give the 6601 // opposive tautological answer. So this lane would need to be fixed up. 6602 bool TautologicalInvertedLane = D.ule(Cmp); 6603 HadTautologicalInvertedLanes |= TautologicalInvertedLane; 6604 6605 // If all lanes are tautological (either all divisors are ones, or divisor 6606 // is not greater than the constant we are comparing with), 6607 // we will prefer to avoid the fold. 6608 bool TautologicalLane = D.isOne() || TautologicalInvertedLane; 6609 HadTautologicalLanes |= TautologicalLane; 6610 AllLanesAreTautological &= TautologicalLane; 6611 6612 // If we are comparing with non-zero, we need'll need to subtract said 6613 // comparison value from the LHS. But there is no point in doing that if 6614 // every lane where we are comparing with non-zero is tautological.. 6615 if (!Cmp.isZero()) 6616 AllComparisonsWithNonZerosAreTautological &= TautologicalLane; 6617 6618 // Decompose D into D0 * 2^K 6619 unsigned K = D.countr_zero(); 6620 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 6621 APInt D0 = D.lshr(K); 6622 6623 // D is even if it has trailing zeros. 6624 HadEvenDivisor |= (K != 0); 6625 // D is a power-of-two if D0 is one. 6626 // If all divisors are power-of-two, we will prefer to avoid the fold. 6627 AllDivisorsArePowerOfTwo &= D0.isOne(); 6628 6629 // P = inv(D0, 2^W) 6630 // 2^W requires W + 1 bits, so we have to extend and then truncate. 6631 unsigned W = D.getBitWidth(); 6632 APInt P = D0.zext(W + 1) 6633 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 6634 .trunc(W); 6635 assert(!P.isZero() && "No multiplicative inverse!"); // unreachable 6636 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 6637 6638 // Q = floor((2^W - 1) u/ D) 6639 // R = ((2^W - 1) u% D) 6640 APInt Q, R; 6641 APInt::udivrem(APInt::getAllOnes(W), D, Q, R); 6642 6643 // If we are comparing with zero, then that comparison constant is okay, 6644 // else it may need to be one less than that. 6645 if (Cmp.ugt(R)) 6646 Q -= 1; 6647 6648 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 6649 "We are expecting that K is always less than all-ones for ShSVT"); 6650 6651 // If the lane is tautological the result can be constant-folded. 6652 if (TautologicalLane) { 6653 // Set P and K amount to a bogus values so we can try to splat them. 6654 P = 0; 6655 K = -1; 6656 // And ensure that comparison constant is tautological, 6657 // it will always compare true/false. 6658 Q = -1; 6659 } 6660 6661 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 6662 KAmts.push_back( 6663 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 6664 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 6665 return true; 6666 }; 6667 6668 SDValue N = REMNode.getOperand(0); 6669 SDValue D = REMNode.getOperand(1); 6670 6671 // Collect the values from each element. 6672 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern)) 6673 return SDValue(); 6674 6675 // If all lanes are tautological, the result can be constant-folded. 6676 if (AllLanesAreTautological) 6677 return SDValue(); 6678 6679 // If this is a urem by a powers-of-two, avoid the fold since it can be 6680 // best implemented as a bit test. 6681 if (AllDivisorsArePowerOfTwo) 6682 return SDValue(); 6683 6684 SDValue PVal, KVal, QVal; 6685 if (D.getOpcode() == ISD::BUILD_VECTOR) { 6686 if (HadTautologicalLanes) { 6687 // Try to turn PAmts into a splat, since we don't care about the values 6688 // that are currently '0'. If we can't, just keep '0'`s. 6689 turnVectorIntoSplatVector(PAmts, isNullConstant); 6690 // Try to turn KAmts into a splat, since we don't care about the values 6691 // that are currently '-1'. If we can't, change them to '0'`s. 6692 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 6693 DAG.getConstant(0, DL, ShSVT)); 6694 } 6695 6696 PVal = DAG.getBuildVector(VT, DL, PAmts); 6697 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 6698 QVal = DAG.getBuildVector(VT, DL, QAmts); 6699 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 6700 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 && 6701 "Expected matchBinaryPredicate to return one element for " 6702 "SPLAT_VECTORs"); 6703 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 6704 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 6705 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 6706 } else { 6707 PVal = PAmts[0]; 6708 KVal = KAmts[0]; 6709 QVal = QAmts[0]; 6710 } 6711 6712 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) { 6713 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT)) 6714 return SDValue(); // FIXME: Could/should use `ISD::ADD`? 6715 assert(CompTargetNode.getValueType() == N.getValueType() && 6716 "Expecting that the types on LHS and RHS of comparisons match."); 6717 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode); 6718 } 6719 6720 // (mul N, P) 6721 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6722 Created.push_back(Op0.getNode()); 6723 6724 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6725 // divisors as a performance improvement, since rotating by 0 is a no-op. 6726 if (HadEvenDivisor) { 6727 // We need ROTR to do this. 6728 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6729 return SDValue(); 6730 // UREM: (rotr (mul N, P), K) 6731 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6732 Created.push_back(Op0.getNode()); 6733 } 6734 6735 // UREM: (setule/setugt (rotr (mul N, P), K), Q) 6736 SDValue NewCC = 6737 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 6738 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 6739 if (!HadTautologicalInvertedLanes) 6740 return NewCC; 6741 6742 // If any lanes previously compared always-false, the NewCC will give 6743 // always-true result for them, so we need to fixup those lanes. 6744 // Or the other way around for inequality predicate. 6745 assert(VT.isVector() && "Can/should only get here for vectors."); 6746 Created.push_back(NewCC.getNode()); 6747 6748 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6749 // if C2 is not less than C1, the comparison is always false. 6750 // But we have produced the comparison that will give the 6751 // opposive tautological answer. So these lanes would need to be fixed up. 6752 SDValue TautologicalInvertedChannels = 6753 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE); 6754 Created.push_back(TautologicalInvertedChannels.getNode()); 6755 6756 // NOTE: we avoid letting illegal types through even if we're before legalize 6757 // ops – legalization has a hard time producing good code for this. 6758 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) { 6759 // If we have a vector select, let's replace the comparison results in the 6760 // affected lanes with the correct tautological result. 6761 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true, 6762 DL, SETCCVT, SETCCVT); 6763 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels, 6764 Replacement, NewCC); 6765 } 6766 6767 // Else, we can just invert the comparison result in the appropriate lanes. 6768 // 6769 // NOTE: see the note above VSELECT above. 6770 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT)) 6771 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC, 6772 TautologicalInvertedChannels); 6773 6774 return SDValue(); // Don't know how to lower. 6775 } 6776 6777 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE 6778 /// where the divisor is constant and the comparison target is zero, 6779 /// return a DAG expression that will generate the same comparison result 6780 /// using only multiplications, additions and shifts/rotations. 6781 /// Ref: "Hacker's Delight" 10-17. 6782 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode, 6783 SDValue CompTargetNode, 6784 ISD::CondCode Cond, 6785 DAGCombinerInfo &DCI, 6786 const SDLoc &DL) const { 6787 SmallVector<SDNode *, 7> Built; 6788 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 6789 DCI, DL, Built)) { 6790 assert(Built.size() <= 7 && "Max size prediction failed."); 6791 for (SDNode *N : Built) 6792 DCI.AddToWorklist(N); 6793 return Folded; 6794 } 6795 6796 return SDValue(); 6797 } 6798 6799 SDValue 6800 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode, 6801 SDValue CompTargetNode, ISD::CondCode Cond, 6802 DAGCombinerInfo &DCI, const SDLoc &DL, 6803 SmallVectorImpl<SDNode *> &Created) const { 6804 // Fold: 6805 // (seteq/ne (srem N, D), 0) 6806 // To: 6807 // (setule/ugt (rotr (add (mul N, P), A), K), Q) 6808 // 6809 // - D must be constant, with D = D0 * 2^K where D0 is odd 6810 // - P is the multiplicative inverse of D0 modulo 2^W 6811 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k))) 6812 // - Q = floor((2 * A) / (2^K)) 6813 // where W is the width of the common type of N and D. 6814 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 6815 "Only applicable for (in)equality comparisons."); 6816 6817 SelectionDAG &DAG = DCI.DAG; 6818 6819 EVT VT = REMNode.getValueType(); 6820 EVT SVT = VT.getScalarType(); 6821 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize()); 6822 EVT ShSVT = ShVT.getScalarType(); 6823 6824 // If we are after ops legalization, and MUL is unavailable, we can not 6825 // proceed. 6826 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 6827 return SDValue(); 6828 6829 // TODO: Could support comparing with non-zero too. 6830 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode); 6831 if (!CompTarget || !CompTarget->isZero()) 6832 return SDValue(); 6833 6834 bool HadIntMinDivisor = false; 6835 bool HadOneDivisor = false; 6836 bool AllDivisorsAreOnes = true; 6837 bool HadEvenDivisor = false; 6838 bool NeedToApplyOffset = false; 6839 bool AllDivisorsArePowerOfTwo = true; 6840 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts; 6841 6842 auto BuildSREMPattern = [&](ConstantSDNode *C) { 6843 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6844 if (C->isZero()) 6845 return false; 6846 6847 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine. 6848 6849 // WARNING: this fold is only valid for positive divisors! 6850 APInt D = C->getAPIntValue(); 6851 if (D.isNegative()) 6852 D.negate(); // `rem %X, -C` is equivalent to `rem %X, C` 6853 6854 HadIntMinDivisor |= D.isMinSignedValue(); 6855 6856 // If all divisors are ones, we will prefer to avoid the fold. 6857 HadOneDivisor |= D.isOne(); 6858 AllDivisorsAreOnes &= D.isOne(); 6859 6860 // Decompose D into D0 * 2^K 6861 unsigned K = D.countr_zero(); 6862 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 6863 APInt D0 = D.lshr(K); 6864 6865 if (!D.isMinSignedValue()) { 6866 // D is even if it has trailing zeros; unless it's INT_MIN, in which case 6867 // we don't care about this lane in this fold, we'll special-handle it. 6868 HadEvenDivisor |= (K != 0); 6869 } 6870 6871 // D is a power-of-two if D0 is one. This includes INT_MIN. 6872 // If all divisors are power-of-two, we will prefer to avoid the fold. 6873 AllDivisorsArePowerOfTwo &= D0.isOne(); 6874 6875 // P = inv(D0, 2^W) 6876 // 2^W requires W + 1 bits, so we have to extend and then truncate. 6877 unsigned W = D.getBitWidth(); 6878 APInt P = D0.zext(W + 1) 6879 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 6880 .trunc(W); 6881 assert(!P.isZero() && "No multiplicative inverse!"); // unreachable 6882 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 6883 6884 // A = floor((2^(W - 1) - 1) / D0) & -2^K 6885 APInt A = APInt::getSignedMaxValue(W).udiv(D0); 6886 A.clearLowBits(K); 6887 6888 if (!D.isMinSignedValue()) { 6889 // If divisor INT_MIN, then we don't care about this lane in this fold, 6890 // we'll special-handle it. 6891 NeedToApplyOffset |= A != 0; 6892 } 6893 6894 // Q = floor((2 * A) / (2^K)) 6895 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K)); 6896 6897 assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) && 6898 "We are expecting that A is always less than all-ones for SVT"); 6899 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 6900 "We are expecting that K is always less than all-ones for ShSVT"); 6901 6902 // If the divisor is 1 the result can be constant-folded. Likewise, we 6903 // don't care about INT_MIN lanes, those can be set to undef if appropriate. 6904 if (D.isOne()) { 6905 // Set P, A and K to a bogus values so we can try to splat them. 6906 P = 0; 6907 A = -1; 6908 K = -1; 6909 6910 // x ?% 1 == 0 <--> true <--> x u<= -1 6911 Q = -1; 6912 } 6913 6914 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 6915 AAmts.push_back(DAG.getConstant(A, DL, SVT)); 6916 KAmts.push_back( 6917 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 6918 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 6919 return true; 6920 }; 6921 6922 SDValue N = REMNode.getOperand(0); 6923 SDValue D = REMNode.getOperand(1); 6924 6925 // Collect the values from each element. 6926 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern)) 6927 return SDValue(); 6928 6929 // If this is a srem by a one, avoid the fold since it can be constant-folded. 6930 if (AllDivisorsAreOnes) 6931 return SDValue(); 6932 6933 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold 6934 // since it can be best implemented as a bit test. 6935 if (AllDivisorsArePowerOfTwo) 6936 return SDValue(); 6937 6938 SDValue PVal, AVal, KVal, QVal; 6939 if (D.getOpcode() == ISD::BUILD_VECTOR) { 6940 if (HadOneDivisor) { 6941 // Try to turn PAmts into a splat, since we don't care about the values 6942 // that are currently '0'. If we can't, just keep '0'`s. 6943 turnVectorIntoSplatVector(PAmts, isNullConstant); 6944 // Try to turn AAmts into a splat, since we don't care about the 6945 // values that are currently '-1'. If we can't, change them to '0'`s. 6946 turnVectorIntoSplatVector(AAmts, isAllOnesConstant, 6947 DAG.getConstant(0, DL, SVT)); 6948 // Try to turn KAmts into a splat, since we don't care about the values 6949 // that are currently '-1'. If we can't, change them to '0'`s. 6950 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 6951 DAG.getConstant(0, DL, ShSVT)); 6952 } 6953 6954 PVal = DAG.getBuildVector(VT, DL, PAmts); 6955 AVal = DAG.getBuildVector(VT, DL, AAmts); 6956 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 6957 QVal = DAG.getBuildVector(VT, DL, QAmts); 6958 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 6959 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 && 6960 QAmts.size() == 1 && 6961 "Expected matchUnaryPredicate to return one element for scalable " 6962 "vectors"); 6963 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 6964 AVal = DAG.getSplatVector(VT, DL, AAmts[0]); 6965 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 6966 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 6967 } else { 6968 assert(isa<ConstantSDNode>(D) && "Expected a constant"); 6969 PVal = PAmts[0]; 6970 AVal = AAmts[0]; 6971 KVal = KAmts[0]; 6972 QVal = QAmts[0]; 6973 } 6974 6975 // (mul N, P) 6976 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6977 Created.push_back(Op0.getNode()); 6978 6979 if (NeedToApplyOffset) { 6980 // We need ADD to do this. 6981 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT)) 6982 return SDValue(); 6983 6984 // (add (mul N, P), A) 6985 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal); 6986 Created.push_back(Op0.getNode()); 6987 } 6988 6989 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6990 // divisors as a performance improvement, since rotating by 0 is a no-op. 6991 if (HadEvenDivisor) { 6992 // We need ROTR to do this. 6993 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6994 return SDValue(); 6995 // SREM: (rotr (add (mul N, P), A), K) 6996 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6997 Created.push_back(Op0.getNode()); 6998 } 6999 7000 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q) 7001 SDValue Fold = 7002 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 7003 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 7004 7005 // If we didn't have lanes with INT_MIN divisor, then we're done. 7006 if (!HadIntMinDivisor) 7007 return Fold; 7008 7009 // That fold is only valid for positive divisors. Which effectively means, 7010 // it is invalid for INT_MIN divisors. So if we have such a lane, 7011 // we must fix-up results for said lanes. 7012 assert(VT.isVector() && "Can/should only get here for vectors."); 7013 7014 // NOTE: we avoid letting illegal types through even if we're before legalize 7015 // ops – legalization has a hard time producing good code for the code that 7016 // follows. 7017 if (!isOperationLegalOrCustom(ISD::SETCC, SETCCVT) || 7018 !isOperationLegalOrCustom(ISD::AND, VT) || 7019 !isCondCodeLegalOrCustom(Cond, VT.getSimpleVT()) || 7020 !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) 7021 return SDValue(); 7022 7023 Created.push_back(Fold.getNode()); 7024 7025 SDValue IntMin = DAG.getConstant( 7026 APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT); 7027 SDValue IntMax = DAG.getConstant( 7028 APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT); 7029 SDValue Zero = 7030 DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT); 7031 7032 // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded. 7033 SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ); 7034 Created.push_back(DivisorIsIntMin.getNode()); 7035 7036 // (N s% INT_MIN) ==/!= 0 <--> (N & INT_MAX) ==/!= 0 7037 SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax); 7038 Created.push_back(Masked.getNode()); 7039 SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond); 7040 Created.push_back(MaskedIsZero.getNode()); 7041 7042 // To produce final result we need to blend 2 vectors: 'SetCC' and 7043 // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick 7044 // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is 7045 // constant-folded, select can get lowered to a shuffle with constant mask. 7046 SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin, 7047 MaskedIsZero, Fold); 7048 7049 return Blended; 7050 } 7051 7052 bool TargetLowering:: 7053 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 7054 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 7055 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 7056 "be a constant integer"); 7057 return true; 7058 } 7059 7060 return false; 7061 } 7062 7063 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 7064 const DenormalMode &Mode) const { 7065 SDLoc DL(Op); 7066 EVT VT = Op.getValueType(); 7067 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7068 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 7069 7070 // This is specifically a check for the handling of denormal inputs, not the 7071 // result. 7072 if (Mode.Input == DenormalMode::PreserveSign || 7073 Mode.Input == DenormalMode::PositiveZero) { 7074 // Test = X == 0.0 7075 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 7076 } 7077 7078 // Testing it with denormal inputs to avoid wrong estimate. 7079 // 7080 // Test = fabs(X) < SmallestNormal 7081 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 7082 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 7083 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 7084 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 7085 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 7086 } 7087 7088 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 7089 bool LegalOps, bool OptForSize, 7090 NegatibleCost &Cost, 7091 unsigned Depth) const { 7092 // fneg is removable even if it has multiple uses. 7093 if (Op.getOpcode() == ISD::FNEG || Op.getOpcode() == ISD::VP_FNEG) { 7094 Cost = NegatibleCost::Cheaper; 7095 return Op.getOperand(0); 7096 } 7097 7098 // Don't recurse exponentially. 7099 if (Depth > SelectionDAG::MaxRecursionDepth) 7100 return SDValue(); 7101 7102 // Pre-increment recursion depth for use in recursive calls. 7103 ++Depth; 7104 const SDNodeFlags Flags = Op->getFlags(); 7105 const TargetOptions &Options = DAG.getTarget().Options; 7106 EVT VT = Op.getValueType(); 7107 unsigned Opcode = Op.getOpcode(); 7108 7109 // Don't allow anything with multiple uses unless we know it is free. 7110 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) { 7111 bool IsFreeExtend = Opcode == ISD::FP_EXTEND && 7112 isFPExtFree(VT, Op.getOperand(0).getValueType()); 7113 if (!IsFreeExtend) 7114 return SDValue(); 7115 } 7116 7117 auto RemoveDeadNode = [&](SDValue N) { 7118 if (N && N.getNode()->use_empty()) 7119 DAG.RemoveDeadNode(N.getNode()); 7120 }; 7121 7122 SDLoc DL(Op); 7123 7124 // Because getNegatedExpression can delete nodes we need a handle to keep 7125 // temporary nodes alive in case the recursion manages to create an identical 7126 // node. 7127 std::list<HandleSDNode> Handles; 7128 7129 switch (Opcode) { 7130 case ISD::ConstantFP: { 7131 // Don't invert constant FP values after legalization unless the target says 7132 // the negated constant is legal. 7133 bool IsOpLegal = 7134 isOperationLegal(ISD::ConstantFP, VT) || 7135 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT, 7136 OptForSize); 7137 7138 if (LegalOps && !IsOpLegal) 7139 break; 7140 7141 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 7142 V.changeSign(); 7143 SDValue CFP = DAG.getConstantFP(V, DL, VT); 7144 7145 // If we already have the use of the negated floating constant, it is free 7146 // to negate it even it has multiple uses. 7147 if (!Op.hasOneUse() && CFP.use_empty()) 7148 break; 7149 Cost = NegatibleCost::Neutral; 7150 return CFP; 7151 } 7152 case ISD::BUILD_VECTOR: { 7153 // Only permit BUILD_VECTOR of constants. 7154 if (llvm::any_of(Op->op_values(), [&](SDValue N) { 7155 return !N.isUndef() && !isa<ConstantFPSDNode>(N); 7156 })) 7157 break; 7158 7159 bool IsOpLegal = 7160 (isOperationLegal(ISD::ConstantFP, VT) && 7161 isOperationLegal(ISD::BUILD_VECTOR, VT)) || 7162 llvm::all_of(Op->op_values(), [&](SDValue N) { 7163 return N.isUndef() || 7164 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT, 7165 OptForSize); 7166 }); 7167 7168 if (LegalOps && !IsOpLegal) 7169 break; 7170 7171 SmallVector<SDValue, 4> Ops; 7172 for (SDValue C : Op->op_values()) { 7173 if (C.isUndef()) { 7174 Ops.push_back(C); 7175 continue; 7176 } 7177 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF(); 7178 V.changeSign(); 7179 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType())); 7180 } 7181 Cost = NegatibleCost::Neutral; 7182 return DAG.getBuildVector(VT, DL, Ops); 7183 } 7184 case ISD::FADD: { 7185 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 7186 break; 7187 7188 // After operation legalization, it might not be legal to create new FSUBs. 7189 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT)) 7190 break; 7191 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 7192 7193 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y) 7194 NegatibleCost CostX = NegatibleCost::Expensive; 7195 SDValue NegX = 7196 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 7197 // Prevent this node from being deleted by the next call. 7198 if (NegX) 7199 Handles.emplace_back(NegX); 7200 7201 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X) 7202 NegatibleCost CostY = NegatibleCost::Expensive; 7203 SDValue NegY = 7204 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 7205 7206 // We're done with the handles. 7207 Handles.clear(); 7208 7209 // Negate the X if its cost is less or equal than Y. 7210 if (NegX && (CostX <= CostY)) { 7211 Cost = CostX; 7212 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags); 7213 if (NegY != N) 7214 RemoveDeadNode(NegY); 7215 return N; 7216 } 7217 7218 // Negate the Y if it is not expensive. 7219 if (NegY) { 7220 Cost = CostY; 7221 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags); 7222 if (NegX != N) 7223 RemoveDeadNode(NegX); 7224 return N; 7225 } 7226 break; 7227 } 7228 case ISD::FSUB: { 7229 // We can't turn -(A-B) into B-A when we honor signed zeros. 7230 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 7231 break; 7232 7233 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 7234 // fold (fneg (fsub 0, Y)) -> Y 7235 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true)) 7236 if (C->isZero()) { 7237 Cost = NegatibleCost::Cheaper; 7238 return Y; 7239 } 7240 7241 // fold (fneg (fsub X, Y)) -> (fsub Y, X) 7242 Cost = NegatibleCost::Neutral; 7243 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags); 7244 } 7245 case ISD::FMUL: 7246 case ISD::FDIV: { 7247 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 7248 7249 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 7250 NegatibleCost CostX = NegatibleCost::Expensive; 7251 SDValue NegX = 7252 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 7253 // Prevent this node from being deleted by the next call. 7254 if (NegX) 7255 Handles.emplace_back(NegX); 7256 7257 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 7258 NegatibleCost CostY = NegatibleCost::Expensive; 7259 SDValue NegY = 7260 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 7261 7262 // We're done with the handles. 7263 Handles.clear(); 7264 7265 // Negate the X if its cost is less or equal than Y. 7266 if (NegX && (CostX <= CostY)) { 7267 Cost = CostX; 7268 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags); 7269 if (NegY != N) 7270 RemoveDeadNode(NegY); 7271 return N; 7272 } 7273 7274 // Ignore X * 2.0 because that is expected to be canonicalized to X + X. 7275 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1))) 7276 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL) 7277 break; 7278 7279 // Negate the Y if it is not expensive. 7280 if (NegY) { 7281 Cost = CostY; 7282 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags); 7283 if (NegX != N) 7284 RemoveDeadNode(NegX); 7285 return N; 7286 } 7287 break; 7288 } 7289 case ISD::FMA: 7290 case ISD::FMAD: { 7291 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 7292 break; 7293 7294 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2); 7295 NegatibleCost CostZ = NegatibleCost::Expensive; 7296 SDValue NegZ = 7297 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth); 7298 // Give up if fail to negate the Z. 7299 if (!NegZ) 7300 break; 7301 7302 // Prevent this node from being deleted by the next two calls. 7303 Handles.emplace_back(NegZ); 7304 7305 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z)) 7306 NegatibleCost CostX = NegatibleCost::Expensive; 7307 SDValue NegX = 7308 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 7309 // Prevent this node from being deleted by the next call. 7310 if (NegX) 7311 Handles.emplace_back(NegX); 7312 7313 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z)) 7314 NegatibleCost CostY = NegatibleCost::Expensive; 7315 SDValue NegY = 7316 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 7317 7318 // We're done with the handles. 7319 Handles.clear(); 7320 7321 // Negate the X if its cost is less or equal than Y. 7322 if (NegX && (CostX <= CostY)) { 7323 Cost = std::min(CostX, CostZ); 7324 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags); 7325 if (NegY != N) 7326 RemoveDeadNode(NegY); 7327 return N; 7328 } 7329 7330 // Negate the Y if it is not expensive. 7331 if (NegY) { 7332 Cost = std::min(CostY, CostZ); 7333 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags); 7334 if (NegX != N) 7335 RemoveDeadNode(NegX); 7336 return N; 7337 } 7338 break; 7339 } 7340 7341 case ISD::FP_EXTEND: 7342 case ISD::FSIN: 7343 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 7344 OptForSize, Cost, Depth)) 7345 return DAG.getNode(Opcode, DL, VT, NegV); 7346 break; 7347 case ISD::FP_ROUND: 7348 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 7349 OptForSize, Cost, Depth)) 7350 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1)); 7351 break; 7352 case ISD::SELECT: 7353 case ISD::VSELECT: { 7354 // fold (fneg (select C, LHS, RHS)) -> (select C, (fneg LHS), (fneg RHS)) 7355 // iff at least one cost is cheaper and the other is neutral/cheaper 7356 SDValue LHS = Op.getOperand(1); 7357 NegatibleCost CostLHS = NegatibleCost::Expensive; 7358 SDValue NegLHS = 7359 getNegatedExpression(LHS, DAG, LegalOps, OptForSize, CostLHS, Depth); 7360 if (!NegLHS || CostLHS > NegatibleCost::Neutral) { 7361 RemoveDeadNode(NegLHS); 7362 break; 7363 } 7364 7365 // Prevent this node from being deleted by the next call. 7366 Handles.emplace_back(NegLHS); 7367 7368 SDValue RHS = Op.getOperand(2); 7369 NegatibleCost CostRHS = NegatibleCost::Expensive; 7370 SDValue NegRHS = 7371 getNegatedExpression(RHS, DAG, LegalOps, OptForSize, CostRHS, Depth); 7372 7373 // We're done with the handles. 7374 Handles.clear(); 7375 7376 if (!NegRHS || CostRHS > NegatibleCost::Neutral || 7377 (CostLHS != NegatibleCost::Cheaper && 7378 CostRHS != NegatibleCost::Cheaper)) { 7379 RemoveDeadNode(NegLHS); 7380 RemoveDeadNode(NegRHS); 7381 break; 7382 } 7383 7384 Cost = std::min(CostLHS, CostRHS); 7385 return DAG.getSelect(DL, VT, Op.getOperand(0), NegLHS, NegRHS); 7386 } 7387 } 7388 7389 return SDValue(); 7390 } 7391 7392 //===----------------------------------------------------------------------===// 7393 // Legalization Utilities 7394 //===----------------------------------------------------------------------===// 7395 7396 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, 7397 SDValue LHS, SDValue RHS, 7398 SmallVectorImpl<SDValue> &Result, 7399 EVT HiLoVT, SelectionDAG &DAG, 7400 MulExpansionKind Kind, SDValue LL, 7401 SDValue LH, SDValue RL, SDValue RH) const { 7402 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 7403 Opcode == ISD::SMUL_LOHI); 7404 7405 bool HasMULHS = (Kind == MulExpansionKind::Always) || 7406 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 7407 bool HasMULHU = (Kind == MulExpansionKind::Always) || 7408 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 7409 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 7410 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 7411 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 7412 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 7413 7414 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 7415 return false; 7416 7417 unsigned OuterBitSize = VT.getScalarSizeInBits(); 7418 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 7419 7420 // LL, LH, RL, and RH must be either all NULL or all set to a value. 7421 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 7422 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 7423 7424 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 7425 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 7426 bool Signed) -> bool { 7427 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 7428 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 7429 Hi = SDValue(Lo.getNode(), 1); 7430 return true; 7431 } 7432 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 7433 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 7434 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 7435 return true; 7436 } 7437 return false; 7438 }; 7439 7440 SDValue Lo, Hi; 7441 7442 if (!LL.getNode() && !RL.getNode() && 7443 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 7444 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 7445 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 7446 } 7447 7448 if (!LL.getNode()) 7449 return false; 7450 7451 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 7452 if (DAG.MaskedValueIsZero(LHS, HighMask) && 7453 DAG.MaskedValueIsZero(RHS, HighMask)) { 7454 // The inputs are both zero-extended. 7455 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 7456 Result.push_back(Lo); 7457 Result.push_back(Hi); 7458 if (Opcode != ISD::MUL) { 7459 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 7460 Result.push_back(Zero); 7461 Result.push_back(Zero); 7462 } 7463 return true; 7464 } 7465 } 7466 7467 if (!VT.isVector() && Opcode == ISD::MUL && 7468 DAG.ComputeMaxSignificantBits(LHS) <= InnerBitSize && 7469 DAG.ComputeMaxSignificantBits(RHS) <= InnerBitSize) { 7470 // The input values are both sign-extended. 7471 // TODO non-MUL case? 7472 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 7473 Result.push_back(Lo); 7474 Result.push_back(Hi); 7475 return true; 7476 } 7477 } 7478 7479 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 7480 SDValue Shift = DAG.getShiftAmountConstant(ShiftAmount, VT, dl); 7481 7482 if (!LH.getNode() && !RH.getNode() && 7483 isOperationLegalOrCustom(ISD::SRL, VT) && 7484 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 7485 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 7486 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 7487 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 7488 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 7489 } 7490 7491 if (!LH.getNode()) 7492 return false; 7493 7494 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 7495 return false; 7496 7497 Result.push_back(Lo); 7498 7499 if (Opcode == ISD::MUL) { 7500 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 7501 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 7502 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 7503 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 7504 Result.push_back(Hi); 7505 return true; 7506 } 7507 7508 // Compute the full width result. 7509 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 7510 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 7511 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 7512 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 7513 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 7514 }; 7515 7516 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 7517 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 7518 return false; 7519 7520 // This is effectively the add part of a multiply-add of half-sized operands, 7521 // so it cannot overflow. 7522 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 7523 7524 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 7525 return false; 7526 7527 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 7528 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7529 7530 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) && 7531 isOperationLegalOrCustom(ISD::ADDE, VT)); 7532 if (UseGlue) 7533 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 7534 Merge(Lo, Hi)); 7535 else 7536 Next = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(VT, BoolType), Next, 7537 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType)); 7538 7539 SDValue Carry = Next.getValue(1); 7540 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7541 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 7542 7543 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 7544 return false; 7545 7546 if (UseGlue) 7547 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 7548 Carry); 7549 else 7550 Hi = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi, 7551 Zero, Carry); 7552 7553 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 7554 7555 if (Opcode == ISD::SMUL_LOHI) { 7556 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 7557 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 7558 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 7559 7560 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 7561 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 7562 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 7563 } 7564 7565 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7566 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 7567 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7568 return true; 7569 } 7570 7571 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 7572 SelectionDAG &DAG, MulExpansionKind Kind, 7573 SDValue LL, SDValue LH, SDValue RL, 7574 SDValue RH) const { 7575 SmallVector<SDValue, 2> Result; 7576 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N), 7577 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 7578 DAG, Kind, LL, LH, RL, RH); 7579 if (Ok) { 7580 assert(Result.size() == 2); 7581 Lo = Result[0]; 7582 Hi = Result[1]; 7583 } 7584 return Ok; 7585 } 7586 7587 // Optimize unsigned division or remainder by constants for types twice as large 7588 // as a legal VT. 7589 // 7590 // If (1 << (BitWidth / 2)) % Constant == 1, then the remainder 7591 // can be computed 7592 // as: 7593 // Sum += __builtin_uadd_overflow(Lo, High, &Sum); 7594 // Remainder = Sum % Constant 7595 // This is based on "Remainder by Summing Digits" from Hacker's Delight. 7596 // 7597 // For division, we can compute the remainder using the algorithm described 7598 // above, subtract it from the dividend to get an exact multiple of Constant. 7599 // Then multiply that extact multiply by the multiplicative inverse modulo 7600 // (1 << (BitWidth / 2)) to get the quotient. 7601 7602 // If Constant is even, we can shift right the dividend and the divisor by the 7603 // number of trailing zeros in Constant before applying the remainder algorithm. 7604 // If we're after the quotient, we can subtract this value from the shifted 7605 // dividend and multiply by the multiplicative inverse of the shifted divisor. 7606 // If we want the remainder, we shift the value left by the number of trailing 7607 // zeros and add the bits that were shifted out of the dividend. 7608 bool TargetLowering::expandDIVREMByConstant(SDNode *N, 7609 SmallVectorImpl<SDValue> &Result, 7610 EVT HiLoVT, SelectionDAG &DAG, 7611 SDValue LL, SDValue LH) const { 7612 unsigned Opcode = N->getOpcode(); 7613 EVT VT = N->getValueType(0); 7614 7615 // TODO: Support signed division/remainder. 7616 if (Opcode == ISD::SREM || Opcode == ISD::SDIV || Opcode == ISD::SDIVREM) 7617 return false; 7618 assert( 7619 (Opcode == ISD::UREM || Opcode == ISD::UDIV || Opcode == ISD::UDIVREM) && 7620 "Unexpected opcode"); 7621 7622 auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7623 if (!CN) 7624 return false; 7625 7626 APInt Divisor = CN->getAPIntValue(); 7627 unsigned BitWidth = Divisor.getBitWidth(); 7628 unsigned HBitWidth = BitWidth / 2; 7629 assert(VT.getScalarSizeInBits() == BitWidth && 7630 HiLoVT.getScalarSizeInBits() == HBitWidth && "Unexpected VTs"); 7631 7632 // Divisor needs to less than (1 << HBitWidth). 7633 APInt HalfMaxPlus1 = APInt::getOneBitSet(BitWidth, HBitWidth); 7634 if (Divisor.uge(HalfMaxPlus1)) 7635 return false; 7636 7637 // We depend on the UREM by constant optimization in DAGCombiner that requires 7638 // high multiply. 7639 if (!isOperationLegalOrCustom(ISD::MULHU, HiLoVT) && 7640 !isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT)) 7641 return false; 7642 7643 // Don't expand if optimizing for size. 7644 if (DAG.shouldOptForSize()) 7645 return false; 7646 7647 // Early out for 0 or 1 divisors. 7648 if (Divisor.ule(1)) 7649 return false; 7650 7651 // If the divisor is even, shift it until it becomes odd. 7652 unsigned TrailingZeros = 0; 7653 if (!Divisor[0]) { 7654 TrailingZeros = Divisor.countr_zero(); 7655 Divisor.lshrInPlace(TrailingZeros); 7656 } 7657 7658 SDLoc dl(N); 7659 SDValue Sum; 7660 SDValue PartialRem; 7661 7662 // If (1 << HBitWidth) % divisor == 1, we can add the two halves together and 7663 // then add in the carry. 7664 // TODO: If we can't split it in half, we might be able to split into 3 or 7665 // more pieces using a smaller bit width. 7666 if (HalfMaxPlus1.urem(Divisor).isOne()) { 7667 assert(!LL == !LH && "Expected both input halves or no input halves!"); 7668 if (!LL) 7669 std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT); 7670 7671 // Shift the input by the number of TrailingZeros in the divisor. The 7672 // shifted out bits will be added to the remainder later. 7673 if (TrailingZeros) { 7674 // Save the shifted off bits if we need the remainder. 7675 if (Opcode != ISD::UDIV) { 7676 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros); 7677 PartialRem = DAG.getNode(ISD::AND, dl, HiLoVT, LL, 7678 DAG.getConstant(Mask, dl, HiLoVT)); 7679 } 7680 7681 LL = DAG.getNode( 7682 ISD::OR, dl, HiLoVT, 7683 DAG.getNode(ISD::SRL, dl, HiLoVT, LL, 7684 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl)), 7685 DAG.getNode(ISD::SHL, dl, HiLoVT, LH, 7686 DAG.getShiftAmountConstant(HBitWidth - TrailingZeros, 7687 HiLoVT, dl))); 7688 LH = DAG.getNode(ISD::SRL, dl, HiLoVT, LH, 7689 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl)); 7690 } 7691 7692 // Use uaddo_carry if we can, otherwise use a compare to detect overflow. 7693 EVT SetCCType = 7694 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), HiLoVT); 7695 if (isOperationLegalOrCustom(ISD::UADDO_CARRY, HiLoVT)) { 7696 SDVTList VTList = DAG.getVTList(HiLoVT, SetCCType); 7697 Sum = DAG.getNode(ISD::UADDO, dl, VTList, LL, LH); 7698 Sum = DAG.getNode(ISD::UADDO_CARRY, dl, VTList, Sum, 7699 DAG.getConstant(0, dl, HiLoVT), Sum.getValue(1)); 7700 } else { 7701 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, LL, LH); 7702 SDValue Carry = DAG.getSetCC(dl, SetCCType, Sum, LL, ISD::SETULT); 7703 // If the boolean for the target is 0 or 1, we can add the setcc result 7704 // directly. 7705 if (getBooleanContents(HiLoVT) == 7706 TargetLoweringBase::ZeroOrOneBooleanContent) 7707 Carry = DAG.getZExtOrTrunc(Carry, dl, HiLoVT); 7708 else 7709 Carry = DAG.getSelect(dl, HiLoVT, Carry, DAG.getConstant(1, dl, HiLoVT), 7710 DAG.getConstant(0, dl, HiLoVT)); 7711 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, Carry); 7712 } 7713 } 7714 7715 // If we didn't find a sum, we can't do the expansion. 7716 if (!Sum) 7717 return false; 7718 7719 // Perform a HiLoVT urem on the Sum using truncated divisor. 7720 SDValue RemL = 7721 DAG.getNode(ISD::UREM, dl, HiLoVT, Sum, 7722 DAG.getConstant(Divisor.trunc(HBitWidth), dl, HiLoVT)); 7723 SDValue RemH = DAG.getConstant(0, dl, HiLoVT); 7724 7725 if (Opcode != ISD::UREM) { 7726 // Subtract the remainder from the shifted dividend. 7727 SDValue Dividend = DAG.getNode(ISD::BUILD_PAIR, dl, VT, LL, LH); 7728 SDValue Rem = DAG.getNode(ISD::BUILD_PAIR, dl, VT, RemL, RemH); 7729 7730 Dividend = DAG.getNode(ISD::SUB, dl, VT, Dividend, Rem); 7731 7732 // Multiply by the multiplicative inverse of the divisor modulo 7733 // (1 << BitWidth). 7734 APInt Mod = APInt::getSignedMinValue(BitWidth + 1); 7735 APInt MulFactor = Divisor.zext(BitWidth + 1); 7736 MulFactor = MulFactor.multiplicativeInverse(Mod); 7737 MulFactor = MulFactor.trunc(BitWidth); 7738 7739 SDValue Quotient = DAG.getNode(ISD::MUL, dl, VT, Dividend, 7740 DAG.getConstant(MulFactor, dl, VT)); 7741 7742 // Split the quotient into low and high parts. 7743 SDValue QuotL, QuotH; 7744 std::tie(QuotL, QuotH) = DAG.SplitScalar(Quotient, dl, HiLoVT, HiLoVT); 7745 Result.push_back(QuotL); 7746 Result.push_back(QuotH); 7747 } 7748 7749 if (Opcode != ISD::UDIV) { 7750 // If we shifted the input, shift the remainder left and add the bits we 7751 // shifted off the input. 7752 if (TrailingZeros) { 7753 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros); 7754 RemL = DAG.getNode(ISD::SHL, dl, HiLoVT, RemL, 7755 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl)); 7756 RemL = DAG.getNode(ISD::ADD, dl, HiLoVT, RemL, PartialRem); 7757 } 7758 Result.push_back(RemL); 7759 Result.push_back(DAG.getConstant(0, dl, HiLoVT)); 7760 } 7761 7762 return true; 7763 } 7764 7765 // Check that (every element of) Z is undef or not an exact multiple of BW. 7766 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) { 7767 return ISD::matchUnaryPredicate( 7768 Z, 7769 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; }, 7770 true); 7771 } 7772 7773 static SDValue expandVPFunnelShift(SDNode *Node, SelectionDAG &DAG) { 7774 EVT VT = Node->getValueType(0); 7775 SDValue ShX, ShY; 7776 SDValue ShAmt, InvShAmt; 7777 SDValue X = Node->getOperand(0); 7778 SDValue Y = Node->getOperand(1); 7779 SDValue Z = Node->getOperand(2); 7780 SDValue Mask = Node->getOperand(3); 7781 SDValue VL = Node->getOperand(4); 7782 7783 unsigned BW = VT.getScalarSizeInBits(); 7784 bool IsFSHL = Node->getOpcode() == ISD::VP_FSHL; 7785 SDLoc DL(SDValue(Node, 0)); 7786 7787 EVT ShVT = Z.getValueType(); 7788 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 7789 // fshl: X << C | Y >> (BW - C) 7790 // fshr: X << (BW - C) | Y >> C 7791 // where C = Z % BW is not zero 7792 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7793 ShAmt = DAG.getNode(ISD::VP_UREM, DL, ShVT, Z, BitWidthC, Mask, VL); 7794 InvShAmt = DAG.getNode(ISD::VP_SUB, DL, ShVT, BitWidthC, ShAmt, Mask, VL); 7795 ShX = DAG.getNode(ISD::VP_SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt, Mask, 7796 VL); 7797 ShY = DAG.getNode(ISD::VP_LSHR, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt, Mask, 7798 VL); 7799 } else { 7800 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW)) 7801 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW) 7802 SDValue BitMask = DAG.getConstant(BW - 1, DL, ShVT); 7803 if (isPowerOf2_32(BW)) { 7804 // Z % BW -> Z & (BW - 1) 7805 ShAmt = DAG.getNode(ISD::VP_AND, DL, ShVT, Z, BitMask, Mask, VL); 7806 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1) 7807 SDValue NotZ = DAG.getNode(ISD::VP_XOR, DL, ShVT, Z, 7808 DAG.getAllOnesConstant(DL, ShVT), Mask, VL); 7809 InvShAmt = DAG.getNode(ISD::VP_AND, DL, ShVT, NotZ, BitMask, Mask, VL); 7810 } else { 7811 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7812 ShAmt = DAG.getNode(ISD::VP_UREM, DL, ShVT, Z, BitWidthC, Mask, VL); 7813 InvShAmt = DAG.getNode(ISD::VP_SUB, DL, ShVT, BitMask, ShAmt, Mask, VL); 7814 } 7815 7816 SDValue One = DAG.getConstant(1, DL, ShVT); 7817 if (IsFSHL) { 7818 ShX = DAG.getNode(ISD::VP_SHL, DL, VT, X, ShAmt, Mask, VL); 7819 SDValue ShY1 = DAG.getNode(ISD::VP_LSHR, DL, VT, Y, One, Mask, VL); 7820 ShY = DAG.getNode(ISD::VP_LSHR, DL, VT, ShY1, InvShAmt, Mask, VL); 7821 } else { 7822 SDValue ShX1 = DAG.getNode(ISD::VP_SHL, DL, VT, X, One, Mask, VL); 7823 ShX = DAG.getNode(ISD::VP_SHL, DL, VT, ShX1, InvShAmt, Mask, VL); 7824 ShY = DAG.getNode(ISD::VP_LSHR, DL, VT, Y, ShAmt, Mask, VL); 7825 } 7826 } 7827 return DAG.getNode(ISD::VP_OR, DL, VT, ShX, ShY, Mask, VL); 7828 } 7829 7830 SDValue TargetLowering::expandFunnelShift(SDNode *Node, 7831 SelectionDAG &DAG) const { 7832 if (Node->isVPOpcode()) 7833 return expandVPFunnelShift(Node, DAG); 7834 7835 EVT VT = Node->getValueType(0); 7836 7837 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 7838 !isOperationLegalOrCustom(ISD::SRL, VT) || 7839 !isOperationLegalOrCustom(ISD::SUB, VT) || 7840 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 7841 return SDValue(); 7842 7843 SDValue X = Node->getOperand(0); 7844 SDValue Y = Node->getOperand(1); 7845 SDValue Z = Node->getOperand(2); 7846 7847 unsigned BW = VT.getScalarSizeInBits(); 7848 bool IsFSHL = Node->getOpcode() == ISD::FSHL; 7849 SDLoc DL(SDValue(Node, 0)); 7850 7851 EVT ShVT = Z.getValueType(); 7852 7853 // If a funnel shift in the other direction is more supported, use it. 7854 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL; 7855 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 7856 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) { 7857 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 7858 // fshl X, Y, Z -> fshr X, Y, -Z 7859 // fshr X, Y, Z -> fshl X, Y, -Z 7860 SDValue Zero = DAG.getConstant(0, DL, ShVT); 7861 Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z); 7862 } else { 7863 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z 7864 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z 7865 SDValue One = DAG.getConstant(1, DL, ShVT); 7866 if (IsFSHL) { 7867 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 7868 X = DAG.getNode(ISD::SRL, DL, VT, X, One); 7869 } else { 7870 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 7871 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One); 7872 } 7873 Z = DAG.getNOT(DL, Z, ShVT); 7874 } 7875 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z); 7876 } 7877 7878 SDValue ShX, ShY; 7879 SDValue ShAmt, InvShAmt; 7880 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 7881 // fshl: X << C | Y >> (BW - C) 7882 // fshr: X << (BW - C) | Y >> C 7883 // where C = Z % BW is not zero 7884 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7885 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 7886 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt); 7887 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt); 7888 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt); 7889 } else { 7890 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW)) 7891 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW) 7892 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT); 7893 if (isPowerOf2_32(BW)) { 7894 // Z % BW -> Z & (BW - 1) 7895 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask); 7896 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1) 7897 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask); 7898 } else { 7899 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7900 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 7901 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt); 7902 } 7903 7904 SDValue One = DAG.getConstant(1, DL, ShVT); 7905 if (IsFSHL) { 7906 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt); 7907 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One); 7908 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt); 7909 } else { 7910 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One); 7911 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt); 7912 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt); 7913 } 7914 } 7915 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY); 7916 } 7917 7918 // TODO: Merge with expandFunnelShift. 7919 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps, 7920 SelectionDAG &DAG) const { 7921 EVT VT = Node->getValueType(0); 7922 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 7923 bool IsLeft = Node->getOpcode() == ISD::ROTL; 7924 SDValue Op0 = Node->getOperand(0); 7925 SDValue Op1 = Node->getOperand(1); 7926 SDLoc DL(SDValue(Node, 0)); 7927 7928 EVT ShVT = Op1.getValueType(); 7929 SDValue Zero = DAG.getConstant(0, DL, ShVT); 7930 7931 // If a rotate in the other direction is more supported, use it. 7932 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL; 7933 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 7934 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) { 7935 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 7936 return DAG.getNode(RevRot, DL, VT, Op0, Sub); 7937 } 7938 7939 if (!AllowVectorOps && VT.isVector() && 7940 (!isOperationLegalOrCustom(ISD::SHL, VT) || 7941 !isOperationLegalOrCustom(ISD::SRL, VT) || 7942 !isOperationLegalOrCustom(ISD::SUB, VT) || 7943 !isOperationLegalOrCustomOrPromote(ISD::OR, VT) || 7944 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 7945 return SDValue(); 7946 7947 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL; 7948 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL; 7949 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 7950 SDValue ShVal; 7951 SDValue HsVal; 7952 if (isPowerOf2_32(EltSizeInBits)) { 7953 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1)) 7954 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1)) 7955 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 7956 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC); 7957 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 7958 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC); 7959 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt); 7960 } else { 7961 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w)) 7962 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w)) 7963 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 7964 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC); 7965 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 7966 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt); 7967 SDValue One = DAG.getConstant(1, DL, ShVT); 7968 HsVal = 7969 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt); 7970 } 7971 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal); 7972 } 7973 7974 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi, 7975 SelectionDAG &DAG) const { 7976 assert(Node->getNumOperands() == 3 && "Not a double-shift!"); 7977 EVT VT = Node->getValueType(0); 7978 unsigned VTBits = VT.getScalarSizeInBits(); 7979 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected"); 7980 7981 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS; 7982 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS; 7983 SDValue ShOpLo = Node->getOperand(0); 7984 SDValue ShOpHi = Node->getOperand(1); 7985 SDValue ShAmt = Node->getOperand(2); 7986 EVT ShAmtVT = ShAmt.getValueType(); 7987 EVT ShAmtCCVT = 7988 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT); 7989 SDLoc dl(Node); 7990 7991 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and 7992 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized 7993 // away during isel. 7994 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 7995 DAG.getConstant(VTBits - 1, dl, ShAmtVT)); 7996 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 7997 DAG.getConstant(VTBits - 1, dl, ShAmtVT)) 7998 : DAG.getConstant(0, dl, VT); 7999 8000 SDValue Tmp2, Tmp3; 8001 if (IsSHL) { 8002 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt); 8003 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt); 8004 } else { 8005 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt); 8006 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt); 8007 } 8008 8009 // If the shift amount is larger or equal than the width of a part we don't 8010 // use the result from the FSHL/FSHR. Insert a test and select the appropriate 8011 // values for large shift amounts. 8012 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 8013 DAG.getConstant(VTBits, dl, ShAmtVT)); 8014 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode, 8015 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE); 8016 8017 if (IsSHL) { 8018 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 8019 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 8020 } else { 8021 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 8022 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 8023 } 8024 } 8025 8026 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 8027 SelectionDAG &DAG) const { 8028 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 8029 SDValue Src = Node->getOperand(OpNo); 8030 EVT SrcVT = Src.getValueType(); 8031 EVT DstVT = Node->getValueType(0); 8032 SDLoc dl(SDValue(Node, 0)); 8033 8034 // FIXME: Only f32 to i64 conversions are supported. 8035 if (SrcVT != MVT::f32 || DstVT != MVT::i64) 8036 return false; 8037 8038 if (Node->isStrictFPOpcode()) 8039 // When a NaN is converted to an integer a trap is allowed. We can't 8040 // use this expansion here because it would eliminate that trap. Other 8041 // traps are also allowed and cannot be eliminated. See 8042 // IEEE 754-2008 sec 5.8. 8043 return false; 8044 8045 // Expand f32 -> i64 conversion 8046 // This algorithm comes from compiler-rt's implementation of fixsfdi: 8047 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c 8048 unsigned SrcEltBits = SrcVT.getScalarSizeInBits(); 8049 EVT IntVT = SrcVT.changeTypeToInteger(); 8050 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout()); 8051 8052 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 8053 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 8054 SDValue Bias = DAG.getConstant(127, dl, IntVT); 8055 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT); 8056 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT); 8057 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 8058 8059 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src); 8060 8061 SDValue ExponentBits = DAG.getNode( 8062 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 8063 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT)); 8064 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 8065 8066 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT, 8067 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 8068 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT)); 8069 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT); 8070 8071 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 8072 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 8073 DAG.getConstant(0x00800000, dl, IntVT)); 8074 8075 R = DAG.getZExtOrTrunc(R, dl, DstVT); 8076 8077 R = DAG.getSelectCC( 8078 dl, Exponent, ExponentLoBit, 8079 DAG.getNode(ISD::SHL, dl, DstVT, R, 8080 DAG.getZExtOrTrunc( 8081 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 8082 dl, IntShVT)), 8083 DAG.getNode(ISD::SRL, dl, DstVT, R, 8084 DAG.getZExtOrTrunc( 8085 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 8086 dl, IntShVT)), 8087 ISD::SETGT); 8088 8089 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT, 8090 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign); 8091 8092 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 8093 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT); 8094 return true; 8095 } 8096 8097 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result, 8098 SDValue &Chain, 8099 SelectionDAG &DAG) const { 8100 SDLoc dl(SDValue(Node, 0)); 8101 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 8102 SDValue Src = Node->getOperand(OpNo); 8103 8104 EVT SrcVT = Src.getValueType(); 8105 EVT DstVT = Node->getValueType(0); 8106 EVT SetCCVT = 8107 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 8108 EVT DstSetCCVT = 8109 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 8110 8111 // Only expand vector types if we have the appropriate vector bit operations. 8112 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT : 8113 ISD::FP_TO_SINT; 8114 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) || 8115 !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT))) 8116 return false; 8117 8118 // If the maximum float value is smaller then the signed integer range, 8119 // the destination signmask can't be represented by the float, so we can 8120 // just use FP_TO_SINT directly. 8121 const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT); 8122 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits())); 8123 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits()); 8124 if (APFloat::opOverflow & 8125 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) { 8126 if (Node->isStrictFPOpcode()) { 8127 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 8128 { Node->getOperand(0), Src }); 8129 Chain = Result.getValue(1); 8130 } else 8131 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 8132 return true; 8133 } 8134 8135 // Don't expand it if there isn't cheap fsub instruction. 8136 if (!isOperationLegalOrCustom( 8137 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT)) 8138 return false; 8139 8140 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 8141 SDValue Sel; 8142 8143 if (Node->isStrictFPOpcode()) { 8144 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 8145 Node->getOperand(0), /*IsSignaling*/ true); 8146 Chain = Sel.getValue(1); 8147 } else { 8148 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT); 8149 } 8150 8151 bool Strict = Node->isStrictFPOpcode() || 8152 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false); 8153 8154 if (Strict) { 8155 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the 8156 // signmask then offset (the result of which should be fully representable). 8157 // Sel = Src < 0x8000000000000000 8158 // FltOfs = select Sel, 0, 0x8000000000000000 8159 // IntOfs = select Sel, 0, 0x8000000000000000 8160 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 8161 8162 // TODO: Should any fast-math-flags be set for the FSUB? 8163 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel, 8164 DAG.getConstantFP(0.0, dl, SrcVT), Cst); 8165 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8166 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel, 8167 DAG.getConstant(0, dl, DstVT), 8168 DAG.getConstant(SignMask, dl, DstVT)); 8169 SDValue SInt; 8170 if (Node->isStrictFPOpcode()) { 8171 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other }, 8172 { Chain, Src, FltOfs }); 8173 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 8174 { Val.getValue(1), Val }); 8175 Chain = SInt.getValue(1); 8176 } else { 8177 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs); 8178 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val); 8179 } 8180 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 8181 } else { 8182 // Expand based on maximum range of FP_TO_SINT: 8183 // True = fp_to_sint(Src) 8184 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000) 8185 // Result = select (Src < 0x8000000000000000), True, False 8186 8187 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 8188 // TODO: Should any fast-math-flags be set for the FSUB? 8189 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, 8190 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 8191 False = DAG.getNode(ISD::XOR, dl, DstVT, False, 8192 DAG.getConstant(SignMask, dl, DstVT)); 8193 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8194 Result = DAG.getSelect(dl, DstVT, Sel, True, False); 8195 } 8196 return true; 8197 } 8198 8199 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result, 8200 SDValue &Chain, 8201 SelectionDAG &DAG) const { 8202 // This transform is not correct for converting 0 when rounding mode is set 8203 // to round toward negative infinity which will produce -0.0. So disable under 8204 // strictfp. 8205 if (Node->isStrictFPOpcode()) 8206 return false; 8207 8208 SDValue Src = Node->getOperand(0); 8209 EVT SrcVT = Src.getValueType(); 8210 EVT DstVT = Node->getValueType(0); 8211 8212 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64) 8213 return false; 8214 8215 // Only expand vector types if we have the appropriate vector bit operations. 8216 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 8217 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 8218 !isOperationLegalOrCustom(ISD::FSUB, DstVT) || 8219 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 8220 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 8221 return false; 8222 8223 SDLoc dl(SDValue(Node, 0)); 8224 EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout()); 8225 8226 // Implementation of unsigned i64 to f64 following the algorithm in 8227 // __floatundidf in compiler_rt. This implementation performs rounding 8228 // correctly in all rounding modes with the exception of converting 0 8229 // when rounding toward negative infinity. In that case the fsub will produce 8230 // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect. 8231 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT); 8232 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP( 8233 llvm::bit_cast<double>(UINT64_C(0x4530000000100000)), dl, DstVT); 8234 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT); 8235 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT); 8236 SDValue HiShift = DAG.getConstant(32, dl, ShiftVT); 8237 8238 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask); 8239 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift); 8240 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52); 8241 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84); 8242 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr); 8243 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr); 8244 SDValue HiSub = 8245 DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52); 8246 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub); 8247 return true; 8248 } 8249 8250 SDValue 8251 TargetLowering::createSelectForFMINNUM_FMAXNUM(SDNode *Node, 8252 SelectionDAG &DAG) const { 8253 unsigned Opcode = Node->getOpcode(); 8254 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM || 8255 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) && 8256 "Wrong opcode"); 8257 8258 if (Node->getFlags().hasNoNaNs()) { 8259 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT; 8260 SDValue Op1 = Node->getOperand(0); 8261 SDValue Op2 = Node->getOperand(1); 8262 SDValue SelCC = DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred); 8263 // Copy FMF flags, but always set the no-signed-zeros flag 8264 // as this is implied by the FMINNUM/FMAXNUM semantics. 8265 SDNodeFlags Flags = Node->getFlags(); 8266 Flags.setNoSignedZeros(true); 8267 SelCC->setFlags(Flags); 8268 return SelCC; 8269 } 8270 8271 return SDValue(); 8272 } 8273 8274 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node, 8275 SelectionDAG &DAG) const { 8276 SDLoc dl(Node); 8277 unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ? 8278 ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 8279 EVT VT = Node->getValueType(0); 8280 8281 if (VT.isScalableVector()) 8282 report_fatal_error( 8283 "Expanding fminnum/fmaxnum for scalable vectors is undefined."); 8284 8285 if (isOperationLegalOrCustom(NewOp, VT)) { 8286 SDValue Quiet0 = Node->getOperand(0); 8287 SDValue Quiet1 = Node->getOperand(1); 8288 8289 if (!Node->getFlags().hasNoNaNs()) { 8290 // Insert canonicalizes if it's possible we need to quiet to get correct 8291 // sNaN behavior. 8292 if (!DAG.isKnownNeverSNaN(Quiet0)) { 8293 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0, 8294 Node->getFlags()); 8295 } 8296 if (!DAG.isKnownNeverSNaN(Quiet1)) { 8297 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1, 8298 Node->getFlags()); 8299 } 8300 } 8301 8302 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags()); 8303 } 8304 8305 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that 8306 // instead if there are no NaNs and there can't be an incompatible zero 8307 // compare: at least one operand isn't +/-0, or there are no signed-zeros. 8308 if ((Node->getFlags().hasNoNaNs() || 8309 (DAG.isKnownNeverNaN(Node->getOperand(0)) && 8310 DAG.isKnownNeverNaN(Node->getOperand(1)))) && 8311 (Node->getFlags().hasNoSignedZeros() || 8312 DAG.isKnownNeverZeroFloat(Node->getOperand(0)) || 8313 DAG.isKnownNeverZeroFloat(Node->getOperand(1)))) { 8314 unsigned IEEE2018Op = 8315 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM; 8316 if (isOperationLegalOrCustom(IEEE2018Op, VT)) 8317 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0), 8318 Node->getOperand(1), Node->getFlags()); 8319 } 8320 8321 if (SDValue SelCC = createSelectForFMINNUM_FMAXNUM(Node, DAG)) 8322 return SelCC; 8323 8324 return SDValue(); 8325 } 8326 8327 /// Returns a true value if if this FPClassTest can be performed with an ordered 8328 /// fcmp to 0, and a false value if it's an unordered fcmp to 0. Returns 8329 /// std::nullopt if it cannot be performed as a compare with 0. 8330 static std::optional<bool> isFCmpEqualZero(FPClassTest Test, 8331 const fltSemantics &Semantics, 8332 const MachineFunction &MF) { 8333 FPClassTest OrderedMask = Test & ~fcNan; 8334 FPClassTest NanTest = Test & fcNan; 8335 bool IsOrdered = NanTest == fcNone; 8336 bool IsUnordered = NanTest == fcNan; 8337 8338 // Skip cases that are testing for only a qnan or snan. 8339 if (!IsOrdered && !IsUnordered) 8340 return std::nullopt; 8341 8342 if (OrderedMask == fcZero && 8343 MF.getDenormalMode(Semantics).Input == DenormalMode::IEEE) 8344 return IsOrdered; 8345 if (OrderedMask == (fcZero | fcSubnormal) && 8346 MF.getDenormalMode(Semantics).inputsAreZero()) 8347 return IsOrdered; 8348 return std::nullopt; 8349 } 8350 8351 SDValue TargetLowering::expandIS_FPCLASS(EVT ResultVT, SDValue Op, 8352 FPClassTest Test, SDNodeFlags Flags, 8353 const SDLoc &DL, 8354 SelectionDAG &DAG) const { 8355 EVT OperandVT = Op.getValueType(); 8356 assert(OperandVT.isFloatingPoint()); 8357 8358 // Degenerated cases. 8359 if (Test == fcNone) 8360 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT); 8361 if ((Test & fcAllFlags) == fcAllFlags) 8362 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT); 8363 8364 // PPC double double is a pair of doubles, of which the higher part determines 8365 // the value class. 8366 if (OperandVT == MVT::ppcf128) { 8367 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op, 8368 DAG.getConstant(1, DL, MVT::i32)); 8369 OperandVT = MVT::f64; 8370 } 8371 8372 // Some checks may be represented as inversion of simpler check, for example 8373 // "inf|normal|subnormal|zero" => !"nan". 8374 bool IsInverted = false; 8375 if (FPClassTest InvertedCheck = invertFPClassTestIfSimpler(Test)) { 8376 IsInverted = true; 8377 Test = InvertedCheck; 8378 } 8379 8380 // Floating-point type properties. 8381 EVT ScalarFloatVT = OperandVT.getScalarType(); 8382 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext()); 8383 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics(); 8384 bool IsF80 = (ScalarFloatVT == MVT::f80); 8385 8386 // Some checks can be implemented using float comparisons, if floating point 8387 // exceptions are ignored. 8388 if (Flags.hasNoFPExcept() && 8389 isOperationLegalOrCustom(ISD::SETCC, OperandVT.getScalarType())) { 8390 ISD::CondCode OrderedCmpOpcode = IsInverted ? ISD::SETUNE : ISD::SETOEQ; 8391 ISD::CondCode UnorderedCmpOpcode = IsInverted ? ISD::SETONE : ISD::SETUEQ; 8392 8393 if (std::optional<bool> IsCmp0 = 8394 isFCmpEqualZero(Test, Semantics, DAG.getMachineFunction()); 8395 IsCmp0 && (isCondCodeLegalOrCustom( 8396 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode, 8397 OperandVT.getScalarType().getSimpleVT()))) { 8398 8399 // If denormals could be implicitly treated as 0, this is not equivalent 8400 // to a compare with 0 since it will also be true for denormals. 8401 return DAG.getSetCC(DL, ResultVT, Op, 8402 DAG.getConstantFP(0.0, DL, OperandVT), 8403 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode); 8404 } 8405 8406 if (Test == fcNan && 8407 isCondCodeLegalOrCustom(IsInverted ? ISD::SETO : ISD::SETUO, 8408 OperandVT.getScalarType().getSimpleVT())) { 8409 return DAG.getSetCC(DL, ResultVT, Op, Op, 8410 IsInverted ? ISD::SETO : ISD::SETUO); 8411 } 8412 8413 if (Test == fcInf && 8414 isCondCodeLegalOrCustom(IsInverted ? ISD::SETUNE : ISD::SETOEQ, 8415 OperandVT.getScalarType().getSimpleVT()) && 8416 isOperationLegalOrCustom(ISD::FABS, OperandVT.getScalarType())) { 8417 // isinf(x) --> fabs(x) == inf 8418 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op); 8419 SDValue Inf = 8420 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT); 8421 return DAG.getSetCC(DL, ResultVT, Abs, Inf, 8422 IsInverted ? ISD::SETUNE : ISD::SETOEQ); 8423 } 8424 } 8425 8426 // In the general case use integer operations. 8427 unsigned BitSize = OperandVT.getScalarSizeInBits(); 8428 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), BitSize); 8429 if (OperandVT.isVector()) 8430 IntVT = EVT::getVectorVT(*DAG.getContext(), IntVT, 8431 OperandVT.getVectorElementCount()); 8432 SDValue OpAsInt = DAG.getBitcast(IntVT, Op); 8433 8434 // Various masks. 8435 APInt SignBit = APInt::getSignMask(BitSize); 8436 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign. 8437 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit. 8438 const unsigned ExplicitIntBitInF80 = 63; 8439 APInt ExpMask = Inf; 8440 if (IsF80) 8441 ExpMask.clearBit(ExplicitIntBitInF80); 8442 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf; 8443 APInt QNaNBitMask = 8444 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1); 8445 APInt InvertionMask = APInt::getAllOnes(ResultVT.getScalarSizeInBits()); 8446 8447 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT); 8448 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT); 8449 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT); 8450 SDValue ZeroV = DAG.getConstant(0, DL, IntVT); 8451 SDValue InfV = DAG.getConstant(Inf, DL, IntVT); 8452 SDValue ResultInvertionMask = DAG.getConstant(InvertionMask, DL, ResultVT); 8453 8454 SDValue Res; 8455 const auto appendResult = [&](SDValue PartialRes) { 8456 if (PartialRes) { 8457 if (Res) 8458 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes); 8459 else 8460 Res = PartialRes; 8461 } 8462 }; 8463 8464 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set. 8465 const auto getIntBitIsSet = [&]() -> SDValue { 8466 if (!IntBitIsSetV) { 8467 APInt IntBitMask(BitSize, 0); 8468 IntBitMask.setBit(ExplicitIntBitInF80); 8469 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT); 8470 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV); 8471 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE); 8472 } 8473 return IntBitIsSetV; 8474 }; 8475 8476 // Split the value into sign bit and absolute value. 8477 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV); 8478 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt, 8479 DAG.getConstant(0.0, DL, IntVT), ISD::SETLT); 8480 8481 // Tests that involve more than one class should be processed first. 8482 SDValue PartialRes; 8483 8484 if (IsF80) 8485 ; // Detect finite numbers of f80 by checking individual classes because 8486 // they have different settings of the explicit integer bit. 8487 else if ((Test & fcFinite) == fcFinite) { 8488 // finite(V) ==> abs(V) < exp_mask 8489 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 8490 Test &= ~fcFinite; 8491 } else if ((Test & fcFinite) == fcPosFinite) { 8492 // finite(V) && V > 0 ==> V < exp_mask 8493 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT); 8494 Test &= ~fcPosFinite; 8495 } else if ((Test & fcFinite) == fcNegFinite) { 8496 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1 8497 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 8498 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 8499 Test &= ~fcNegFinite; 8500 } 8501 appendResult(PartialRes); 8502 8503 if (FPClassTest PartialCheck = Test & (fcZero | fcSubnormal)) { 8504 // fcZero | fcSubnormal => test all exponent bits are 0 8505 // TODO: Handle sign bit specific cases 8506 if (PartialCheck == (fcZero | fcSubnormal)) { 8507 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ExpMaskV); 8508 SDValue ExpIsZero = 8509 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ); 8510 appendResult(ExpIsZero); 8511 Test &= ~PartialCheck & fcAllFlags; 8512 } 8513 } 8514 8515 // Check for individual classes. 8516 8517 if (unsigned PartialCheck = Test & fcZero) { 8518 if (PartialCheck == fcPosZero) 8519 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ); 8520 else if (PartialCheck == fcZero) 8521 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ); 8522 else // ISD::fcNegZero 8523 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ); 8524 appendResult(PartialRes); 8525 } 8526 8527 if (unsigned PartialCheck = Test & fcSubnormal) { 8528 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set) 8529 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set) 8530 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV; 8531 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT); 8532 SDValue VMinusOneV = 8533 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT)); 8534 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT); 8535 if (PartialCheck == fcNegSubnormal) 8536 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 8537 appendResult(PartialRes); 8538 } 8539 8540 if (unsigned PartialCheck = Test & fcInf) { 8541 if (PartialCheck == fcPosInf) 8542 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ); 8543 else if (PartialCheck == fcInf) 8544 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ); 8545 else { // ISD::fcNegInf 8546 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt(); 8547 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT); 8548 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ); 8549 } 8550 appendResult(PartialRes); 8551 } 8552 8553 if (unsigned PartialCheck = Test & fcNan) { 8554 APInt InfWithQnanBit = Inf | QNaNBitMask; 8555 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT); 8556 if (PartialCheck == fcNan) { 8557 // isnan(V) ==> abs(V) > int(inf) 8558 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 8559 if (IsF80) { 8560 // Recognize unsupported values as NaNs for compatibility with glibc. 8561 // In them (exp(V)==0) == int_bit. 8562 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV); 8563 SDValue ExpIsZero = 8564 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ); 8565 SDValue IsPseudo = 8566 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ); 8567 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo); 8568 } 8569 } else if (PartialCheck == fcQNan) { 8570 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit) 8571 PartialRes = 8572 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE); 8573 } else { // ISD::fcSNan 8574 // issignaling(V) ==> abs(V) > unsigned(Inf) && 8575 // abs(V) < (unsigned(Inf) | quiet_bit) 8576 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 8577 SDValue IsNotQnan = 8578 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT); 8579 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan); 8580 } 8581 appendResult(PartialRes); 8582 } 8583 8584 if (unsigned PartialCheck = Test & fcNormal) { 8585 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1)) 8586 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1)); 8587 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT); 8588 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV); 8589 APInt ExpLimit = ExpMask - ExpLSB; 8590 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT); 8591 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT); 8592 if (PartialCheck == fcNegNormal) 8593 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 8594 else if (PartialCheck == fcPosNormal) { 8595 SDValue PosSignV = 8596 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInvertionMask); 8597 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV); 8598 } 8599 if (IsF80) 8600 PartialRes = 8601 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet()); 8602 appendResult(PartialRes); 8603 } 8604 8605 if (!Res) 8606 return DAG.getConstant(IsInverted, DL, ResultVT); 8607 if (IsInverted) 8608 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInvertionMask); 8609 return Res; 8610 } 8611 8612 // Only expand vector types if we have the appropriate vector bit operations. 8613 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) { 8614 assert(VT.isVector() && "Expected vector type"); 8615 unsigned Len = VT.getScalarSizeInBits(); 8616 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) && 8617 TLI.isOperationLegalOrCustom(ISD::SUB, VT) && 8618 TLI.isOperationLegalOrCustom(ISD::SRL, VT) && 8619 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) && 8620 TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT); 8621 } 8622 8623 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const { 8624 SDLoc dl(Node); 8625 EVT VT = Node->getValueType(0); 8626 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 8627 SDValue Op = Node->getOperand(0); 8628 unsigned Len = VT.getScalarSizeInBits(); 8629 assert(VT.isInteger() && "CTPOP not implemented for this type."); 8630 8631 // TODO: Add support for irregular type lengths. 8632 if (!(Len <= 128 && Len % 8 == 0)) 8633 return SDValue(); 8634 8635 // Only expand vector types if we have the appropriate vector bit operations. 8636 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT)) 8637 return SDValue(); 8638 8639 // This is the "best" algorithm from 8640 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 8641 SDValue Mask55 = 8642 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 8643 SDValue Mask33 = 8644 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 8645 SDValue Mask0F = 8646 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 8647 8648 // v = v - ((v >> 1) & 0x55555555...) 8649 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 8650 DAG.getNode(ISD::AND, dl, VT, 8651 DAG.getNode(ISD::SRL, dl, VT, Op, 8652 DAG.getConstant(1, dl, ShVT)), 8653 Mask55)); 8654 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 8655 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 8656 DAG.getNode(ISD::AND, dl, VT, 8657 DAG.getNode(ISD::SRL, dl, VT, Op, 8658 DAG.getConstant(2, dl, ShVT)), 8659 Mask33)); 8660 // v = (v + (v >> 4)) & 0x0F0F0F0F... 8661 Op = DAG.getNode(ISD::AND, dl, VT, 8662 DAG.getNode(ISD::ADD, dl, VT, Op, 8663 DAG.getNode(ISD::SRL, dl, VT, Op, 8664 DAG.getConstant(4, dl, ShVT))), 8665 Mask0F); 8666 8667 if (Len <= 8) 8668 return Op; 8669 8670 // Avoid the multiply if we only have 2 bytes to add. 8671 // TODO: Only doing this for scalars because vectors weren't as obviously 8672 // improved. 8673 if (Len == 16 && !VT.isVector()) { 8674 // v = (v + (v >> 8)) & 0x00FF; 8675 return DAG.getNode(ISD::AND, dl, VT, 8676 DAG.getNode(ISD::ADD, dl, VT, Op, 8677 DAG.getNode(ISD::SRL, dl, VT, Op, 8678 DAG.getConstant(8, dl, ShVT))), 8679 DAG.getConstant(0xFF, dl, VT)); 8680 } 8681 8682 // v = (v * 0x01010101...) >> (Len - 8) 8683 SDValue Mask01 = 8684 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 8685 return DAG.getNode(ISD::SRL, dl, VT, 8686 DAG.getNode(ISD::MUL, dl, VT, Op, Mask01), 8687 DAG.getConstant(Len - 8, dl, ShVT)); 8688 } 8689 8690 SDValue TargetLowering::expandVPCTPOP(SDNode *Node, SelectionDAG &DAG) const { 8691 SDLoc dl(Node); 8692 EVT VT = Node->getValueType(0); 8693 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 8694 SDValue Op = Node->getOperand(0); 8695 SDValue Mask = Node->getOperand(1); 8696 SDValue VL = Node->getOperand(2); 8697 unsigned Len = VT.getScalarSizeInBits(); 8698 assert(VT.isInteger() && "VP_CTPOP not implemented for this type."); 8699 8700 // TODO: Add support for irregular type lengths. 8701 if (!(Len <= 128 && Len % 8 == 0)) 8702 return SDValue(); 8703 8704 // This is same algorithm of expandCTPOP from 8705 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 8706 SDValue Mask55 = 8707 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 8708 SDValue Mask33 = 8709 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 8710 SDValue Mask0F = 8711 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 8712 8713 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5; 8714 8715 // v = v - ((v >> 1) & 0x55555555...) 8716 Tmp1 = DAG.getNode(ISD::VP_AND, dl, VT, 8717 DAG.getNode(ISD::VP_LSHR, dl, VT, Op, 8718 DAG.getConstant(1, dl, ShVT), Mask, VL), 8719 Mask55, Mask, VL); 8720 Op = DAG.getNode(ISD::VP_SUB, dl, VT, Op, Tmp1, Mask, VL); 8721 8722 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 8723 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Op, Mask33, Mask, VL); 8724 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, 8725 DAG.getNode(ISD::VP_LSHR, dl, VT, Op, 8726 DAG.getConstant(2, dl, ShVT), Mask, VL), 8727 Mask33, Mask, VL); 8728 Op = DAG.getNode(ISD::VP_ADD, dl, VT, Tmp2, Tmp3, Mask, VL); 8729 8730 // v = (v + (v >> 4)) & 0x0F0F0F0F... 8731 Tmp4 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(4, dl, ShVT), 8732 Mask, VL), 8733 Tmp5 = DAG.getNode(ISD::VP_ADD, dl, VT, Op, Tmp4, Mask, VL); 8734 Op = DAG.getNode(ISD::VP_AND, dl, VT, Tmp5, Mask0F, Mask, VL); 8735 8736 if (Len <= 8) 8737 return Op; 8738 8739 // v = (v * 0x01010101...) >> (Len - 8) 8740 SDValue Mask01 = 8741 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 8742 return DAG.getNode(ISD::VP_LSHR, dl, VT, 8743 DAG.getNode(ISD::VP_MUL, dl, VT, Op, Mask01, Mask, VL), 8744 DAG.getConstant(Len - 8, dl, ShVT), Mask, VL); 8745 } 8746 8747 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const { 8748 SDLoc dl(Node); 8749 EVT VT = Node->getValueType(0); 8750 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 8751 SDValue Op = Node->getOperand(0); 8752 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 8753 8754 // If the non-ZERO_UNDEF version is supported we can use that instead. 8755 if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF && 8756 isOperationLegalOrCustom(ISD::CTLZ, VT)) 8757 return DAG.getNode(ISD::CTLZ, dl, VT, Op); 8758 8759 // If the ZERO_UNDEF version is supported use that and handle the zero case. 8760 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 8761 EVT SetCCVT = 8762 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8763 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 8764 SDValue Zero = DAG.getConstant(0, dl, VT); 8765 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 8766 return DAG.getSelect(dl, VT, SrcIsZero, 8767 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ); 8768 } 8769 8770 // Only expand vector types if we have the appropriate vector bit operations. 8771 // This includes the operations needed to expand CTPOP if it isn't supported. 8772 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 8773 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 8774 !canExpandVectorCTPOP(*this, VT)) || 8775 !isOperationLegalOrCustom(ISD::SRL, VT) || 8776 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 8777 return SDValue(); 8778 8779 // for now, we do this: 8780 // x = x | (x >> 1); 8781 // x = x | (x >> 2); 8782 // ... 8783 // x = x | (x >>16); 8784 // x = x | (x >>32); // for 64-bit input 8785 // return popcount(~x); 8786 // 8787 // Ref: "Hacker's Delight" by Henry Warren 8788 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) { 8789 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 8790 Op = DAG.getNode(ISD::OR, dl, VT, Op, 8791 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp)); 8792 } 8793 Op = DAG.getNOT(dl, Op, VT); 8794 return DAG.getNode(ISD::CTPOP, dl, VT, Op); 8795 } 8796 8797 SDValue TargetLowering::expandVPCTLZ(SDNode *Node, SelectionDAG &DAG) const { 8798 SDLoc dl(Node); 8799 EVT VT = Node->getValueType(0); 8800 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 8801 SDValue Op = Node->getOperand(0); 8802 SDValue Mask = Node->getOperand(1); 8803 SDValue VL = Node->getOperand(2); 8804 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 8805 8806 // do this: 8807 // x = x | (x >> 1); 8808 // x = x | (x >> 2); 8809 // ... 8810 // x = x | (x >>16); 8811 // x = x | (x >>32); // for 64-bit input 8812 // return popcount(~x); 8813 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) { 8814 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 8815 Op = DAG.getNode(ISD::VP_OR, dl, VT, Op, 8816 DAG.getNode(ISD::VP_LSHR, dl, VT, Op, Tmp, Mask, VL), Mask, 8817 VL); 8818 } 8819 Op = DAG.getNode(ISD::VP_XOR, dl, VT, Op, DAG.getConstant(-1, dl, VT), Mask, 8820 VL); 8821 return DAG.getNode(ISD::VP_CTPOP, dl, VT, Op, Mask, VL); 8822 } 8823 8824 SDValue TargetLowering::CTTZTableLookup(SDNode *Node, SelectionDAG &DAG, 8825 const SDLoc &DL, EVT VT, SDValue Op, 8826 unsigned BitWidth) const { 8827 if (BitWidth != 32 && BitWidth != 64) 8828 return SDValue(); 8829 APInt DeBruijn = BitWidth == 32 ? APInt(32, 0x077CB531U) 8830 : APInt(64, 0x0218A392CD3D5DBFULL); 8831 const DataLayout &TD = DAG.getDataLayout(); 8832 MachinePointerInfo PtrInfo = 8833 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()); 8834 unsigned ShiftAmt = BitWidth - Log2_32(BitWidth); 8835 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 8836 SDValue Lookup = DAG.getNode( 8837 ISD::SRL, DL, VT, 8838 DAG.getNode(ISD::MUL, DL, VT, DAG.getNode(ISD::AND, DL, VT, Op, Neg), 8839 DAG.getConstant(DeBruijn, DL, VT)), 8840 DAG.getConstant(ShiftAmt, DL, VT)); 8841 Lookup = DAG.getSExtOrTrunc(Lookup, DL, getPointerTy(TD)); 8842 8843 SmallVector<uint8_t> Table(BitWidth, 0); 8844 for (unsigned i = 0; i < BitWidth; i++) { 8845 APInt Shl = DeBruijn.shl(i); 8846 APInt Lshr = Shl.lshr(ShiftAmt); 8847 Table[Lshr.getZExtValue()] = i; 8848 } 8849 8850 // Create a ConstantArray in Constant Pool 8851 auto *CA = ConstantDataArray::get(*DAG.getContext(), Table); 8852 SDValue CPIdx = DAG.getConstantPool(CA, getPointerTy(TD), 8853 TD.getPrefTypeAlign(CA->getType())); 8854 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getEntryNode(), 8855 DAG.getMemBasePlusOffset(CPIdx, Lookup, DL), 8856 PtrInfo, MVT::i8); 8857 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF) 8858 return ExtLoad; 8859 8860 EVT SetCCVT = 8861 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8862 SDValue Zero = DAG.getConstant(0, DL, VT); 8863 SDValue SrcIsZero = DAG.getSetCC(DL, SetCCVT, Op, Zero, ISD::SETEQ); 8864 return DAG.getSelect(DL, VT, SrcIsZero, 8865 DAG.getConstant(BitWidth, DL, VT), ExtLoad); 8866 } 8867 8868 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const { 8869 SDLoc dl(Node); 8870 EVT VT = Node->getValueType(0); 8871 SDValue Op = Node->getOperand(0); 8872 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 8873 8874 // If the non-ZERO_UNDEF version is supported we can use that instead. 8875 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF && 8876 isOperationLegalOrCustom(ISD::CTTZ, VT)) 8877 return DAG.getNode(ISD::CTTZ, dl, VT, Op); 8878 8879 // If the ZERO_UNDEF version is supported use that and handle the zero case. 8880 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) { 8881 EVT SetCCVT = 8882 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8883 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op); 8884 SDValue Zero = DAG.getConstant(0, dl, VT); 8885 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 8886 return DAG.getSelect(dl, VT, SrcIsZero, 8887 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ); 8888 } 8889 8890 // Only expand vector types if we have the appropriate vector bit operations. 8891 // This includes the operations needed to expand CTPOP if it isn't supported. 8892 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 8893 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 8894 !isOperationLegalOrCustom(ISD::CTLZ, VT) && 8895 !canExpandVectorCTPOP(*this, VT)) || 8896 !isOperationLegalOrCustom(ISD::SUB, VT) || 8897 !isOperationLegalOrCustomOrPromote(ISD::AND, VT) || 8898 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 8899 return SDValue(); 8900 8901 // Emit Table Lookup if ISD::CTLZ and ISD::CTPOP are not legal. 8902 if (!VT.isVector() && isOperationExpand(ISD::CTPOP, VT) && 8903 !isOperationLegal(ISD::CTLZ, VT)) 8904 if (SDValue V = CTTZTableLookup(Node, DAG, dl, VT, Op, NumBitsPerElt)) 8905 return V; 8906 8907 // for now, we use: { return popcount(~x & (x - 1)); } 8908 // unless the target has ctlz but not ctpop, in which case we use: 8909 // { return 32 - nlz(~x & (x-1)); } 8910 // Ref: "Hacker's Delight" by Henry Warren 8911 SDValue Tmp = DAG.getNode( 8912 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT), 8913 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT))); 8914 8915 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 8916 if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) { 8917 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT), 8918 DAG.getNode(ISD::CTLZ, dl, VT, Tmp)); 8919 } 8920 8921 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp); 8922 } 8923 8924 SDValue TargetLowering::expandVPCTTZ(SDNode *Node, SelectionDAG &DAG) const { 8925 SDValue Op = Node->getOperand(0); 8926 SDValue Mask = Node->getOperand(1); 8927 SDValue VL = Node->getOperand(2); 8928 SDLoc dl(Node); 8929 EVT VT = Node->getValueType(0); 8930 8931 // Same as the vector part of expandCTTZ, use: popcount(~x & (x - 1)) 8932 SDValue Not = DAG.getNode(ISD::VP_XOR, dl, VT, Op, 8933 DAG.getConstant(-1, dl, VT), Mask, VL); 8934 SDValue MinusOne = DAG.getNode(ISD::VP_SUB, dl, VT, Op, 8935 DAG.getConstant(1, dl, VT), Mask, VL); 8936 SDValue Tmp = DAG.getNode(ISD::VP_AND, dl, VT, Not, MinusOne, Mask, VL); 8937 return DAG.getNode(ISD::VP_CTPOP, dl, VT, Tmp, Mask, VL); 8938 } 8939 8940 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG, 8941 bool IsNegative) const { 8942 SDLoc dl(N); 8943 EVT VT = N->getValueType(0); 8944 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 8945 SDValue Op = N->getOperand(0); 8946 8947 // abs(x) -> smax(x,sub(0,x)) 8948 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 8949 isOperationLegal(ISD::SMAX, VT)) { 8950 SDValue Zero = DAG.getConstant(0, dl, VT); 8951 return DAG.getNode(ISD::SMAX, dl, VT, Op, 8952 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 8953 } 8954 8955 // abs(x) -> umin(x,sub(0,x)) 8956 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 8957 isOperationLegal(ISD::UMIN, VT)) { 8958 SDValue Zero = DAG.getConstant(0, dl, VT); 8959 Op = DAG.getFreeze(Op); 8960 return DAG.getNode(ISD::UMIN, dl, VT, Op, 8961 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 8962 } 8963 8964 // 0 - abs(x) -> smin(x, sub(0,x)) 8965 if (IsNegative && isOperationLegal(ISD::SUB, VT) && 8966 isOperationLegal(ISD::SMIN, VT)) { 8967 Op = DAG.getFreeze(Op); 8968 SDValue Zero = DAG.getConstant(0, dl, VT); 8969 return DAG.getNode(ISD::SMIN, dl, VT, Op, 8970 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 8971 } 8972 8973 // Only expand vector types if we have the appropriate vector operations. 8974 if (VT.isVector() && 8975 (!isOperationLegalOrCustom(ISD::SRA, VT) || 8976 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) || 8977 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) || 8978 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 8979 return SDValue(); 8980 8981 Op = DAG.getFreeze(Op); 8982 SDValue Shift = 8983 DAG.getNode(ISD::SRA, dl, VT, Op, 8984 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT)); 8985 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift); 8986 8987 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y) 8988 if (!IsNegative) 8989 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift); 8990 8991 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y)) 8992 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor); 8993 } 8994 8995 SDValue TargetLowering::expandABD(SDNode *N, SelectionDAG &DAG) const { 8996 SDLoc dl(N); 8997 EVT VT = N->getValueType(0); 8998 SDValue LHS = DAG.getFreeze(N->getOperand(0)); 8999 SDValue RHS = DAG.getFreeze(N->getOperand(1)); 9000 bool IsSigned = N->getOpcode() == ISD::ABDS; 9001 9002 // abds(lhs, rhs) -> sub(smax(lhs,rhs), smin(lhs,rhs)) 9003 // abdu(lhs, rhs) -> sub(umax(lhs,rhs), umin(lhs,rhs)) 9004 unsigned MaxOpc = IsSigned ? ISD::SMAX : ISD::UMAX; 9005 unsigned MinOpc = IsSigned ? ISD::SMIN : ISD::UMIN; 9006 if (isOperationLegal(MaxOpc, VT) && isOperationLegal(MinOpc, VT)) { 9007 SDValue Max = DAG.getNode(MaxOpc, dl, VT, LHS, RHS); 9008 SDValue Min = DAG.getNode(MinOpc, dl, VT, LHS, RHS); 9009 return DAG.getNode(ISD::SUB, dl, VT, Max, Min); 9010 } 9011 9012 // abdu(lhs, rhs) -> or(usubsat(lhs,rhs), usubsat(rhs,lhs)) 9013 if (!IsSigned && isOperationLegal(ISD::USUBSAT, VT)) 9014 return DAG.getNode(ISD::OR, dl, VT, 9015 DAG.getNode(ISD::USUBSAT, dl, VT, LHS, RHS), 9016 DAG.getNode(ISD::USUBSAT, dl, VT, RHS, LHS)); 9017 9018 // abds(lhs, rhs) -> select(sgt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs)) 9019 // abdu(lhs, rhs) -> select(ugt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs)) 9020 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9021 ISD::CondCode CC = IsSigned ? ISD::CondCode::SETGT : ISD::CondCode::SETUGT; 9022 SDValue Cmp = DAG.getSetCC(dl, CCVT, LHS, RHS, CC); 9023 return DAG.getSelect(dl, VT, Cmp, DAG.getNode(ISD::SUB, dl, VT, LHS, RHS), 9024 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS)); 9025 } 9026 9027 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const { 9028 SDLoc dl(N); 9029 EVT VT = N->getValueType(0); 9030 SDValue Op = N->getOperand(0); 9031 9032 if (!VT.isSimple()) 9033 return SDValue(); 9034 9035 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9036 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 9037 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 9038 default: 9039 return SDValue(); 9040 case MVT::i16: 9041 // Use a rotate by 8. This can be further expanded if necessary. 9042 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 9043 case MVT::i32: 9044 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 9045 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Op, 9046 DAG.getConstant(0xFF00, dl, VT)); 9047 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT)); 9048 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 9049 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT)); 9050 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 9051 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 9052 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 9053 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 9054 case MVT::i64: 9055 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 9056 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Op, 9057 DAG.getConstant(255ULL<<8, dl, VT)); 9058 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT)); 9059 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Op, 9060 DAG.getConstant(255ULL<<16, dl, VT)); 9061 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT)); 9062 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Op, 9063 DAG.getConstant(255ULL<<24, dl, VT)); 9064 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT)); 9065 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 9066 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, 9067 DAG.getConstant(255ULL<<24, dl, VT)); 9068 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 9069 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 9070 DAG.getConstant(255ULL<<16, dl, VT)); 9071 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 9072 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, 9073 DAG.getConstant(255ULL<<8, dl, VT)); 9074 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 9075 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7); 9076 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5); 9077 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 9078 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 9079 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6); 9080 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 9081 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4); 9082 } 9083 } 9084 9085 SDValue TargetLowering::expandVPBSWAP(SDNode *N, SelectionDAG &DAG) const { 9086 SDLoc dl(N); 9087 EVT VT = N->getValueType(0); 9088 SDValue Op = N->getOperand(0); 9089 SDValue Mask = N->getOperand(1); 9090 SDValue EVL = N->getOperand(2); 9091 9092 if (!VT.isSimple()) 9093 return SDValue(); 9094 9095 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9096 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 9097 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 9098 default: 9099 return SDValue(); 9100 case MVT::i16: 9101 Tmp1 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT), 9102 Mask, EVL); 9103 Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(8, dl, SHVT), 9104 Mask, EVL); 9105 return DAG.getNode(ISD::VP_OR, dl, VT, Tmp1, Tmp2, Mask, EVL); 9106 case MVT::i32: 9107 Tmp4 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT), 9108 Mask, EVL); 9109 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Op, DAG.getConstant(0xFF00, dl, VT), 9110 Mask, EVL); 9111 Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT), 9112 Mask, EVL); 9113 Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(8, dl, SHVT), 9114 Mask, EVL); 9115 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2, 9116 DAG.getConstant(0xFF00, dl, VT), Mask, EVL); 9117 Tmp1 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(24, dl, SHVT), 9118 Mask, EVL); 9119 Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp3, Mask, EVL); 9120 Tmp2 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp1, Mask, EVL); 9121 return DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp2, Mask, EVL); 9122 case MVT::i64: 9123 Tmp8 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT), 9124 Mask, EVL); 9125 Tmp7 = DAG.getNode(ISD::VP_AND, dl, VT, Op, 9126 DAG.getConstant(255ULL << 8, dl, VT), Mask, EVL); 9127 Tmp7 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT), 9128 Mask, EVL); 9129 Tmp6 = DAG.getNode(ISD::VP_AND, dl, VT, Op, 9130 DAG.getConstant(255ULL << 16, dl, VT), Mask, EVL); 9131 Tmp6 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT), 9132 Mask, EVL); 9133 Tmp5 = DAG.getNode(ISD::VP_AND, dl, VT, Op, 9134 DAG.getConstant(255ULL << 24, dl, VT), Mask, EVL); 9135 Tmp5 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT), 9136 Mask, EVL); 9137 Tmp4 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(8, dl, SHVT), 9138 Mask, EVL); 9139 Tmp4 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp4, 9140 DAG.getConstant(255ULL << 24, dl, VT), Mask, EVL); 9141 Tmp3 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(24, dl, SHVT), 9142 Mask, EVL); 9143 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp3, 9144 DAG.getConstant(255ULL << 16, dl, VT), Mask, EVL); 9145 Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(40, dl, SHVT), 9146 Mask, EVL); 9147 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2, 9148 DAG.getConstant(255ULL << 8, dl, VT), Mask, EVL); 9149 Tmp1 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(56, dl, SHVT), 9150 Mask, EVL); 9151 Tmp8 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp7, Mask, EVL); 9152 Tmp6 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp6, Tmp5, Mask, EVL); 9153 Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp3, Mask, EVL); 9154 Tmp2 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp1, Mask, EVL); 9155 Tmp8 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp6, Mask, EVL); 9156 Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp2, Mask, EVL); 9157 return DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp4, Mask, EVL); 9158 } 9159 } 9160 9161 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const { 9162 SDLoc dl(N); 9163 EVT VT = N->getValueType(0); 9164 SDValue Op = N->getOperand(0); 9165 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9166 unsigned Sz = VT.getScalarSizeInBits(); 9167 9168 SDValue Tmp, Tmp2, Tmp3; 9169 9170 // If we can, perform BSWAP first and then the mask+swap the i4, then i2 9171 // and finally the i1 pairs. 9172 // TODO: We can easily support i4/i2 legal types if any target ever does. 9173 if (Sz >= 8 && isPowerOf2_32(Sz)) { 9174 // Create the masks - repeating the pattern every byte. 9175 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F)); 9176 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33)); 9177 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55)); 9178 9179 // BSWAP if the type is wider than a single byte. 9180 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op); 9181 9182 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4) 9183 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT)); 9184 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT)); 9185 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT)); 9186 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT)); 9187 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 9188 9189 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2) 9190 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT)); 9191 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT)); 9192 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT)); 9193 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT)); 9194 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 9195 9196 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1) 9197 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT)); 9198 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT)); 9199 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT)); 9200 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT)); 9201 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 9202 return Tmp; 9203 } 9204 9205 Tmp = DAG.getConstant(0, dl, VT); 9206 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) { 9207 if (I < J) 9208 Tmp2 = 9209 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT)); 9210 else 9211 Tmp2 = 9212 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT)); 9213 9214 APInt Shift = APInt::getOneBitSet(Sz, J); 9215 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT)); 9216 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2); 9217 } 9218 9219 return Tmp; 9220 } 9221 9222 SDValue TargetLowering::expandVPBITREVERSE(SDNode *N, SelectionDAG &DAG) const { 9223 assert(N->getOpcode() == ISD::VP_BITREVERSE); 9224 9225 SDLoc dl(N); 9226 EVT VT = N->getValueType(0); 9227 SDValue Op = N->getOperand(0); 9228 SDValue Mask = N->getOperand(1); 9229 SDValue EVL = N->getOperand(2); 9230 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 9231 unsigned Sz = VT.getScalarSizeInBits(); 9232 9233 SDValue Tmp, Tmp2, Tmp3; 9234 9235 // If we can, perform BSWAP first and then the mask+swap the i4, then i2 9236 // and finally the i1 pairs. 9237 // TODO: We can easily support i4/i2 legal types if any target ever does. 9238 if (Sz >= 8 && isPowerOf2_32(Sz)) { 9239 // Create the masks - repeating the pattern every byte. 9240 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F)); 9241 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33)); 9242 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55)); 9243 9244 // BSWAP if the type is wider than a single byte. 9245 Tmp = (Sz > 8 ? DAG.getNode(ISD::VP_BSWAP, dl, VT, Op, Mask, EVL) : Op); 9246 9247 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4) 9248 Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT), 9249 Mask, EVL); 9250 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2, 9251 DAG.getConstant(Mask4, dl, VT), Mask, EVL); 9252 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT), 9253 Mask, EVL); 9254 Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT), 9255 Mask, EVL); 9256 Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL); 9257 9258 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2) 9259 Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT), 9260 Mask, EVL); 9261 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2, 9262 DAG.getConstant(Mask2, dl, VT), Mask, EVL); 9263 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT), 9264 Mask, EVL); 9265 Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT), 9266 Mask, EVL); 9267 Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL); 9268 9269 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1) 9270 Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT), 9271 Mask, EVL); 9272 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2, 9273 DAG.getConstant(Mask1, dl, VT), Mask, EVL); 9274 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT), 9275 Mask, EVL); 9276 Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT), 9277 Mask, EVL); 9278 Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL); 9279 return Tmp; 9280 } 9281 return SDValue(); 9282 } 9283 9284 std::pair<SDValue, SDValue> 9285 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 9286 SelectionDAG &DAG) const { 9287 SDLoc SL(LD); 9288 SDValue Chain = LD->getChain(); 9289 SDValue BasePTR = LD->getBasePtr(); 9290 EVT SrcVT = LD->getMemoryVT(); 9291 EVT DstVT = LD->getValueType(0); 9292 ISD::LoadExtType ExtType = LD->getExtensionType(); 9293 9294 if (SrcVT.isScalableVector()) 9295 report_fatal_error("Cannot scalarize scalable vector loads"); 9296 9297 unsigned NumElem = SrcVT.getVectorNumElements(); 9298 9299 EVT SrcEltVT = SrcVT.getScalarType(); 9300 EVT DstEltVT = DstVT.getScalarType(); 9301 9302 // A vector must always be stored in memory as-is, i.e. without any padding 9303 // between the elements, since various code depend on it, e.g. in the 9304 // handling of a bitcast of a vector type to int, which may be done with a 9305 // vector store followed by an integer load. A vector that does not have 9306 // elements that are byte-sized must therefore be stored as an integer 9307 // built out of the extracted vector elements. 9308 if (!SrcEltVT.isByteSized()) { 9309 unsigned NumLoadBits = SrcVT.getStoreSizeInBits(); 9310 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits); 9311 9312 unsigned NumSrcBits = SrcVT.getSizeInBits(); 9313 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits); 9314 9315 unsigned SrcEltBits = SrcEltVT.getSizeInBits(); 9316 SDValue SrcEltBitMask = DAG.getConstant( 9317 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT); 9318 9319 // Load the whole vector and avoid masking off the top bits as it makes 9320 // the codegen worse. 9321 SDValue Load = 9322 DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, 9323 LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(), 9324 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 9325 9326 SmallVector<SDValue, 8> Vals; 9327 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 9328 unsigned ShiftIntoIdx = 9329 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 9330 SDValue ShiftAmount = 9331 DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(), 9332 LoadVT, SL, /*LegalTypes=*/false); 9333 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount); 9334 SDValue Elt = 9335 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask); 9336 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt); 9337 9338 if (ExtType != ISD::NON_EXTLOAD) { 9339 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType); 9340 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar); 9341 } 9342 9343 Vals.push_back(Scalar); 9344 } 9345 9346 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 9347 return std::make_pair(Value, Load.getValue(1)); 9348 } 9349 9350 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 9351 assert(SrcEltVT.isByteSized()); 9352 9353 SmallVector<SDValue, 8> Vals; 9354 SmallVector<SDValue, 8> LoadChains; 9355 9356 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 9357 SDValue ScalarLoad = 9358 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 9359 LD->getPointerInfo().getWithOffset(Idx * Stride), 9360 SrcEltVT, LD->getOriginalAlign(), 9361 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 9362 9363 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::getFixed(Stride)); 9364 9365 Vals.push_back(ScalarLoad.getValue(0)); 9366 LoadChains.push_back(ScalarLoad.getValue(1)); 9367 } 9368 9369 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 9370 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 9371 9372 return std::make_pair(Value, NewChain); 9373 } 9374 9375 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 9376 SelectionDAG &DAG) const { 9377 SDLoc SL(ST); 9378 9379 SDValue Chain = ST->getChain(); 9380 SDValue BasePtr = ST->getBasePtr(); 9381 SDValue Value = ST->getValue(); 9382 EVT StVT = ST->getMemoryVT(); 9383 9384 if (StVT.isScalableVector()) 9385 report_fatal_error("Cannot scalarize scalable vector stores"); 9386 9387 // The type of the data we want to save 9388 EVT RegVT = Value.getValueType(); 9389 EVT RegSclVT = RegVT.getScalarType(); 9390 9391 // The type of data as saved in memory. 9392 EVT MemSclVT = StVT.getScalarType(); 9393 9394 unsigned NumElem = StVT.getVectorNumElements(); 9395 9396 // A vector must always be stored in memory as-is, i.e. without any padding 9397 // between the elements, since various code depend on it, e.g. in the 9398 // handling of a bitcast of a vector type to int, which may be done with a 9399 // vector store followed by an integer load. A vector that does not have 9400 // elements that are byte-sized must therefore be stored as an integer 9401 // built out of the extracted vector elements. 9402 if (!MemSclVT.isByteSized()) { 9403 unsigned NumBits = StVT.getSizeInBits(); 9404 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 9405 9406 SDValue CurrVal = DAG.getConstant(0, SL, IntVT); 9407 9408 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 9409 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 9410 DAG.getVectorIdxConstant(Idx, SL)); 9411 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt); 9412 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc); 9413 unsigned ShiftIntoIdx = 9414 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 9415 SDValue ShiftAmount = 9416 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT); 9417 SDValue ShiftedElt = 9418 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount); 9419 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt); 9420 } 9421 9422 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(), 9423 ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 9424 ST->getAAInfo()); 9425 } 9426 9427 // Store Stride in bytes 9428 unsigned Stride = MemSclVT.getSizeInBits() / 8; 9429 assert(Stride && "Zero stride!"); 9430 // Extract each of the elements from the original vector and save them into 9431 // memory individually. 9432 SmallVector<SDValue, 8> Stores; 9433 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 9434 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 9435 DAG.getVectorIdxConstant(Idx, SL)); 9436 9437 SDValue Ptr = 9438 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Idx * Stride)); 9439 9440 // This scalar TruncStore may be illegal, but we legalize it later. 9441 SDValue Store = DAG.getTruncStore( 9442 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 9443 MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 9444 ST->getAAInfo()); 9445 9446 Stores.push_back(Store); 9447 } 9448 9449 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 9450 } 9451 9452 std::pair<SDValue, SDValue> 9453 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 9454 assert(LD->getAddressingMode() == ISD::UNINDEXED && 9455 "unaligned indexed loads not implemented!"); 9456 SDValue Chain = LD->getChain(); 9457 SDValue Ptr = LD->getBasePtr(); 9458 EVT VT = LD->getValueType(0); 9459 EVT LoadedVT = LD->getMemoryVT(); 9460 SDLoc dl(LD); 9461 auto &MF = DAG.getMachineFunction(); 9462 9463 if (VT.isFloatingPoint() || VT.isVector()) { 9464 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 9465 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 9466 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) && 9467 LoadedVT.isVector()) { 9468 // Scalarize the load and let the individual components be handled. 9469 return scalarizeVectorLoad(LD, DAG); 9470 } 9471 9472 // Expand to a (misaligned) integer load of the same size, 9473 // then bitconvert to floating point or vector. 9474 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 9475 LD->getMemOperand()); 9476 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 9477 if (LoadedVT != VT) 9478 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 9479 ISD::ANY_EXTEND, dl, VT, Result); 9480 9481 return std::make_pair(Result, newLoad.getValue(1)); 9482 } 9483 9484 // Copy the value to a (aligned) stack slot using (unaligned) integer 9485 // loads and stores, then do a (aligned) load from the stack slot. 9486 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 9487 unsigned LoadedBytes = LoadedVT.getStoreSize(); 9488 unsigned RegBytes = RegVT.getSizeInBits() / 8; 9489 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 9490 9491 // Make sure the stack slot is also aligned for the register type. 9492 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 9493 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex(); 9494 SmallVector<SDValue, 8> Stores; 9495 SDValue StackPtr = StackBase; 9496 unsigned Offset = 0; 9497 9498 EVT PtrVT = Ptr.getValueType(); 9499 EVT StackPtrVT = StackPtr.getValueType(); 9500 9501 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 9502 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 9503 9504 // Do all but one copies using the full register width. 9505 for (unsigned i = 1; i < NumRegs; i++) { 9506 // Load one integer register's worth from the original location. 9507 SDValue Load = DAG.getLoad( 9508 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 9509 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 9510 LD->getAAInfo()); 9511 // Follow the load with a store to the stack slot. Remember the store. 9512 Stores.push_back(DAG.getStore( 9513 Load.getValue(1), dl, Load, StackPtr, 9514 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset))); 9515 // Increment the pointers. 9516 Offset += RegBytes; 9517 9518 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 9519 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 9520 } 9521 9522 // The last copy may be partial. Do an extending load. 9523 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 9524 8 * (LoadedBytes - Offset)); 9525 SDValue Load = 9526 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 9527 LD->getPointerInfo().getWithOffset(Offset), MemVT, 9528 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 9529 LD->getAAInfo()); 9530 // Follow the load with a store to the stack slot. Remember the store. 9531 // On big-endian machines this requires a truncating store to ensure 9532 // that the bits end up in the right place. 9533 Stores.push_back(DAG.getTruncStore( 9534 Load.getValue(1), dl, Load, StackPtr, 9535 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT)); 9536 9537 // The order of the stores doesn't matter - say it with a TokenFactor. 9538 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9539 9540 // Finally, perform the original load only redirected to the stack slot. 9541 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 9542 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), 9543 LoadedVT); 9544 9545 // Callers expect a MERGE_VALUES node. 9546 return std::make_pair(Load, TF); 9547 } 9548 9549 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 9550 "Unaligned load of unsupported type."); 9551 9552 // Compute the new VT that is half the size of the old one. This is an 9553 // integer MVT. 9554 unsigned NumBits = LoadedVT.getSizeInBits(); 9555 EVT NewLoadedVT; 9556 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 9557 NumBits >>= 1; 9558 9559 Align Alignment = LD->getOriginalAlign(); 9560 unsigned IncrementSize = NumBits / 8; 9561 ISD::LoadExtType HiExtType = LD->getExtensionType(); 9562 9563 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 9564 if (HiExtType == ISD::NON_EXTLOAD) 9565 HiExtType = ISD::ZEXTLOAD; 9566 9567 // Load the value in two parts 9568 SDValue Lo, Hi; 9569 if (DAG.getDataLayout().isLittleEndian()) { 9570 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 9571 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 9572 LD->getAAInfo()); 9573 9574 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize)); 9575 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 9576 LD->getPointerInfo().getWithOffset(IncrementSize), 9577 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 9578 LD->getAAInfo()); 9579 } else { 9580 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 9581 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 9582 LD->getAAInfo()); 9583 9584 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize)); 9585 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 9586 LD->getPointerInfo().getWithOffset(IncrementSize), 9587 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 9588 LD->getAAInfo()); 9589 } 9590 9591 // aggregate the two parts 9592 SDValue ShiftAmount = 9593 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(), 9594 DAG.getDataLayout())); 9595 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 9596 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 9597 9598 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 9599 Hi.getValue(1)); 9600 9601 return std::make_pair(Result, TF); 9602 } 9603 9604 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 9605 SelectionDAG &DAG) const { 9606 assert(ST->getAddressingMode() == ISD::UNINDEXED && 9607 "unaligned indexed stores not implemented!"); 9608 SDValue Chain = ST->getChain(); 9609 SDValue Ptr = ST->getBasePtr(); 9610 SDValue Val = ST->getValue(); 9611 EVT VT = Val.getValueType(); 9612 Align Alignment = ST->getOriginalAlign(); 9613 auto &MF = DAG.getMachineFunction(); 9614 EVT StoreMemVT = ST->getMemoryVT(); 9615 9616 SDLoc dl(ST); 9617 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) { 9618 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 9619 if (isTypeLegal(intVT)) { 9620 if (!isOperationLegalOrCustom(ISD::STORE, intVT) && 9621 StoreMemVT.isVector()) { 9622 // Scalarize the store and let the individual components be handled. 9623 SDValue Result = scalarizeVectorStore(ST, DAG); 9624 return Result; 9625 } 9626 // Expand to a bitconvert of the value to the integer type of the 9627 // same size, then a (misaligned) int store. 9628 // FIXME: Does not handle truncating floating point stores! 9629 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 9630 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 9631 Alignment, ST->getMemOperand()->getFlags()); 9632 return Result; 9633 } 9634 // Do a (aligned) store to a stack slot, then copy from the stack slot 9635 // to the final destination using (unaligned) integer loads and stores. 9636 MVT RegVT = getRegisterType( 9637 *DAG.getContext(), 9638 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits())); 9639 EVT PtrVT = Ptr.getValueType(); 9640 unsigned StoredBytes = StoreMemVT.getStoreSize(); 9641 unsigned RegBytes = RegVT.getSizeInBits() / 8; 9642 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 9643 9644 // Make sure the stack slot is also aligned for the register type. 9645 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT); 9646 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 9647 9648 // Perform the original store, only redirected to the stack slot. 9649 SDValue Store = DAG.getTruncStore( 9650 Chain, dl, Val, StackPtr, 9651 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT); 9652 9653 EVT StackPtrVT = StackPtr.getValueType(); 9654 9655 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 9656 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 9657 SmallVector<SDValue, 8> Stores; 9658 unsigned Offset = 0; 9659 9660 // Do all but one copies using the full register width. 9661 for (unsigned i = 1; i < NumRegs; i++) { 9662 // Load one integer register's worth from the stack slot. 9663 SDValue Load = DAG.getLoad( 9664 RegVT, dl, Store, StackPtr, 9665 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)); 9666 // Store it to the final location. Remember the store. 9667 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 9668 ST->getPointerInfo().getWithOffset(Offset), 9669 ST->getOriginalAlign(), 9670 ST->getMemOperand()->getFlags())); 9671 // Increment the pointers. 9672 Offset += RegBytes; 9673 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 9674 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 9675 } 9676 9677 // The last store may be partial. Do a truncating store. On big-endian 9678 // machines this requires an extending load from the stack slot to ensure 9679 // that the bits are in the right place. 9680 EVT LoadMemVT = 9681 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset)); 9682 9683 // Load from the stack slot. 9684 SDValue Load = DAG.getExtLoad( 9685 ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 9686 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT); 9687 9688 Stores.push_back( 9689 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 9690 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT, 9691 ST->getOriginalAlign(), 9692 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 9693 // The order of the stores doesn't matter - say it with a TokenFactor. 9694 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9695 return Result; 9696 } 9697 9698 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() && 9699 "Unaligned store of unknown type."); 9700 // Get the half-size VT 9701 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext()); 9702 unsigned NumBits = NewStoredVT.getFixedSizeInBits(); 9703 unsigned IncrementSize = NumBits / 8; 9704 9705 // Divide the stored value in two parts. 9706 SDValue ShiftAmount = DAG.getConstant( 9707 NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout())); 9708 SDValue Lo = Val; 9709 // If Val is a constant, replace the upper bits with 0. The SRL will constant 9710 // fold and not use the upper bits. A smaller constant may be easier to 9711 // materialize. 9712 if (auto *C = dyn_cast<ConstantSDNode>(Lo); C && !C->isOpaque()) 9713 Lo = DAG.getNode( 9714 ISD::AND, dl, VT, Lo, 9715 DAG.getConstant(APInt::getLowBitsSet(VT.getSizeInBits(), NumBits), dl, 9716 VT)); 9717 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 9718 9719 // Store the two parts 9720 SDValue Store1, Store2; 9721 Store1 = DAG.getTruncStore(Chain, dl, 9722 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 9723 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 9724 ST->getMemOperand()->getFlags()); 9725 9726 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize)); 9727 Store2 = DAG.getTruncStore( 9728 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 9729 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 9730 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 9731 9732 SDValue Result = 9733 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 9734 return Result; 9735 } 9736 9737 SDValue 9738 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 9739 const SDLoc &DL, EVT DataVT, 9740 SelectionDAG &DAG, 9741 bool IsCompressedMemory) const { 9742 SDValue Increment; 9743 EVT AddrVT = Addr.getValueType(); 9744 EVT MaskVT = Mask.getValueType(); 9745 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() && 9746 "Incompatible types of Data and Mask"); 9747 if (IsCompressedMemory) { 9748 if (DataVT.isScalableVector()) 9749 report_fatal_error( 9750 "Cannot currently handle compressed memory with scalable vectors"); 9751 // Incrementing the pointer according to number of '1's in the mask. 9752 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 9753 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 9754 if (MaskIntVT.getSizeInBits() < 32) { 9755 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 9756 MaskIntVT = MVT::i32; 9757 } 9758 9759 // Count '1's with POPCNT. 9760 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 9761 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 9762 // Scale is an element size in bytes. 9763 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 9764 AddrVT); 9765 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 9766 } else if (DataVT.isScalableVector()) { 9767 Increment = DAG.getVScale(DL, AddrVT, 9768 APInt(AddrVT.getFixedSizeInBits(), 9769 DataVT.getStoreSize().getKnownMinValue())); 9770 } else 9771 Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT); 9772 9773 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 9774 } 9775 9776 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx, 9777 EVT VecVT, const SDLoc &dl, 9778 ElementCount SubEC) { 9779 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) && 9780 "Cannot index a scalable vector within a fixed-width vector"); 9781 9782 unsigned NElts = VecVT.getVectorMinNumElements(); 9783 unsigned NumSubElts = SubEC.getKnownMinValue(); 9784 EVT IdxVT = Idx.getValueType(); 9785 9786 if (VecVT.isScalableVector() && !SubEC.isScalable()) { 9787 // If this is a constant index and we know the value plus the number of the 9788 // elements in the subvector minus one is less than the minimum number of 9789 // elements then it's safe to return Idx. 9790 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx)) 9791 if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts) 9792 return Idx; 9793 SDValue VS = 9794 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts)); 9795 unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT; 9796 SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS, 9797 DAG.getConstant(NumSubElts, dl, IdxVT)); 9798 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub); 9799 } 9800 if (isPowerOf2_32(NElts) && NumSubElts == 1) { 9801 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts)); 9802 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 9803 DAG.getConstant(Imm, dl, IdxVT)); 9804 } 9805 unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0; 9806 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 9807 DAG.getConstant(MaxIndex, dl, IdxVT)); 9808 } 9809 9810 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 9811 SDValue VecPtr, EVT VecVT, 9812 SDValue Index) const { 9813 return getVectorSubVecPointer( 9814 DAG, VecPtr, VecVT, 9815 EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1), 9816 Index); 9817 } 9818 9819 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG, 9820 SDValue VecPtr, EVT VecVT, 9821 EVT SubVecVT, 9822 SDValue Index) const { 9823 SDLoc dl(Index); 9824 // Make sure the index type is big enough to compute in. 9825 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType()); 9826 9827 EVT EltVT = VecVT.getVectorElementType(); 9828 9829 // Calculate the element offset and add it to the pointer. 9830 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size. 9831 assert(EltSize * 8 == EltVT.getFixedSizeInBits() && 9832 "Converting bits to bytes lost precision"); 9833 assert(SubVecVT.getVectorElementType() == EltVT && 9834 "Sub-vector must be a vector with matching element type"); 9835 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl, 9836 SubVecVT.getVectorElementCount()); 9837 9838 EVT IdxVT = Index.getValueType(); 9839 if (SubVecVT.isScalableVector()) 9840 Index = 9841 DAG.getNode(ISD::MUL, dl, IdxVT, Index, 9842 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1))); 9843 9844 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 9845 DAG.getConstant(EltSize, dl, IdxVT)); 9846 return DAG.getMemBasePlusOffset(VecPtr, Index, dl); 9847 } 9848 9849 //===----------------------------------------------------------------------===// 9850 // Implementation of Emulated TLS Model 9851 //===----------------------------------------------------------------------===// 9852 9853 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 9854 SelectionDAG &DAG) const { 9855 // Access to address of TLS varialbe xyz is lowered to a function call: 9856 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 9857 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9858 PointerType *VoidPtrType = PointerType::get(*DAG.getContext(), 0); 9859 SDLoc dl(GA); 9860 9861 ArgListTy Args; 9862 ArgListEntry Entry; 9863 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 9864 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 9865 StringRef EmuTlsVarName(NameString); 9866 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 9867 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 9868 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 9869 Entry.Ty = VoidPtrType; 9870 Args.push_back(Entry); 9871 9872 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 9873 9874 TargetLowering::CallLoweringInfo CLI(DAG); 9875 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 9876 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 9877 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 9878 9879 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 9880 // At last for X86 targets, maybe good for other targets too? 9881 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9882 MFI.setAdjustsStack(true); // Is this only for X86 target? 9883 MFI.setHasCalls(true); 9884 9885 assert((GA->getOffset() == 0) && 9886 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 9887 return CallResult.first; 9888 } 9889 9890 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 9891 SelectionDAG &DAG) const { 9892 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 9893 if (!isCtlzFast()) 9894 return SDValue(); 9895 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 9896 SDLoc dl(Op); 9897 if (isNullConstant(Op.getOperand(1)) && CC == ISD::SETEQ) { 9898 EVT VT = Op.getOperand(0).getValueType(); 9899 SDValue Zext = Op.getOperand(0); 9900 if (VT.bitsLT(MVT::i32)) { 9901 VT = MVT::i32; 9902 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 9903 } 9904 unsigned Log2b = Log2_32(VT.getSizeInBits()); 9905 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 9906 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 9907 DAG.getConstant(Log2b, dl, MVT::i32)); 9908 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 9909 } 9910 return SDValue(); 9911 } 9912 9913 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const { 9914 SDValue Op0 = Node->getOperand(0); 9915 SDValue Op1 = Node->getOperand(1); 9916 EVT VT = Op0.getValueType(); 9917 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9918 unsigned Opcode = Node->getOpcode(); 9919 SDLoc DL(Node); 9920 9921 // umax(x,1) --> sub(x,cmpeq(x,0)) iff cmp result is allbits 9922 if (Opcode == ISD::UMAX && llvm::isOneOrOneSplat(Op1, true) && BoolVT == VT && 9923 getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 9924 Op0 = DAG.getFreeze(Op0); 9925 SDValue Zero = DAG.getConstant(0, DL, VT); 9926 return DAG.getNode(ISD::SUB, DL, VT, Op0, 9927 DAG.getSetCC(DL, VT, Op0, Zero, ISD::SETEQ)); 9928 } 9929 9930 // umin(x,y) -> sub(x,usubsat(x,y)) 9931 // TODO: Missing freeze(Op0)? 9932 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) && 9933 isOperationLegal(ISD::USUBSAT, VT)) { 9934 return DAG.getNode(ISD::SUB, DL, VT, Op0, 9935 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1)); 9936 } 9937 9938 // umax(x,y) -> add(x,usubsat(y,x)) 9939 // TODO: Missing freeze(Op0)? 9940 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) && 9941 isOperationLegal(ISD::USUBSAT, VT)) { 9942 return DAG.getNode(ISD::ADD, DL, VT, Op0, 9943 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0)); 9944 } 9945 9946 // FIXME: Should really try to split the vector in case it's legal on a 9947 // subvector. 9948 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 9949 return DAG.UnrollVectorOp(Node); 9950 9951 // Attempt to find an existing SETCC node that we can reuse. 9952 // TODO: Do we need a generic doesSETCCNodeExist? 9953 // TODO: Missing freeze(Op0)/freeze(Op1)? 9954 auto buildMinMax = [&](ISD::CondCode PrefCC, ISD::CondCode AltCC, 9955 ISD::CondCode PrefCommuteCC, 9956 ISD::CondCode AltCommuteCC) { 9957 SDVTList BoolVTList = DAG.getVTList(BoolVT); 9958 for (ISD::CondCode CC : {PrefCC, AltCC}) { 9959 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList, 9960 {Op0, Op1, DAG.getCondCode(CC)})) { 9961 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC); 9962 return DAG.getSelect(DL, VT, Cond, Op0, Op1); 9963 } 9964 } 9965 for (ISD::CondCode CC : {PrefCommuteCC, AltCommuteCC}) { 9966 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList, 9967 {Op0, Op1, DAG.getCondCode(CC)})) { 9968 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC); 9969 return DAG.getSelect(DL, VT, Cond, Op1, Op0); 9970 } 9971 } 9972 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, PrefCC); 9973 return DAG.getSelect(DL, VT, Cond, Op0, Op1); 9974 }; 9975 9976 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 9977 // -> Y = (A < B) ? B : A 9978 // -> Y = (A >= B) ? A : B 9979 // -> Y = (A <= B) ? B : A 9980 switch (Opcode) { 9981 case ISD::SMAX: 9982 return buildMinMax(ISD::SETGT, ISD::SETGE, ISD::SETLT, ISD::SETLE); 9983 case ISD::SMIN: 9984 return buildMinMax(ISD::SETLT, ISD::SETLE, ISD::SETGT, ISD::SETGE); 9985 case ISD::UMAX: 9986 return buildMinMax(ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE); 9987 case ISD::UMIN: 9988 return buildMinMax(ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE); 9989 } 9990 9991 llvm_unreachable("How did we get here?"); 9992 } 9993 9994 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const { 9995 unsigned Opcode = Node->getOpcode(); 9996 SDValue LHS = Node->getOperand(0); 9997 SDValue RHS = Node->getOperand(1); 9998 EVT VT = LHS.getValueType(); 9999 SDLoc dl(Node); 10000 10001 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 10002 assert(VT.isInteger() && "Expected operands to be integers"); 10003 10004 // usub.sat(a, b) -> umax(a, b) - b 10005 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) { 10006 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS); 10007 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS); 10008 } 10009 10010 // uadd.sat(a, b) -> umin(a, ~b) + b 10011 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) { 10012 SDValue InvRHS = DAG.getNOT(dl, RHS, VT); 10013 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS); 10014 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS); 10015 } 10016 10017 unsigned OverflowOp; 10018 switch (Opcode) { 10019 case ISD::SADDSAT: 10020 OverflowOp = ISD::SADDO; 10021 break; 10022 case ISD::UADDSAT: 10023 OverflowOp = ISD::UADDO; 10024 break; 10025 case ISD::SSUBSAT: 10026 OverflowOp = ISD::SSUBO; 10027 break; 10028 case ISD::USUBSAT: 10029 OverflowOp = ISD::USUBO; 10030 break; 10031 default: 10032 llvm_unreachable("Expected method to receive signed or unsigned saturation " 10033 "addition or subtraction node."); 10034 } 10035 10036 // FIXME: Should really try to split the vector in case it's legal on a 10037 // subvector. 10038 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 10039 return DAG.UnrollVectorOp(Node); 10040 10041 unsigned BitWidth = LHS.getScalarValueSizeInBits(); 10042 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 10043 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 10044 SDValue SumDiff = Result.getValue(0); 10045 SDValue Overflow = Result.getValue(1); 10046 SDValue Zero = DAG.getConstant(0, dl, VT); 10047 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT); 10048 10049 if (Opcode == ISD::UADDSAT) { 10050 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 10051 // (LHS + RHS) | OverflowMask 10052 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 10053 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask); 10054 } 10055 // Overflow ? 0xffff.... : (LHS + RHS) 10056 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff); 10057 } 10058 10059 if (Opcode == ISD::USUBSAT) { 10060 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 10061 // (LHS - RHS) & ~OverflowMask 10062 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 10063 SDValue Not = DAG.getNOT(dl, OverflowMask, VT); 10064 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not); 10065 } 10066 // Overflow ? 0 : (LHS - RHS) 10067 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff); 10068 } 10069 10070 if (Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) { 10071 APInt MinVal = APInt::getSignedMinValue(BitWidth); 10072 APInt MaxVal = APInt::getSignedMaxValue(BitWidth); 10073 10074 KnownBits KnownLHS = DAG.computeKnownBits(LHS); 10075 KnownBits KnownRHS = DAG.computeKnownBits(RHS); 10076 10077 // If either of the operand signs are known, then they are guaranteed to 10078 // only saturate in one direction. If non-negative they will saturate 10079 // towards SIGNED_MAX, if negative they will saturate towards SIGNED_MIN. 10080 // 10081 // In the case of ISD::SSUBSAT, 'x - y' is equivalent to 'x + (-y)', so the 10082 // sign of 'y' has to be flipped. 10083 10084 bool LHSIsNonNegative = KnownLHS.isNonNegative(); 10085 bool RHSIsNonNegative = Opcode == ISD::SADDSAT ? KnownRHS.isNonNegative() 10086 : KnownRHS.isNegative(); 10087 if (LHSIsNonNegative || RHSIsNonNegative) { 10088 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 10089 return DAG.getSelect(dl, VT, Overflow, SatMax, SumDiff); 10090 } 10091 10092 bool LHSIsNegative = KnownLHS.isNegative(); 10093 bool RHSIsNegative = Opcode == ISD::SADDSAT ? KnownRHS.isNegative() 10094 : KnownRHS.isNonNegative(); 10095 if (LHSIsNegative || RHSIsNegative) { 10096 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 10097 return DAG.getSelect(dl, VT, Overflow, SatMin, SumDiff); 10098 } 10099 } 10100 10101 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff 10102 APInt MinVal = APInt::getSignedMinValue(BitWidth); 10103 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 10104 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff, 10105 DAG.getConstant(BitWidth - 1, dl, VT)); 10106 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin); 10107 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff); 10108 } 10109 10110 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const { 10111 unsigned Opcode = Node->getOpcode(); 10112 bool IsSigned = Opcode == ISD::SSHLSAT; 10113 SDValue LHS = Node->getOperand(0); 10114 SDValue RHS = Node->getOperand(1); 10115 EVT VT = LHS.getValueType(); 10116 SDLoc dl(Node); 10117 10118 assert((Node->getOpcode() == ISD::SSHLSAT || 10119 Node->getOpcode() == ISD::USHLSAT) && 10120 "Expected a SHLSAT opcode"); 10121 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 10122 assert(VT.isInteger() && "Expected operands to be integers"); 10123 10124 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 10125 return DAG.UnrollVectorOp(Node); 10126 10127 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate. 10128 10129 unsigned BW = VT.getScalarSizeInBits(); 10130 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 10131 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS); 10132 SDValue Orig = 10133 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS); 10134 10135 SDValue SatVal; 10136 if (IsSigned) { 10137 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT); 10138 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT); 10139 SDValue Cond = 10140 DAG.getSetCC(dl, BoolVT, LHS, DAG.getConstant(0, dl, VT), ISD::SETLT); 10141 SatVal = DAG.getSelect(dl, VT, Cond, SatMin, SatMax); 10142 } else { 10143 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT); 10144 } 10145 SDValue Cond = DAG.getSetCC(dl, BoolVT, LHS, Orig, ISD::SETNE); 10146 return DAG.getSelect(dl, VT, Cond, SatVal, Result); 10147 } 10148 10149 SDValue 10150 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const { 10151 assert((Node->getOpcode() == ISD::SMULFIX || 10152 Node->getOpcode() == ISD::UMULFIX || 10153 Node->getOpcode() == ISD::SMULFIXSAT || 10154 Node->getOpcode() == ISD::UMULFIXSAT) && 10155 "Expected a fixed point multiplication opcode"); 10156 10157 SDLoc dl(Node); 10158 SDValue LHS = Node->getOperand(0); 10159 SDValue RHS = Node->getOperand(1); 10160 EVT VT = LHS.getValueType(); 10161 unsigned Scale = Node->getConstantOperandVal(2); 10162 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT || 10163 Node->getOpcode() == ISD::UMULFIXSAT); 10164 bool Signed = (Node->getOpcode() == ISD::SMULFIX || 10165 Node->getOpcode() == ISD::SMULFIXSAT); 10166 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 10167 unsigned VTSize = VT.getScalarSizeInBits(); 10168 10169 if (!Scale) { 10170 // [us]mul.fix(a, b, 0) -> mul(a, b) 10171 if (!Saturating) { 10172 if (isOperationLegalOrCustom(ISD::MUL, VT)) 10173 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 10174 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) { 10175 SDValue Result = 10176 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 10177 SDValue Product = Result.getValue(0); 10178 SDValue Overflow = Result.getValue(1); 10179 SDValue Zero = DAG.getConstant(0, dl, VT); 10180 10181 APInt MinVal = APInt::getSignedMinValue(VTSize); 10182 APInt MaxVal = APInt::getSignedMaxValue(VTSize); 10183 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 10184 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 10185 // Xor the inputs, if resulting sign bit is 0 the product will be 10186 // positive, else negative. 10187 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS); 10188 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT); 10189 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax); 10190 return DAG.getSelect(dl, VT, Overflow, Result, Product); 10191 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) { 10192 SDValue Result = 10193 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 10194 SDValue Product = Result.getValue(0); 10195 SDValue Overflow = Result.getValue(1); 10196 10197 APInt MaxVal = APInt::getMaxValue(VTSize); 10198 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 10199 return DAG.getSelect(dl, VT, Overflow, SatMax, Product); 10200 } 10201 } 10202 10203 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) && 10204 "Expected scale to be less than the number of bits if signed or at " 10205 "most the number of bits if unsigned."); 10206 assert(LHS.getValueType() == RHS.getValueType() && 10207 "Expected both operands to be the same type"); 10208 10209 // Get the upper and lower bits of the result. 10210 SDValue Lo, Hi; 10211 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI; 10212 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU; 10213 if (isOperationLegalOrCustom(LoHiOp, VT)) { 10214 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS); 10215 Lo = Result.getValue(0); 10216 Hi = Result.getValue(1); 10217 } else if (isOperationLegalOrCustom(HiOp, VT)) { 10218 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 10219 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS); 10220 } else if (VT.isVector()) { 10221 return SDValue(); 10222 } else { 10223 report_fatal_error("Unable to expand fixed point multiplication."); 10224 } 10225 10226 if (Scale == VTSize) 10227 // Result is just the top half since we'd be shifting by the width of the 10228 // operand. Overflow impossible so this works for both UMULFIX and 10229 // UMULFIXSAT. 10230 return Hi; 10231 10232 // The result will need to be shifted right by the scale since both operands 10233 // are scaled. The result is given to us in 2 halves, so we only want part of 10234 // both in the result. 10235 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 10236 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo, 10237 DAG.getConstant(Scale, dl, ShiftTy)); 10238 if (!Saturating) 10239 return Result; 10240 10241 if (!Signed) { 10242 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the 10243 // widened multiplication) aren't all zeroes. 10244 10245 // Saturate to max if ((Hi >> Scale) != 0), 10246 // which is the same as if (Hi > ((1 << Scale) - 1)) 10247 APInt MaxVal = APInt::getMaxValue(VTSize); 10248 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), 10249 dl, VT); 10250 Result = DAG.getSelectCC(dl, Hi, LowMask, 10251 DAG.getConstant(MaxVal, dl, VT), Result, 10252 ISD::SETUGT); 10253 10254 return Result; 10255 } 10256 10257 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the 10258 // widened multiplication) aren't all ones or all zeroes. 10259 10260 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT); 10261 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT); 10262 10263 if (Scale == 0) { 10264 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo, 10265 DAG.getConstant(VTSize - 1, dl, ShiftTy)); 10266 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE); 10267 // Saturated to SatMin if wide product is negative, and SatMax if wide 10268 // product is positive ... 10269 SDValue Zero = DAG.getConstant(0, dl, VT); 10270 SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax, 10271 ISD::SETLT); 10272 // ... but only if we overflowed. 10273 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result); 10274 } 10275 10276 // We handled Scale==0 above so all the bits to examine is in Hi. 10277 10278 // Saturate to max if ((Hi >> (Scale - 1)) > 0), 10279 // which is the same as if (Hi > (1 << (Scale - 1)) - 1) 10280 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), 10281 dl, VT); 10282 Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT); 10283 // Saturate to min if (Hi >> (Scale - 1)) < -1), 10284 // which is the same as if (HI < (-1 << (Scale - 1)) 10285 SDValue HighMask = 10286 DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), 10287 dl, VT); 10288 Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT); 10289 return Result; 10290 } 10291 10292 SDValue 10293 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, 10294 SDValue LHS, SDValue RHS, 10295 unsigned Scale, SelectionDAG &DAG) const { 10296 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT || 10297 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) && 10298 "Expected a fixed point division opcode"); 10299 10300 EVT VT = LHS.getValueType(); 10301 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 10302 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 10303 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 10304 10305 // If there is enough room in the type to upscale the LHS or downscale the 10306 // RHS before the division, we can perform it in this type without having to 10307 // resize. For signed operations, the LHS headroom is the number of 10308 // redundant sign bits, and for unsigned ones it is the number of zeroes. 10309 // The headroom for the RHS is the number of trailing zeroes. 10310 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1 10311 : DAG.computeKnownBits(LHS).countMinLeadingZeros(); 10312 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros(); 10313 10314 // For signed saturating operations, we need to be able to detect true integer 10315 // division overflow; that is, when you have MIN / -EPS. However, this 10316 // is undefined behavior and if we emit divisions that could take such 10317 // values it may cause undesired behavior (arithmetic exceptions on x86, for 10318 // example). 10319 // Avoid this by requiring an extra bit so that we never get this case. 10320 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale 10321 // signed saturating division, we need to emit a whopping 32-bit division. 10322 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed)) 10323 return SDValue(); 10324 10325 unsigned LHSShift = std::min(LHSLead, Scale); 10326 unsigned RHSShift = Scale - LHSShift; 10327 10328 // At this point, we know that if we shift the LHS up by LHSShift and the 10329 // RHS down by RHSShift, we can emit a regular division with a final scaling 10330 // factor of Scale. 10331 10332 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 10333 if (LHSShift) 10334 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS, 10335 DAG.getConstant(LHSShift, dl, ShiftTy)); 10336 if (RHSShift) 10337 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS, 10338 DAG.getConstant(RHSShift, dl, ShiftTy)); 10339 10340 SDValue Quot; 10341 if (Signed) { 10342 // For signed operations, if the resulting quotient is negative and the 10343 // remainder is nonzero, subtract 1 from the quotient to round towards 10344 // negative infinity. 10345 SDValue Rem; 10346 // FIXME: Ideally we would always produce an SDIVREM here, but if the 10347 // type isn't legal, SDIVREM cannot be expanded. There is no reason why 10348 // we couldn't just form a libcall, but the type legalizer doesn't do it. 10349 if (isTypeLegal(VT) && 10350 isOperationLegalOrCustom(ISD::SDIVREM, VT)) { 10351 Quot = DAG.getNode(ISD::SDIVREM, dl, 10352 DAG.getVTList(VT, VT), 10353 LHS, RHS); 10354 Rem = Quot.getValue(1); 10355 Quot = Quot.getValue(0); 10356 } else { 10357 Quot = DAG.getNode(ISD::SDIV, dl, VT, 10358 LHS, RHS); 10359 Rem = DAG.getNode(ISD::SREM, dl, VT, 10360 LHS, RHS); 10361 } 10362 SDValue Zero = DAG.getConstant(0, dl, VT); 10363 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE); 10364 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT); 10365 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT); 10366 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg); 10367 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot, 10368 DAG.getConstant(1, dl, VT)); 10369 Quot = DAG.getSelect(dl, VT, 10370 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg), 10371 Sub1, Quot); 10372 } else 10373 Quot = DAG.getNode(ISD::UDIV, dl, VT, 10374 LHS, RHS); 10375 10376 return Quot; 10377 } 10378 10379 void TargetLowering::expandUADDSUBO( 10380 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 10381 SDLoc dl(Node); 10382 SDValue LHS = Node->getOperand(0); 10383 SDValue RHS = Node->getOperand(1); 10384 bool IsAdd = Node->getOpcode() == ISD::UADDO; 10385 10386 // If UADDO_CARRY/SUBO_CARRY is legal, use that instead. 10387 unsigned OpcCarry = IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY; 10388 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) { 10389 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1)); 10390 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(), 10391 { LHS, RHS, CarryIn }); 10392 Result = SDValue(NodeCarry.getNode(), 0); 10393 Overflow = SDValue(NodeCarry.getNode(), 1); 10394 return; 10395 } 10396 10397 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 10398 LHS.getValueType(), LHS, RHS); 10399 10400 EVT ResultType = Node->getValueType(1); 10401 EVT SetCCType = getSetCCResultType( 10402 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 10403 SDValue SetCC; 10404 if (IsAdd && isOneConstant(RHS)) { 10405 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces 10406 // the live range of X. We assume comparing with 0 is cheap. 10407 // The general case (X + C) < C is not necessarily beneficial. Although we 10408 // reduce the live range of X, we may introduce the materialization of 10409 // constant C. 10410 SetCC = 10411 DAG.getSetCC(dl, SetCCType, Result, 10412 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ); 10413 } else if (IsAdd && isAllOnesConstant(RHS)) { 10414 // Special case: uaddo X, -1 overflows if X != 0. 10415 SetCC = 10416 DAG.getSetCC(dl, SetCCType, LHS, 10417 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETNE); 10418 } else { 10419 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 10420 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC); 10421 } 10422 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 10423 } 10424 10425 void TargetLowering::expandSADDSUBO( 10426 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 10427 SDLoc dl(Node); 10428 SDValue LHS = Node->getOperand(0); 10429 SDValue RHS = Node->getOperand(1); 10430 bool IsAdd = Node->getOpcode() == ISD::SADDO; 10431 10432 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 10433 LHS.getValueType(), LHS, RHS); 10434 10435 EVT ResultType = Node->getValueType(1); 10436 EVT OType = getSetCCResultType( 10437 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 10438 10439 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow. 10440 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT; 10441 if (isOperationLegal(OpcSat, LHS.getValueType())) { 10442 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS); 10443 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE); 10444 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 10445 return; 10446 } 10447 10448 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 10449 10450 // For an addition, the result should be less than one of the operands (LHS) 10451 // if and only if the other operand (RHS) is negative, otherwise there will 10452 // be overflow. 10453 // For a subtraction, the result should be less than one of the operands 10454 // (LHS) if and only if the other operand (RHS) is (non-zero) positive, 10455 // otherwise there will be overflow. 10456 SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT); 10457 SDValue ConditionRHS = 10458 DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT); 10459 10460 Overflow = DAG.getBoolExtOrTrunc( 10461 DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl, 10462 ResultType, ResultType); 10463 } 10464 10465 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result, 10466 SDValue &Overflow, SelectionDAG &DAG) const { 10467 SDLoc dl(Node); 10468 EVT VT = Node->getValueType(0); 10469 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 10470 SDValue LHS = Node->getOperand(0); 10471 SDValue RHS = Node->getOperand(1); 10472 bool isSigned = Node->getOpcode() == ISD::SMULO; 10473 10474 // For power-of-two multiplications we can use a simpler shift expansion. 10475 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 10476 const APInt &C = RHSC->getAPIntValue(); 10477 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 10478 if (C.isPowerOf2()) { 10479 // smulo(x, signed_min) is same as umulo(x, signed_min). 10480 bool UseArithShift = isSigned && !C.isMinSignedValue(); 10481 EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout()); 10482 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy); 10483 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt); 10484 Overflow = DAG.getSetCC(dl, SetCCVT, 10485 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 10486 dl, VT, Result, ShiftAmt), 10487 LHS, ISD::SETNE); 10488 return true; 10489 } 10490 } 10491 10492 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2); 10493 if (VT.isVector()) 10494 WideVT = 10495 EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount()); 10496 10497 SDValue BottomHalf; 10498 SDValue TopHalf; 10499 static const unsigned Ops[2][3] = 10500 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 10501 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 10502 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 10503 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 10504 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 10505 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 10506 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 10507 RHS); 10508 TopHalf = BottomHalf.getValue(1); 10509 } else if (isTypeLegal(WideVT)) { 10510 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 10511 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 10512 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 10513 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul); 10514 SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl, 10515 getShiftAmountTy(WideVT, DAG.getDataLayout())); 10516 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, 10517 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt)); 10518 } else { 10519 if (VT.isVector()) 10520 return false; 10521 10522 // We can fall back to a libcall with an illegal type for the MUL if we 10523 // have a libcall big enough. 10524 // Also, we can fall back to a division in some cases, but that's a big 10525 // performance hit in the general case. 10526 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 10527 if (WideVT == MVT::i16) 10528 LC = RTLIB::MUL_I16; 10529 else if (WideVT == MVT::i32) 10530 LC = RTLIB::MUL_I32; 10531 else if (WideVT == MVT::i64) 10532 LC = RTLIB::MUL_I64; 10533 else if (WideVT == MVT::i128) 10534 LC = RTLIB::MUL_I128; 10535 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!"); 10536 10537 SDValue HiLHS; 10538 SDValue HiRHS; 10539 if (isSigned) { 10540 // The high part is obtained by SRA'ing all but one of the bits of low 10541 // part. 10542 unsigned LoSize = VT.getFixedSizeInBits(); 10543 HiLHS = 10544 DAG.getNode(ISD::SRA, dl, VT, LHS, 10545 DAG.getConstant(LoSize - 1, dl, 10546 getPointerTy(DAG.getDataLayout()))); 10547 HiRHS = 10548 DAG.getNode(ISD::SRA, dl, VT, RHS, 10549 DAG.getConstant(LoSize - 1, dl, 10550 getPointerTy(DAG.getDataLayout()))); 10551 } else { 10552 HiLHS = DAG.getConstant(0, dl, VT); 10553 HiRHS = DAG.getConstant(0, dl, VT); 10554 } 10555 10556 // Here we're passing the 2 arguments explicitly as 4 arguments that are 10557 // pre-lowered to the correct types. This all depends upon WideVT not 10558 // being a legal type for the architecture and thus has to be split to 10559 // two arguments. 10560 SDValue Ret; 10561 TargetLowering::MakeLibCallOptions CallOptions; 10562 CallOptions.setSExt(isSigned); 10563 CallOptions.setIsPostTypeLegalization(true); 10564 if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) { 10565 // Halves of WideVT are packed into registers in different order 10566 // depending on platform endianness. This is usually handled by 10567 // the C calling convention, but we can't defer to it in 10568 // the legalizer. 10569 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS }; 10570 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 10571 } else { 10572 SDValue Args[] = { HiLHS, LHS, HiRHS, RHS }; 10573 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 10574 } 10575 assert(Ret.getOpcode() == ISD::MERGE_VALUES && 10576 "Ret value is a collection of constituent nodes holding result."); 10577 if (DAG.getDataLayout().isLittleEndian()) { 10578 // Same as above. 10579 BottomHalf = Ret.getOperand(0); 10580 TopHalf = Ret.getOperand(1); 10581 } else { 10582 BottomHalf = Ret.getOperand(1); 10583 TopHalf = Ret.getOperand(0); 10584 } 10585 } 10586 10587 Result = BottomHalf; 10588 if (isSigned) { 10589 SDValue ShiftAmt = DAG.getConstant( 10590 VT.getScalarSizeInBits() - 1, dl, 10591 getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout())); 10592 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt); 10593 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE); 10594 } else { 10595 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, 10596 DAG.getConstant(0, dl, VT), ISD::SETNE); 10597 } 10598 10599 // Truncate the result if SetCC returns a larger type than needed. 10600 EVT RType = Node->getValueType(1); 10601 if (RType.bitsLT(Overflow.getValueType())) 10602 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow); 10603 10604 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() && 10605 "Unexpected result type for S/UMULO legalization"); 10606 return true; 10607 } 10608 10609 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const { 10610 SDLoc dl(Node); 10611 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 10612 SDValue Op = Node->getOperand(0); 10613 EVT VT = Op.getValueType(); 10614 10615 if (VT.isScalableVector()) 10616 report_fatal_error( 10617 "Expanding reductions for scalable vectors is undefined."); 10618 10619 // Try to use a shuffle reduction for power of two vectors. 10620 if (VT.isPow2VectorType()) { 10621 while (VT.getVectorNumElements() > 1) { 10622 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 10623 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) 10624 break; 10625 10626 SDValue Lo, Hi; 10627 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl); 10628 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi); 10629 VT = HalfVT; 10630 } 10631 } 10632 10633 EVT EltVT = VT.getVectorElementType(); 10634 unsigned NumElts = VT.getVectorNumElements(); 10635 10636 SmallVector<SDValue, 8> Ops; 10637 DAG.ExtractVectorElements(Op, Ops, 0, NumElts); 10638 10639 SDValue Res = Ops[0]; 10640 for (unsigned i = 1; i < NumElts; i++) 10641 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags()); 10642 10643 // Result type may be wider than element type. 10644 if (EltVT != Node->getValueType(0)) 10645 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res); 10646 return Res; 10647 } 10648 10649 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const { 10650 SDLoc dl(Node); 10651 SDValue AccOp = Node->getOperand(0); 10652 SDValue VecOp = Node->getOperand(1); 10653 SDNodeFlags Flags = Node->getFlags(); 10654 10655 EVT VT = VecOp.getValueType(); 10656 EVT EltVT = VT.getVectorElementType(); 10657 10658 if (VT.isScalableVector()) 10659 report_fatal_error( 10660 "Expanding reductions for scalable vectors is undefined."); 10661 10662 unsigned NumElts = VT.getVectorNumElements(); 10663 10664 SmallVector<SDValue, 8> Ops; 10665 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts); 10666 10667 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 10668 10669 SDValue Res = AccOp; 10670 for (unsigned i = 0; i < NumElts; i++) 10671 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags); 10672 10673 return Res; 10674 } 10675 10676 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result, 10677 SelectionDAG &DAG) const { 10678 EVT VT = Node->getValueType(0); 10679 SDLoc dl(Node); 10680 bool isSigned = Node->getOpcode() == ISD::SREM; 10681 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV; 10682 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 10683 SDValue Dividend = Node->getOperand(0); 10684 SDValue Divisor = Node->getOperand(1); 10685 if (isOperationLegalOrCustom(DivRemOpc, VT)) { 10686 SDVTList VTs = DAG.getVTList(VT, VT); 10687 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1); 10688 return true; 10689 } 10690 if (isOperationLegalOrCustom(DivOpc, VT)) { 10691 // X % Y -> X-X/Y*Y 10692 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor); 10693 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor); 10694 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 10695 return true; 10696 } 10697 return false; 10698 } 10699 10700 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node, 10701 SelectionDAG &DAG) const { 10702 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT; 10703 SDLoc dl(SDValue(Node, 0)); 10704 SDValue Src = Node->getOperand(0); 10705 10706 // DstVT is the result type, while SatVT is the size to which we saturate 10707 EVT SrcVT = Src.getValueType(); 10708 EVT DstVT = Node->getValueType(0); 10709 10710 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 10711 unsigned SatWidth = SatVT.getScalarSizeInBits(); 10712 unsigned DstWidth = DstVT.getScalarSizeInBits(); 10713 assert(SatWidth <= DstWidth && 10714 "Expected saturation width smaller than result width"); 10715 10716 // Determine minimum and maximum integer values and their corresponding 10717 // floating-point values. 10718 APInt MinInt, MaxInt; 10719 if (IsSigned) { 10720 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth); 10721 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth); 10722 } else { 10723 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth); 10724 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth); 10725 } 10726 10727 // We cannot risk emitting FP_TO_XINT nodes with a source VT of [b]f16, as 10728 // libcall emission cannot handle this. Large result types will fail. 10729 if (SrcVT == MVT::f16 || SrcVT == MVT::bf16) { 10730 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src); 10731 SrcVT = Src.getValueType(); 10732 } 10733 10734 APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 10735 APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 10736 10737 APFloat::opStatus MinStatus = 10738 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero); 10739 APFloat::opStatus MaxStatus = 10740 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero); 10741 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) && 10742 !(MaxStatus & APFloat::opStatus::opInexact); 10743 10744 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT); 10745 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT); 10746 10747 // If the integer bounds are exactly representable as floats and min/max are 10748 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence 10749 // of comparisons and selects. 10750 bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) && 10751 isOperationLegal(ISD::FMAXNUM, SrcVT); 10752 if (AreExactFloatBounds && MinMaxLegal) { 10753 SDValue Clamped = Src; 10754 10755 // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat. 10756 Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode); 10757 // Clamp by MaxFloat from above. NaN cannot occur. 10758 Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode); 10759 // Convert clamped value to integer. 10760 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, 10761 dl, DstVT, Clamped); 10762 10763 // In the unsigned case we're done, because we mapped NaN to MinFloat, 10764 // which will cast to zero. 10765 if (!IsSigned) 10766 return FpToInt; 10767 10768 // Otherwise, select 0 if Src is NaN. 10769 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 10770 EVT SetCCVT = 10771 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 10772 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO); 10773 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, FpToInt); 10774 } 10775 10776 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT); 10777 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT); 10778 10779 // Result of direct conversion. The assumption here is that the operation is 10780 // non-trapping and it's fine to apply it to an out-of-range value if we 10781 // select it away later. 10782 SDValue FpToInt = 10783 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src); 10784 10785 SDValue Select = FpToInt; 10786 10787 EVT SetCCVT = 10788 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 10789 10790 // If Src ULT MinFloat, select MinInt. In particular, this also selects 10791 // MinInt if Src is NaN. 10792 SDValue ULT = DAG.getSetCC(dl, SetCCVT, Src, MinFloatNode, ISD::SETULT); 10793 Select = DAG.getSelect(dl, DstVT, ULT, MinIntNode, Select); 10794 // If Src OGT MaxFloat, select MaxInt. 10795 SDValue OGT = DAG.getSetCC(dl, SetCCVT, Src, MaxFloatNode, ISD::SETOGT); 10796 Select = DAG.getSelect(dl, DstVT, OGT, MaxIntNode, Select); 10797 10798 // In the unsigned case we are done, because we mapped NaN to MinInt, which 10799 // is already zero. 10800 if (!IsSigned) 10801 return Select; 10802 10803 // Otherwise, select 0 if Src is NaN. 10804 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 10805 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO); 10806 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, Select); 10807 } 10808 10809 SDValue TargetLowering::expandVectorSplice(SDNode *Node, 10810 SelectionDAG &DAG) const { 10811 assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!"); 10812 assert(Node->getValueType(0).isScalableVector() && 10813 "Fixed length vector types expected to use SHUFFLE_VECTOR!"); 10814 10815 EVT VT = Node->getValueType(0); 10816 SDValue V1 = Node->getOperand(0); 10817 SDValue V2 = Node->getOperand(1); 10818 int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue(); 10819 SDLoc DL(Node); 10820 10821 // Expand through memory thusly: 10822 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr 10823 // Store V1, Ptr 10824 // Store V2, Ptr + sizeof(V1) 10825 // If (Imm < 0) 10826 // TrailingElts = -Imm 10827 // Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt)) 10828 // else 10829 // Ptr = Ptr + (Imm * sizeof(VT.Elt)) 10830 // Res = Load Ptr 10831 10832 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false); 10833 10834 EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 10835 VT.getVectorElementCount() * 2); 10836 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment); 10837 EVT PtrVT = StackPtr.getValueType(); 10838 auto &MF = DAG.getMachineFunction(); 10839 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 10840 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex); 10841 10842 // Store the lo part of CONCAT_VECTORS(V1, V2) 10843 SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo); 10844 // Store the hi part of CONCAT_VECTORS(V1, V2) 10845 SDValue OffsetToV2 = DAG.getVScale( 10846 DL, PtrVT, 10847 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinValue())); 10848 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2); 10849 SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo); 10850 10851 if (Imm >= 0) { 10852 // Load back the required element. getVectorElementPointer takes care of 10853 // clamping the index if it's out-of-bounds. 10854 StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2)); 10855 // Load the spliced result 10856 return DAG.getLoad(VT, DL, StoreV2, StackPtr, 10857 MachinePointerInfo::getUnknownStack(MF)); 10858 } 10859 10860 uint64_t TrailingElts = -Imm; 10861 10862 // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2. 10863 TypeSize EltByteSize = VT.getVectorElementType().getStoreSize(); 10864 SDValue TrailingBytes = 10865 DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT); 10866 10867 if (TrailingElts > VT.getVectorMinNumElements()) { 10868 SDValue VLBytes = 10869 DAG.getVScale(DL, PtrVT, 10870 APInt(PtrVT.getFixedSizeInBits(), 10871 VT.getStoreSize().getKnownMinValue())); 10872 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes); 10873 } 10874 10875 // Calculate the start address of the spliced result. 10876 StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes); 10877 10878 // Load the spliced result 10879 return DAG.getLoad(VT, DL, StoreV2, StackPtr2, 10880 MachinePointerInfo::getUnknownStack(MF)); 10881 } 10882 10883 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, 10884 SDValue &LHS, SDValue &RHS, 10885 SDValue &CC, SDValue Mask, 10886 SDValue EVL, bool &NeedInvert, 10887 const SDLoc &dl, SDValue &Chain, 10888 bool IsSignaling) const { 10889 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10890 MVT OpVT = LHS.getSimpleValueType(); 10891 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get(); 10892 NeedInvert = false; 10893 assert(!EVL == !Mask && "VP Mask and EVL must either both be set or unset"); 10894 bool IsNonVP = !EVL; 10895 switch (TLI.getCondCodeAction(CCCode, OpVT)) { 10896 default: 10897 llvm_unreachable("Unknown condition code action!"); 10898 case TargetLowering::Legal: 10899 // Nothing to do. 10900 break; 10901 case TargetLowering::Expand: { 10902 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode); 10903 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 10904 std::swap(LHS, RHS); 10905 CC = DAG.getCondCode(InvCC); 10906 return true; 10907 } 10908 // Swapping operands didn't work. Try inverting the condition. 10909 bool NeedSwap = false; 10910 InvCC = getSetCCInverse(CCCode, OpVT); 10911 if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 10912 // If inverting the condition is not enough, try swapping operands 10913 // on top of it. 10914 InvCC = ISD::getSetCCSwappedOperands(InvCC); 10915 NeedSwap = true; 10916 } 10917 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 10918 CC = DAG.getCondCode(InvCC); 10919 NeedInvert = true; 10920 if (NeedSwap) 10921 std::swap(LHS, RHS); 10922 return true; 10923 } 10924 10925 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID; 10926 unsigned Opc = 0; 10927 switch (CCCode) { 10928 default: 10929 llvm_unreachable("Don't know how to expand this condition!"); 10930 case ISD::SETUO: 10931 if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) { 10932 CC1 = ISD::SETUNE; 10933 CC2 = ISD::SETUNE; 10934 Opc = ISD::OR; 10935 break; 10936 } 10937 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 10938 "If SETUE is expanded, SETOEQ or SETUNE must be legal!"); 10939 NeedInvert = true; 10940 [[fallthrough]]; 10941 case ISD::SETO: 10942 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 10943 "If SETO is expanded, SETOEQ must be legal!"); 10944 CC1 = ISD::SETOEQ; 10945 CC2 = ISD::SETOEQ; 10946 Opc = ISD::AND; 10947 break; 10948 case ISD::SETONE: 10949 case ISD::SETUEQ: 10950 // If the SETUO or SETO CC isn't legal, we might be able to use 10951 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one 10952 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping 10953 // the operands. 10954 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 10955 if (!TLI.isCondCodeLegal(CC2, OpVT) && 10956 (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) || 10957 TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) { 10958 CC1 = ISD::SETOGT; 10959 CC2 = ISD::SETOLT; 10960 Opc = ISD::OR; 10961 NeedInvert = ((unsigned)CCCode & 0x8U); 10962 break; 10963 } 10964 [[fallthrough]]; 10965 case ISD::SETOEQ: 10966 case ISD::SETOGT: 10967 case ISD::SETOGE: 10968 case ISD::SETOLT: 10969 case ISD::SETOLE: 10970 case ISD::SETUNE: 10971 case ISD::SETUGT: 10972 case ISD::SETUGE: 10973 case ISD::SETULT: 10974 case ISD::SETULE: 10975 // If we are floating point, assign and break, otherwise fall through. 10976 if (!OpVT.isInteger()) { 10977 // We can use the 4th bit to tell if we are the unordered 10978 // or ordered version of the opcode. 10979 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 10980 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND; 10981 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10); 10982 break; 10983 } 10984 // Fallthrough if we are unsigned integer. 10985 [[fallthrough]]; 10986 case ISD::SETLE: 10987 case ISD::SETGT: 10988 case ISD::SETGE: 10989 case ISD::SETLT: 10990 case ISD::SETNE: 10991 case ISD::SETEQ: 10992 // If all combinations of inverting the condition and swapping operands 10993 // didn't work then we have no means to expand the condition. 10994 llvm_unreachable("Don't know how to expand this condition!"); 10995 } 10996 10997 SDValue SetCC1, SetCC2; 10998 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) { 10999 // If we aren't the ordered or unorder operation, 11000 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS). 11001 if (IsNonVP) { 11002 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling); 11003 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling); 11004 } else { 11005 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC1, Mask, EVL); 11006 SetCC2 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC2, Mask, EVL); 11007 } 11008 } else { 11009 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS) 11010 if (IsNonVP) { 11011 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling); 11012 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling); 11013 } else { 11014 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, LHS, CC1, Mask, EVL); 11015 SetCC2 = DAG.getSetCCVP(dl, VT, RHS, RHS, CC2, Mask, EVL); 11016 } 11017 } 11018 if (Chain) 11019 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1), 11020 SetCC2.getValue(1)); 11021 if (IsNonVP) 11022 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2); 11023 else { 11024 // Transform the binary opcode to the VP equivalent. 11025 assert((Opc == ISD::OR || Opc == ISD::AND) && "Unexpected opcode"); 11026 Opc = Opc == ISD::OR ? ISD::VP_OR : ISD::VP_AND; 11027 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2, Mask, EVL); 11028 } 11029 RHS = SDValue(); 11030 CC = SDValue(); 11031 return true; 11032 } 11033 } 11034 return false; 11035 } 11036