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/CodeGen/CallingConvLower.h" 16 #include "llvm/CodeGen/CodeGenCommonISel.h" 17 #include "llvm/CodeGen/MachineFrameInfo.h" 18 #include "llvm/CodeGen/MachineFunction.h" 19 #include "llvm/CodeGen/MachineJumpTableInfo.h" 20 #include "llvm/CodeGen/MachineRegisterInfo.h" 21 #include "llvm/CodeGen/SelectionDAG.h" 22 #include "llvm/CodeGen/TargetRegisterInfo.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/DerivedTypes.h" 25 #include "llvm/IR/GlobalVariable.h" 26 #include "llvm/IR/LLVMContext.h" 27 #include "llvm/MC/MCAsmInfo.h" 28 #include "llvm/MC/MCExpr.h" 29 #include "llvm/Support/DivisionByConstantInfo.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/KnownBits.h" 32 #include "llvm/Support/MathExtras.h" 33 #include "llvm/Target/TargetMachine.h" 34 #include <cctype> 35 using namespace llvm; 36 37 /// NOTE: The TargetMachine owns TLOF. 38 TargetLowering::TargetLowering(const TargetMachine &tm) 39 : TargetLoweringBase(tm) {} 40 41 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const { 42 return nullptr; 43 } 44 45 bool TargetLowering::isPositionIndependent() const { 46 return getTargetMachine().isPositionIndependent(); 47 } 48 49 /// Check whether a given call node is in tail position within its function. If 50 /// so, it sets Chain to the input chain of the tail call. 51 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node, 52 SDValue &Chain) const { 53 const Function &F = DAG.getMachineFunction().getFunction(); 54 55 // First, check if tail calls have been disabled in this function. 56 if (F.getFnAttribute("disable-tail-calls").getValueAsBool()) 57 return false; 58 59 // Conservatively require the attributes of the call to match those of 60 // the return. Ignore following attributes because they don't affect the 61 // call sequence. 62 AttrBuilder CallerAttrs(F.getContext(), F.getAttributes().getRetAttrs()); 63 for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable, 64 Attribute::DereferenceableOrNull, Attribute::NoAlias, 65 Attribute::NonNull, Attribute::NoUndef}) 66 CallerAttrs.removeAttribute(Attr); 67 68 if (CallerAttrs.hasAttributes()) 69 return false; 70 71 // It's not safe to eliminate the sign / zero extension of the return value. 72 if (CallerAttrs.contains(Attribute::ZExt) || 73 CallerAttrs.contains(Attribute::SExt)) 74 return false; 75 76 // Check if the only use is a function return node. 77 return isUsedByReturnOnly(Node, Chain); 78 } 79 80 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI, 81 const uint32_t *CallerPreservedMask, 82 const SmallVectorImpl<CCValAssign> &ArgLocs, 83 const SmallVectorImpl<SDValue> &OutVals) const { 84 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 85 const CCValAssign &ArgLoc = ArgLocs[I]; 86 if (!ArgLoc.isRegLoc()) 87 continue; 88 MCRegister Reg = ArgLoc.getLocReg(); 89 // Only look at callee saved registers. 90 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg)) 91 continue; 92 // Check that we pass the value used for the caller. 93 // (We look for a CopyFromReg reading a virtual register that is used 94 // for the function live-in value of register Reg) 95 SDValue Value = OutVals[I]; 96 if (Value->getOpcode() == ISD::AssertZext) 97 Value = Value.getOperand(0); 98 if (Value->getOpcode() != ISD::CopyFromReg) 99 return false; 100 Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg(); 101 if (MRI.getLiveInPhysReg(ArgReg) != Reg) 102 return false; 103 } 104 return true; 105 } 106 107 /// Set CallLoweringInfo attribute flags based on a call instruction 108 /// and called function attributes. 109 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call, 110 unsigned ArgIdx) { 111 IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt); 112 IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt); 113 IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg); 114 IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet); 115 IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest); 116 IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal); 117 IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated); 118 IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca); 119 IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned); 120 IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf); 121 IsSwiftAsync = Call->paramHasAttr(ArgIdx, Attribute::SwiftAsync); 122 IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError); 123 Alignment = Call->getParamStackAlign(ArgIdx); 124 IndirectType = nullptr; 125 assert(IsByVal + IsPreallocated + IsInAlloca + IsSRet <= 1 && 126 "multiple ABI attributes?"); 127 if (IsByVal) { 128 IndirectType = Call->getParamByValType(ArgIdx); 129 if (!Alignment) 130 Alignment = Call->getParamAlign(ArgIdx); 131 } 132 if (IsPreallocated) 133 IndirectType = Call->getParamPreallocatedType(ArgIdx); 134 if (IsInAlloca) 135 IndirectType = Call->getParamInAllocaType(ArgIdx); 136 if (IsSRet) 137 IndirectType = Call->getParamStructRetType(ArgIdx); 138 } 139 140 /// Generate a libcall taking the given operands as arguments and returning a 141 /// result of type RetVT. 142 std::pair<SDValue, SDValue> 143 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, 144 ArrayRef<SDValue> Ops, 145 MakeLibCallOptions CallOptions, 146 const SDLoc &dl, 147 SDValue InChain) const { 148 if (!InChain) 149 InChain = DAG.getEntryNode(); 150 151 TargetLowering::ArgListTy Args; 152 Args.reserve(Ops.size()); 153 154 TargetLowering::ArgListEntry Entry; 155 for (unsigned i = 0; i < Ops.size(); ++i) { 156 SDValue NewOp = Ops[i]; 157 Entry.Node = NewOp; 158 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 159 Entry.IsSExt = shouldSignExtendTypeInLibCall(NewOp.getValueType(), 160 CallOptions.IsSExt); 161 Entry.IsZExt = !Entry.IsSExt; 162 163 if (CallOptions.IsSoften && 164 !shouldExtendTypeInLibCall(CallOptions.OpsVTBeforeSoften[i])) { 165 Entry.IsSExt = Entry.IsZExt = false; 166 } 167 Args.push_back(Entry); 168 } 169 170 if (LC == RTLIB::UNKNOWN_LIBCALL) 171 report_fatal_error("Unsupported library call operation!"); 172 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 173 getPointerTy(DAG.getDataLayout())); 174 175 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 176 TargetLowering::CallLoweringInfo CLI(DAG); 177 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, CallOptions.IsSExt); 178 bool zeroExtend = !signExtend; 179 180 if (CallOptions.IsSoften && 181 !shouldExtendTypeInLibCall(CallOptions.RetVTBeforeSoften)) { 182 signExtend = zeroExtend = false; 183 } 184 185 CLI.setDebugLoc(dl) 186 .setChain(InChain) 187 .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 188 .setNoReturn(CallOptions.DoesNotReturn) 189 .setDiscardResult(!CallOptions.IsReturnValueUsed) 190 .setIsPostTypeLegalization(CallOptions.IsPostTypeLegalization) 191 .setSExtResult(signExtend) 192 .setZExtResult(zeroExtend); 193 return LowerCallTo(CLI); 194 } 195 196 bool TargetLowering::findOptimalMemOpLowering( 197 std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, 198 unsigned SrcAS, const AttributeList &FuncAttributes) const { 199 if (Limit != ~unsigned(0) && Op.isMemcpyWithFixedDstAlign() && 200 Op.getSrcAlign() < Op.getDstAlign()) 201 return false; 202 203 EVT VT = getOptimalMemOpType(Op, FuncAttributes); 204 205 if (VT == MVT::Other) { 206 // Use the largest integer type whose alignment constraints are satisfied. 207 // We only need to check DstAlign here as SrcAlign is always greater or 208 // equal to DstAlign (or zero). 209 VT = MVT::i64; 210 if (Op.isFixedDstAlign()) 211 while (Op.getDstAlign() < (VT.getSizeInBits() / 8) && 212 !allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign())) 213 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1); 214 assert(VT.isInteger()); 215 216 // Find the largest legal integer type. 217 MVT LVT = MVT::i64; 218 while (!isTypeLegal(LVT)) 219 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1); 220 assert(LVT.isInteger()); 221 222 // If the type we've chosen is larger than the largest legal integer type 223 // then use that instead. 224 if (VT.bitsGT(LVT)) 225 VT = LVT; 226 } 227 228 unsigned NumMemOps = 0; 229 uint64_t Size = Op.size(); 230 while (Size) { 231 unsigned VTSize = VT.getSizeInBits() / 8; 232 while (VTSize > Size) { 233 // For now, only use non-vector load / store's for the left-over pieces. 234 EVT NewVT = VT; 235 unsigned NewVTSize; 236 237 bool Found = false; 238 if (VT.isVector() || VT.isFloatingPoint()) { 239 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32; 240 if (isOperationLegalOrCustom(ISD::STORE, NewVT) && 241 isSafeMemOpType(NewVT.getSimpleVT())) 242 Found = true; 243 else if (NewVT == MVT::i64 && 244 isOperationLegalOrCustom(ISD::STORE, MVT::f64) && 245 isSafeMemOpType(MVT::f64)) { 246 // i64 is usually not legal on 32-bit targets, but f64 may be. 247 NewVT = MVT::f64; 248 Found = true; 249 } 250 } 251 252 if (!Found) { 253 do { 254 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1); 255 if (NewVT == MVT::i8) 256 break; 257 } while (!isSafeMemOpType(NewVT.getSimpleVT())); 258 } 259 NewVTSize = NewVT.getSizeInBits() / 8; 260 261 // If the new VT cannot cover all of the remaining bits, then consider 262 // issuing a (or a pair of) unaligned and overlapping load / store. 263 bool Fast; 264 if (NumMemOps && Op.allowOverlap() && NewVTSize < Size && 265 allowsMisalignedMemoryAccesses( 266 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1), 267 MachineMemOperand::MONone, &Fast) && 268 Fast) 269 VTSize = Size; 270 else { 271 VT = NewVT; 272 VTSize = NewVTSize; 273 } 274 } 275 276 if (++NumMemOps > Limit) 277 return false; 278 279 MemOps.push_back(VT); 280 Size -= VTSize; 281 } 282 283 return true; 284 } 285 286 /// Soften the operands of a comparison. This code is shared among BR_CC, 287 /// SELECT_CC, and SETCC handlers. 288 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 289 SDValue &NewLHS, SDValue &NewRHS, 290 ISD::CondCode &CCCode, 291 const SDLoc &dl, const SDValue OldLHS, 292 const SDValue OldRHS) const { 293 SDValue Chain; 294 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS, 295 OldRHS, Chain); 296 } 297 298 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 299 SDValue &NewLHS, SDValue &NewRHS, 300 ISD::CondCode &CCCode, 301 const SDLoc &dl, const SDValue OldLHS, 302 const SDValue OldRHS, 303 SDValue &Chain, 304 bool IsSignaling) const { 305 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc 306 // not supporting it. We can update this code when libgcc provides such 307 // functions. 308 309 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128) 310 && "Unsupported setcc type!"); 311 312 // Expand into one or more soft-fp libcall(s). 313 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL; 314 bool ShouldInvertCC = false; 315 switch (CCCode) { 316 case ISD::SETEQ: 317 case ISD::SETOEQ: 318 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 319 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 320 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 321 break; 322 case ISD::SETNE: 323 case ISD::SETUNE: 324 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : 325 (VT == MVT::f64) ? RTLIB::UNE_F64 : 326 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128; 327 break; 328 case ISD::SETGE: 329 case ISD::SETOGE: 330 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 331 (VT == MVT::f64) ? RTLIB::OGE_F64 : 332 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 333 break; 334 case ISD::SETLT: 335 case ISD::SETOLT: 336 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 337 (VT == MVT::f64) ? RTLIB::OLT_F64 : 338 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 339 break; 340 case ISD::SETLE: 341 case ISD::SETOLE: 342 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 343 (VT == MVT::f64) ? RTLIB::OLE_F64 : 344 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 345 break; 346 case ISD::SETGT: 347 case ISD::SETOGT: 348 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 349 (VT == MVT::f64) ? RTLIB::OGT_F64 : 350 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 351 break; 352 case ISD::SETO: 353 ShouldInvertCC = true; 354 LLVM_FALLTHROUGH; 355 case ISD::SETUO: 356 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 357 (VT == MVT::f64) ? RTLIB::UO_F64 : 358 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 359 break; 360 case ISD::SETONE: 361 // SETONE = O && UNE 362 ShouldInvertCC = true; 363 LLVM_FALLTHROUGH; 364 case ISD::SETUEQ: 365 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 366 (VT == MVT::f64) ? RTLIB::UO_F64 : 367 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 368 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 369 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 370 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 371 break; 372 default: 373 // Invert CC for unordered comparisons 374 ShouldInvertCC = true; 375 switch (CCCode) { 376 case ISD::SETULT: 377 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 378 (VT == MVT::f64) ? RTLIB::OGE_F64 : 379 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 380 break; 381 case ISD::SETULE: 382 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 383 (VT == MVT::f64) ? RTLIB::OGT_F64 : 384 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 385 break; 386 case ISD::SETUGT: 387 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 388 (VT == MVT::f64) ? RTLIB::OLE_F64 : 389 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 390 break; 391 case ISD::SETUGE: 392 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 393 (VT == MVT::f64) ? RTLIB::OLT_F64 : 394 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 395 break; 396 default: llvm_unreachable("Do not know how to soften this setcc!"); 397 } 398 } 399 400 // Use the target specific return value for comparions lib calls. 401 EVT RetVT = getCmpLibcallReturnType(); 402 SDValue Ops[2] = {NewLHS, NewRHS}; 403 TargetLowering::MakeLibCallOptions CallOptions; 404 EVT OpsVT[2] = { OldLHS.getValueType(), 405 OldRHS.getValueType() }; 406 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT, true); 407 auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain); 408 NewLHS = Call.first; 409 NewRHS = DAG.getConstant(0, dl, RetVT); 410 411 CCCode = getCmpLibcallCC(LC1); 412 if (ShouldInvertCC) { 413 assert(RetVT.isInteger()); 414 CCCode = getSetCCInverse(CCCode, RetVT); 415 } 416 417 if (LC2 == RTLIB::UNKNOWN_LIBCALL) { 418 // Update Chain. 419 Chain = Call.second; 420 } else { 421 EVT SetCCVT = 422 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT); 423 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode); 424 auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain); 425 CCCode = getCmpLibcallCC(LC2); 426 if (ShouldInvertCC) 427 CCCode = getSetCCInverse(CCCode, RetVT); 428 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode); 429 if (Chain) 430 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second, 431 Call2.second); 432 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl, 433 Tmp.getValueType(), Tmp, NewLHS); 434 NewRHS = SDValue(); 435 } 436 } 437 438 /// Return the entry encoding for a jump table in the current function. The 439 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum. 440 unsigned TargetLowering::getJumpTableEncoding() const { 441 // In non-pic modes, just use the address of a block. 442 if (!isPositionIndependent()) 443 return MachineJumpTableInfo::EK_BlockAddress; 444 445 // In PIC mode, if the target supports a GPRel32 directive, use it. 446 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr) 447 return MachineJumpTableInfo::EK_GPRel32BlockAddress; 448 449 // Otherwise, use a label difference. 450 return MachineJumpTableInfo::EK_LabelDifference32; 451 } 452 453 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table, 454 SelectionDAG &DAG) const { 455 // If our PIC model is GP relative, use the global offset table as the base. 456 unsigned JTEncoding = getJumpTableEncoding(); 457 458 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) || 459 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress)) 460 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout())); 461 462 return Table; 463 } 464 465 /// This returns the relocation base for the given PIC jumptable, the same as 466 /// getPICJumpTableRelocBase, but as an MCExpr. 467 const MCExpr * 468 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 469 unsigned JTI,MCContext &Ctx) const{ 470 // The normal PIC reloc base is the label at the start of the jump table. 471 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx); 472 } 473 474 bool 475 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 476 const TargetMachine &TM = getTargetMachine(); 477 const GlobalValue *GV = GA->getGlobal(); 478 479 // If the address is not even local to this DSO we will have to load it from 480 // a got and then add the offset. 481 if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 482 return false; 483 484 // If the code is position independent we will have to add a base register. 485 if (isPositionIndependent()) 486 return false; 487 488 // Otherwise we can do it. 489 return true; 490 } 491 492 //===----------------------------------------------------------------------===// 493 // Optimization Methods 494 //===----------------------------------------------------------------------===// 495 496 /// If the specified instruction has a constant integer operand and there are 497 /// bits set in that constant that are not demanded, then clear those bits and 498 /// return true. 499 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 500 const APInt &DemandedBits, 501 const APInt &DemandedElts, 502 TargetLoweringOpt &TLO) const { 503 SDLoc DL(Op); 504 unsigned Opcode = Op.getOpcode(); 505 506 // Do target-specific constant optimization. 507 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 508 return TLO.New.getNode(); 509 510 // FIXME: ISD::SELECT, ISD::SELECT_CC 511 switch (Opcode) { 512 default: 513 break; 514 case ISD::XOR: 515 case ISD::AND: 516 case ISD::OR: { 517 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 518 if (!Op1C || Op1C->isOpaque()) 519 return false; 520 521 // If this is a 'not' op, don't touch it because that's a canonical form. 522 const APInt &C = Op1C->getAPIntValue(); 523 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C)) 524 return false; 525 526 if (!C.isSubsetOf(DemandedBits)) { 527 EVT VT = Op.getValueType(); 528 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT); 529 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC); 530 return TLO.CombineTo(Op, NewOp); 531 } 532 533 break; 534 } 535 } 536 537 return false; 538 } 539 540 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 541 const APInt &DemandedBits, 542 TargetLoweringOpt &TLO) const { 543 EVT VT = Op.getValueType(); 544 APInt DemandedElts = VT.isVector() 545 ? APInt::getAllOnes(VT.getVectorNumElements()) 546 : APInt(1, 1); 547 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO); 548 } 549 550 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. 551 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be 552 /// generalized for targets with other types of implicit widening casts. 553 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth, 554 const APInt &Demanded, 555 TargetLoweringOpt &TLO) const { 556 assert(Op.getNumOperands() == 2 && 557 "ShrinkDemandedOp only supports binary operators!"); 558 assert(Op.getNode()->getNumValues() == 1 && 559 "ShrinkDemandedOp only supports nodes with one result!"); 560 561 SelectionDAG &DAG = TLO.DAG; 562 SDLoc dl(Op); 563 564 // Early return, as this function cannot handle vector types. 565 if (Op.getValueType().isVector()) 566 return false; 567 568 // Don't do this if the node has another user, which may require the 569 // full value. 570 if (!Op.getNode()->hasOneUse()) 571 return false; 572 573 // Search for the smallest integer type with free casts to and from 574 // Op's type. For expedience, just check power-of-2 integer types. 575 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 576 unsigned DemandedSize = Demanded.getActiveBits(); 577 unsigned SmallVTBits = DemandedSize; 578 if (!isPowerOf2_32(SmallVTBits)) 579 SmallVTBits = NextPowerOf2(SmallVTBits); 580 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) { 581 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits); 582 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) && 583 TLI.isZExtFree(SmallVT, Op.getValueType())) { 584 // We found a type with free casts. 585 SDValue X = DAG.getNode( 586 Op.getOpcode(), dl, SmallVT, 587 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)), 588 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1))); 589 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?"); 590 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X); 591 return TLO.CombineTo(Op, Z); 592 } 593 } 594 return false; 595 } 596 597 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 598 DAGCombinerInfo &DCI) const { 599 SelectionDAG &DAG = DCI.DAG; 600 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 601 !DCI.isBeforeLegalizeOps()); 602 KnownBits Known; 603 604 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO); 605 if (Simplified) { 606 DCI.AddToWorklist(Op.getNode()); 607 DCI.CommitTargetLoweringOpt(TLO); 608 } 609 return Simplified; 610 } 611 612 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 613 const APInt &DemandedElts, 614 DAGCombinerInfo &DCI) const { 615 SelectionDAG &DAG = DCI.DAG; 616 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 617 !DCI.isBeforeLegalizeOps()); 618 KnownBits Known; 619 620 bool Simplified = 621 SimplifyDemandedBits(Op, DemandedBits, DemandedElts, 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 KnownBits &Known, 631 TargetLoweringOpt &TLO, 632 unsigned Depth, 633 bool AssumeSingleUse) const { 634 EVT VT = Op.getValueType(); 635 636 // TODO: We can probably do more work on calculating the known bits and 637 // simplifying the operations for scalable vectors, but for now we just 638 // bail out. 639 if (VT.isScalableVector()) { 640 // Pretend we don't know anything for now. 641 Known = KnownBits(DemandedBits.getBitWidth()); 642 return false; 643 } 644 645 APInt DemandedElts = VT.isVector() 646 ? APInt::getAllOnes(VT.getVectorNumElements()) 647 : APInt(1, 1); 648 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth, 649 AssumeSingleUse); 650 } 651 652 // TODO: Can we merge SelectionDAG::GetDemandedBits into this? 653 // TODO: Under what circumstances can we create nodes? Constant folding? 654 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 655 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 656 SelectionDAG &DAG, unsigned Depth) const { 657 // Limit search depth. 658 if (Depth >= SelectionDAG::MaxRecursionDepth) 659 return SDValue(); 660 661 // Ignore UNDEFs. 662 if (Op.isUndef()) 663 return SDValue(); 664 665 // Not demanding any bits/elts from Op. 666 if (DemandedBits == 0 || DemandedElts == 0) 667 return DAG.getUNDEF(Op.getValueType()); 668 669 bool IsLE = DAG.getDataLayout().isLittleEndian(); 670 unsigned NumElts = DemandedElts.getBitWidth(); 671 unsigned BitWidth = DemandedBits.getBitWidth(); 672 KnownBits LHSKnown, RHSKnown; 673 switch (Op.getOpcode()) { 674 case ISD::BITCAST: { 675 SDValue Src = peekThroughBitcasts(Op.getOperand(0)); 676 EVT SrcVT = Src.getValueType(); 677 EVT DstVT = Op.getValueType(); 678 if (SrcVT == DstVT) 679 return Src; 680 681 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 682 unsigned NumDstEltBits = DstVT.getScalarSizeInBits(); 683 if (NumSrcEltBits == NumDstEltBits) 684 if (SDValue V = SimplifyMultipleUseDemandedBits( 685 Src, DemandedBits, DemandedElts, DAG, Depth + 1)) 686 return DAG.getBitcast(DstVT, V); 687 688 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) { 689 unsigned Scale = NumDstEltBits / NumSrcEltBits; 690 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 691 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 692 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 693 for (unsigned i = 0; i != Scale; ++i) { 694 unsigned EltOffset = IsLE ? i : (Scale - 1 - i); 695 unsigned BitOffset = EltOffset * NumSrcEltBits; 696 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset); 697 if (!Sub.isZero()) { 698 DemandedSrcBits |= Sub; 699 for (unsigned j = 0; j != NumElts; ++j) 700 if (DemandedElts[j]) 701 DemandedSrcElts.setBit((j * Scale) + i); 702 } 703 } 704 705 if (SDValue V = SimplifyMultipleUseDemandedBits( 706 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 707 return DAG.getBitcast(DstVT, V); 708 } 709 710 // TODO - bigendian once we have test coverage. 711 if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) { 712 unsigned Scale = NumSrcEltBits / NumDstEltBits; 713 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 714 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 715 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 716 for (unsigned i = 0; i != NumElts; ++i) 717 if (DemandedElts[i]) { 718 unsigned Offset = (i % Scale) * NumDstEltBits; 719 DemandedSrcBits.insertBits(DemandedBits, Offset); 720 DemandedSrcElts.setBit(i / Scale); 721 } 722 723 if (SDValue V = SimplifyMultipleUseDemandedBits( 724 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 725 return DAG.getBitcast(DstVT, V); 726 } 727 728 break; 729 } 730 case ISD::AND: { 731 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 732 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 733 734 // If all of the demanded bits are known 1 on one side, return the other. 735 // These bits cannot contribute to the result of the 'and' in this 736 // context. 737 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) 738 return Op.getOperand(0); 739 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One)) 740 return Op.getOperand(1); 741 break; 742 } 743 case ISD::OR: { 744 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 745 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 746 747 // If all of the demanded bits are known zero on one side, return the 748 // other. These bits cannot contribute to the result of the 'or' in this 749 // context. 750 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero)) 751 return Op.getOperand(0); 752 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero)) 753 return Op.getOperand(1); 754 break; 755 } 756 case ISD::XOR: { 757 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 758 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 759 760 // If all of the demanded bits are known zero on one side, return the 761 // other. 762 if (DemandedBits.isSubsetOf(RHSKnown.Zero)) 763 return Op.getOperand(0); 764 if (DemandedBits.isSubsetOf(LHSKnown.Zero)) 765 return Op.getOperand(1); 766 break; 767 } 768 case ISD::SHL: { 769 // If we are only demanding sign bits then we can use the shift source 770 // directly. 771 if (const APInt *MaxSA = 772 DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 773 SDValue Op0 = Op.getOperand(0); 774 unsigned ShAmt = MaxSA->getZExtValue(); 775 unsigned NumSignBits = 776 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 777 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 778 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 779 return Op0; 780 } 781 break; 782 } 783 case ISD::SETCC: { 784 SDValue Op0 = Op.getOperand(0); 785 SDValue Op1 = Op.getOperand(1); 786 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 787 // If (1) we only need the sign-bit, (2) the setcc operands are the same 788 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 789 // -1, we may be able to bypass the setcc. 790 if (DemandedBits.isSignMask() && 791 Op0.getScalarValueSizeInBits() == BitWidth && 792 getBooleanContents(Op0.getValueType()) == 793 BooleanContent::ZeroOrNegativeOneBooleanContent) { 794 // If we're testing X < 0, then this compare isn't needed - just use X! 795 // FIXME: We're limiting to integer types here, but this should also work 796 // if we don't care about FP signed-zero. The use of SETLT with FP means 797 // that we don't care about NaNs. 798 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 799 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 800 return Op0; 801 } 802 break; 803 } 804 case ISD::SIGN_EXTEND_INREG: { 805 // If none of the extended bits are demanded, eliminate the sextinreg. 806 SDValue Op0 = Op.getOperand(0); 807 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 808 unsigned ExBits = ExVT.getScalarSizeInBits(); 809 if (DemandedBits.getActiveBits() <= ExBits) 810 return Op0; 811 // If the input is already sign extended, just drop the extension. 812 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 813 if (NumSignBits >= (BitWidth - ExBits + 1)) 814 return Op0; 815 break; 816 } 817 case ISD::ANY_EXTEND_VECTOR_INREG: 818 case ISD::SIGN_EXTEND_VECTOR_INREG: 819 case ISD::ZERO_EXTEND_VECTOR_INREG: { 820 // If we only want the lowest element and none of extended bits, then we can 821 // return the bitcasted source vector. 822 SDValue Src = Op.getOperand(0); 823 EVT SrcVT = Src.getValueType(); 824 EVT DstVT = Op.getValueType(); 825 if (IsLE && DemandedElts == 1 && 826 DstVT.getSizeInBits() == SrcVT.getSizeInBits() && 827 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) { 828 return DAG.getBitcast(DstVT, Src); 829 } 830 break; 831 } 832 case ISD::INSERT_VECTOR_ELT: { 833 // If we don't demand the inserted element, return the base vector. 834 SDValue Vec = Op.getOperand(0); 835 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 836 EVT VecVT = Vec.getValueType(); 837 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) && 838 !DemandedElts[CIdx->getZExtValue()]) 839 return Vec; 840 break; 841 } 842 case ISD::INSERT_SUBVECTOR: { 843 SDValue Vec = Op.getOperand(0); 844 SDValue Sub = Op.getOperand(1); 845 uint64_t Idx = Op.getConstantOperandVal(2); 846 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 847 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 848 // If we don't demand the inserted subvector, return the base vector. 849 if (DemandedSubElts == 0) 850 return Vec; 851 // If this simply widens the lowest subvector, see if we can do it earlier. 852 if (Idx == 0 && Vec.isUndef()) { 853 if (SDValue NewSub = SimplifyMultipleUseDemandedBits( 854 Sub, DemandedBits, DemandedSubElts, DAG, Depth + 1)) 855 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 856 Op.getOperand(0), NewSub, Op.getOperand(2)); 857 } 858 break; 859 } 860 case ISD::VECTOR_SHUFFLE: { 861 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 862 863 // If all the demanded elts are from one operand and are inline, 864 // then we can use the operand directly. 865 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true; 866 for (unsigned i = 0; i != NumElts; ++i) { 867 int M = ShuffleMask[i]; 868 if (M < 0 || !DemandedElts[i]) 869 continue; 870 AllUndef = false; 871 IdentityLHS &= (M == (int)i); 872 IdentityRHS &= ((M - NumElts) == i); 873 } 874 875 if (AllUndef) 876 return DAG.getUNDEF(Op.getValueType()); 877 if (IdentityLHS) 878 return Op.getOperand(0); 879 if (IdentityRHS) 880 return Op.getOperand(1); 881 break; 882 } 883 default: 884 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) 885 if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode( 886 Op, DemandedBits, DemandedElts, DAG, Depth)) 887 return V; 888 break; 889 } 890 return SDValue(); 891 } 892 893 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 894 SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG, 895 unsigned Depth) const { 896 EVT VT = Op.getValueType(); 897 APInt DemandedElts = VT.isVector() 898 ? APInt::getAllOnes(VT.getVectorNumElements()) 899 : APInt(1, 1); 900 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 901 Depth); 902 } 903 904 SDValue TargetLowering::SimplifyMultipleUseDemandedVectorElts( 905 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG, 906 unsigned Depth) const { 907 APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits()); 908 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 909 Depth); 910 } 911 912 // Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1). 913 // or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1). 914 static SDValue combineShiftToAVG(SDValue Op, SelectionDAG &DAG, 915 const TargetLowering &TLI, 916 const APInt &DemandedBits, 917 const APInt &DemandedElts, 918 unsigned Depth) { 919 assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) && 920 "SRL or SRA node is required here!"); 921 // Is the right shift using an immediate value of 1? 922 ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts); 923 if (!N1C || !N1C->isOne()) 924 return SDValue(); 925 926 // We are looking for an avgfloor 927 // add(ext, ext) 928 // or one of these as a avgceil 929 // add(add(ext, ext), 1) 930 // add(add(ext, 1), ext) 931 // add(ext, add(ext, 1)) 932 SDValue Add = Op.getOperand(0); 933 if (Add.getOpcode() != ISD::ADD) 934 return SDValue(); 935 936 SDValue ExtOpA = Add.getOperand(0); 937 SDValue ExtOpB = Add.getOperand(1); 938 auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3) { 939 ConstantSDNode *ConstOp; 940 if ((ConstOp = isConstOrConstSplat(Op1, DemandedElts)) && 941 ConstOp->isOne()) { 942 ExtOpA = Op2; 943 ExtOpB = Op3; 944 return true; 945 } 946 if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) && 947 ConstOp->isOne()) { 948 ExtOpA = Op1; 949 ExtOpB = Op3; 950 return true; 951 } 952 if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) && 953 ConstOp->isOne()) { 954 ExtOpA = Op1; 955 ExtOpB = Op2; 956 return true; 957 } 958 return false; 959 }; 960 bool IsCeil = 961 (ExtOpA.getOpcode() == ISD::ADD && 962 MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB)) || 963 (ExtOpB.getOpcode() == ISD::ADD && 964 MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA)); 965 966 // If the shift is signed (sra): 967 // - Needs >= 2 sign bit for both operands. 968 // - Needs >= 2 zero bits. 969 // If the shift is unsigned (srl): 970 // - Needs >= 1 zero bit for both operands. 971 // - Needs 1 demanded bit zero and >= 2 sign bits. 972 unsigned ShiftOpc = Op.getOpcode(); 973 bool IsSigned = false; 974 unsigned KnownBits; 975 unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth); 976 unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth); 977 unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1; 978 unsigned NumZeroA = 979 DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros(); 980 unsigned NumZeroB = 981 DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros(); 982 unsigned NumZero = std::min(NumZeroA, NumZeroB); 983 984 switch (ShiftOpc) { 985 default: 986 llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG"); 987 case ISD::SRA: { 988 if (NumZero >= 2 && NumSigned < NumZero) { 989 IsSigned = false; 990 KnownBits = NumZero; 991 break; 992 } 993 if (NumSigned >= 1) { 994 IsSigned = true; 995 KnownBits = NumSigned; 996 break; 997 } 998 return SDValue(); 999 } 1000 case ISD::SRL: { 1001 if (NumZero >= 1 && NumSigned < NumZero) { 1002 IsSigned = false; 1003 KnownBits = NumZero; 1004 break; 1005 } 1006 if (NumSigned >= 1 && DemandedBits.isSignBitClear()) { 1007 IsSigned = true; 1008 KnownBits = NumSigned; 1009 break; 1010 } 1011 return SDValue(); 1012 } 1013 } 1014 1015 unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU) 1016 : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU); 1017 1018 // Find the smallest power-2 type that is legal for this vector size and 1019 // operation, given the original type size and the number of known sign/zero 1020 // bits. 1021 EVT VT = Op.getValueType(); 1022 unsigned MinWidth = 1023 std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8); 1024 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), PowerOf2Ceil(MinWidth)); 1025 if (VT.isVector()) 1026 NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount()); 1027 if (!TLI.isOperationLegalOrCustom(AVGOpc, NVT)) 1028 return SDValue(); 1029 1030 SDLoc DL(Op); 1031 SDValue ResultAVG = 1032 DAG.getNode(AVGOpc, DL, NVT, DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpA), 1033 DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpB)); 1034 return DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, VT, 1035 ResultAVG); 1036 } 1037 1038 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the 1039 /// result of Op are ever used downstream. If we can use this information to 1040 /// simplify Op, create a new simplified DAG node and return true, returning the 1041 /// original and new nodes in Old and New. Otherwise, analyze the expression and 1042 /// return a mask of Known bits for the expression (used to simplify the 1043 /// caller). The Known bits may only be accurate for those bits in the 1044 /// OriginalDemandedBits and OriginalDemandedElts. 1045 bool TargetLowering::SimplifyDemandedBits( 1046 SDValue Op, const APInt &OriginalDemandedBits, 1047 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 1048 unsigned Depth, bool AssumeSingleUse) const { 1049 unsigned BitWidth = OriginalDemandedBits.getBitWidth(); 1050 assert(Op.getScalarValueSizeInBits() == BitWidth && 1051 "Mask size mismatches value type size!"); 1052 1053 // Don't know anything. 1054 Known = KnownBits(BitWidth); 1055 1056 // TODO: We can probably do more work on calculating the known bits and 1057 // simplifying the operations for scalable vectors, but for now we just 1058 // bail out. 1059 if (Op.getValueType().isScalableVector()) 1060 return false; 1061 1062 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 1063 unsigned NumElts = OriginalDemandedElts.getBitWidth(); 1064 assert((!Op.getValueType().isVector() || 1065 NumElts == Op.getValueType().getVectorNumElements()) && 1066 "Unexpected vector size"); 1067 1068 APInt DemandedBits = OriginalDemandedBits; 1069 APInt DemandedElts = OriginalDemandedElts; 1070 SDLoc dl(Op); 1071 auto &DL = TLO.DAG.getDataLayout(); 1072 1073 // Undef operand. 1074 if (Op.isUndef()) 1075 return false; 1076 1077 if (Op.getOpcode() == ISD::Constant) { 1078 // We know all of the bits for a constant! 1079 Known = KnownBits::makeConstant(cast<ConstantSDNode>(Op)->getAPIntValue()); 1080 return false; 1081 } 1082 1083 if (Op.getOpcode() == ISD::ConstantFP) { 1084 // We know all of the bits for a floating point constant! 1085 Known = KnownBits::makeConstant( 1086 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()); 1087 return false; 1088 } 1089 1090 // Other users may use these bits. 1091 EVT VT = Op.getValueType(); 1092 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) { 1093 if (Depth != 0) { 1094 // If not at the root, Just compute the Known bits to 1095 // simplify things downstream. 1096 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1097 return false; 1098 } 1099 // If this is the root being simplified, allow it to have multiple uses, 1100 // just set the DemandedBits/Elts to all bits. 1101 DemandedBits = APInt::getAllOnes(BitWidth); 1102 DemandedElts = APInt::getAllOnes(NumElts); 1103 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) { 1104 // Not demanding any bits/elts from Op. 1105 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1106 } else if (Depth >= SelectionDAG::MaxRecursionDepth) { 1107 // Limit search depth. 1108 return false; 1109 } 1110 1111 KnownBits Known2; 1112 switch (Op.getOpcode()) { 1113 case ISD::TargetConstant: 1114 llvm_unreachable("Can't simplify this node"); 1115 case ISD::SCALAR_TO_VECTOR: { 1116 if (!DemandedElts[0]) 1117 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1118 1119 KnownBits SrcKnown; 1120 SDValue Src = Op.getOperand(0); 1121 unsigned SrcBitWidth = Src.getScalarValueSizeInBits(); 1122 APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth); 1123 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1)) 1124 return true; 1125 1126 // Upper elements are undef, so only get the knownbits if we just demand 1127 // the bottom element. 1128 if (DemandedElts == 1) 1129 Known = SrcKnown.anyextOrTrunc(BitWidth); 1130 break; 1131 } 1132 case ISD::BUILD_VECTOR: 1133 // Collect the known bits that are shared by every demanded element. 1134 // TODO: Call SimplifyDemandedBits for non-constant demanded elements. 1135 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1136 return false; // Don't fall through, will infinitely loop. 1137 case ISD::LOAD: { 1138 auto *LD = cast<LoadSDNode>(Op); 1139 if (getTargetConstantFromLoad(LD)) { 1140 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1141 return false; // Don't fall through, will infinitely loop. 1142 } 1143 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 1144 // If this is a ZEXTLoad and we are looking at the loaded value. 1145 EVT MemVT = LD->getMemoryVT(); 1146 unsigned MemBits = MemVT.getScalarSizeInBits(); 1147 Known.Zero.setBitsFrom(MemBits); 1148 return false; // Don't fall through, will infinitely loop. 1149 } 1150 break; 1151 } 1152 case ISD::INSERT_VECTOR_ELT: { 1153 SDValue Vec = Op.getOperand(0); 1154 SDValue Scl = Op.getOperand(1); 1155 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 1156 EVT VecVT = Vec.getValueType(); 1157 1158 // If index isn't constant, assume we need all vector elements AND the 1159 // inserted element. 1160 APInt DemandedVecElts(DemandedElts); 1161 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) { 1162 unsigned Idx = CIdx->getZExtValue(); 1163 DemandedVecElts.clearBit(Idx); 1164 1165 // Inserted element is not required. 1166 if (!DemandedElts[Idx]) 1167 return TLO.CombineTo(Op, Vec); 1168 } 1169 1170 KnownBits KnownScl; 1171 unsigned NumSclBits = Scl.getScalarValueSizeInBits(); 1172 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits); 1173 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1)) 1174 return true; 1175 1176 Known = KnownScl.anyextOrTrunc(BitWidth); 1177 1178 KnownBits KnownVec; 1179 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO, 1180 Depth + 1)) 1181 return true; 1182 1183 if (!!DemandedVecElts) 1184 Known = KnownBits::commonBits(Known, KnownVec); 1185 1186 return false; 1187 } 1188 case ISD::INSERT_SUBVECTOR: { 1189 // Demand any elements from the subvector and the remainder from the src its 1190 // inserted into. 1191 SDValue Src = Op.getOperand(0); 1192 SDValue Sub = Op.getOperand(1); 1193 uint64_t Idx = Op.getConstantOperandVal(2); 1194 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 1195 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 1196 APInt DemandedSrcElts = DemandedElts; 1197 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 1198 1199 KnownBits KnownSub, KnownSrc; 1200 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO, 1201 Depth + 1)) 1202 return true; 1203 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO, 1204 Depth + 1)) 1205 return true; 1206 1207 Known.Zero.setAllBits(); 1208 Known.One.setAllBits(); 1209 if (!!DemandedSubElts) 1210 Known = KnownBits::commonBits(Known, KnownSub); 1211 if (!!DemandedSrcElts) 1212 Known = KnownBits::commonBits(Known, KnownSrc); 1213 1214 // Attempt to avoid multi-use src if we don't need anything from it. 1215 if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() || 1216 !DemandedSrcElts.isAllOnes()) { 1217 SDValue NewSub = SimplifyMultipleUseDemandedBits( 1218 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1); 1219 SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1220 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1221 if (NewSub || NewSrc) { 1222 NewSub = NewSub ? NewSub : Sub; 1223 NewSrc = NewSrc ? NewSrc : Src; 1224 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub, 1225 Op.getOperand(2)); 1226 return TLO.CombineTo(Op, NewOp); 1227 } 1228 } 1229 break; 1230 } 1231 case ISD::EXTRACT_SUBVECTOR: { 1232 // Offset the demanded elts by the subvector index. 1233 SDValue Src = Op.getOperand(0); 1234 if (Src.getValueType().isScalableVector()) 1235 break; 1236 uint64_t Idx = Op.getConstantOperandVal(1); 1237 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 1238 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 1239 1240 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO, 1241 Depth + 1)) 1242 return true; 1243 1244 // Attempt to avoid multi-use src if we don't need anything from it. 1245 if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 1246 SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 1247 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1248 if (DemandedSrc) { 1249 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, 1250 Op.getOperand(1)); 1251 return TLO.CombineTo(Op, NewOp); 1252 } 1253 } 1254 break; 1255 } 1256 case ISD::CONCAT_VECTORS: { 1257 Known.Zero.setAllBits(); 1258 Known.One.setAllBits(); 1259 EVT SubVT = Op.getOperand(0).getValueType(); 1260 unsigned NumSubVecs = Op.getNumOperands(); 1261 unsigned NumSubElts = SubVT.getVectorNumElements(); 1262 for (unsigned i = 0; i != NumSubVecs; ++i) { 1263 APInt DemandedSubElts = 1264 DemandedElts.extractBits(NumSubElts, i * NumSubElts); 1265 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts, 1266 Known2, TLO, Depth + 1)) 1267 return true; 1268 // Known bits are shared by every demanded subvector element. 1269 if (!!DemandedSubElts) 1270 Known = KnownBits::commonBits(Known, Known2); 1271 } 1272 break; 1273 } 1274 case ISD::VECTOR_SHUFFLE: { 1275 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 1276 1277 // Collect demanded elements from shuffle operands.. 1278 APInt DemandedLHS(NumElts, 0); 1279 APInt DemandedRHS(NumElts, 0); 1280 for (unsigned i = 0; i != NumElts; ++i) { 1281 if (!DemandedElts[i]) 1282 continue; 1283 int M = ShuffleMask[i]; 1284 if (M < 0) { 1285 // For UNDEF elements, we don't know anything about the common state of 1286 // the shuffle result. 1287 DemandedLHS.clearAllBits(); 1288 DemandedRHS.clearAllBits(); 1289 break; 1290 } 1291 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 1292 if (M < (int)NumElts) 1293 DemandedLHS.setBit(M); 1294 else 1295 DemandedRHS.setBit(M - NumElts); 1296 } 1297 1298 if (!!DemandedLHS || !!DemandedRHS) { 1299 SDValue Op0 = Op.getOperand(0); 1300 SDValue Op1 = Op.getOperand(1); 1301 1302 Known.Zero.setAllBits(); 1303 Known.One.setAllBits(); 1304 if (!!DemandedLHS) { 1305 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO, 1306 Depth + 1)) 1307 return true; 1308 Known = KnownBits::commonBits(Known, Known2); 1309 } 1310 if (!!DemandedRHS) { 1311 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO, 1312 Depth + 1)) 1313 return true; 1314 Known = KnownBits::commonBits(Known, Known2); 1315 } 1316 1317 // Attempt to avoid multi-use ops if we don't need anything from them. 1318 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1319 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1); 1320 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1321 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1); 1322 if (DemandedOp0 || DemandedOp1) { 1323 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1324 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1325 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask); 1326 return TLO.CombineTo(Op, NewOp); 1327 } 1328 } 1329 break; 1330 } 1331 case ISD::AND: { 1332 SDValue Op0 = Op.getOperand(0); 1333 SDValue Op1 = Op.getOperand(1); 1334 1335 // If the RHS is a constant, check to see if the LHS would be zero without 1336 // using the bits from the RHS. Below, we use knowledge about the RHS to 1337 // simplify the LHS, here we're using information from the LHS to simplify 1338 // the RHS. 1339 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) { 1340 // Do not increment Depth here; that can cause an infinite loop. 1341 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth); 1342 // If the LHS already has zeros where RHSC does, this 'and' is dead. 1343 if ((LHSKnown.Zero & DemandedBits) == 1344 (~RHSC->getAPIntValue() & DemandedBits)) 1345 return TLO.CombineTo(Op, Op0); 1346 1347 // If any of the set bits in the RHS are known zero on the LHS, shrink 1348 // the constant. 1349 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits, 1350 DemandedElts, TLO)) 1351 return true; 1352 1353 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its 1354 // constant, but if this 'and' is only clearing bits that were just set by 1355 // the xor, then this 'and' can be eliminated by shrinking the mask of 1356 // the xor. For example, for a 32-bit X: 1357 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1 1358 if (isBitwiseNot(Op0) && Op0.hasOneUse() && 1359 LHSKnown.One == ~RHSC->getAPIntValue()) { 1360 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1); 1361 return TLO.CombineTo(Op, Xor); 1362 } 1363 } 1364 1365 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1366 Depth + 1)) 1367 return true; 1368 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1369 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts, 1370 Known2, TLO, Depth + 1)) 1371 return true; 1372 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1373 1374 // Attempt to avoid multi-use ops if we don't need anything from them. 1375 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1376 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1377 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1378 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1379 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1380 if (DemandedOp0 || DemandedOp1) { 1381 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1382 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1383 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1384 return TLO.CombineTo(Op, NewOp); 1385 } 1386 } 1387 1388 // If all of the demanded bits are known one on one side, return the other. 1389 // These bits cannot contribute to the result of the 'and'. 1390 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) 1391 return TLO.CombineTo(Op, Op0); 1392 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One)) 1393 return TLO.CombineTo(Op, Op1); 1394 // If all of the demanded bits in the inputs are known zeros, return zero. 1395 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1396 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT)); 1397 // If the RHS is a constant, see if we can simplify it. 1398 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts, 1399 TLO)) 1400 return true; 1401 // If the operation can be done in a smaller type, do so. 1402 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1403 return true; 1404 1405 Known &= Known2; 1406 break; 1407 } 1408 case ISD::OR: { 1409 SDValue Op0 = Op.getOperand(0); 1410 SDValue Op1 = Op.getOperand(1); 1411 1412 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1413 Depth + 1)) 1414 return true; 1415 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1416 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts, 1417 Known2, TLO, Depth + 1)) 1418 return true; 1419 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1420 1421 // Attempt to avoid multi-use ops if we don't need anything from them. 1422 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1423 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1424 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1425 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1426 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1427 if (DemandedOp0 || DemandedOp1) { 1428 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1429 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1430 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1431 return TLO.CombineTo(Op, NewOp); 1432 } 1433 } 1434 1435 // If all of the demanded bits are known zero on one side, return the other. 1436 // These bits cannot contribute to the result of the 'or'. 1437 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) 1438 return TLO.CombineTo(Op, Op0); 1439 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero)) 1440 return TLO.CombineTo(Op, Op1); 1441 // If the RHS is a constant, see if we can simplify it. 1442 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1443 return true; 1444 // If the operation can be done in a smaller type, do so. 1445 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1446 return true; 1447 1448 Known |= Known2; 1449 break; 1450 } 1451 case ISD::XOR: { 1452 SDValue Op0 = Op.getOperand(0); 1453 SDValue Op1 = Op.getOperand(1); 1454 1455 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1456 Depth + 1)) 1457 return true; 1458 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1459 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO, 1460 Depth + 1)) 1461 return true; 1462 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1463 1464 // Attempt to avoid multi-use ops if we don't need anything from them. 1465 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1466 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1467 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1468 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1469 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1470 if (DemandedOp0 || DemandedOp1) { 1471 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1472 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1473 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1474 return TLO.CombineTo(Op, NewOp); 1475 } 1476 } 1477 1478 // If all of the demanded bits are known zero on one side, return the other. 1479 // These bits cannot contribute to the result of the 'xor'. 1480 if (DemandedBits.isSubsetOf(Known.Zero)) 1481 return TLO.CombineTo(Op, Op0); 1482 if (DemandedBits.isSubsetOf(Known2.Zero)) 1483 return TLO.CombineTo(Op, Op1); 1484 // If the operation can be done in a smaller type, do so. 1485 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1486 return true; 1487 1488 // If all of the unknown bits are known to be zero on one side or the other 1489 // turn this into an *inclusive* or. 1490 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 1491 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1492 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1)); 1493 1494 ConstantSDNode* C = isConstOrConstSplat(Op1, DemandedElts); 1495 if (C) { 1496 // If one side is a constant, and all of the set bits in the constant are 1497 // also known set on the other side, turn this into an AND, as we know 1498 // the bits will be cleared. 1499 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 1500 // NB: it is okay if more bits are known than are requested 1501 if (C->getAPIntValue() == Known2.One) { 1502 SDValue ANDC = 1503 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT); 1504 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC)); 1505 } 1506 1507 // If the RHS is a constant, see if we can change it. Don't alter a -1 1508 // constant because that's a 'not' op, and that is better for combining 1509 // and codegen. 1510 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) { 1511 // We're flipping all demanded bits. Flip the undemanded bits too. 1512 SDValue New = TLO.DAG.getNOT(dl, Op0, VT); 1513 return TLO.CombineTo(Op, New); 1514 } 1515 } 1516 1517 // If we can't turn this into a 'not', try to shrink the constant. 1518 if (!C || !C->isAllOnes()) 1519 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1520 return true; 1521 1522 Known ^= Known2; 1523 break; 1524 } 1525 case ISD::SELECT: 1526 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO, 1527 Depth + 1)) 1528 return true; 1529 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO, 1530 Depth + 1)) 1531 return true; 1532 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1533 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1534 1535 // If the operands are constants, see if we can simplify them. 1536 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1537 return true; 1538 1539 // Only known if known in both the LHS and RHS. 1540 Known = KnownBits::commonBits(Known, Known2); 1541 break; 1542 case ISD::SELECT_CC: 1543 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO, 1544 Depth + 1)) 1545 return true; 1546 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO, 1547 Depth + 1)) 1548 return true; 1549 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1550 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1551 1552 // If the operands are constants, see if we can simplify them. 1553 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1554 return true; 1555 1556 // Only known if known in both the LHS and RHS. 1557 Known = KnownBits::commonBits(Known, Known2); 1558 break; 1559 case ISD::SETCC: { 1560 SDValue Op0 = Op.getOperand(0); 1561 SDValue Op1 = Op.getOperand(1); 1562 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 1563 // If (1) we only need the sign-bit, (2) the setcc operands are the same 1564 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 1565 // -1, we may be able to bypass the setcc. 1566 if (DemandedBits.isSignMask() && 1567 Op0.getScalarValueSizeInBits() == BitWidth && 1568 getBooleanContents(Op0.getValueType()) == 1569 BooleanContent::ZeroOrNegativeOneBooleanContent) { 1570 // If we're testing X < 0, then this compare isn't needed - just use X! 1571 // FIXME: We're limiting to integer types here, but this should also work 1572 // if we don't care about FP signed-zero. The use of SETLT with FP means 1573 // that we don't care about NaNs. 1574 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 1575 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 1576 return TLO.CombineTo(Op, Op0); 1577 1578 // TODO: Should we check for other forms of sign-bit comparisons? 1579 // Examples: X <= -1, X >= 0 1580 } 1581 if (getBooleanContents(Op0.getValueType()) == 1582 TargetLowering::ZeroOrOneBooleanContent && 1583 BitWidth > 1) 1584 Known.Zero.setBitsFrom(1); 1585 break; 1586 } 1587 case ISD::SHL: { 1588 SDValue Op0 = Op.getOperand(0); 1589 SDValue Op1 = Op.getOperand(1); 1590 EVT ShiftVT = Op1.getValueType(); 1591 1592 if (const APInt *SA = 1593 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1594 unsigned ShAmt = SA->getZExtValue(); 1595 if (ShAmt == 0) 1596 return TLO.CombineTo(Op, Op0); 1597 1598 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 1599 // single shift. We can do this if the bottom bits (which are shifted 1600 // out) are never demanded. 1601 // TODO - support non-uniform vector amounts. 1602 if (Op0.getOpcode() == ISD::SRL) { 1603 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) { 1604 if (const APInt *SA2 = 1605 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1606 unsigned C1 = SA2->getZExtValue(); 1607 unsigned Opc = ISD::SHL; 1608 int Diff = ShAmt - C1; 1609 if (Diff < 0) { 1610 Diff = -Diff; 1611 Opc = ISD::SRL; 1612 } 1613 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1614 return TLO.CombineTo( 1615 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1616 } 1617 } 1618 } 1619 1620 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 1621 // are not demanded. This will likely allow the anyext to be folded away. 1622 // TODO - support non-uniform vector amounts. 1623 if (Op0.getOpcode() == ISD::ANY_EXTEND) { 1624 SDValue InnerOp = Op0.getOperand(0); 1625 EVT InnerVT = InnerOp.getValueType(); 1626 unsigned InnerBits = InnerVT.getScalarSizeInBits(); 1627 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits && 1628 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 1629 EVT ShTy = getShiftAmountTy(InnerVT, DL); 1630 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits())) 1631 ShTy = InnerVT; 1632 SDValue NarrowShl = 1633 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp, 1634 TLO.DAG.getConstant(ShAmt, dl, ShTy)); 1635 return TLO.CombineTo( 1636 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl)); 1637 } 1638 1639 // Repeat the SHL optimization above in cases where an extension 1640 // intervenes: (shl (anyext (shr x, c1)), c2) to 1641 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 1642 // aren't demanded (as above) and that the shifted upper c1 bits of 1643 // x aren't demanded. 1644 // TODO - support non-uniform vector amounts. 1645 if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL && 1646 InnerOp.hasOneUse()) { 1647 if (const APInt *SA2 = 1648 TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) { 1649 unsigned InnerShAmt = SA2->getZExtValue(); 1650 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits && 1651 DemandedBits.getActiveBits() <= 1652 (InnerBits - InnerShAmt + ShAmt) && 1653 DemandedBits.countTrailingZeros() >= ShAmt) { 1654 SDValue NewSA = 1655 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT); 1656 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 1657 InnerOp.getOperand(0)); 1658 return TLO.CombineTo( 1659 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA)); 1660 } 1661 } 1662 } 1663 } 1664 1665 APInt InDemandedMask = DemandedBits.lshr(ShAmt); 1666 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1667 Depth + 1)) 1668 return true; 1669 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1670 Known.Zero <<= ShAmt; 1671 Known.One <<= ShAmt; 1672 // low bits known zero. 1673 Known.Zero.setLowBits(ShAmt); 1674 1675 // Attempt to avoid multi-use ops if we don't need anything from them. 1676 if (!InDemandedMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1677 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1678 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1679 if (DemandedOp0) { 1680 SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1); 1681 return TLO.CombineTo(Op, NewOp); 1682 } 1683 } 1684 1685 // Try shrinking the operation as long as the shift amount will still be 1686 // in range. 1687 if ((ShAmt < DemandedBits.getActiveBits()) && 1688 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1689 return true; 1690 } 1691 1692 // If we are only demanding sign bits then we can use the shift source 1693 // directly. 1694 if (const APInt *MaxSA = 1695 TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 1696 unsigned ShAmt = MaxSA->getZExtValue(); 1697 unsigned NumSignBits = 1698 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1699 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1700 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 1701 return TLO.CombineTo(Op, Op0); 1702 } 1703 break; 1704 } 1705 case ISD::SRL: { 1706 SDValue Op0 = Op.getOperand(0); 1707 SDValue Op1 = Op.getOperand(1); 1708 EVT ShiftVT = Op1.getValueType(); 1709 1710 // Try to match AVG patterns. 1711 if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits, 1712 DemandedElts, Depth + 1)) 1713 return TLO.CombineTo(Op, AVG); 1714 1715 if (const APInt *SA = 1716 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1717 unsigned ShAmt = SA->getZExtValue(); 1718 if (ShAmt == 0) 1719 return TLO.CombineTo(Op, Op0); 1720 1721 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 1722 // single shift. We can do this if the top bits (which are shifted out) 1723 // are never demanded. 1724 // TODO - support non-uniform vector amounts. 1725 if (Op0.getOpcode() == ISD::SHL) { 1726 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) { 1727 if (const APInt *SA2 = 1728 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1729 unsigned C1 = SA2->getZExtValue(); 1730 unsigned Opc = ISD::SRL; 1731 int Diff = ShAmt - C1; 1732 if (Diff < 0) { 1733 Diff = -Diff; 1734 Opc = ISD::SHL; 1735 } 1736 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1737 return TLO.CombineTo( 1738 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1739 } 1740 } 1741 } 1742 1743 APInt InDemandedMask = (DemandedBits << ShAmt); 1744 1745 // If the shift is exact, then it does demand the low bits (and knows that 1746 // they are zero). 1747 if (Op->getFlags().hasExact()) 1748 InDemandedMask.setLowBits(ShAmt); 1749 1750 // Compute the new bits that are at the top now. 1751 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1752 Depth + 1)) 1753 return true; 1754 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1755 Known.Zero.lshrInPlace(ShAmt); 1756 Known.One.lshrInPlace(ShAmt); 1757 // High bits known zero. 1758 Known.Zero.setHighBits(ShAmt); 1759 } 1760 break; 1761 } 1762 case ISD::SRA: { 1763 SDValue Op0 = Op.getOperand(0); 1764 SDValue Op1 = Op.getOperand(1); 1765 EVT ShiftVT = Op1.getValueType(); 1766 1767 // If we only want bits that already match the signbit then we don't need 1768 // to shift. 1769 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1770 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >= 1771 NumHiDemandedBits) 1772 return TLO.CombineTo(Op, Op0); 1773 1774 // If this is an arithmetic shift right and only the low-bit is set, we can 1775 // always convert this into a logical shr, even if the shift amount is 1776 // variable. The low bit of the shift cannot be an input sign bit unless 1777 // the shift amount is >= the size of the datatype, which is undefined. 1778 if (DemandedBits.isOne()) 1779 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 1780 1781 // Try to match AVG patterns. 1782 if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits, 1783 DemandedElts, Depth + 1)) 1784 return TLO.CombineTo(Op, AVG); 1785 1786 if (const APInt *SA = 1787 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1788 unsigned ShAmt = SA->getZExtValue(); 1789 if (ShAmt == 0) 1790 return TLO.CombineTo(Op, Op0); 1791 1792 APInt InDemandedMask = (DemandedBits << ShAmt); 1793 1794 // If the shift is exact, then it does demand the low bits (and knows that 1795 // they are zero). 1796 if (Op->getFlags().hasExact()) 1797 InDemandedMask.setLowBits(ShAmt); 1798 1799 // If any of the demanded bits are produced by the sign extension, we also 1800 // demand the input sign bit. 1801 if (DemandedBits.countLeadingZeros() < ShAmt) 1802 InDemandedMask.setSignBit(); 1803 1804 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1805 Depth + 1)) 1806 return true; 1807 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1808 Known.Zero.lshrInPlace(ShAmt); 1809 Known.One.lshrInPlace(ShAmt); 1810 1811 // If the input sign bit is known to be zero, or if none of the top bits 1812 // are demanded, turn this into an unsigned shift right. 1813 if (Known.Zero[BitWidth - ShAmt - 1] || 1814 DemandedBits.countLeadingZeros() >= ShAmt) { 1815 SDNodeFlags Flags; 1816 Flags.setExact(Op->getFlags().hasExact()); 1817 return TLO.CombineTo( 1818 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags)); 1819 } 1820 1821 int Log2 = DemandedBits.exactLogBase2(); 1822 if (Log2 >= 0) { 1823 // The bit must come from the sign. 1824 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT); 1825 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA)); 1826 } 1827 1828 if (Known.One[BitWidth - ShAmt - 1]) 1829 // New bits are known one. 1830 Known.One.setHighBits(ShAmt); 1831 1832 // Attempt to avoid multi-use ops if we don't need anything from them. 1833 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) { 1834 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1835 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1836 if (DemandedOp0) { 1837 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1); 1838 return TLO.CombineTo(Op, NewOp); 1839 } 1840 } 1841 } 1842 break; 1843 } 1844 case ISD::FSHL: 1845 case ISD::FSHR: { 1846 SDValue Op0 = Op.getOperand(0); 1847 SDValue Op1 = Op.getOperand(1); 1848 SDValue Op2 = Op.getOperand(2); 1849 bool IsFSHL = (Op.getOpcode() == ISD::FSHL); 1850 1851 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) { 1852 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 1853 1854 // For fshl, 0-shift returns the 1st arg. 1855 // For fshr, 0-shift returns the 2nd arg. 1856 if (Amt == 0) { 1857 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts, 1858 Known, TLO, Depth + 1)) 1859 return true; 1860 break; 1861 } 1862 1863 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt)) 1864 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt) 1865 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt)); 1866 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt); 1867 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 1868 Depth + 1)) 1869 return true; 1870 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO, 1871 Depth + 1)) 1872 return true; 1873 1874 Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1875 Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1876 Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1877 Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1878 Known.One |= Known2.One; 1879 Known.Zero |= Known2.Zero; 1880 1881 // Attempt to avoid multi-use ops if we don't need anything from them. 1882 if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() || 1883 !DemandedElts.isAllOnes()) { 1884 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1885 Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1); 1886 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1887 Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1); 1888 if (DemandedOp0 || DemandedOp1) { 1889 DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0; 1890 DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1; 1891 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0, 1892 DemandedOp1, Op2); 1893 return TLO.CombineTo(Op, NewOp); 1894 } 1895 } 1896 } 1897 1898 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1899 if (isPowerOf2_32(BitWidth)) { 1900 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1); 1901 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, 1902 Known2, TLO, Depth + 1)) 1903 return true; 1904 } 1905 break; 1906 } 1907 case ISD::ROTL: 1908 case ISD::ROTR: { 1909 SDValue Op0 = Op.getOperand(0); 1910 SDValue Op1 = Op.getOperand(1); 1911 bool IsROTL = (Op.getOpcode() == ISD::ROTL); 1912 1913 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 1914 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1)) 1915 return TLO.CombineTo(Op, Op0); 1916 1917 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) { 1918 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 1919 unsigned RevAmt = BitWidth - Amt; 1920 1921 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt)) 1922 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt) 1923 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt); 1924 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 1925 Depth + 1)) 1926 return true; 1927 1928 // rot*(x, 0) --> x 1929 if (Amt == 0) 1930 return TLO.CombineTo(Op, Op0); 1931 1932 // See if we don't demand either half of the rotated bits. 1933 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) && 1934 DemandedBits.countTrailingZeros() >= (IsROTL ? Amt : RevAmt)) { 1935 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType()); 1936 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1)); 1937 } 1938 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) && 1939 DemandedBits.countLeadingZeros() >= (IsROTL ? RevAmt : Amt)) { 1940 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType()); 1941 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 1942 } 1943 } 1944 1945 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1946 if (isPowerOf2_32(BitWidth)) { 1947 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1); 1948 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO, 1949 Depth + 1)) 1950 return true; 1951 } 1952 break; 1953 } 1954 case ISD::UMIN: { 1955 // Check if one arg is always less than (or equal) to the other arg. 1956 SDValue Op0 = Op.getOperand(0); 1957 SDValue Op1 = Op.getOperand(1); 1958 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 1959 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 1960 Known = KnownBits::umin(Known0, Known1); 1961 if (Optional<bool> IsULE = KnownBits::ule(Known0, Known1)) 1962 return TLO.CombineTo(Op, IsULE.getValue() ? Op0 : Op1); 1963 if (Optional<bool> IsULT = KnownBits::ult(Known0, Known1)) 1964 return TLO.CombineTo(Op, IsULT.getValue() ? Op0 : Op1); 1965 break; 1966 } 1967 case ISD::UMAX: { 1968 // Check if one arg is always greater than (or equal) to the other arg. 1969 SDValue Op0 = Op.getOperand(0); 1970 SDValue Op1 = Op.getOperand(1); 1971 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 1972 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 1973 Known = KnownBits::umax(Known0, Known1); 1974 if (Optional<bool> IsUGE = KnownBits::uge(Known0, Known1)) 1975 return TLO.CombineTo(Op, IsUGE.getValue() ? Op0 : Op1); 1976 if (Optional<bool> IsUGT = KnownBits::ugt(Known0, Known1)) 1977 return TLO.CombineTo(Op, IsUGT.getValue() ? Op0 : Op1); 1978 break; 1979 } 1980 case ISD::BITREVERSE: { 1981 SDValue Src = Op.getOperand(0); 1982 APInt DemandedSrcBits = DemandedBits.reverseBits(); 1983 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 1984 Depth + 1)) 1985 return true; 1986 Known.One = Known2.One.reverseBits(); 1987 Known.Zero = Known2.Zero.reverseBits(); 1988 break; 1989 } 1990 case ISD::BSWAP: { 1991 SDValue Src = Op.getOperand(0); 1992 1993 // If the only bits demanded come from one byte of the bswap result, 1994 // just shift the input byte into position to eliminate the bswap. 1995 unsigned NLZ = DemandedBits.countLeadingZeros(); 1996 unsigned NTZ = DemandedBits.countTrailingZeros(); 1997 1998 // Round NTZ down to the next byte. If we have 11 trailing zeros, then 1999 // we need all the bits down to bit 8. Likewise, round NLZ. If we 2000 // have 14 leading zeros, round to 8. 2001 NLZ = alignDown(NLZ, 8); 2002 NTZ = alignDown(NTZ, 8); 2003 // If we need exactly one byte, we can do this transformation. 2004 if (BitWidth - NLZ - NTZ == 8) { 2005 // Replace this with either a left or right shift to get the byte into 2006 // the right place. 2007 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL; 2008 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) { 2009 EVT ShiftAmtTy = getShiftAmountTy(VT, DL); 2010 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ; 2011 SDValue ShAmt = TLO.DAG.getConstant(ShiftAmount, dl, ShiftAmtTy); 2012 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt); 2013 return TLO.CombineTo(Op, NewOp); 2014 } 2015 } 2016 2017 APInt DemandedSrcBits = DemandedBits.byteSwap(); 2018 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 2019 Depth + 1)) 2020 return true; 2021 Known.One = Known2.One.byteSwap(); 2022 Known.Zero = Known2.Zero.byteSwap(); 2023 break; 2024 } 2025 case ISD::CTPOP: { 2026 // If only 1 bit is demanded, replace with PARITY as long as we're before 2027 // op legalization. 2028 // FIXME: Limit to scalars for now. 2029 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector()) 2030 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT, 2031 Op.getOperand(0))); 2032 2033 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2034 break; 2035 } 2036 case ISD::SIGN_EXTEND_INREG: { 2037 SDValue Op0 = Op.getOperand(0); 2038 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2039 unsigned ExVTBits = ExVT.getScalarSizeInBits(); 2040 2041 // If we only care about the highest bit, don't bother shifting right. 2042 if (DemandedBits.isSignMask()) { 2043 unsigned MinSignedBits = 2044 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1); 2045 bool AlreadySignExtended = ExVTBits >= MinSignedBits; 2046 // However if the input is already sign extended we expect the sign 2047 // extension to be dropped altogether later and do not simplify. 2048 if (!AlreadySignExtended) { 2049 // Compute the correct shift amount type, which must be getShiftAmountTy 2050 // for scalar types after legalization. 2051 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ExVTBits, dl, 2052 getShiftAmountTy(VT, DL)); 2053 return TLO.CombineTo(Op, 2054 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt)); 2055 } 2056 } 2057 2058 // If none of the extended bits are demanded, eliminate the sextinreg. 2059 if (DemandedBits.getActiveBits() <= ExVTBits) 2060 return TLO.CombineTo(Op, Op0); 2061 2062 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits); 2063 2064 // Since the sign extended bits are demanded, we know that the sign 2065 // bit is demanded. 2066 InputDemandedBits.setBit(ExVTBits - 1); 2067 2068 if (SimplifyDemandedBits(Op0, InputDemandedBits, Known, TLO, Depth + 1)) 2069 return true; 2070 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2071 2072 // If the sign bit of the input is known set or clear, then we know the 2073 // top bits of the result. 2074 2075 // If the input sign bit is known zero, convert this into a zero extension. 2076 if (Known.Zero[ExVTBits - 1]) 2077 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT)); 2078 2079 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits); 2080 if (Known.One[ExVTBits - 1]) { // Input sign bit known set 2081 Known.One.setBitsFrom(ExVTBits); 2082 Known.Zero &= Mask; 2083 } else { // Input sign bit unknown 2084 Known.Zero &= Mask; 2085 Known.One &= Mask; 2086 } 2087 break; 2088 } 2089 case ISD::BUILD_PAIR: { 2090 EVT HalfVT = Op.getOperand(0).getValueType(); 2091 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 2092 2093 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 2094 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 2095 2096 KnownBits KnownLo, KnownHi; 2097 2098 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1)) 2099 return true; 2100 2101 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1)) 2102 return true; 2103 2104 Known.Zero = KnownLo.Zero.zext(BitWidth) | 2105 KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth); 2106 2107 Known.One = KnownLo.One.zext(BitWidth) | 2108 KnownHi.One.zext(BitWidth).shl(HalfBitWidth); 2109 break; 2110 } 2111 case ISD::ZERO_EXTEND: 2112 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2113 SDValue Src = Op.getOperand(0); 2114 EVT SrcVT = Src.getValueType(); 2115 unsigned InBits = SrcVT.getScalarSizeInBits(); 2116 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2117 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG; 2118 2119 // If none of the top bits are demanded, convert this into an any_extend. 2120 if (DemandedBits.getActiveBits() <= InBits) { 2121 // If we only need the non-extended bits of the bottom element 2122 // then we can just bitcast to the result. 2123 if (IsLE && IsVecInReg && DemandedElts == 1 && 2124 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2125 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2126 2127 unsigned Opc = 2128 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2129 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2130 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2131 } 2132 2133 APInt InDemandedBits = DemandedBits.trunc(InBits); 2134 APInt InDemandedElts = DemandedElts.zext(InElts); 2135 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2136 Depth + 1)) 2137 return true; 2138 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2139 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2140 Known = Known.zext(BitWidth); 2141 2142 // Attempt to avoid multi-use ops if we don't need anything from them. 2143 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2144 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2145 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2146 break; 2147 } 2148 case ISD::SIGN_EXTEND: 2149 case ISD::SIGN_EXTEND_VECTOR_INREG: { 2150 SDValue Src = Op.getOperand(0); 2151 EVT SrcVT = Src.getValueType(); 2152 unsigned InBits = SrcVT.getScalarSizeInBits(); 2153 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2154 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG; 2155 2156 // If none of the top bits are demanded, convert this into an any_extend. 2157 if (DemandedBits.getActiveBits() <= InBits) { 2158 // If we only need the non-extended bits of the bottom element 2159 // then we can just bitcast to the result. 2160 if (IsLE && IsVecInReg && DemandedElts == 1 && 2161 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2162 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2163 2164 unsigned Opc = 2165 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2166 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2167 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2168 } 2169 2170 APInt InDemandedBits = DemandedBits.trunc(InBits); 2171 APInt InDemandedElts = DemandedElts.zext(InElts); 2172 2173 // Since some of the sign extended bits are demanded, we know that the sign 2174 // bit is demanded. 2175 InDemandedBits.setBit(InBits - 1); 2176 2177 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2178 Depth + 1)) 2179 return true; 2180 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2181 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2182 2183 // If the sign bit is known one, the top bits match. 2184 Known = Known.sext(BitWidth); 2185 2186 // If the sign bit is known zero, convert this to a zero extend. 2187 if (Known.isNonNegative()) { 2188 unsigned Opc = 2189 IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND; 2190 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2191 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2192 } 2193 2194 // Attempt to avoid multi-use ops if we don't need anything from them. 2195 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2196 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2197 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2198 break; 2199 } 2200 case ISD::ANY_EXTEND: 2201 case ISD::ANY_EXTEND_VECTOR_INREG: { 2202 SDValue Src = Op.getOperand(0); 2203 EVT SrcVT = Src.getValueType(); 2204 unsigned InBits = SrcVT.getScalarSizeInBits(); 2205 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2206 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG; 2207 2208 // If we only need the bottom element then we can just bitcast. 2209 // TODO: Handle ANY_EXTEND? 2210 if (IsLE && IsVecInReg && DemandedElts == 1 && 2211 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2212 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2213 2214 APInt InDemandedBits = DemandedBits.trunc(InBits); 2215 APInt InDemandedElts = DemandedElts.zext(InElts); 2216 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2217 Depth + 1)) 2218 return true; 2219 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2220 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2221 Known = Known.anyext(BitWidth); 2222 2223 // Attempt to avoid multi-use ops if we don't need anything from them. 2224 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2225 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2226 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2227 break; 2228 } 2229 case ISD::TRUNCATE: { 2230 SDValue Src = Op.getOperand(0); 2231 2232 // Simplify the input, using demanded bit information, and compute the known 2233 // zero/one bits live out. 2234 unsigned OperandBitWidth = Src.getScalarValueSizeInBits(); 2235 APInt TruncMask = DemandedBits.zext(OperandBitWidth); 2236 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO, 2237 Depth + 1)) 2238 return true; 2239 Known = Known.trunc(BitWidth); 2240 2241 // Attempt to avoid multi-use ops if we don't need anything from them. 2242 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2243 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1)) 2244 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc)); 2245 2246 // If the input is only used by this truncate, see if we can shrink it based 2247 // on the known demanded bits. 2248 if (Src.getNode()->hasOneUse()) { 2249 switch (Src.getOpcode()) { 2250 default: 2251 break; 2252 case ISD::SRL: 2253 // Shrink SRL by a constant if none of the high bits shifted in are 2254 // demanded. 2255 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT)) 2256 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 2257 // undesirable. 2258 break; 2259 2260 const APInt *ShAmtC = 2261 TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts); 2262 if (!ShAmtC || ShAmtC->uge(BitWidth)) 2263 break; 2264 uint64_t ShVal = ShAmtC->getZExtValue(); 2265 2266 APInt HighBits = 2267 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth); 2268 HighBits.lshrInPlace(ShVal); 2269 HighBits = HighBits.trunc(BitWidth); 2270 2271 if (!(HighBits & DemandedBits)) { 2272 // None of the shifted in bits are needed. Add a truncate of the 2273 // shift input, then shift it. 2274 SDValue NewShAmt = TLO.DAG.getConstant( 2275 ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes())); 2276 SDValue NewTrunc = 2277 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0)); 2278 return TLO.CombineTo( 2279 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt)); 2280 } 2281 break; 2282 } 2283 } 2284 2285 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2286 break; 2287 } 2288 case ISD::AssertZext: { 2289 // AssertZext demands all of the high bits, plus any of the low bits 2290 // demanded by its users. 2291 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2292 APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits()); 2293 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known, 2294 TLO, Depth + 1)) 2295 return true; 2296 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2297 2298 Known.Zero |= ~InMask; 2299 break; 2300 } 2301 case ISD::EXTRACT_VECTOR_ELT: { 2302 SDValue Src = Op.getOperand(0); 2303 SDValue Idx = Op.getOperand(1); 2304 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount(); 2305 unsigned EltBitWidth = Src.getScalarValueSizeInBits(); 2306 2307 if (SrcEltCnt.isScalable()) 2308 return false; 2309 2310 // Demand the bits from every vector element without a constant index. 2311 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2312 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 2313 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx)) 2314 if (CIdx->getAPIntValue().ult(NumSrcElts)) 2315 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue()); 2316 2317 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 2318 // anything about the extended bits. 2319 APInt DemandedSrcBits = DemandedBits; 2320 if (BitWidth > EltBitWidth) 2321 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth); 2322 2323 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO, 2324 Depth + 1)) 2325 return true; 2326 2327 // Attempt to avoid multi-use ops if we don't need anything from them. 2328 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 2329 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 2330 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) { 2331 SDValue NewOp = 2332 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx); 2333 return TLO.CombineTo(Op, NewOp); 2334 } 2335 } 2336 2337 Known = Known2; 2338 if (BitWidth > EltBitWidth) 2339 Known = Known.anyext(BitWidth); 2340 break; 2341 } 2342 case ISD::BITCAST: { 2343 SDValue Src = Op.getOperand(0); 2344 EVT SrcVT = Src.getValueType(); 2345 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 2346 2347 // If this is an FP->Int bitcast and if the sign bit is the only 2348 // thing demanded, turn this into a FGETSIGN. 2349 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() && 2350 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) && 2351 SrcVT.isFloatingPoint()) { 2352 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT); 2353 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 2354 if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 && 2355 SrcVT != MVT::f128) { 2356 // Cannot eliminate/lower SHL for f128 yet. 2357 EVT Ty = OpVTLegal ? VT : MVT::i32; 2358 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 2359 // place. We expect the SHL to be eliminated by other optimizations. 2360 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src); 2361 unsigned OpVTSizeInBits = Op.getValueSizeInBits(); 2362 if (!OpVTLegal && OpVTSizeInBits > 32) 2363 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign); 2364 unsigned ShVal = Op.getValueSizeInBits() - 1; 2365 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT); 2366 return TLO.CombineTo(Op, 2367 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt)); 2368 } 2369 } 2370 2371 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts. 2372 // Demand the elt/bit if any of the original elts/bits are demanded. 2373 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) { 2374 unsigned Scale = BitWidth / NumSrcEltBits; 2375 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2376 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2377 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2378 for (unsigned i = 0; i != Scale; ++i) { 2379 unsigned EltOffset = IsLE ? i : (Scale - 1 - i); 2380 unsigned BitOffset = EltOffset * NumSrcEltBits; 2381 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset); 2382 if (!Sub.isZero()) { 2383 DemandedSrcBits |= Sub; 2384 for (unsigned j = 0; j != NumElts; ++j) 2385 if (DemandedElts[j]) 2386 DemandedSrcElts.setBit((j * Scale) + i); 2387 } 2388 } 2389 2390 APInt KnownSrcUndef, KnownSrcZero; 2391 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2392 KnownSrcZero, TLO, Depth + 1)) 2393 return true; 2394 2395 KnownBits KnownSrcBits; 2396 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2397 KnownSrcBits, TLO, Depth + 1)) 2398 return true; 2399 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) { 2400 // TODO - bigendian once we have test coverage. 2401 unsigned Scale = NumSrcEltBits / BitWidth; 2402 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2403 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2404 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2405 for (unsigned i = 0; i != NumElts; ++i) 2406 if (DemandedElts[i]) { 2407 unsigned Offset = (i % Scale) * BitWidth; 2408 DemandedSrcBits.insertBits(DemandedBits, Offset); 2409 DemandedSrcElts.setBit(i / Scale); 2410 } 2411 2412 if (SrcVT.isVector()) { 2413 APInt KnownSrcUndef, KnownSrcZero; 2414 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2415 KnownSrcZero, TLO, Depth + 1)) 2416 return true; 2417 } 2418 2419 KnownBits KnownSrcBits; 2420 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2421 KnownSrcBits, TLO, Depth + 1)) 2422 return true; 2423 } 2424 2425 // If this is a bitcast, let computeKnownBits handle it. Only do this on a 2426 // recursive call where Known may be useful to the caller. 2427 if (Depth > 0) { 2428 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2429 return false; 2430 } 2431 break; 2432 } 2433 case ISD::MUL: 2434 if (DemandedBits.isPowerOf2()) { 2435 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1. 2436 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is 2437 // odd (has LSB set), then the left-shifted low bit of X is the answer. 2438 unsigned CTZ = DemandedBits.countTrailingZeros(); 2439 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts); 2440 if (C && C->getAPIntValue().countTrailingZeros() == CTZ) { 2441 EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout()); 2442 SDValue AmtC = TLO.DAG.getConstant(CTZ, dl, ShiftAmtTy); 2443 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC); 2444 return TLO.CombineTo(Op, Shl); 2445 } 2446 } 2447 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because: 2448 // X * X is odd iff X is odd. 2449 // 'Quadratic Reciprocity': X * X -> 0 for bit[1] 2450 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) { 2451 SDValue One = TLO.DAG.getConstant(1, dl, VT); 2452 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One); 2453 return TLO.CombineTo(Op, And1); 2454 } 2455 LLVM_FALLTHROUGH; 2456 case ISD::ADD: 2457 case ISD::SUB: { 2458 // Add, Sub, and Mul don't demand any bits in positions beyond that 2459 // of the highest bit demanded of them. 2460 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1); 2461 SDNodeFlags Flags = Op.getNode()->getFlags(); 2462 unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros(); 2463 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ); 2464 if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO, 2465 Depth + 1) || 2466 SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO, 2467 Depth + 1) || 2468 // See if the operation should be performed at a smaller bit width. 2469 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) { 2470 if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) { 2471 // Disable the nsw and nuw flags. We can no longer guarantee that we 2472 // won't wrap after simplification. 2473 Flags.setNoSignedWrap(false); 2474 Flags.setNoUnsignedWrap(false); 2475 SDValue NewOp = 2476 TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags); 2477 return TLO.CombineTo(Op, NewOp); 2478 } 2479 return true; 2480 } 2481 2482 // Attempt to avoid multi-use ops if we don't need anything from them. 2483 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) { 2484 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2485 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2486 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 2487 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2488 if (DemandedOp0 || DemandedOp1) { 2489 Flags.setNoSignedWrap(false); 2490 Flags.setNoUnsignedWrap(false); 2491 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 2492 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 2493 SDValue NewOp = 2494 TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags); 2495 return TLO.CombineTo(Op, NewOp); 2496 } 2497 } 2498 2499 // If we have a constant operand, we may be able to turn it into -1 if we 2500 // do not demand the high bits. This can make the constant smaller to 2501 // encode, allow more general folding, or match specialized instruction 2502 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that 2503 // is probably not useful (and could be detrimental). 2504 ConstantSDNode *C = isConstOrConstSplat(Op1); 2505 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ); 2506 if (C && !C->isAllOnes() && !C->isOne() && 2507 (C->getAPIntValue() | HighMask).isAllOnes()) { 2508 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT); 2509 // Disable the nsw and nuw flags. We can no longer guarantee that we 2510 // won't wrap after simplification. 2511 Flags.setNoSignedWrap(false); 2512 Flags.setNoUnsignedWrap(false); 2513 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags); 2514 return TLO.CombineTo(Op, NewOp); 2515 } 2516 2517 // Match a multiply with a disguised negated-power-of-2 and convert to a 2518 // an equivalent shift-left amount. 2519 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2520 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned { 2521 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse()) 2522 return 0; 2523 2524 // Don't touch opaque constants. Also, ignore zero and power-of-2 2525 // multiplies. Those will get folded later. 2526 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1)); 2527 if (MulC && !MulC->isOpaque() && !MulC->isZero() && 2528 !MulC->getAPIntValue().isPowerOf2()) { 2529 APInt UnmaskedC = MulC->getAPIntValue() | HighMask; 2530 if (UnmaskedC.isNegatedPowerOf2()) 2531 return (-UnmaskedC).logBase2(); 2532 } 2533 return 0; 2534 }; 2535 2536 auto foldMul = [&](SDValue X, SDValue Y, unsigned ShlAmt) { 2537 EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout()); 2538 SDValue ShlAmtC = TLO.DAG.getConstant(ShlAmt, dl, ShiftAmtTy); 2539 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC); 2540 SDValue Sub = TLO.DAG.getNode(ISD::SUB, dl, VT, Y, Shl); 2541 return TLO.CombineTo(Op, Sub); 2542 }; 2543 2544 if (isOperationLegalOrCustom(ISD::SHL, VT)) { 2545 if (Op.getOpcode() == ISD::ADD) { 2546 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2547 if (unsigned ShAmt = getShiftLeftAmt(Op0)) 2548 return foldMul(Op0.getOperand(0), Op1, ShAmt); 2549 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC)) 2550 if (unsigned ShAmt = getShiftLeftAmt(Op1)) 2551 return foldMul(Op1.getOperand(0), Op0, ShAmt); 2552 // TODO: 2553 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC)) 2554 } 2555 } 2556 2557 LLVM_FALLTHROUGH; 2558 } 2559 default: 2560 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 2561 if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts, 2562 Known, TLO, Depth)) 2563 return true; 2564 break; 2565 } 2566 2567 // Just use computeKnownBits to compute output bits. 2568 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2569 break; 2570 } 2571 2572 // If we know the value of all of the demanded bits, return this as a 2573 // constant. 2574 if (DemandedBits.isSubsetOf(Known.Zero | Known.One)) { 2575 // Avoid folding to a constant if any OpaqueConstant is involved. 2576 const SDNode *N = Op.getNode(); 2577 for (SDNode *Op : 2578 llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) { 2579 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 2580 if (C->isOpaque()) 2581 return false; 2582 } 2583 if (VT.isInteger()) 2584 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT)); 2585 if (VT.isFloatingPoint()) 2586 return TLO.CombineTo( 2587 Op, 2588 TLO.DAG.getConstantFP( 2589 APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT)); 2590 } 2591 2592 return false; 2593 } 2594 2595 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op, 2596 const APInt &DemandedElts, 2597 DAGCombinerInfo &DCI) const { 2598 SelectionDAG &DAG = DCI.DAG; 2599 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 2600 !DCI.isBeforeLegalizeOps()); 2601 2602 APInt KnownUndef, KnownZero; 2603 bool Simplified = 2604 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO); 2605 if (Simplified) { 2606 DCI.AddToWorklist(Op.getNode()); 2607 DCI.CommitTargetLoweringOpt(TLO); 2608 } 2609 2610 return Simplified; 2611 } 2612 2613 /// Given a vector binary operation and known undefined elements for each input 2614 /// operand, compute whether each element of the output is undefined. 2615 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG, 2616 const APInt &UndefOp0, 2617 const APInt &UndefOp1) { 2618 EVT VT = BO.getValueType(); 2619 assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() && 2620 "Vector binop only"); 2621 2622 EVT EltVT = VT.getVectorElementType(); 2623 unsigned NumElts = VT.getVectorNumElements(); 2624 assert(UndefOp0.getBitWidth() == NumElts && 2625 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis"); 2626 2627 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index, 2628 const APInt &UndefVals) { 2629 if (UndefVals[Index]) 2630 return DAG.getUNDEF(EltVT); 2631 2632 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 2633 // Try hard to make sure that the getNode() call is not creating temporary 2634 // nodes. Ignore opaque integers because they do not constant fold. 2635 SDValue Elt = BV->getOperand(Index); 2636 auto *C = dyn_cast<ConstantSDNode>(Elt); 2637 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque())) 2638 return Elt; 2639 } 2640 2641 return SDValue(); 2642 }; 2643 2644 APInt KnownUndef = APInt::getZero(NumElts); 2645 for (unsigned i = 0; i != NumElts; ++i) { 2646 // If both inputs for this element are either constant or undef and match 2647 // the element type, compute the constant/undef result for this element of 2648 // the vector. 2649 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does 2650 // not handle FP constants. The code within getNode() should be refactored 2651 // to avoid the danger of creating a bogus temporary node here. 2652 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0); 2653 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1); 2654 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT) 2655 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef()) 2656 KnownUndef.setBit(i); 2657 } 2658 return KnownUndef; 2659 } 2660 2661 bool TargetLowering::SimplifyDemandedVectorElts( 2662 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef, 2663 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth, 2664 bool AssumeSingleUse) const { 2665 EVT VT = Op.getValueType(); 2666 unsigned Opcode = Op.getOpcode(); 2667 APInt DemandedElts = OriginalDemandedElts; 2668 unsigned NumElts = DemandedElts.getBitWidth(); 2669 assert(VT.isVector() && "Expected vector op"); 2670 2671 KnownUndef = KnownZero = APInt::getZero(NumElts); 2672 2673 const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo(); 2674 if (!TLI.shouldSimplifyDemandedVectorElts(Op, TLO)) 2675 return false; 2676 2677 // TODO: For now we assume we know nothing about scalable vectors. 2678 if (VT.isScalableVector()) 2679 return false; 2680 2681 assert(VT.getVectorNumElements() == NumElts && 2682 "Mask size mismatches value type element count!"); 2683 2684 // Undef operand. 2685 if (Op.isUndef()) { 2686 KnownUndef.setAllBits(); 2687 return false; 2688 } 2689 2690 // If Op has other users, assume that all elements are needed. 2691 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) 2692 DemandedElts.setAllBits(); 2693 2694 // Not demanding any elements from Op. 2695 if (DemandedElts == 0) { 2696 KnownUndef.setAllBits(); 2697 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2698 } 2699 2700 // Limit search depth. 2701 if (Depth >= SelectionDAG::MaxRecursionDepth) 2702 return false; 2703 2704 SDLoc DL(Op); 2705 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 2706 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 2707 2708 // Helper for demanding the specified elements and all the bits of both binary 2709 // operands. 2710 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) { 2711 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts, 2712 TLO.DAG, Depth + 1); 2713 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts, 2714 TLO.DAG, Depth + 1); 2715 if (NewOp0 || NewOp1) { 2716 SDValue NewOp = TLO.DAG.getNode( 2717 Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, NewOp1 ? NewOp1 : Op1); 2718 return TLO.CombineTo(Op, NewOp); 2719 } 2720 return false; 2721 }; 2722 2723 switch (Opcode) { 2724 case ISD::SCALAR_TO_VECTOR: { 2725 if (!DemandedElts[0]) { 2726 KnownUndef.setAllBits(); 2727 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2728 } 2729 SDValue ScalarSrc = Op.getOperand(0); 2730 if (ScalarSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 2731 SDValue Src = ScalarSrc.getOperand(0); 2732 SDValue Idx = ScalarSrc.getOperand(1); 2733 EVT SrcVT = Src.getValueType(); 2734 2735 ElementCount SrcEltCnt = SrcVT.getVectorElementCount(); 2736 2737 if (SrcEltCnt.isScalable()) 2738 return false; 2739 2740 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2741 if (isNullConstant(Idx)) { 2742 APInt SrcDemandedElts = APInt::getOneBitSet(NumSrcElts, 0); 2743 APInt SrcUndef = KnownUndef.zextOrTrunc(NumSrcElts); 2744 APInt SrcZero = KnownZero.zextOrTrunc(NumSrcElts); 2745 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2746 TLO, Depth + 1)) 2747 return true; 2748 } 2749 } 2750 KnownUndef.setHighBits(NumElts - 1); 2751 break; 2752 } 2753 case ISD::BITCAST: { 2754 SDValue Src = Op.getOperand(0); 2755 EVT SrcVT = Src.getValueType(); 2756 2757 // We only handle vectors here. 2758 // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits? 2759 if (!SrcVT.isVector()) 2760 break; 2761 2762 // Fast handling of 'identity' bitcasts. 2763 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2764 if (NumSrcElts == NumElts) 2765 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, 2766 KnownZero, TLO, Depth + 1); 2767 2768 APInt SrcDemandedElts, SrcZero, SrcUndef; 2769 2770 // Bitcast from 'large element' src vector to 'small element' vector, we 2771 // must demand a source element if any DemandedElt maps to it. 2772 if ((NumElts % NumSrcElts) == 0) { 2773 unsigned Scale = NumElts / NumSrcElts; 2774 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2775 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2776 TLO, Depth + 1)) 2777 return true; 2778 2779 // Try calling SimplifyDemandedBits, converting demanded elts to the bits 2780 // of the large element. 2781 // TODO - bigendian once we have test coverage. 2782 if (IsLE) { 2783 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits(); 2784 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits); 2785 for (unsigned i = 0; i != NumElts; ++i) 2786 if (DemandedElts[i]) { 2787 unsigned Ofs = (i % Scale) * EltSizeInBits; 2788 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits); 2789 } 2790 2791 KnownBits Known; 2792 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known, 2793 TLO, Depth + 1)) 2794 return true; 2795 2796 // The bitcast has split each wide element into a number of 2797 // narrow subelements. We have just computed the Known bits 2798 // for wide elements. See if element splitting results in 2799 // some subelements being zero. Only for demanded elements! 2800 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) { 2801 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits) 2802 .isAllOnes()) 2803 continue; 2804 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) { 2805 unsigned Elt = Scale * SrcElt + SubElt; 2806 if (DemandedElts[Elt]) 2807 KnownZero.setBit(Elt); 2808 } 2809 } 2810 } 2811 2812 // If the src element is zero/undef then all the output elements will be - 2813 // only demanded elements are guaranteed to be correct. 2814 for (unsigned i = 0; i != NumSrcElts; ++i) { 2815 if (SrcDemandedElts[i]) { 2816 if (SrcZero[i]) 2817 KnownZero.setBits(i * Scale, (i + 1) * Scale); 2818 if (SrcUndef[i]) 2819 KnownUndef.setBits(i * Scale, (i + 1) * Scale); 2820 } 2821 } 2822 } 2823 2824 // Bitcast from 'small element' src vector to 'large element' vector, we 2825 // demand all smaller source elements covered by the larger demanded element 2826 // of this vector. 2827 if ((NumSrcElts % NumElts) == 0) { 2828 unsigned Scale = NumSrcElts / NumElts; 2829 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2830 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2831 TLO, Depth + 1)) 2832 return true; 2833 2834 // If all the src elements covering an output element are zero/undef, then 2835 // the output element will be as well, assuming it was demanded. 2836 for (unsigned i = 0; i != NumElts; ++i) { 2837 if (DemandedElts[i]) { 2838 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes()) 2839 KnownZero.setBit(i); 2840 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes()) 2841 KnownUndef.setBit(i); 2842 } 2843 } 2844 } 2845 break; 2846 } 2847 case ISD::BUILD_VECTOR: { 2848 // Check all elements and simplify any unused elements with UNDEF. 2849 if (!DemandedElts.isAllOnes()) { 2850 // Don't simplify BROADCASTS. 2851 if (llvm::any_of(Op->op_values(), 2852 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) { 2853 SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end()); 2854 bool Updated = false; 2855 for (unsigned i = 0; i != NumElts; ++i) { 2856 if (!DemandedElts[i] && !Ops[i].isUndef()) { 2857 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType()); 2858 KnownUndef.setBit(i); 2859 Updated = true; 2860 } 2861 } 2862 if (Updated) 2863 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops)); 2864 } 2865 } 2866 for (unsigned i = 0; i != NumElts; ++i) { 2867 SDValue SrcOp = Op.getOperand(i); 2868 if (SrcOp.isUndef()) { 2869 KnownUndef.setBit(i); 2870 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() && 2871 (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) { 2872 KnownZero.setBit(i); 2873 } 2874 } 2875 break; 2876 } 2877 case ISD::CONCAT_VECTORS: { 2878 EVT SubVT = Op.getOperand(0).getValueType(); 2879 unsigned NumSubVecs = Op.getNumOperands(); 2880 unsigned NumSubElts = SubVT.getVectorNumElements(); 2881 for (unsigned i = 0; i != NumSubVecs; ++i) { 2882 SDValue SubOp = Op.getOperand(i); 2883 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 2884 APInt SubUndef, SubZero; 2885 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO, 2886 Depth + 1)) 2887 return true; 2888 KnownUndef.insertBits(SubUndef, i * NumSubElts); 2889 KnownZero.insertBits(SubZero, i * NumSubElts); 2890 } 2891 2892 // Attempt to avoid multi-use ops if we don't need anything from them. 2893 if (!DemandedElts.isAllOnes()) { 2894 bool FoundNewSub = false; 2895 SmallVector<SDValue, 2> DemandedSubOps; 2896 for (unsigned i = 0; i != NumSubVecs; ++i) { 2897 SDValue SubOp = Op.getOperand(i); 2898 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 2899 SDValue NewSubOp = SimplifyMultipleUseDemandedVectorElts( 2900 SubOp, SubElts, TLO.DAG, Depth + 1); 2901 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp); 2902 FoundNewSub = NewSubOp ? true : FoundNewSub; 2903 } 2904 if (FoundNewSub) { 2905 SDValue NewOp = 2906 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps); 2907 return TLO.CombineTo(Op, NewOp); 2908 } 2909 } 2910 break; 2911 } 2912 case ISD::INSERT_SUBVECTOR: { 2913 // Demand any elements from the subvector and the remainder from the src its 2914 // inserted into. 2915 SDValue Src = Op.getOperand(0); 2916 SDValue Sub = Op.getOperand(1); 2917 uint64_t Idx = Op.getConstantOperandVal(2); 2918 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2919 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2920 APInt DemandedSrcElts = DemandedElts; 2921 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 2922 2923 APInt SubUndef, SubZero; 2924 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO, 2925 Depth + 1)) 2926 return true; 2927 2928 // If none of the src operand elements are demanded, replace it with undef. 2929 if (!DemandedSrcElts && !Src.isUndef()) 2930 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 2931 TLO.DAG.getUNDEF(VT), Sub, 2932 Op.getOperand(2))); 2933 2934 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero, 2935 TLO, Depth + 1)) 2936 return true; 2937 KnownUndef.insertBits(SubUndef, Idx); 2938 KnownZero.insertBits(SubZero, Idx); 2939 2940 // Attempt to avoid multi-use ops if we don't need anything from them. 2941 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) { 2942 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 2943 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 2944 SDValue NewSub = SimplifyMultipleUseDemandedVectorElts( 2945 Sub, DemandedSubElts, TLO.DAG, Depth + 1); 2946 if (NewSrc || NewSub) { 2947 NewSrc = NewSrc ? NewSrc : Src; 2948 NewSub = NewSub ? NewSub : Sub; 2949 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 2950 NewSub, Op.getOperand(2)); 2951 return TLO.CombineTo(Op, NewOp); 2952 } 2953 } 2954 break; 2955 } 2956 case ISD::EXTRACT_SUBVECTOR: { 2957 // Offset the demanded elts by the subvector index. 2958 SDValue Src = Op.getOperand(0); 2959 if (Src.getValueType().isScalableVector()) 2960 break; 2961 uint64_t Idx = Op.getConstantOperandVal(1); 2962 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2963 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 2964 2965 APInt SrcUndef, SrcZero; 2966 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 2967 Depth + 1)) 2968 return true; 2969 KnownUndef = SrcUndef.extractBits(NumElts, Idx); 2970 KnownZero = SrcZero.extractBits(NumElts, Idx); 2971 2972 // Attempt to avoid multi-use ops if we don't need anything from them. 2973 if (!DemandedElts.isAllOnes()) { 2974 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 2975 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 2976 if (NewSrc) { 2977 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 2978 Op.getOperand(1)); 2979 return TLO.CombineTo(Op, NewOp); 2980 } 2981 } 2982 break; 2983 } 2984 case ISD::INSERT_VECTOR_ELT: { 2985 SDValue Vec = Op.getOperand(0); 2986 SDValue Scl = Op.getOperand(1); 2987 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 2988 2989 // For a legal, constant insertion index, if we don't need this insertion 2990 // then strip it, else remove it from the demanded elts. 2991 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) { 2992 unsigned Idx = CIdx->getZExtValue(); 2993 if (!DemandedElts[Idx]) 2994 return TLO.CombineTo(Op, Vec); 2995 2996 APInt DemandedVecElts(DemandedElts); 2997 DemandedVecElts.clearBit(Idx); 2998 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef, 2999 KnownZero, TLO, Depth + 1)) 3000 return true; 3001 3002 KnownUndef.setBitVal(Idx, Scl.isUndef()); 3003 3004 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl)); 3005 break; 3006 } 3007 3008 APInt VecUndef, VecZero; 3009 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO, 3010 Depth + 1)) 3011 return true; 3012 // Without knowing the insertion index we can't set KnownUndef/KnownZero. 3013 break; 3014 } 3015 case ISD::VSELECT: { 3016 // Try to transform the select condition based on the current demanded 3017 // elements. 3018 // TODO: If a condition element is undef, we can choose from one arm of the 3019 // select (and if one arm is undef, then we can propagate that to the 3020 // result). 3021 // TODO - add support for constant vselect masks (see IR version of this). 3022 APInt UnusedUndef, UnusedZero; 3023 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef, 3024 UnusedZero, TLO, Depth + 1)) 3025 return true; 3026 3027 // See if we can simplify either vselect operand. 3028 APInt DemandedLHS(DemandedElts); 3029 APInt DemandedRHS(DemandedElts); 3030 APInt UndefLHS, ZeroLHS; 3031 APInt UndefRHS, ZeroRHS; 3032 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS, 3033 ZeroLHS, TLO, Depth + 1)) 3034 return true; 3035 if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS, 3036 ZeroRHS, TLO, Depth + 1)) 3037 return true; 3038 3039 KnownUndef = UndefLHS & UndefRHS; 3040 KnownZero = ZeroLHS & ZeroRHS; 3041 break; 3042 } 3043 case ISD::VECTOR_SHUFFLE: { 3044 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 3045 3046 // Collect demanded elements from shuffle operands.. 3047 APInt DemandedLHS(NumElts, 0); 3048 APInt DemandedRHS(NumElts, 0); 3049 for (unsigned i = 0; i != NumElts; ++i) { 3050 int M = ShuffleMask[i]; 3051 if (M < 0 || !DemandedElts[i]) 3052 continue; 3053 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 3054 if (M < (int)NumElts) 3055 DemandedLHS.setBit(M); 3056 else 3057 DemandedRHS.setBit(M - NumElts); 3058 } 3059 3060 // See if we can simplify either shuffle operand. 3061 APInt UndefLHS, ZeroLHS; 3062 APInt UndefRHS, ZeroRHS; 3063 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS, 3064 ZeroLHS, TLO, Depth + 1)) 3065 return true; 3066 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS, 3067 ZeroRHS, TLO, Depth + 1)) 3068 return true; 3069 3070 // Simplify mask using undef elements from LHS/RHS. 3071 bool Updated = false; 3072 bool IdentityLHS = true, IdentityRHS = true; 3073 SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end()); 3074 for (unsigned i = 0; i != NumElts; ++i) { 3075 int &M = NewMask[i]; 3076 if (M < 0) 3077 continue; 3078 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) || 3079 (M >= (int)NumElts && UndefRHS[M - NumElts])) { 3080 Updated = true; 3081 M = -1; 3082 } 3083 IdentityLHS &= (M < 0) || (M == (int)i); 3084 IdentityRHS &= (M < 0) || ((M - NumElts) == i); 3085 } 3086 3087 // Update legal shuffle masks based on demanded elements if it won't reduce 3088 // to Identity which can cause premature removal of the shuffle mask. 3089 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) { 3090 SDValue LegalShuffle = 3091 buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1), 3092 NewMask, TLO.DAG); 3093 if (LegalShuffle) 3094 return TLO.CombineTo(Op, LegalShuffle); 3095 } 3096 3097 // Propagate undef/zero elements from LHS/RHS. 3098 for (unsigned i = 0; i != NumElts; ++i) { 3099 int M = ShuffleMask[i]; 3100 if (M < 0) { 3101 KnownUndef.setBit(i); 3102 } else if (M < (int)NumElts) { 3103 if (UndefLHS[M]) 3104 KnownUndef.setBit(i); 3105 if (ZeroLHS[M]) 3106 KnownZero.setBit(i); 3107 } else { 3108 if (UndefRHS[M - NumElts]) 3109 KnownUndef.setBit(i); 3110 if (ZeroRHS[M - NumElts]) 3111 KnownZero.setBit(i); 3112 } 3113 } 3114 break; 3115 } 3116 case ISD::ANY_EXTEND_VECTOR_INREG: 3117 case ISD::SIGN_EXTEND_VECTOR_INREG: 3118 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3119 APInt SrcUndef, SrcZero; 3120 SDValue Src = Op.getOperand(0); 3121 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3122 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts); 3123 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 3124 Depth + 1)) 3125 return true; 3126 KnownZero = SrcZero.zextOrTrunc(NumElts); 3127 KnownUndef = SrcUndef.zextOrTrunc(NumElts); 3128 3129 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG && 3130 Op.getValueSizeInBits() == Src.getValueSizeInBits() && 3131 DemandedSrcElts == 1) { 3132 // aext - if we just need the bottom element then we can bitcast. 3133 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 3134 } 3135 3136 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { 3137 // zext(undef) upper bits are guaranteed to be zero. 3138 if (DemandedElts.isSubsetOf(KnownUndef)) 3139 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3140 KnownUndef.clearAllBits(); 3141 3142 // zext - if we just need the bottom element then we can mask: 3143 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and. 3144 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND && 3145 Op->isOnlyUserOf(Src.getNode()) && 3146 Op.getValueSizeInBits() == Src.getValueSizeInBits()) { 3147 SDLoc DL(Op); 3148 EVT SrcVT = Src.getValueType(); 3149 EVT SrcSVT = SrcVT.getScalarType(); 3150 SmallVector<SDValue> MaskElts; 3151 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT)); 3152 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT)); 3153 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts); 3154 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic( 3155 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) { 3156 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold); 3157 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold)); 3158 } 3159 } 3160 } 3161 break; 3162 } 3163 3164 // TODO: There are more binop opcodes that could be handled here - MIN, 3165 // MAX, saturated math, etc. 3166 case ISD::ADD: { 3167 SDValue Op0 = Op.getOperand(0); 3168 SDValue Op1 = Op.getOperand(1); 3169 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) { 3170 APInt UndefLHS, ZeroLHS; 3171 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3172 Depth + 1, /*AssumeSingleUse*/ true)) 3173 return true; 3174 } 3175 LLVM_FALLTHROUGH; 3176 } 3177 case ISD::OR: 3178 case ISD::XOR: 3179 case ISD::SUB: 3180 case ISD::FADD: 3181 case ISD::FSUB: 3182 case ISD::FMUL: 3183 case ISD::FDIV: 3184 case ISD::FREM: { 3185 SDValue Op0 = Op.getOperand(0); 3186 SDValue Op1 = Op.getOperand(1); 3187 3188 APInt UndefRHS, ZeroRHS; 3189 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3190 Depth + 1)) 3191 return true; 3192 APInt UndefLHS, ZeroLHS; 3193 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3194 Depth + 1)) 3195 return true; 3196 3197 KnownZero = ZeroLHS & ZeroRHS; 3198 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS); 3199 3200 // Attempt to avoid multi-use ops if we don't need anything from them. 3201 // TODO - use KnownUndef to relax the demandedelts? 3202 if (!DemandedElts.isAllOnes()) 3203 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3204 return true; 3205 break; 3206 } 3207 case ISD::SHL: 3208 case ISD::SRL: 3209 case ISD::SRA: 3210 case ISD::ROTL: 3211 case ISD::ROTR: { 3212 SDValue Op0 = Op.getOperand(0); 3213 SDValue Op1 = Op.getOperand(1); 3214 3215 APInt UndefRHS, ZeroRHS; 3216 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3217 Depth + 1)) 3218 return true; 3219 APInt UndefLHS, ZeroLHS; 3220 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3221 Depth + 1)) 3222 return true; 3223 3224 KnownZero = ZeroLHS; 3225 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop? 3226 3227 // Attempt to avoid multi-use ops if we don't need anything from them. 3228 // TODO - use KnownUndef to relax the demandedelts? 3229 if (!DemandedElts.isAllOnes()) 3230 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3231 return true; 3232 break; 3233 } 3234 case ISD::MUL: 3235 case ISD::AND: { 3236 SDValue Op0 = Op.getOperand(0); 3237 SDValue Op1 = Op.getOperand(1); 3238 3239 APInt SrcUndef, SrcZero; 3240 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO, 3241 Depth + 1)) 3242 return true; 3243 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero, 3244 TLO, Depth + 1)) 3245 return true; 3246 3247 // If either side has a zero element, then the result element is zero, even 3248 // if the other is an UNDEF. 3249 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros 3250 // and then handle 'and' nodes with the rest of the binop opcodes. 3251 KnownZero |= SrcZero; 3252 KnownUndef &= SrcUndef; 3253 KnownUndef &= ~KnownZero; 3254 3255 // Attempt to avoid multi-use ops if we don't need anything from them. 3256 // TODO - use KnownUndef to relax the demandedelts? 3257 if (!DemandedElts.isAllOnes()) 3258 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3259 return true; 3260 break; 3261 } 3262 case ISD::TRUNCATE: 3263 case ISD::SIGN_EXTEND: 3264 case ISD::ZERO_EXTEND: 3265 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 3266 KnownZero, TLO, Depth + 1)) 3267 return true; 3268 3269 if (Op.getOpcode() == ISD::ZERO_EXTEND) { 3270 // zext(undef) upper bits are guaranteed to be zero. 3271 if (DemandedElts.isSubsetOf(KnownUndef)) 3272 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3273 KnownUndef.clearAllBits(); 3274 } 3275 break; 3276 default: { 3277 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 3278 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef, 3279 KnownZero, TLO, Depth)) 3280 return true; 3281 } else { 3282 KnownBits Known; 3283 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits); 3284 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known, 3285 TLO, Depth, AssumeSingleUse)) 3286 return true; 3287 } 3288 break; 3289 } 3290 } 3291 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero"); 3292 3293 // Constant fold all undef cases. 3294 // TODO: Handle zero cases as well. 3295 if (DemandedElts.isSubsetOf(KnownUndef)) 3296 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 3297 3298 return false; 3299 } 3300 3301 /// Determine which of the bits specified in Mask are known to be either zero or 3302 /// one and return them in the Known. 3303 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 3304 KnownBits &Known, 3305 const APInt &DemandedElts, 3306 const SelectionDAG &DAG, 3307 unsigned Depth) const { 3308 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3309 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3310 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3311 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3312 "Should use MaskedValueIsZero if you don't know whether Op" 3313 " is a target node!"); 3314 Known.resetAll(); 3315 } 3316 3317 void TargetLowering::computeKnownBitsForTargetInstr( 3318 GISelKnownBits &Analysis, Register R, KnownBits &Known, 3319 const APInt &DemandedElts, const MachineRegisterInfo &MRI, 3320 unsigned Depth) const { 3321 Known.resetAll(); 3322 } 3323 3324 void TargetLowering::computeKnownBitsForFrameIndex( 3325 const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const { 3326 // The low bits are known zero if the pointer is aligned. 3327 Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx))); 3328 } 3329 3330 Align TargetLowering::computeKnownAlignForTargetInstr( 3331 GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI, 3332 unsigned Depth) const { 3333 return Align(1); 3334 } 3335 3336 /// This method can be implemented by targets that want to expose additional 3337 /// information about sign bits to the DAG Combiner. 3338 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 3339 const APInt &, 3340 const SelectionDAG &, 3341 unsigned Depth) const { 3342 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3343 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3344 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3345 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3346 "Should use ComputeNumSignBits if you don't know whether Op" 3347 " is a target node!"); 3348 return 1; 3349 } 3350 3351 unsigned TargetLowering::computeNumSignBitsForTargetInstr( 3352 GISelKnownBits &Analysis, Register R, const APInt &DemandedElts, 3353 const MachineRegisterInfo &MRI, unsigned Depth) const { 3354 return 1; 3355 } 3356 3357 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode( 3358 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero, 3359 TargetLoweringOpt &TLO, unsigned Depth) const { 3360 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3361 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3362 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3363 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3364 "Should use SimplifyDemandedVectorElts if you don't know whether Op" 3365 " is a target node!"); 3366 return false; 3367 } 3368 3369 bool TargetLowering::SimplifyDemandedBitsForTargetNode( 3370 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3371 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const { 3372 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3373 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3374 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3375 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3376 "Should use SimplifyDemandedBits if you don't know whether Op" 3377 " is a target node!"); 3378 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth); 3379 return false; 3380 } 3381 3382 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode( 3383 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3384 SelectionDAG &DAG, unsigned Depth) const { 3385 assert( 3386 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3387 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3388 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3389 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3390 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op" 3391 " is a target node!"); 3392 return SDValue(); 3393 } 3394 3395 SDValue 3396 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, 3397 SDValue N1, MutableArrayRef<int> Mask, 3398 SelectionDAG &DAG) const { 3399 bool LegalMask = isShuffleMaskLegal(Mask, VT); 3400 if (!LegalMask) { 3401 std::swap(N0, N1); 3402 ShuffleVectorSDNode::commuteMask(Mask); 3403 LegalMask = isShuffleMaskLegal(Mask, VT); 3404 } 3405 3406 if (!LegalMask) 3407 return SDValue(); 3408 3409 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask); 3410 } 3411 3412 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const { 3413 return nullptr; 3414 } 3415 3416 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode( 3417 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 3418 bool PoisonOnly, unsigned Depth) const { 3419 assert( 3420 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3421 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3422 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3423 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3424 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op" 3425 " is a target node!"); 3426 return false; 3427 } 3428 3429 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 3430 const SelectionDAG &DAG, 3431 bool SNaN, 3432 unsigned Depth) const { 3433 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3434 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3435 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3436 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3437 "Should use isKnownNeverNaN if you don't know whether Op" 3438 " is a target node!"); 3439 return false; 3440 } 3441 3442 bool TargetLowering::isSplatValueForTargetNode(SDValue Op, 3443 const APInt &DemandedElts, 3444 APInt &UndefElts, 3445 unsigned Depth) const { 3446 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3447 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3448 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3449 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3450 "Should use isSplatValue if you don't know whether Op" 3451 " is a target node!"); 3452 return false; 3453 } 3454 3455 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must 3456 // work with truncating build vectors and vectors with elements of less than 3457 // 8 bits. 3458 bool TargetLowering::isConstTrueVal(SDValue N) const { 3459 if (!N) 3460 return false; 3461 3462 unsigned EltWidth; 3463 APInt CVal; 3464 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false, 3465 /*AllowTruncation=*/true)) { 3466 CVal = CN->getAPIntValue(); 3467 EltWidth = N.getValueType().getScalarSizeInBits(); 3468 } else 3469 return false; 3470 3471 // If this is a truncating splat, truncate the splat value. 3472 // Otherwise, we may fail to match the expected values below. 3473 if (EltWidth < CVal.getBitWidth()) 3474 CVal = CVal.trunc(EltWidth); 3475 3476 switch (getBooleanContents(N.getValueType())) { 3477 case UndefinedBooleanContent: 3478 return CVal[0]; 3479 case ZeroOrOneBooleanContent: 3480 return CVal.isOne(); 3481 case ZeroOrNegativeOneBooleanContent: 3482 return CVal.isAllOnes(); 3483 } 3484 3485 llvm_unreachable("Invalid boolean contents"); 3486 } 3487 3488 bool TargetLowering::isConstFalseVal(SDValue N) const { 3489 if (!N) 3490 return false; 3491 3492 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 3493 if (!CN) { 3494 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 3495 if (!BV) 3496 return false; 3497 3498 // Only interested in constant splats, we don't care about undef 3499 // elements in identifying boolean constants and getConstantSplatNode 3500 // returns NULL if all ops are undef; 3501 CN = BV->getConstantSplatNode(); 3502 if (!CN) 3503 return false; 3504 } 3505 3506 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 3507 return !CN->getAPIntValue()[0]; 3508 3509 return CN->isZero(); 3510 } 3511 3512 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 3513 bool SExt) const { 3514 if (VT == MVT::i1) 3515 return N->isOne(); 3516 3517 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 3518 switch (Cnt) { 3519 case TargetLowering::ZeroOrOneBooleanContent: 3520 // An extended value of 1 is always true, unless its original type is i1, 3521 // in which case it will be sign extended to -1. 3522 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 3523 case TargetLowering::UndefinedBooleanContent: 3524 case TargetLowering::ZeroOrNegativeOneBooleanContent: 3525 return N->isAllOnes() && SExt; 3526 } 3527 llvm_unreachable("Unexpected enumeration."); 3528 } 3529 3530 /// This helper function of SimplifySetCC tries to optimize the comparison when 3531 /// either operand of the SetCC node is a bitwise-and instruction. 3532 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 3533 ISD::CondCode Cond, const SDLoc &DL, 3534 DAGCombinerInfo &DCI) const { 3535 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 3536 std::swap(N0, N1); 3537 3538 SelectionDAG &DAG = DCI.DAG; 3539 EVT OpVT = N0.getValueType(); 3540 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 3541 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 3542 return SDValue(); 3543 3544 // (X & Y) != 0 --> zextOrTrunc(X & Y) 3545 // iff everything but LSB is known zero: 3546 if (Cond == ISD::SETNE && isNullConstant(N1) && 3547 (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent || 3548 getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) { 3549 unsigned NumEltBits = OpVT.getScalarSizeInBits(); 3550 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1); 3551 if (DAG.MaskedValueIsZero(N0, UpperBits)) 3552 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT); 3553 } 3554 3555 // Match these patterns in any of their permutations: 3556 // (X & Y) == Y 3557 // (X & Y) != Y 3558 SDValue X, Y; 3559 if (N0.getOperand(0) == N1) { 3560 X = N0.getOperand(1); 3561 Y = N0.getOperand(0); 3562 } else if (N0.getOperand(1) == N1) { 3563 X = N0.getOperand(0); 3564 Y = N0.getOperand(1); 3565 } else { 3566 return SDValue(); 3567 } 3568 3569 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3570 if (DAG.isKnownToBeAPowerOfTwo(Y)) { 3571 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 3572 // Note that where Y is variable and is known to have at most one bit set 3573 // (for example, if it is Z & 1) we cannot do this; the expressions are not 3574 // equivalent when Y == 0. 3575 assert(OpVT.isInteger()); 3576 Cond = ISD::getSetCCInverse(Cond, OpVT); 3577 if (DCI.isBeforeLegalizeOps() || 3578 isCondCodeLegal(Cond, N0.getSimpleValueType())) 3579 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 3580 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 3581 // If the target supports an 'and-not' or 'and-complement' logic operation, 3582 // try to use that to make a comparison operation more efficient. 3583 // But don't do this transform if the mask is a single bit because there are 3584 // more efficient ways to deal with that case (for example, 'bt' on x86 or 3585 // 'rlwinm' on PPC). 3586 3587 // Bail out if the compare operand that we want to turn into a zero is 3588 // already a zero (otherwise, infinite loop). 3589 auto *YConst = dyn_cast<ConstantSDNode>(Y); 3590 if (YConst && YConst->isZero()) 3591 return SDValue(); 3592 3593 // Transform this into: ~X & Y == 0. 3594 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 3595 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 3596 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 3597 } 3598 3599 return SDValue(); 3600 } 3601 3602 /// There are multiple IR patterns that could be checking whether certain 3603 /// truncation of a signed number would be lossy or not. The pattern which is 3604 /// best at IR level, may not lower optimally. Thus, we want to unfold it. 3605 /// We are looking for the following pattern: (KeptBits is a constant) 3606 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits) 3607 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false. 3608 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0 3609 /// We will unfold it into the natural trunc+sext pattern: 3610 /// ((%x << C) a>> C) dstcond %x 3611 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x) 3612 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck( 3613 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI, 3614 const SDLoc &DL) const { 3615 // We must be comparing with a constant. 3616 ConstantSDNode *C1; 3617 if (!(C1 = dyn_cast<ConstantSDNode>(N1))) 3618 return SDValue(); 3619 3620 // N0 should be: add %x, (1 << (KeptBits-1)) 3621 if (N0->getOpcode() != ISD::ADD) 3622 return SDValue(); 3623 3624 // And we must be 'add'ing a constant. 3625 ConstantSDNode *C01; 3626 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1)))) 3627 return SDValue(); 3628 3629 SDValue X = N0->getOperand(0); 3630 EVT XVT = X.getValueType(); 3631 3632 // Validate constants ... 3633 3634 APInt I1 = C1->getAPIntValue(); 3635 3636 ISD::CondCode NewCond; 3637 if (Cond == ISD::CondCode::SETULT) { 3638 NewCond = ISD::CondCode::SETEQ; 3639 } else if (Cond == ISD::CondCode::SETULE) { 3640 NewCond = ISD::CondCode::SETEQ; 3641 // But need to 'canonicalize' the constant. 3642 I1 += 1; 3643 } else if (Cond == ISD::CondCode::SETUGT) { 3644 NewCond = ISD::CondCode::SETNE; 3645 // But need to 'canonicalize' the constant. 3646 I1 += 1; 3647 } else if (Cond == ISD::CondCode::SETUGE) { 3648 NewCond = ISD::CondCode::SETNE; 3649 } else 3650 return SDValue(); 3651 3652 APInt I01 = C01->getAPIntValue(); 3653 3654 auto checkConstants = [&I1, &I01]() -> bool { 3655 // Both of them must be power-of-two, and the constant from setcc is bigger. 3656 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2(); 3657 }; 3658 3659 if (checkConstants()) { 3660 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256 3661 } else { 3662 // What if we invert constants? (and the target predicate) 3663 I1.negate(); 3664 I01.negate(); 3665 assert(XVT.isInteger()); 3666 NewCond = getSetCCInverse(NewCond, XVT); 3667 if (!checkConstants()) 3668 return SDValue(); 3669 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256 3670 } 3671 3672 // They are power-of-two, so which bit is set? 3673 const unsigned KeptBits = I1.logBase2(); 3674 const unsigned KeptBitsMinusOne = I01.logBase2(); 3675 3676 // Magic! 3677 if (KeptBits != (KeptBitsMinusOne + 1)) 3678 return SDValue(); 3679 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable"); 3680 3681 // We don't want to do this in every single case. 3682 SelectionDAG &DAG = DCI.DAG; 3683 if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck( 3684 XVT, KeptBits)) 3685 return SDValue(); 3686 3687 const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits; 3688 assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable"); 3689 3690 // Unfold into: ((%x << C) a>> C) cond %x 3691 // Where 'cond' will be either 'eq' or 'ne'. 3692 SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT); 3693 SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt); 3694 SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt); 3695 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond); 3696 3697 return T2; 3698 } 3699 3700 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 3701 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift( 3702 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond, 3703 DAGCombinerInfo &DCI, const SDLoc &DL) const { 3704 assert(isConstOrConstSplat(N1C) && 3705 isConstOrConstSplat(N1C)->getAPIntValue().isZero() && 3706 "Should be a comparison with 0."); 3707 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3708 "Valid only for [in]equality comparisons."); 3709 3710 unsigned NewShiftOpcode; 3711 SDValue X, C, Y; 3712 3713 SelectionDAG &DAG = DCI.DAG; 3714 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3715 3716 // Look for '(C l>>/<< Y)'. 3717 auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) { 3718 // The shift should be one-use. 3719 if (!V.hasOneUse()) 3720 return false; 3721 unsigned OldShiftOpcode = V.getOpcode(); 3722 switch (OldShiftOpcode) { 3723 case ISD::SHL: 3724 NewShiftOpcode = ISD::SRL; 3725 break; 3726 case ISD::SRL: 3727 NewShiftOpcode = ISD::SHL; 3728 break; 3729 default: 3730 return false; // must be a logical shift. 3731 } 3732 // We should be shifting a constant. 3733 // FIXME: best to use isConstantOrConstantVector(). 3734 C = V.getOperand(0); 3735 ConstantSDNode *CC = 3736 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3737 if (!CC) 3738 return false; 3739 Y = V.getOperand(1); 3740 3741 ConstantSDNode *XC = 3742 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3743 return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 3744 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG); 3745 }; 3746 3747 // LHS of comparison should be an one-use 'and'. 3748 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 3749 return SDValue(); 3750 3751 X = N0.getOperand(0); 3752 SDValue Mask = N0.getOperand(1); 3753 3754 // 'and' is commutative! 3755 if (!Match(Mask)) { 3756 std::swap(X, Mask); 3757 if (!Match(Mask)) 3758 return SDValue(); 3759 } 3760 3761 EVT VT = X.getValueType(); 3762 3763 // Produce: 3764 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0 3765 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y); 3766 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C); 3767 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond); 3768 return T2; 3769 } 3770 3771 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as 3772 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to 3773 /// handle the commuted versions of these patterns. 3774 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, 3775 ISD::CondCode Cond, const SDLoc &DL, 3776 DAGCombinerInfo &DCI) const { 3777 unsigned BOpcode = N0.getOpcode(); 3778 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) && 3779 "Unexpected binop"); 3780 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode"); 3781 3782 // (X + Y) == X --> Y == 0 3783 // (X - Y) == X --> Y == 0 3784 // (X ^ Y) == X --> Y == 0 3785 SelectionDAG &DAG = DCI.DAG; 3786 EVT OpVT = N0.getValueType(); 3787 SDValue X = N0.getOperand(0); 3788 SDValue Y = N0.getOperand(1); 3789 if (X == N1) 3790 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond); 3791 3792 if (Y != N1) 3793 return SDValue(); 3794 3795 // (X + Y) == Y --> X == 0 3796 // (X ^ Y) == Y --> X == 0 3797 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR) 3798 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond); 3799 3800 // The shift would not be valid if the operands are boolean (i1). 3801 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1) 3802 return SDValue(); 3803 3804 // (X - Y) == Y --> X == Y << 1 3805 EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(), 3806 !DCI.isBeforeLegalize()); 3807 SDValue One = DAG.getConstant(1, DL, ShiftVT); 3808 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One); 3809 if (!DCI.isCalledByLegalizer()) 3810 DCI.AddToWorklist(YShl1.getNode()); 3811 return DAG.getSetCC(DL, VT, X, YShl1, Cond); 3812 } 3813 3814 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT, 3815 SDValue N0, const APInt &C1, 3816 ISD::CondCode Cond, const SDLoc &dl, 3817 SelectionDAG &DAG) { 3818 // Look through truncs that don't change the value of a ctpop. 3819 // FIXME: Add vector support? Need to be careful with setcc result type below. 3820 SDValue CTPOP = N0; 3821 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() && 3822 N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits())) 3823 CTPOP = N0.getOperand(0); 3824 3825 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse()) 3826 return SDValue(); 3827 3828 EVT CTVT = CTPOP.getValueType(); 3829 SDValue CTOp = CTPOP.getOperand(0); 3830 3831 // If this is a vector CTPOP, keep the CTPOP if it is legal. 3832 // TODO: Should we check if CTPOP is legal(or custom) for scalars? 3833 if (VT.isVector() && TLI.isOperationLegal(ISD::CTPOP, CTVT)) 3834 return SDValue(); 3835 3836 // (ctpop x) u< 2 -> (x & x-1) == 0 3837 // (ctpop x) u> 1 -> (x & x-1) != 0 3838 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) { 3839 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond); 3840 if (C1.ugt(CostLimit + (Cond == ISD::SETULT))) 3841 return SDValue(); 3842 if (C1 == 0 && (Cond == ISD::SETULT)) 3843 return SDValue(); // This is handled elsewhere. 3844 3845 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT); 3846 3847 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3848 SDValue Result = CTOp; 3849 for (unsigned i = 0; i < Passes; i++) { 3850 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne); 3851 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add); 3852 } 3853 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 3854 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC); 3855 } 3856 3857 // If ctpop is not supported, expand a power-of-2 comparison based on it. 3858 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) { 3859 // For scalars, keep CTPOP if it is legal or custom. 3860 if (!VT.isVector() && TLI.isOperationLegalOrCustom(ISD::CTPOP, CTVT)) 3861 return SDValue(); 3862 // This is based on X86's custom lowering for CTPOP which produces more 3863 // instructions than the expansion here. 3864 3865 // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0) 3866 // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0) 3867 SDValue Zero = DAG.getConstant(0, dl, CTVT); 3868 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3869 assert(CTVT.isInteger()); 3870 ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT); 3871 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne); 3872 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add); 3873 SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond); 3874 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond); 3875 unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR; 3876 return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS); 3877 } 3878 3879 return SDValue(); 3880 } 3881 3882 static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1, 3883 ISD::CondCode Cond, const SDLoc &dl, 3884 SelectionDAG &DAG) { 3885 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 3886 return SDValue(); 3887 3888 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 3889 if (!C1 || !(C1->isZero() || C1->isAllOnes())) 3890 return SDValue(); 3891 3892 auto getRotateSource = [](SDValue X) { 3893 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR) 3894 return X.getOperand(0); 3895 return SDValue(); 3896 }; 3897 3898 // Peek through a rotated value compared against 0 or -1: 3899 // (rot X, Y) == 0/-1 --> X == 0/-1 3900 // (rot X, Y) != 0/-1 --> X != 0/-1 3901 if (SDValue R = getRotateSource(N0)) 3902 return DAG.getSetCC(dl, VT, R, N1, Cond); 3903 3904 // Peek through an 'or' of a rotated value compared against 0: 3905 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0 3906 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0 3907 // 3908 // TODO: Add the 'and' with -1 sibling. 3909 // TODO: Recurse through a series of 'or' ops to find the rotate. 3910 EVT OpVT = N0.getValueType(); 3911 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) { 3912 if (SDValue R = getRotateSource(N0.getOperand(0))) { 3913 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1)); 3914 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 3915 } 3916 if (SDValue R = getRotateSource(N0.getOperand(1))) { 3917 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0)); 3918 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 3919 } 3920 } 3921 3922 return SDValue(); 3923 } 3924 3925 static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1, 3926 ISD::CondCode Cond, const SDLoc &dl, 3927 SelectionDAG &DAG) { 3928 // If we are testing for all-bits-clear, we might be able to do that with 3929 // less shifting since bit-order does not matter. 3930 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 3931 return SDValue(); 3932 3933 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 3934 if (!C1 || !C1->isZero()) 3935 return SDValue(); 3936 3937 if (!N0.hasOneUse() || 3938 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR)) 3939 return SDValue(); 3940 3941 unsigned BitWidth = N0.getScalarValueSizeInBits(); 3942 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2)); 3943 if (!ShAmtC || ShAmtC->getAPIntValue().uge(BitWidth)) 3944 return SDValue(); 3945 3946 // Canonicalize fshr as fshl to reduce pattern-matching. 3947 unsigned ShAmt = ShAmtC->getZExtValue(); 3948 if (N0.getOpcode() == ISD::FSHR) 3949 ShAmt = BitWidth - ShAmt; 3950 3951 // Match an 'or' with a specific operand 'Other' in either commuted variant. 3952 SDValue X, Y; 3953 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) { 3954 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse()) 3955 return false; 3956 if (Or.getOperand(0) == Other) { 3957 X = Or.getOperand(0); 3958 Y = Or.getOperand(1); 3959 return true; 3960 } 3961 if (Or.getOperand(1) == Other) { 3962 X = Or.getOperand(1); 3963 Y = Or.getOperand(0); 3964 return true; 3965 } 3966 return false; 3967 }; 3968 3969 EVT OpVT = N0.getValueType(); 3970 EVT ShAmtVT = N0.getOperand(2).getValueType(); 3971 SDValue F0 = N0.getOperand(0); 3972 SDValue F1 = N0.getOperand(1); 3973 if (matchOr(F0, F1)) { 3974 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0 3975 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT); 3976 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt); 3977 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 3978 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 3979 } 3980 if (matchOr(F1, F0)) { 3981 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0 3982 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT); 3983 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt); 3984 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 3985 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 3986 } 3987 3988 return SDValue(); 3989 } 3990 3991 /// Try to simplify a setcc built with the specified operands and cc. If it is 3992 /// unable to simplify it, return a null SDValue. 3993 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 3994 ISD::CondCode Cond, bool foldBooleans, 3995 DAGCombinerInfo &DCI, 3996 const SDLoc &dl) const { 3997 SelectionDAG &DAG = DCI.DAG; 3998 const DataLayout &Layout = DAG.getDataLayout(); 3999 EVT OpVT = N0.getValueType(); 4000 4001 // Constant fold or commute setcc. 4002 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl)) 4003 return Fold; 4004 4005 bool N0ConstOrSplat = 4006 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 4007 bool N1ConstOrSplat = 4008 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 4009 4010 // Ensure that the constant occurs on the RHS and fold constant comparisons. 4011 // TODO: Handle non-splat vector constants. All undef causes trouble. 4012 // FIXME: We can't yet fold constant scalable vector splats, so avoid an 4013 // infinite loop here when we encounter one. 4014 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 4015 if (N0ConstOrSplat && (!OpVT.isScalableVector() || !N1ConstOrSplat) && 4016 (DCI.isBeforeLegalizeOps() || 4017 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 4018 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4019 4020 // If we have a subtract with the same 2 non-constant operands as this setcc 4021 // -- but in reverse order -- then try to commute the operands of this setcc 4022 // to match. A matching pair of setcc (cmp) and sub may be combined into 1 4023 // instruction on some targets. 4024 if (!N0ConstOrSplat && !N1ConstOrSplat && 4025 (DCI.isBeforeLegalizeOps() || 4026 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) && 4027 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) && 4028 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1})) 4029 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4030 4031 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG)) 4032 return V; 4033 4034 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG)) 4035 return V; 4036 4037 if (auto *N1C = isConstOrConstSplat(N1)) { 4038 const APInt &C1 = N1C->getAPIntValue(); 4039 4040 // Optimize some CTPOP cases. 4041 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG)) 4042 return V; 4043 4044 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 4045 // equality comparison, then we're just comparing whether X itself is 4046 // zero. 4047 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) && 4048 N0.getOperand(0).getOpcode() == ISD::CTLZ && 4049 isPowerOf2_32(N0.getScalarValueSizeInBits())) { 4050 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) { 4051 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4052 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) { 4053 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 4054 // (srl (ctlz x), 5) == 0 -> X != 0 4055 // (srl (ctlz x), 5) != 1 -> X != 0 4056 Cond = ISD::SETNE; 4057 } else { 4058 // (srl (ctlz x), 5) != 0 -> X == 0 4059 // (srl (ctlz x), 5) == 1 -> X == 0 4060 Cond = ISD::SETEQ; 4061 } 4062 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 4063 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero, 4064 Cond); 4065 } 4066 } 4067 } 4068 } 4069 4070 // FIXME: Support vectors. 4071 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4072 const APInt &C1 = N1C->getAPIntValue(); 4073 4074 // (zext x) == C --> x == (trunc C) 4075 // (sext x) == C --> x == (trunc C) 4076 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4077 DCI.isBeforeLegalize() && N0->hasOneUse()) { 4078 unsigned MinBits = N0.getValueSizeInBits(); 4079 SDValue PreExt; 4080 bool Signed = false; 4081 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 4082 // ZExt 4083 MinBits = N0->getOperand(0).getValueSizeInBits(); 4084 PreExt = N0->getOperand(0); 4085 } else if (N0->getOpcode() == ISD::AND) { 4086 // DAGCombine turns costly ZExts into ANDs 4087 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 4088 if ((C->getAPIntValue()+1).isPowerOf2()) { 4089 MinBits = C->getAPIntValue().countTrailingOnes(); 4090 PreExt = N0->getOperand(0); 4091 } 4092 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 4093 // SExt 4094 MinBits = N0->getOperand(0).getValueSizeInBits(); 4095 PreExt = N0->getOperand(0); 4096 Signed = true; 4097 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 4098 // ZEXTLOAD / SEXTLOAD 4099 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 4100 MinBits = LN0->getMemoryVT().getSizeInBits(); 4101 PreExt = N0; 4102 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 4103 Signed = true; 4104 MinBits = LN0->getMemoryVT().getSizeInBits(); 4105 PreExt = N0; 4106 } 4107 } 4108 4109 // Figure out how many bits we need to preserve this constant. 4110 unsigned ReqdBits = Signed ? C1.getMinSignedBits() : C1.getActiveBits(); 4111 4112 // Make sure we're not losing bits from the constant. 4113 if (MinBits > 0 && 4114 MinBits < C1.getBitWidth() && 4115 MinBits >= ReqdBits) { 4116 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 4117 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 4118 // Will get folded away. 4119 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 4120 if (MinBits == 1 && C1 == 1) 4121 // Invert the condition. 4122 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 4123 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4124 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 4125 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 4126 } 4127 4128 // If truncating the setcc operands is not desirable, we can still 4129 // simplify the expression in some cases: 4130 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 4131 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 4132 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 4133 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 4134 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 4135 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 4136 SDValue TopSetCC = N0->getOperand(0); 4137 unsigned N0Opc = N0->getOpcode(); 4138 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 4139 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 4140 TopSetCC.getOpcode() == ISD::SETCC && 4141 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 4142 (isConstFalseVal(N1) || 4143 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 4144 4145 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) || 4146 (!N1C->isZero() && Cond == ISD::SETNE); 4147 4148 if (!Inverse) 4149 return TopSetCC; 4150 4151 ISD::CondCode InvCond = ISD::getSetCCInverse( 4152 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 4153 TopSetCC.getOperand(0).getValueType()); 4154 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 4155 TopSetCC.getOperand(1), 4156 InvCond); 4157 } 4158 } 4159 } 4160 4161 // If the LHS is '(and load, const)', the RHS is 0, the test is for 4162 // equality or unsigned, and all 1 bits of the const are in the same 4163 // partial word, see if we can shorten the load. 4164 if (DCI.isBeforeLegalize() && 4165 !ISD::isSignedIntSetCC(Cond) && 4166 N0.getOpcode() == ISD::AND && C1 == 0 && 4167 N0.getNode()->hasOneUse() && 4168 isa<LoadSDNode>(N0.getOperand(0)) && 4169 N0.getOperand(0).getNode()->hasOneUse() && 4170 isa<ConstantSDNode>(N0.getOperand(1))) { 4171 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 4172 APInt bestMask; 4173 unsigned bestWidth = 0, bestOffset = 0; 4174 if (Lod->isSimple() && Lod->isUnindexed()) { 4175 unsigned origWidth = N0.getValueSizeInBits(); 4176 unsigned maskWidth = origWidth; 4177 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 4178 // 8 bits, but have to be careful... 4179 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 4180 origWidth = Lod->getMemoryVT().getSizeInBits(); 4181 const APInt &Mask = N0.getConstantOperandAPInt(1); 4182 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 4183 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 4184 for (unsigned offset=0; offset<origWidth/width; offset++) { 4185 if (Mask.isSubsetOf(newMask)) { 4186 if (Layout.isLittleEndian()) 4187 bestOffset = (uint64_t)offset * (width/8); 4188 else 4189 bestOffset = (origWidth/width - offset - 1) * (width/8); 4190 bestMask = Mask.lshr(offset * (width/8) * 8); 4191 bestWidth = width; 4192 break; 4193 } 4194 newMask <<= width; 4195 } 4196 } 4197 } 4198 if (bestWidth) { 4199 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 4200 if (newVT.isRound() && 4201 shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) { 4202 SDValue Ptr = Lod->getBasePtr(); 4203 if (bestOffset != 0) 4204 Ptr = 4205 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(bestOffset), dl); 4206 SDValue NewLoad = 4207 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr, 4208 Lod->getPointerInfo().getWithOffset(bestOffset), 4209 Lod->getOriginalAlign()); 4210 return DAG.getSetCC(dl, VT, 4211 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 4212 DAG.getConstant(bestMask.trunc(bestWidth), 4213 dl, newVT)), 4214 DAG.getConstant(0LL, dl, newVT), Cond); 4215 } 4216 } 4217 } 4218 4219 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 4220 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 4221 unsigned InSize = N0.getOperand(0).getValueSizeInBits(); 4222 4223 // If the comparison constant has bits in the upper part, the 4224 // zero-extended value could never match. 4225 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 4226 C1.getBitWidth() - InSize))) { 4227 switch (Cond) { 4228 case ISD::SETUGT: 4229 case ISD::SETUGE: 4230 case ISD::SETEQ: 4231 return DAG.getConstant(0, dl, VT); 4232 case ISD::SETULT: 4233 case ISD::SETULE: 4234 case ISD::SETNE: 4235 return DAG.getConstant(1, dl, VT); 4236 case ISD::SETGT: 4237 case ISD::SETGE: 4238 // True if the sign bit of C1 is set. 4239 return DAG.getConstant(C1.isNegative(), dl, VT); 4240 case ISD::SETLT: 4241 case ISD::SETLE: 4242 // True if the sign bit of C1 isn't set. 4243 return DAG.getConstant(C1.isNonNegative(), dl, VT); 4244 default: 4245 break; 4246 } 4247 } 4248 4249 // Otherwise, we can perform the comparison with the low bits. 4250 switch (Cond) { 4251 case ISD::SETEQ: 4252 case ISD::SETNE: 4253 case ISD::SETUGT: 4254 case ISD::SETUGE: 4255 case ISD::SETULT: 4256 case ISD::SETULE: { 4257 EVT newVT = N0.getOperand(0).getValueType(); 4258 if (DCI.isBeforeLegalizeOps() || 4259 (isOperationLegal(ISD::SETCC, newVT) && 4260 isCondCodeLegal(Cond, newVT.getSimpleVT()))) { 4261 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT); 4262 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 4263 4264 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 4265 NewConst, Cond); 4266 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 4267 } 4268 break; 4269 } 4270 default: 4271 break; // todo, be more careful with signed comparisons 4272 } 4273 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 4274 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4275 !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(), 4276 OpVT)) { 4277 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 4278 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 4279 EVT ExtDstTy = N0.getValueType(); 4280 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 4281 4282 // If the constant doesn't fit into the number of bits for the source of 4283 // the sign extension, it is impossible for both sides to be equal. 4284 if (C1.getMinSignedBits() > ExtSrcTyBits) 4285 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT); 4286 4287 assert(ExtDstTy == N0.getOperand(0).getValueType() && 4288 ExtDstTy != ExtSrcTy && "Unexpected types!"); 4289 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 4290 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0), 4291 DAG.getConstant(Imm, dl, ExtDstTy)); 4292 if (!DCI.isCalledByLegalizer()) 4293 DCI.AddToWorklist(ZextOp.getNode()); 4294 // Otherwise, make this a use of a zext. 4295 return DAG.getSetCC(dl, VT, ZextOp, 4296 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond); 4297 } else if ((N1C->isZero() || N1C->isOne()) && 4298 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4299 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 4300 if (N0.getOpcode() == ISD::SETCC && 4301 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) && 4302 (N0.getValueType() == MVT::i1 || 4303 getBooleanContents(N0.getOperand(0).getValueType()) == 4304 ZeroOrOneBooleanContent)) { 4305 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne()); 4306 if (TrueWhenTrue) 4307 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 4308 // Invert the condition. 4309 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4310 CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType()); 4311 if (DCI.isBeforeLegalizeOps() || 4312 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 4313 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 4314 } 4315 4316 if ((N0.getOpcode() == ISD::XOR || 4317 (N0.getOpcode() == ISD::AND && 4318 N0.getOperand(0).getOpcode() == ISD::XOR && 4319 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 4320 isOneConstant(N0.getOperand(1))) { 4321 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 4322 // can only do this if the top bits are known zero. 4323 unsigned BitWidth = N0.getValueSizeInBits(); 4324 if (DAG.MaskedValueIsZero(N0, 4325 APInt::getHighBitsSet(BitWidth, 4326 BitWidth-1))) { 4327 // Okay, get the un-inverted input value. 4328 SDValue Val; 4329 if (N0.getOpcode() == ISD::XOR) { 4330 Val = N0.getOperand(0); 4331 } else { 4332 assert(N0.getOpcode() == ISD::AND && 4333 N0.getOperand(0).getOpcode() == ISD::XOR); 4334 // ((X^1)&1)^1 -> X & 1 4335 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 4336 N0.getOperand(0).getOperand(0), 4337 N0.getOperand(1)); 4338 } 4339 4340 return DAG.getSetCC(dl, VT, Val, N1, 4341 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4342 } 4343 } else if (N1C->isOne()) { 4344 SDValue Op0 = N0; 4345 if (Op0.getOpcode() == ISD::TRUNCATE) 4346 Op0 = Op0.getOperand(0); 4347 4348 if ((Op0.getOpcode() == ISD::XOR) && 4349 Op0.getOperand(0).getOpcode() == ISD::SETCC && 4350 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 4351 SDValue XorLHS = Op0.getOperand(0); 4352 SDValue XorRHS = Op0.getOperand(1); 4353 // Ensure that the input setccs return an i1 type or 0/1 value. 4354 if (Op0.getValueType() == MVT::i1 || 4355 (getBooleanContents(XorLHS.getOperand(0).getValueType()) == 4356 ZeroOrOneBooleanContent && 4357 getBooleanContents(XorRHS.getOperand(0).getValueType()) == 4358 ZeroOrOneBooleanContent)) { 4359 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 4360 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 4361 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond); 4362 } 4363 } 4364 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) { 4365 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 4366 if (Op0.getValueType().bitsGT(VT)) 4367 Op0 = DAG.getNode(ISD::AND, dl, VT, 4368 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 4369 DAG.getConstant(1, dl, VT)); 4370 else if (Op0.getValueType().bitsLT(VT)) 4371 Op0 = DAG.getNode(ISD::AND, dl, VT, 4372 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 4373 DAG.getConstant(1, dl, VT)); 4374 4375 return DAG.getSetCC(dl, VT, Op0, 4376 DAG.getConstant(0, dl, Op0.getValueType()), 4377 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4378 } 4379 if (Op0.getOpcode() == ISD::AssertZext && 4380 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 4381 return DAG.getSetCC(dl, VT, Op0, 4382 DAG.getConstant(0, dl, Op0.getValueType()), 4383 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4384 } 4385 } 4386 4387 // Given: 4388 // icmp eq/ne (urem %x, %y), 0 4389 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem': 4390 // icmp eq/ne %x, 0 4391 if (N0.getOpcode() == ISD::UREM && N1C->isZero() && 4392 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4393 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0)); 4394 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1)); 4395 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2) 4396 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 4397 } 4398 4399 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0 4400 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0 4401 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4402 N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) && 4403 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 && 4404 N1C && N1C->isAllOnes()) { 4405 return DAG.getSetCC(dl, VT, N0.getOperand(0), 4406 DAG.getConstant(0, dl, OpVT), 4407 Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE); 4408 } 4409 4410 if (SDValue V = 4411 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl)) 4412 return V; 4413 } 4414 4415 // These simplifications apply to splat vectors as well. 4416 // TODO: Handle more splat vector cases. 4417 if (auto *N1C = isConstOrConstSplat(N1)) { 4418 const APInt &C1 = N1C->getAPIntValue(); 4419 4420 APInt MinVal, MaxVal; 4421 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits(); 4422 if (ISD::isSignedIntSetCC(Cond)) { 4423 MinVal = APInt::getSignedMinValue(OperandBitSize); 4424 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 4425 } else { 4426 MinVal = APInt::getMinValue(OperandBitSize); 4427 MaxVal = APInt::getMaxValue(OperandBitSize); 4428 } 4429 4430 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 4431 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 4432 // X >= MIN --> true 4433 if (C1 == MinVal) 4434 return DAG.getBoolConstant(true, dl, VT, OpVT); 4435 4436 if (!VT.isVector()) { // TODO: Support this for vectors. 4437 // X >= C0 --> X > (C0 - 1) 4438 APInt C = C1 - 1; 4439 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 4440 if ((DCI.isBeforeLegalizeOps() || 4441 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4442 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4443 isLegalICmpImmediate(C.getSExtValue())))) { 4444 return DAG.getSetCC(dl, VT, N0, 4445 DAG.getConstant(C, dl, N1.getValueType()), 4446 NewCC); 4447 } 4448 } 4449 } 4450 4451 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 4452 // X <= MAX --> true 4453 if (C1 == MaxVal) 4454 return DAG.getBoolConstant(true, dl, VT, OpVT); 4455 4456 // X <= C0 --> X < (C0 + 1) 4457 if (!VT.isVector()) { // TODO: Support this for vectors. 4458 APInt C = C1 + 1; 4459 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 4460 if ((DCI.isBeforeLegalizeOps() || 4461 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4462 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4463 isLegalICmpImmediate(C.getSExtValue())))) { 4464 return DAG.getSetCC(dl, VT, N0, 4465 DAG.getConstant(C, dl, N1.getValueType()), 4466 NewCC); 4467 } 4468 } 4469 } 4470 4471 if (Cond == ISD::SETLT || Cond == ISD::SETULT) { 4472 if (C1 == MinVal) 4473 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false 4474 4475 // TODO: Support this for vectors after legalize ops. 4476 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4477 // Canonicalize setlt X, Max --> setne X, Max 4478 if (C1 == MaxVal) 4479 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 4480 4481 // If we have setult X, 1, turn it into seteq X, 0 4482 if (C1 == MinVal+1) 4483 return DAG.getSetCC(dl, VT, N0, 4484 DAG.getConstant(MinVal, dl, N0.getValueType()), 4485 ISD::SETEQ); 4486 } 4487 } 4488 4489 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) { 4490 if (C1 == MaxVal) 4491 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false 4492 4493 // TODO: Support this for vectors after legalize ops. 4494 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4495 // Canonicalize setgt X, Min --> setne X, Min 4496 if (C1 == MinVal) 4497 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 4498 4499 // If we have setugt X, Max-1, turn it into seteq X, Max 4500 if (C1 == MaxVal-1) 4501 return DAG.getSetCC(dl, VT, N0, 4502 DAG.getConstant(MaxVal, dl, N0.getValueType()), 4503 ISD::SETEQ); 4504 } 4505 } 4506 4507 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) { 4508 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 4509 if (C1.isZero()) 4510 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift( 4511 VT, N0, N1, Cond, DCI, dl)) 4512 return CC; 4513 4514 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y). 4515 // For example, when high 32-bits of i64 X are known clear: 4516 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0 4517 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1 4518 bool CmpZero = N1C->getAPIntValue().isZero(); 4519 bool CmpNegOne = N1C->getAPIntValue().isAllOnes(); 4520 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) { 4521 // Match or(lo,shl(hi,bw/2)) pattern. 4522 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) { 4523 unsigned EltBits = V.getScalarValueSizeInBits(); 4524 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0) 4525 return false; 4526 SDValue LHS = V.getOperand(0); 4527 SDValue RHS = V.getOperand(1); 4528 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2); 4529 // Unshifted element must have zero upperbits. 4530 if (RHS.getOpcode() == ISD::SHL && 4531 isa<ConstantSDNode>(RHS.getOperand(1)) && 4532 RHS.getConstantOperandAPInt(1) == (EltBits / 2) && 4533 DAG.MaskedValueIsZero(LHS, HiBits)) { 4534 Lo = LHS; 4535 Hi = RHS.getOperand(0); 4536 return true; 4537 } 4538 if (LHS.getOpcode() == ISD::SHL && 4539 isa<ConstantSDNode>(LHS.getOperand(1)) && 4540 LHS.getConstantOperandAPInt(1) == (EltBits / 2) && 4541 DAG.MaskedValueIsZero(RHS, HiBits)) { 4542 Lo = RHS; 4543 Hi = LHS.getOperand(0); 4544 return true; 4545 } 4546 return false; 4547 }; 4548 4549 auto MergeConcat = [&](SDValue Lo, SDValue Hi) { 4550 unsigned EltBits = N0.getScalarValueSizeInBits(); 4551 unsigned HalfBits = EltBits / 2; 4552 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits); 4553 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT); 4554 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits); 4555 SDValue NewN0 = 4556 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask); 4557 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits; 4558 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond); 4559 }; 4560 4561 SDValue Lo, Hi; 4562 if (IsConcat(N0, Lo, Hi)) 4563 return MergeConcat(Lo, Hi); 4564 4565 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) { 4566 SDValue Lo0, Lo1, Hi0, Hi1; 4567 if (IsConcat(N0.getOperand(0), Lo0, Hi0) && 4568 IsConcat(N0.getOperand(1), Lo1, Hi1)) { 4569 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1), 4570 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1)); 4571 } 4572 } 4573 } 4574 } 4575 4576 // If we have "setcc X, C0", check to see if we can shrink the immediate 4577 // by changing cc. 4578 // TODO: Support this for vectors after legalize ops. 4579 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4580 // SETUGT X, SINTMAX -> SETLT X, 0 4581 // SETUGE X, SINTMIN -> SETLT X, 0 4582 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) || 4583 (Cond == ISD::SETUGE && C1.isMinSignedValue())) 4584 return DAG.getSetCC(dl, VT, N0, 4585 DAG.getConstant(0, dl, N1.getValueType()), 4586 ISD::SETLT); 4587 4588 // SETULT X, SINTMIN -> SETGT X, -1 4589 // SETULE X, SINTMAX -> SETGT X, -1 4590 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) || 4591 (Cond == ISD::SETULE && C1.isMaxSignedValue())) 4592 return DAG.getSetCC(dl, VT, N0, 4593 DAG.getAllOnesConstant(dl, N1.getValueType()), 4594 ISD::SETGT); 4595 } 4596 } 4597 4598 // Back to non-vector simplifications. 4599 // TODO: Can we do these for vector splats? 4600 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4601 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4602 const APInt &C1 = N1C->getAPIntValue(); 4603 EVT ShValTy = N0.getValueType(); 4604 4605 // Fold bit comparisons when we can. This will result in an 4606 // incorrect value when boolean false is negative one, unless 4607 // the bitsize is 1 in which case the false value is the same 4608 // in practice regardless of the representation. 4609 if ((VT.getSizeInBits() == 1 || 4610 getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) && 4611 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4612 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) && 4613 N0.getOpcode() == ISD::AND) { 4614 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4615 EVT ShiftTy = 4616 getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4617 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 4618 // Perform the xform if the AND RHS is a single bit. 4619 unsigned ShCt = AndRHS->getAPIntValue().logBase2(); 4620 if (AndRHS->getAPIntValue().isPowerOf2() && 4621 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4622 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4623 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4624 DAG.getConstant(ShCt, dl, ShiftTy))); 4625 } 4626 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 4627 // (X & 8) == 8 --> (X & 8) >> 3 4628 // Perform the xform if C1 is a single bit. 4629 unsigned ShCt = C1.logBase2(); 4630 if (C1.isPowerOf2() && 4631 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4632 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4633 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4634 DAG.getConstant(ShCt, dl, ShiftTy))); 4635 } 4636 } 4637 } 4638 } 4639 4640 if (C1.getMinSignedBits() <= 64 && 4641 !isLegalICmpImmediate(C1.getSExtValue())) { 4642 EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4643 // (X & -256) == 256 -> (X >> 8) == 1 4644 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4645 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 4646 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4647 const APInt &AndRHSC = AndRHS->getAPIntValue(); 4648 if (AndRHSC.isNegatedPowerOf2() && (AndRHSC & C1) == C1) { 4649 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 4650 if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4651 SDValue Shift = 4652 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0), 4653 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4654 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy); 4655 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 4656 } 4657 } 4658 } 4659 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 4660 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 4661 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 4662 // X < 0x100000000 -> (X >> 32) < 1 4663 // X >= 0x100000000 -> (X >> 32) >= 1 4664 // X <= 0x0ffffffff -> (X >> 32) < 1 4665 // X > 0x0ffffffff -> (X >> 32) >= 1 4666 unsigned ShiftBits; 4667 APInt NewC = C1; 4668 ISD::CondCode NewCond = Cond; 4669 if (AdjOne) { 4670 ShiftBits = C1.countTrailingOnes(); 4671 NewC = NewC + 1; 4672 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4673 } else { 4674 ShiftBits = C1.countTrailingZeros(); 4675 } 4676 NewC.lshrInPlace(ShiftBits); 4677 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 4678 isLegalICmpImmediate(NewC.getSExtValue()) && 4679 !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4680 SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4681 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4682 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy); 4683 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 4684 } 4685 } 4686 } 4687 } 4688 4689 if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) { 4690 auto *CFP = cast<ConstantFPSDNode>(N1); 4691 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value"); 4692 4693 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 4694 // constant if knowing that the operand is non-nan is enough. We prefer to 4695 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 4696 // materialize 0.0. 4697 if (Cond == ISD::SETO || Cond == ISD::SETUO) 4698 return DAG.getSetCC(dl, VT, N0, N0, Cond); 4699 4700 // setcc (fneg x), C -> setcc swap(pred) x, -C 4701 if (N0.getOpcode() == ISD::FNEG) { 4702 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 4703 if (DCI.isBeforeLegalizeOps() || 4704 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 4705 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 4706 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 4707 } 4708 } 4709 4710 // If the condition is not legal, see if we can find an equivalent one 4711 // which is legal. 4712 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 4713 // If the comparison was an awkward floating-point == or != and one of 4714 // the comparison operands is infinity or negative infinity, convert the 4715 // condition to a less-awkward <= or >=. 4716 if (CFP->getValueAPF().isInfinity()) { 4717 bool IsNegInf = CFP->getValueAPF().isNegative(); 4718 ISD::CondCode NewCond = ISD::SETCC_INVALID; 4719 switch (Cond) { 4720 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break; 4721 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break; 4722 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break; 4723 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break; 4724 default: break; 4725 } 4726 if (NewCond != ISD::SETCC_INVALID && 4727 isCondCodeLegal(NewCond, N0.getSimpleValueType())) 4728 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4729 } 4730 } 4731 } 4732 4733 if (N0 == N1) { 4734 // The sext(setcc()) => setcc() optimization relies on the appropriate 4735 // constant being emitted. 4736 assert(!N0.getValueType().isInteger() && 4737 "Integer types should be handled by FoldSetCC"); 4738 4739 bool EqTrue = ISD::isTrueWhenEqual(Cond); 4740 unsigned UOF = ISD::getUnorderedFlavor(Cond); 4741 if (UOF == 2) // FP operators that are undefined on NaNs. 4742 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4743 if (UOF == unsigned(EqTrue)) 4744 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4745 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 4746 // if it is not already. 4747 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 4748 if (NewCond != Cond && 4749 (DCI.isBeforeLegalizeOps() || 4750 isCondCodeLegal(NewCond, N0.getSimpleValueType()))) 4751 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4752 } 4753 4754 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4755 N0.getValueType().isInteger()) { 4756 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 4757 N0.getOpcode() == ISD::XOR) { 4758 // Simplify (X+Y) == (X+Z) --> Y == Z 4759 if (N0.getOpcode() == N1.getOpcode()) { 4760 if (N0.getOperand(0) == N1.getOperand(0)) 4761 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 4762 if (N0.getOperand(1) == N1.getOperand(1)) 4763 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 4764 if (isCommutativeBinOp(N0.getOpcode())) { 4765 // If X op Y == Y op X, try other combinations. 4766 if (N0.getOperand(0) == N1.getOperand(1)) 4767 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 4768 Cond); 4769 if (N0.getOperand(1) == N1.getOperand(0)) 4770 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 4771 Cond); 4772 } 4773 } 4774 4775 // If RHS is a legal immediate value for a compare instruction, we need 4776 // to be careful about increasing register pressure needlessly. 4777 bool LegalRHSImm = false; 4778 4779 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 4780 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4781 // Turn (X+C1) == C2 --> X == C2-C1 4782 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) 4783 return DAG.getSetCC( 4784 dl, VT, N0.getOperand(0), 4785 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(), 4786 dl, N0.getValueType()), 4787 Cond); 4788 4789 // Turn (X^C1) == C2 --> X == C1^C2 4790 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse()) 4791 return DAG.getSetCC( 4792 dl, VT, N0.getOperand(0), 4793 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(), 4794 dl, N0.getValueType()), 4795 Cond); 4796 } 4797 4798 // Turn (C1-X) == C2 --> X == C1-C2 4799 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 4800 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) 4801 return DAG.getSetCC( 4802 dl, VT, N0.getOperand(1), 4803 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(), 4804 dl, N0.getValueType()), 4805 Cond); 4806 4807 // Could RHSC fold directly into a compare? 4808 if (RHSC->getValueType(0).getSizeInBits() <= 64) 4809 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 4810 } 4811 4812 // (X+Y) == X --> Y == 0 and similar folds. 4813 // Don't do this if X is an immediate that can fold into a cmp 4814 // instruction and X+Y has other uses. It could be an induction variable 4815 // chain, and the transform would increase register pressure. 4816 if (!LegalRHSImm || N0.hasOneUse()) 4817 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI)) 4818 return V; 4819 } 4820 4821 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 4822 N1.getOpcode() == ISD::XOR) 4823 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI)) 4824 return V; 4825 4826 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI)) 4827 return V; 4828 } 4829 4830 // Fold remainder of division by a constant. 4831 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) && 4832 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4833 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4834 4835 // When division is cheap or optimizing for minimum size, 4836 // fall through to DIVREM creation by skipping this fold. 4837 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) { 4838 if (N0.getOpcode() == ISD::UREM) { 4839 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4840 return Folded; 4841 } else if (N0.getOpcode() == ISD::SREM) { 4842 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4843 return Folded; 4844 } 4845 } 4846 } 4847 4848 // Fold away ALL boolean setcc's. 4849 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) { 4850 SDValue Temp; 4851 switch (Cond) { 4852 default: llvm_unreachable("Unknown integer setcc!"); 4853 case ISD::SETEQ: // X == Y -> ~(X^Y) 4854 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4855 N0 = DAG.getNOT(dl, Temp, OpVT); 4856 if (!DCI.isCalledByLegalizer()) 4857 DCI.AddToWorklist(Temp.getNode()); 4858 break; 4859 case ISD::SETNE: // X != Y --> (X^Y) 4860 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4861 break; 4862 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 4863 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 4864 Temp = DAG.getNOT(dl, N0, OpVT); 4865 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp); 4866 if (!DCI.isCalledByLegalizer()) 4867 DCI.AddToWorklist(Temp.getNode()); 4868 break; 4869 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 4870 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 4871 Temp = DAG.getNOT(dl, N1, OpVT); 4872 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp); 4873 if (!DCI.isCalledByLegalizer()) 4874 DCI.AddToWorklist(Temp.getNode()); 4875 break; 4876 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 4877 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 4878 Temp = DAG.getNOT(dl, N0, OpVT); 4879 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp); 4880 if (!DCI.isCalledByLegalizer()) 4881 DCI.AddToWorklist(Temp.getNode()); 4882 break; 4883 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 4884 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 4885 Temp = DAG.getNOT(dl, N1, OpVT); 4886 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp); 4887 break; 4888 } 4889 if (VT.getScalarType() != MVT::i1) { 4890 if (!DCI.isCalledByLegalizer()) 4891 DCI.AddToWorklist(N0.getNode()); 4892 // FIXME: If running after legalize, we probably can't do this. 4893 ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT)); 4894 N0 = DAG.getNode(ExtendCode, dl, VT, N0); 4895 } 4896 return N0; 4897 } 4898 4899 // Could not fold it. 4900 return SDValue(); 4901 } 4902 4903 /// Returns true (and the GlobalValue and the offset) if the node is a 4904 /// GlobalAddress + offset. 4905 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA, 4906 int64_t &Offset) const { 4907 4908 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode(); 4909 4910 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 4911 GA = GASD->getGlobal(); 4912 Offset += GASD->getOffset(); 4913 return true; 4914 } 4915 4916 if (N->getOpcode() == ISD::ADD) { 4917 SDValue N1 = N->getOperand(0); 4918 SDValue N2 = N->getOperand(1); 4919 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 4920 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 4921 Offset += V->getSExtValue(); 4922 return true; 4923 } 4924 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 4925 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 4926 Offset += V->getSExtValue(); 4927 return true; 4928 } 4929 } 4930 } 4931 4932 return false; 4933 } 4934 4935 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 4936 DAGCombinerInfo &DCI) const { 4937 // Default implementation: no optimization. 4938 return SDValue(); 4939 } 4940 4941 //===----------------------------------------------------------------------===// 4942 // Inline Assembler Implementation Methods 4943 //===----------------------------------------------------------------------===// 4944 4945 TargetLowering::ConstraintType 4946 TargetLowering::getConstraintType(StringRef Constraint) const { 4947 unsigned S = Constraint.size(); 4948 4949 if (S == 1) { 4950 switch (Constraint[0]) { 4951 default: break; 4952 case 'r': 4953 return C_RegisterClass; 4954 case 'm': // memory 4955 case 'o': // offsetable 4956 case 'V': // not offsetable 4957 return C_Memory; 4958 case 'p': // Address. 4959 return C_Address; 4960 case 'n': // Simple Integer 4961 case 'E': // Floating Point Constant 4962 case 'F': // Floating Point Constant 4963 return C_Immediate; 4964 case 'i': // Simple Integer or Relocatable Constant 4965 case 's': // Relocatable Constant 4966 case 'X': // Allow ANY value. 4967 case 'I': // Target registers. 4968 case 'J': 4969 case 'K': 4970 case 'L': 4971 case 'M': 4972 case 'N': 4973 case 'O': 4974 case 'P': 4975 case '<': 4976 case '>': 4977 return C_Other; 4978 } 4979 } 4980 4981 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') { 4982 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 4983 return C_Memory; 4984 return C_Register; 4985 } 4986 return C_Unknown; 4987 } 4988 4989 /// Try to replace an X constraint, which matches anything, with another that 4990 /// has more specific requirements based on the type of the corresponding 4991 /// operand. 4992 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 4993 if (ConstraintVT.isInteger()) 4994 return "r"; 4995 if (ConstraintVT.isFloatingPoint()) 4996 return "f"; // works for many targets 4997 return nullptr; 4998 } 4999 5000 SDValue TargetLowering::LowerAsmOutputForConstraint( 5001 SDValue &Chain, SDValue &Flag, const SDLoc &DL, 5002 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const { 5003 return SDValue(); 5004 } 5005 5006 /// Lower the specified operand into the Ops vector. 5007 /// If it is invalid, don't add anything to Ops. 5008 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 5009 std::string &Constraint, 5010 std::vector<SDValue> &Ops, 5011 SelectionDAG &DAG) const { 5012 5013 if (Constraint.length() > 1) return; 5014 5015 char ConstraintLetter = Constraint[0]; 5016 switch (ConstraintLetter) { 5017 default: break; 5018 case 'X': // Allows any operand 5019 case 'i': // Simple Integer or Relocatable Constant 5020 case 'n': // Simple Integer 5021 case 's': { // Relocatable Constant 5022 5023 ConstantSDNode *C; 5024 uint64_t Offset = 0; 5025 5026 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C), 5027 // etc., since getelementpointer is variadic. We can't use 5028 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible 5029 // while in this case the GA may be furthest from the root node which is 5030 // likely an ISD::ADD. 5031 while (true) { 5032 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') { 5033 // gcc prints these as sign extended. Sign extend value to 64 bits 5034 // now; without this it would get ZExt'd later in 5035 // ScheduleDAGSDNodes::EmitNode, which is very generic. 5036 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1; 5037 BooleanContent BCont = getBooleanContents(MVT::i64); 5038 ISD::NodeType ExtOpc = 5039 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND; 5040 int64_t ExtVal = 5041 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue(); 5042 Ops.push_back( 5043 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64)); 5044 return; 5045 } 5046 if (ConstraintLetter != 'n') { 5047 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 5048 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 5049 GA->getValueType(0), 5050 Offset + GA->getOffset())); 5051 return; 5052 } 5053 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 5054 Ops.push_back(DAG.getTargetBlockAddress( 5055 BA->getBlockAddress(), BA->getValueType(0), 5056 Offset + BA->getOffset(), BA->getTargetFlags())); 5057 return; 5058 } 5059 if (isa<BasicBlockSDNode>(Op)) { 5060 Ops.push_back(Op); 5061 return; 5062 } 5063 } 5064 const unsigned OpCode = Op.getOpcode(); 5065 if (OpCode == ISD::ADD || OpCode == ISD::SUB) { 5066 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0)))) 5067 Op = Op.getOperand(1); 5068 // Subtraction is not commutative. 5069 else if (OpCode == ISD::ADD && 5070 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))) 5071 Op = Op.getOperand(0); 5072 else 5073 return; 5074 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue(); 5075 continue; 5076 } 5077 return; 5078 } 5079 break; 5080 } 5081 } 5082 } 5083 5084 std::pair<unsigned, const TargetRegisterClass *> 5085 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 5086 StringRef Constraint, 5087 MVT VT) const { 5088 if (Constraint.empty() || Constraint[0] != '{') 5089 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr)); 5090 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?"); 5091 5092 // Remove the braces from around the name. 5093 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 5094 5095 std::pair<unsigned, const TargetRegisterClass *> R = 5096 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr)); 5097 5098 // Figure out which register class contains this reg. 5099 for (const TargetRegisterClass *RC : RI->regclasses()) { 5100 // If none of the value types for this register class are valid, we 5101 // can't use it. For example, 64-bit reg classes on 32-bit targets. 5102 if (!isLegalRC(*RI, *RC)) 5103 continue; 5104 5105 for (const MCPhysReg &PR : *RC) { 5106 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) { 5107 std::pair<unsigned, const TargetRegisterClass *> S = 5108 std::make_pair(PR, RC); 5109 5110 // If this register class has the requested value type, return it, 5111 // otherwise keep searching and return the first class found 5112 // if no other is found which explicitly has the requested type. 5113 if (RI->isTypeLegalForClass(*RC, VT)) 5114 return S; 5115 if (!R.second) 5116 R = S; 5117 } 5118 } 5119 } 5120 5121 return R; 5122 } 5123 5124 //===----------------------------------------------------------------------===// 5125 // Constraint Selection. 5126 5127 /// Return true of this is an input operand that is a matching constraint like 5128 /// "4". 5129 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 5130 assert(!ConstraintCode.empty() && "No known constraint!"); 5131 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 5132 } 5133 5134 /// If this is an input matching constraint, this method returns the output 5135 /// operand it matches. 5136 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 5137 assert(!ConstraintCode.empty() && "No known constraint!"); 5138 return atoi(ConstraintCode.c_str()); 5139 } 5140 5141 /// Split up the constraint string from the inline assembly value into the 5142 /// specific constraints and their prefixes, and also tie in the associated 5143 /// operand values. 5144 /// If this returns an empty vector, and if the constraint string itself 5145 /// isn't empty, there was an error parsing. 5146 TargetLowering::AsmOperandInfoVector 5147 TargetLowering::ParseConstraints(const DataLayout &DL, 5148 const TargetRegisterInfo *TRI, 5149 const CallBase &Call) const { 5150 /// Information about all of the constraints. 5151 AsmOperandInfoVector ConstraintOperands; 5152 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 5153 unsigned maCount = 0; // Largest number of multiple alternative constraints. 5154 5155 // Do a prepass over the constraints, canonicalizing them, and building up the 5156 // ConstraintOperands list. 5157 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 5158 unsigned ResNo = 0; // ResNo - The result number of the next output. 5159 5160 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 5161 ConstraintOperands.emplace_back(std::move(CI)); 5162 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 5163 5164 // Update multiple alternative constraint count. 5165 if (OpInfo.multipleAlternatives.size() > maCount) 5166 maCount = OpInfo.multipleAlternatives.size(); 5167 5168 OpInfo.ConstraintVT = MVT::Other; 5169 5170 // Compute the value type for each operand. 5171 switch (OpInfo.Type) { 5172 case InlineAsm::isOutput: 5173 // Indirect outputs just consume an argument. 5174 if (OpInfo.isIndirect) { 5175 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5176 break; 5177 } 5178 5179 // The return value of the call is this value. As such, there is no 5180 // corresponding argument. 5181 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 5182 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 5183 OpInfo.ConstraintVT = 5184 getSimpleValueType(DL, STy->getElementType(ResNo)); 5185 } else { 5186 assert(ResNo == 0 && "Asm only has one result!"); 5187 OpInfo.ConstraintVT = 5188 getAsmOperandValueType(DL, Call.getType()).getSimpleVT(); 5189 } 5190 ++ResNo; 5191 break; 5192 case InlineAsm::isInput: 5193 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5194 break; 5195 case InlineAsm::isClobber: 5196 // Nothing to do. 5197 break; 5198 } 5199 5200 if (OpInfo.CallOperandVal) { 5201 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 5202 if (OpInfo.isIndirect) { 5203 OpTy = Call.getParamElementType(ArgNo); 5204 assert(OpTy && "Indirect operand must have elementtype attribute"); 5205 } 5206 5207 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 5208 if (StructType *STy = dyn_cast<StructType>(OpTy)) 5209 if (STy->getNumElements() == 1) 5210 OpTy = STy->getElementType(0); 5211 5212 // If OpTy is not a single value, it may be a struct/union that we 5213 // can tile with integers. 5214 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 5215 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 5216 switch (BitSize) { 5217 default: break; 5218 case 1: 5219 case 8: 5220 case 16: 5221 case 32: 5222 case 64: 5223 case 128: 5224 OpInfo.ConstraintVT = 5225 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true); 5226 break; 5227 } 5228 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) { 5229 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace()); 5230 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize); 5231 } else { 5232 OpInfo.ConstraintVT = MVT::getVT(OpTy, true); 5233 } 5234 5235 ArgNo++; 5236 } 5237 } 5238 5239 // If we have multiple alternative constraints, select the best alternative. 5240 if (!ConstraintOperands.empty()) { 5241 if (maCount) { 5242 unsigned bestMAIndex = 0; 5243 int bestWeight = -1; 5244 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 5245 int weight = -1; 5246 unsigned maIndex; 5247 // Compute the sums of the weights for each alternative, keeping track 5248 // of the best (highest weight) one so far. 5249 for (maIndex = 0; maIndex < maCount; ++maIndex) { 5250 int weightSum = 0; 5251 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5252 cIndex != eIndex; ++cIndex) { 5253 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5254 if (OpInfo.Type == InlineAsm::isClobber) 5255 continue; 5256 5257 // If this is an output operand with a matching input operand, 5258 // look up the matching input. If their types mismatch, e.g. one 5259 // is an integer, the other is floating point, or their sizes are 5260 // different, flag it as an maCantMatch. 5261 if (OpInfo.hasMatchingInput()) { 5262 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5263 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5264 if ((OpInfo.ConstraintVT.isInteger() != 5265 Input.ConstraintVT.isInteger()) || 5266 (OpInfo.ConstraintVT.getSizeInBits() != 5267 Input.ConstraintVT.getSizeInBits())) { 5268 weightSum = -1; // Can't match. 5269 break; 5270 } 5271 } 5272 } 5273 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 5274 if (weight == -1) { 5275 weightSum = -1; 5276 break; 5277 } 5278 weightSum += weight; 5279 } 5280 // Update best. 5281 if (weightSum > bestWeight) { 5282 bestWeight = weightSum; 5283 bestMAIndex = maIndex; 5284 } 5285 } 5286 5287 // Now select chosen alternative in each constraint. 5288 for (AsmOperandInfo &cInfo : ConstraintOperands) 5289 if (cInfo.Type != InlineAsm::isClobber) 5290 cInfo.selectAlternative(bestMAIndex); 5291 } 5292 } 5293 5294 // Check and hook up tied operands, choose constraint code to use. 5295 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5296 cIndex != eIndex; ++cIndex) { 5297 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5298 5299 // If this is an output operand with a matching input operand, look up the 5300 // matching input. If their types mismatch, e.g. one is an integer, the 5301 // other is floating point, or their sizes are different, flag it as an 5302 // error. 5303 if (OpInfo.hasMatchingInput()) { 5304 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5305 5306 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5307 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 5308 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 5309 OpInfo.ConstraintVT); 5310 std::pair<unsigned, const TargetRegisterClass *> InputRC = 5311 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 5312 Input.ConstraintVT); 5313 if ((OpInfo.ConstraintVT.isInteger() != 5314 Input.ConstraintVT.isInteger()) || 5315 (MatchRC.second != InputRC.second)) { 5316 report_fatal_error("Unsupported asm: input constraint" 5317 " with a matching output constraint of" 5318 " incompatible type!"); 5319 } 5320 } 5321 } 5322 } 5323 5324 return ConstraintOperands; 5325 } 5326 5327 /// Return an integer indicating how general CT is. 5328 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 5329 switch (CT) { 5330 case TargetLowering::C_Immediate: 5331 case TargetLowering::C_Other: 5332 case TargetLowering::C_Unknown: 5333 return 0; 5334 case TargetLowering::C_Register: 5335 return 1; 5336 case TargetLowering::C_RegisterClass: 5337 return 2; 5338 case TargetLowering::C_Memory: 5339 case TargetLowering::C_Address: 5340 return 3; 5341 } 5342 llvm_unreachable("Invalid constraint type"); 5343 } 5344 5345 /// Examine constraint type and operand type and determine a weight value. 5346 /// This object must already have been set up with the operand type 5347 /// and the current alternative constraint selected. 5348 TargetLowering::ConstraintWeight 5349 TargetLowering::getMultipleConstraintMatchWeight( 5350 AsmOperandInfo &info, int maIndex) const { 5351 InlineAsm::ConstraintCodeVector *rCodes; 5352 if (maIndex >= (int)info.multipleAlternatives.size()) 5353 rCodes = &info.Codes; 5354 else 5355 rCodes = &info.multipleAlternatives[maIndex].Codes; 5356 ConstraintWeight BestWeight = CW_Invalid; 5357 5358 // Loop over the options, keeping track of the most general one. 5359 for (const std::string &rCode : *rCodes) { 5360 ConstraintWeight weight = 5361 getSingleConstraintMatchWeight(info, rCode.c_str()); 5362 if (weight > BestWeight) 5363 BestWeight = weight; 5364 } 5365 5366 return BestWeight; 5367 } 5368 5369 /// Examine constraint type and operand type and determine a weight value. 5370 /// This object must already have been set up with the operand type 5371 /// and the current alternative constraint selected. 5372 TargetLowering::ConstraintWeight 5373 TargetLowering::getSingleConstraintMatchWeight( 5374 AsmOperandInfo &info, const char *constraint) const { 5375 ConstraintWeight weight = CW_Invalid; 5376 Value *CallOperandVal = info.CallOperandVal; 5377 // If we don't have a value, we can't do a match, 5378 // but allow it at the lowest weight. 5379 if (!CallOperandVal) 5380 return CW_Default; 5381 // Look at the constraint type. 5382 switch (*constraint) { 5383 case 'i': // immediate integer. 5384 case 'n': // immediate integer with a known value. 5385 if (isa<ConstantInt>(CallOperandVal)) 5386 weight = CW_Constant; 5387 break; 5388 case 's': // non-explicit intregal immediate. 5389 if (isa<GlobalValue>(CallOperandVal)) 5390 weight = CW_Constant; 5391 break; 5392 case 'E': // immediate float if host format. 5393 case 'F': // immediate float. 5394 if (isa<ConstantFP>(CallOperandVal)) 5395 weight = CW_Constant; 5396 break; 5397 case '<': // memory operand with autodecrement. 5398 case '>': // memory operand with autoincrement. 5399 case 'm': // memory operand. 5400 case 'o': // offsettable memory operand 5401 case 'V': // non-offsettable memory operand 5402 weight = CW_Memory; 5403 break; 5404 case 'r': // general register. 5405 case 'g': // general register, memory operand or immediate integer. 5406 // note: Clang converts "g" to "imr". 5407 if (CallOperandVal->getType()->isIntegerTy()) 5408 weight = CW_Register; 5409 break; 5410 case 'X': // any operand. 5411 default: 5412 weight = CW_Default; 5413 break; 5414 } 5415 return weight; 5416 } 5417 5418 /// If there are multiple different constraints that we could pick for this 5419 /// operand (e.g. "imr") try to pick the 'best' one. 5420 /// This is somewhat tricky: constraints fall into four classes: 5421 /// Other -> immediates and magic values 5422 /// Register -> one specific register 5423 /// RegisterClass -> a group of regs 5424 /// Memory -> memory 5425 /// Ideally, we would pick the most specific constraint possible: if we have 5426 /// something that fits into a register, we would pick it. The problem here 5427 /// is that if we have something that could either be in a register or in 5428 /// memory that use of the register could cause selection of *other* 5429 /// operands to fail: they might only succeed if we pick memory. Because of 5430 /// this the heuristic we use is: 5431 /// 5432 /// 1) If there is an 'other' constraint, and if the operand is valid for 5433 /// that constraint, use it. This makes us take advantage of 'i' 5434 /// constraints when available. 5435 /// 2) Otherwise, pick the most general constraint present. This prefers 5436 /// 'm' over 'r', for example. 5437 /// 5438 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 5439 const TargetLowering &TLI, 5440 SDValue Op, SelectionDAG *DAG) { 5441 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 5442 unsigned BestIdx = 0; 5443 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 5444 int BestGenerality = -1; 5445 5446 // Loop over the options, keeping track of the most general one. 5447 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 5448 TargetLowering::ConstraintType CType = 5449 TLI.getConstraintType(OpInfo.Codes[i]); 5450 5451 // Indirect 'other' or 'immediate' constraints are not allowed. 5452 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory || 5453 CType == TargetLowering::C_Register || 5454 CType == TargetLowering::C_RegisterClass)) 5455 continue; 5456 5457 // If this is an 'other' or 'immediate' constraint, see if the operand is 5458 // valid for it. For example, on X86 we might have an 'rI' constraint. If 5459 // the operand is an integer in the range [0..31] we want to use I (saving a 5460 // load of a register), otherwise we must use 'r'. 5461 if ((CType == TargetLowering::C_Other || 5462 CType == TargetLowering::C_Immediate) && Op.getNode()) { 5463 assert(OpInfo.Codes[i].size() == 1 && 5464 "Unhandled multi-letter 'other' constraint"); 5465 std::vector<SDValue> ResultOps; 5466 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 5467 ResultOps, *DAG); 5468 if (!ResultOps.empty()) { 5469 BestType = CType; 5470 BestIdx = i; 5471 break; 5472 } 5473 } 5474 5475 // Things with matching constraints can only be registers, per gcc 5476 // documentation. This mainly affects "g" constraints. 5477 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 5478 continue; 5479 5480 // This constraint letter is more general than the previous one, use it. 5481 int Generality = getConstraintGenerality(CType); 5482 if (Generality > BestGenerality) { 5483 BestType = CType; 5484 BestIdx = i; 5485 BestGenerality = Generality; 5486 } 5487 } 5488 5489 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 5490 OpInfo.ConstraintType = BestType; 5491 } 5492 5493 /// Determines the constraint code and constraint type to use for the specific 5494 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 5495 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 5496 SDValue Op, 5497 SelectionDAG *DAG) const { 5498 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 5499 5500 // Single-letter constraints ('r') are very common. 5501 if (OpInfo.Codes.size() == 1) { 5502 OpInfo.ConstraintCode = OpInfo.Codes[0]; 5503 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 5504 } else { 5505 ChooseConstraint(OpInfo, *this, Op, DAG); 5506 } 5507 5508 // 'X' matches anything. 5509 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 5510 // Constants are handled elsewhere. For Functions, the type here is the 5511 // type of the result, which is not what we want to look at; leave them 5512 // alone. 5513 Value *v = OpInfo.CallOperandVal; 5514 if (isa<ConstantInt>(v) || isa<Function>(v)) { 5515 return; 5516 } 5517 5518 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) { 5519 OpInfo.ConstraintCode = "i"; 5520 return; 5521 } 5522 5523 // Otherwise, try to resolve it to something we know about by looking at 5524 // the actual operand type. 5525 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 5526 OpInfo.ConstraintCode = Repl; 5527 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 5528 } 5529 } 5530 } 5531 5532 /// Given an exact SDIV by a constant, create a multiplication 5533 /// with the multiplicative inverse of the constant. 5534 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, 5535 const SDLoc &dl, SelectionDAG &DAG, 5536 SmallVectorImpl<SDNode *> &Created) { 5537 SDValue Op0 = N->getOperand(0); 5538 SDValue Op1 = N->getOperand(1); 5539 EVT VT = N->getValueType(0); 5540 EVT SVT = VT.getScalarType(); 5541 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 5542 EVT ShSVT = ShVT.getScalarType(); 5543 5544 bool UseSRA = false; 5545 SmallVector<SDValue, 16> Shifts, Factors; 5546 5547 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5548 if (C->isZero()) 5549 return false; 5550 APInt Divisor = C->getAPIntValue(); 5551 unsigned Shift = Divisor.countTrailingZeros(); 5552 if (Shift) { 5553 Divisor.ashrInPlace(Shift); 5554 UseSRA = true; 5555 } 5556 // Calculate the multiplicative inverse, using Newton's method. 5557 APInt t; 5558 APInt Factor = Divisor; 5559 while ((t = Divisor * Factor) != 1) 5560 Factor *= APInt(Divisor.getBitWidth(), 2) - t; 5561 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 5562 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 5563 return true; 5564 }; 5565 5566 // Collect all magic values from the build vector. 5567 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern)) 5568 return SDValue(); 5569 5570 SDValue Shift, Factor; 5571 if (Op1.getOpcode() == ISD::BUILD_VECTOR) { 5572 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5573 Factor = DAG.getBuildVector(VT, dl, Factors); 5574 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) { 5575 assert(Shifts.size() == 1 && Factors.size() == 1 && 5576 "Expected matchUnaryPredicate to return one element for scalable " 5577 "vectors"); 5578 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5579 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5580 } else { 5581 assert(isa<ConstantSDNode>(Op1) && "Expected a constant"); 5582 Shift = Shifts[0]; 5583 Factor = Factors[0]; 5584 } 5585 5586 SDValue Res = Op0; 5587 5588 // Shift the value upfront if it is even, so the LSB is one. 5589 if (UseSRA) { 5590 // TODO: For UDIV use SRL instead of SRA. 5591 SDNodeFlags Flags; 5592 Flags.setExact(true); 5593 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags); 5594 Created.push_back(Res.getNode()); 5595 } 5596 5597 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 5598 } 5599 5600 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 5601 SelectionDAG &DAG, 5602 SmallVectorImpl<SDNode *> &Created) const { 5603 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 5604 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5605 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 5606 return SDValue(N, 0); // Lower SDIV as SDIV 5607 return SDValue(); 5608 } 5609 5610 SDValue 5611 TargetLowering::BuildSREMPow2(SDNode *N, const APInt &Divisor, 5612 SelectionDAG &DAG, 5613 SmallVectorImpl<SDNode *> &Created) const { 5614 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 5615 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5616 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 5617 return SDValue(N, 0); // Lower SREM as SREM 5618 return SDValue(); 5619 } 5620 5621 /// Given an ISD::SDIV node expressing a divide by constant, 5622 /// return a DAG expression to select that will generate the same value by 5623 /// multiplying by a magic number. 5624 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5625 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 5626 bool IsAfterLegalization, 5627 SmallVectorImpl<SDNode *> &Created) const { 5628 SDLoc dl(N); 5629 EVT VT = N->getValueType(0); 5630 EVT SVT = VT.getScalarType(); 5631 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5632 EVT ShSVT = ShVT.getScalarType(); 5633 unsigned EltBits = VT.getScalarSizeInBits(); 5634 EVT MulVT; 5635 5636 // Check to see if we can do this. 5637 // FIXME: We should be more aggressive here. 5638 if (!isTypeLegal(VT)) { 5639 // Limit this to simple scalars for now. 5640 if (VT.isVector() || !VT.isSimple()) 5641 return SDValue(); 5642 5643 // If this type will be promoted to a large enough type with a legal 5644 // multiply operation, we can go ahead and do this transform. 5645 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5646 return SDValue(); 5647 5648 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5649 if (MulVT.getSizeInBits() < (2 * EltBits) || 5650 !isOperationLegal(ISD::MUL, MulVT)) 5651 return SDValue(); 5652 } 5653 5654 // If the sdiv has an 'exact' bit we can use a simpler lowering. 5655 if (N->getFlags().hasExact()) 5656 return BuildExactSDIV(*this, N, dl, DAG, Created); 5657 5658 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks; 5659 5660 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5661 if (C->isZero()) 5662 return false; 5663 5664 const APInt &Divisor = C->getAPIntValue(); 5665 SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor); 5666 int NumeratorFactor = 0; 5667 int ShiftMask = -1; 5668 5669 if (Divisor.isOne() || Divisor.isAllOnes()) { 5670 // If d is +1/-1, we just multiply the numerator by +1/-1. 5671 NumeratorFactor = Divisor.getSExtValue(); 5672 magics.Magic = 0; 5673 magics.ShiftAmount = 0; 5674 ShiftMask = 0; 5675 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) { 5676 // If d > 0 and m < 0, add the numerator. 5677 NumeratorFactor = 1; 5678 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) { 5679 // If d < 0 and m > 0, subtract the numerator. 5680 NumeratorFactor = -1; 5681 } 5682 5683 MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT)); 5684 Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT)); 5685 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT)); 5686 ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT)); 5687 return true; 5688 }; 5689 5690 SDValue N0 = N->getOperand(0); 5691 SDValue N1 = N->getOperand(1); 5692 5693 // Collect the shifts / magic values from each element. 5694 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern)) 5695 return SDValue(); 5696 5697 SDValue MagicFactor, Factor, Shift, ShiftMask; 5698 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5699 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5700 Factor = DAG.getBuildVector(VT, dl, Factors); 5701 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5702 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks); 5703 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5704 assert(MagicFactors.size() == 1 && Factors.size() == 1 && 5705 Shifts.size() == 1 && ShiftMasks.size() == 1 && 5706 "Expected matchUnaryPredicate to return one element for scalable " 5707 "vectors"); 5708 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5709 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5710 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5711 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]); 5712 } else { 5713 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 5714 MagicFactor = MagicFactors[0]; 5715 Factor = Factors[0]; 5716 Shift = Shifts[0]; 5717 ShiftMask = ShiftMasks[0]; 5718 } 5719 5720 // Multiply the numerator (operand 0) by the magic value. 5721 // FIXME: We should support doing a MUL in a wider type. 5722 auto GetMULHS = [&](SDValue X, SDValue Y) { 5723 // If the type isn't legal, use a wider mul of the the type calculated 5724 // earlier. 5725 if (!isTypeLegal(VT)) { 5726 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X); 5727 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y); 5728 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 5729 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 5730 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 5731 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 5732 } 5733 5734 if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization)) 5735 return DAG.getNode(ISD::MULHS, dl, VT, X, Y); 5736 if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) { 5737 SDValue LoHi = 5738 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5739 return SDValue(LoHi.getNode(), 1); 5740 } 5741 return SDValue(); 5742 }; 5743 5744 SDValue Q = GetMULHS(N0, MagicFactor); 5745 if (!Q) 5746 return SDValue(); 5747 5748 Created.push_back(Q.getNode()); 5749 5750 // (Optionally) Add/subtract the numerator using Factor. 5751 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor); 5752 Created.push_back(Factor.getNode()); 5753 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor); 5754 Created.push_back(Q.getNode()); 5755 5756 // Shift right algebraic by shift value. 5757 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift); 5758 Created.push_back(Q.getNode()); 5759 5760 // Extract the sign bit, mask it and add it to the quotient. 5761 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT); 5762 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift); 5763 Created.push_back(T.getNode()); 5764 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask); 5765 Created.push_back(T.getNode()); 5766 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 5767 } 5768 5769 /// Given an ISD::UDIV node expressing a divide by constant, 5770 /// return a DAG expression to select that will generate the same value by 5771 /// multiplying by a magic number. 5772 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5773 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG, 5774 bool IsAfterLegalization, 5775 SmallVectorImpl<SDNode *> &Created) const { 5776 SDLoc dl(N); 5777 EVT VT = N->getValueType(0); 5778 EVT SVT = VT.getScalarType(); 5779 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5780 EVT ShSVT = ShVT.getScalarType(); 5781 unsigned EltBits = VT.getScalarSizeInBits(); 5782 EVT MulVT; 5783 5784 // Check to see if we can do this. 5785 // FIXME: We should be more aggressive here. 5786 if (!isTypeLegal(VT)) { 5787 // Limit this to simple scalars for now. 5788 if (VT.isVector() || !VT.isSimple()) 5789 return SDValue(); 5790 5791 // If this type will be promoted to a large enough type with a legal 5792 // multiply operation, we can go ahead and do this transform. 5793 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5794 return SDValue(); 5795 5796 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5797 if (MulVT.getSizeInBits() < (2 * EltBits) || 5798 !isOperationLegal(ISD::MUL, MulVT)) 5799 return SDValue(); 5800 } 5801 5802 bool UseNPQ = false; 5803 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors; 5804 5805 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 5806 if (C->isZero()) 5807 return false; 5808 // FIXME: We should use a narrower constant when the upper 5809 // bits are known to be zero. 5810 const APInt& Divisor = C->getAPIntValue(); 5811 UnsignedDivisonByConstantInfo magics = UnsignedDivisonByConstantInfo::get(Divisor); 5812 unsigned PreShift = 0, PostShift = 0; 5813 5814 // If the divisor is even, we can avoid using the expensive fixup by 5815 // shifting the divided value upfront. 5816 if (magics.IsAdd != 0 && !Divisor[0]) { 5817 PreShift = Divisor.countTrailingZeros(); 5818 // Get magic number for the shifted divisor. 5819 magics = UnsignedDivisonByConstantInfo::get(Divisor.lshr(PreShift), PreShift); 5820 assert(magics.IsAdd == 0 && "Should use cheap fixup now"); 5821 } 5822 5823 APInt Magic = magics.Magic; 5824 5825 unsigned SelNPQ; 5826 if (magics.IsAdd == 0 || Divisor.isOne()) { 5827 assert(magics.ShiftAmount < Divisor.getBitWidth() && 5828 "We shouldn't generate an undefined shift!"); 5829 PostShift = magics.ShiftAmount; 5830 SelNPQ = false; 5831 } else { 5832 PostShift = magics.ShiftAmount - 1; 5833 SelNPQ = true; 5834 } 5835 5836 PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT)); 5837 MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT)); 5838 NPQFactors.push_back( 5839 DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1) 5840 : APInt::getZero(EltBits), 5841 dl, SVT)); 5842 PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT)); 5843 UseNPQ |= SelNPQ; 5844 return true; 5845 }; 5846 5847 SDValue N0 = N->getOperand(0); 5848 SDValue N1 = N->getOperand(1); 5849 5850 // Collect the shifts/magic values from each element. 5851 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern)) 5852 return SDValue(); 5853 5854 SDValue PreShift, PostShift, MagicFactor, NPQFactor; 5855 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5856 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts); 5857 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5858 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors); 5859 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts); 5860 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5861 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 && 5862 NPQFactors.size() == 1 && PostShifts.size() == 1 && 5863 "Expected matchUnaryPredicate to return one for scalable vectors"); 5864 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]); 5865 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5866 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]); 5867 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]); 5868 } else { 5869 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 5870 PreShift = PreShifts[0]; 5871 MagicFactor = MagicFactors[0]; 5872 PostShift = PostShifts[0]; 5873 } 5874 5875 SDValue Q = N0; 5876 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift); 5877 Created.push_back(Q.getNode()); 5878 5879 // FIXME: We should support doing a MUL in a wider type. 5880 auto GetMULHU = [&](SDValue X, SDValue Y) { 5881 // If the type isn't legal, use a wider mul of the the type calculated 5882 // earlier. 5883 if (!isTypeLegal(VT)) { 5884 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X); 5885 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y); 5886 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 5887 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 5888 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 5889 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 5890 } 5891 5892 if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization)) 5893 return DAG.getNode(ISD::MULHU, dl, VT, X, Y); 5894 if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) { 5895 SDValue LoHi = 5896 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5897 return SDValue(LoHi.getNode(), 1); 5898 } 5899 return SDValue(); // No mulhu or equivalent 5900 }; 5901 5902 // Multiply the numerator (operand 0) by the magic value. 5903 Q = GetMULHU(Q, MagicFactor); 5904 if (!Q) 5905 return SDValue(); 5906 5907 Created.push_back(Q.getNode()); 5908 5909 if (UseNPQ) { 5910 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q); 5911 Created.push_back(NPQ.getNode()); 5912 5913 // For vectors we might have a mix of non-NPQ/NPQ paths, so use 5914 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero. 5915 if (VT.isVector()) 5916 NPQ = GetMULHU(NPQ, NPQFactor); 5917 else 5918 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT)); 5919 5920 Created.push_back(NPQ.getNode()); 5921 5922 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 5923 Created.push_back(Q.getNode()); 5924 } 5925 5926 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift); 5927 Created.push_back(Q.getNode()); 5928 5929 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 5930 5931 SDValue One = DAG.getConstant(1, dl, VT); 5932 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ); 5933 return DAG.getSelect(dl, VT, IsOne, N0, Q); 5934 } 5935 5936 /// If all values in Values that *don't* match the predicate are same 'splat' 5937 /// value, then replace all values with that splat value. 5938 /// Else, if AlternativeReplacement was provided, then replace all values that 5939 /// do match predicate with AlternativeReplacement value. 5940 static void 5941 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values, 5942 std::function<bool(SDValue)> Predicate, 5943 SDValue AlternativeReplacement = SDValue()) { 5944 SDValue Replacement; 5945 // Is there a value for which the Predicate does *NOT* match? What is it? 5946 auto SplatValue = llvm::find_if_not(Values, Predicate); 5947 if (SplatValue != Values.end()) { 5948 // Does Values consist only of SplatValue's and values matching Predicate? 5949 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) { 5950 return Value == *SplatValue || Predicate(Value); 5951 })) // Then we shall replace values matching predicate with SplatValue. 5952 Replacement = *SplatValue; 5953 } 5954 if (!Replacement) { 5955 // Oops, we did not find the "baseline" splat value. 5956 if (!AlternativeReplacement) 5957 return; // Nothing to do. 5958 // Let's replace with provided value then. 5959 Replacement = AlternativeReplacement; 5960 } 5961 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement); 5962 } 5963 5964 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE 5965 /// where the divisor is constant and the comparison target is zero, 5966 /// return a DAG expression that will generate the same comparison result 5967 /// using only multiplications, additions and shifts/rotations. 5968 /// Ref: "Hacker's Delight" 10-17. 5969 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode, 5970 SDValue CompTargetNode, 5971 ISD::CondCode Cond, 5972 DAGCombinerInfo &DCI, 5973 const SDLoc &DL) const { 5974 SmallVector<SDNode *, 5> Built; 5975 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 5976 DCI, DL, Built)) { 5977 for (SDNode *N : Built) 5978 DCI.AddToWorklist(N); 5979 return Folded; 5980 } 5981 5982 return SDValue(); 5983 } 5984 5985 SDValue 5986 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode, 5987 SDValue CompTargetNode, ISD::CondCode Cond, 5988 DAGCombinerInfo &DCI, const SDLoc &DL, 5989 SmallVectorImpl<SDNode *> &Created) const { 5990 // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q) 5991 // - D must be constant, with D = D0 * 2^K where D0 is odd 5992 // - P is the multiplicative inverse of D0 modulo 2^W 5993 // - Q = floor(((2^W) - 1) / D) 5994 // where W is the width of the common type of N and D. 5995 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5996 "Only applicable for (in)equality comparisons."); 5997 5998 SelectionDAG &DAG = DCI.DAG; 5999 6000 EVT VT = REMNode.getValueType(); 6001 EVT SVT = VT.getScalarType(); 6002 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize()); 6003 EVT ShSVT = ShVT.getScalarType(); 6004 6005 // If MUL is unavailable, we cannot proceed in any case. 6006 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 6007 return SDValue(); 6008 6009 bool ComparingWithAllZeros = true; 6010 bool AllComparisonsWithNonZerosAreTautological = true; 6011 bool HadTautologicalLanes = false; 6012 bool AllLanesAreTautological = true; 6013 bool HadEvenDivisor = false; 6014 bool AllDivisorsArePowerOfTwo = true; 6015 bool HadTautologicalInvertedLanes = false; 6016 SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts; 6017 6018 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) { 6019 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6020 if (CDiv->isZero()) 6021 return false; 6022 6023 const APInt &D = CDiv->getAPIntValue(); 6024 const APInt &Cmp = CCmp->getAPIntValue(); 6025 6026 ComparingWithAllZeros &= Cmp.isZero(); 6027 6028 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6029 // if C2 is not less than C1, the comparison is always false. 6030 // But we will only be able to produce the comparison that will give the 6031 // opposive tautological answer. So this lane would need to be fixed up. 6032 bool TautologicalInvertedLane = D.ule(Cmp); 6033 HadTautologicalInvertedLanes |= TautologicalInvertedLane; 6034 6035 // If all lanes are tautological (either all divisors are ones, or divisor 6036 // is not greater than the constant we are comparing with), 6037 // we will prefer to avoid the fold. 6038 bool TautologicalLane = D.isOne() || TautologicalInvertedLane; 6039 HadTautologicalLanes |= TautologicalLane; 6040 AllLanesAreTautological &= TautologicalLane; 6041 6042 // If we are comparing with non-zero, we need'll need to subtract said 6043 // comparison value from the LHS. But there is no point in doing that if 6044 // every lane where we are comparing with non-zero is tautological.. 6045 if (!Cmp.isZero()) 6046 AllComparisonsWithNonZerosAreTautological &= TautologicalLane; 6047 6048 // Decompose D into D0 * 2^K 6049 unsigned K = D.countTrailingZeros(); 6050 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 6051 APInt D0 = D.lshr(K); 6052 6053 // D is even if it has trailing zeros. 6054 HadEvenDivisor |= (K != 0); 6055 // D is a power-of-two if D0 is one. 6056 // If all divisors are power-of-two, we will prefer to avoid the fold. 6057 AllDivisorsArePowerOfTwo &= D0.isOne(); 6058 6059 // P = inv(D0, 2^W) 6060 // 2^W requires W + 1 bits, so we have to extend and then truncate. 6061 unsigned W = D.getBitWidth(); 6062 APInt P = D0.zext(W + 1) 6063 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 6064 .trunc(W); 6065 assert(!P.isZero() && "No multiplicative inverse!"); // unreachable 6066 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 6067 6068 // Q = floor((2^W - 1) u/ D) 6069 // R = ((2^W - 1) u% D) 6070 APInt Q, R; 6071 APInt::udivrem(APInt::getAllOnes(W), D, Q, R); 6072 6073 // If we are comparing with zero, then that comparison constant is okay, 6074 // else it may need to be one less than that. 6075 if (Cmp.ugt(R)) 6076 Q -= 1; 6077 6078 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 6079 "We are expecting that K is always less than all-ones for ShSVT"); 6080 6081 // If the lane is tautological the result can be constant-folded. 6082 if (TautologicalLane) { 6083 // Set P and K amount to a bogus values so we can try to splat them. 6084 P = 0; 6085 K = -1; 6086 // And ensure that comparison constant is tautological, 6087 // it will always compare true/false. 6088 Q = -1; 6089 } 6090 6091 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 6092 KAmts.push_back( 6093 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 6094 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 6095 return true; 6096 }; 6097 6098 SDValue N = REMNode.getOperand(0); 6099 SDValue D = REMNode.getOperand(1); 6100 6101 // Collect the values from each element. 6102 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern)) 6103 return SDValue(); 6104 6105 // If all lanes are tautological, the result can be constant-folded. 6106 if (AllLanesAreTautological) 6107 return SDValue(); 6108 6109 // If this is a urem by a powers-of-two, avoid the fold since it can be 6110 // best implemented as a bit test. 6111 if (AllDivisorsArePowerOfTwo) 6112 return SDValue(); 6113 6114 SDValue PVal, KVal, QVal; 6115 if (D.getOpcode() == ISD::BUILD_VECTOR) { 6116 if (HadTautologicalLanes) { 6117 // Try to turn PAmts into a splat, since we don't care about the values 6118 // that are currently '0'. If we can't, just keep '0'`s. 6119 turnVectorIntoSplatVector(PAmts, isNullConstant); 6120 // Try to turn KAmts into a splat, since we don't care about the values 6121 // that are currently '-1'. If we can't, change them to '0'`s. 6122 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 6123 DAG.getConstant(0, DL, ShSVT)); 6124 } 6125 6126 PVal = DAG.getBuildVector(VT, DL, PAmts); 6127 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 6128 QVal = DAG.getBuildVector(VT, DL, QAmts); 6129 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 6130 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 && 6131 "Expected matchBinaryPredicate to return one element for " 6132 "SPLAT_VECTORs"); 6133 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 6134 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 6135 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 6136 } else { 6137 PVal = PAmts[0]; 6138 KVal = KAmts[0]; 6139 QVal = QAmts[0]; 6140 } 6141 6142 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) { 6143 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT)) 6144 return SDValue(); // FIXME: Could/should use `ISD::ADD`? 6145 assert(CompTargetNode.getValueType() == N.getValueType() && 6146 "Expecting that the types on LHS and RHS of comparisons match."); 6147 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode); 6148 } 6149 6150 // (mul N, P) 6151 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6152 Created.push_back(Op0.getNode()); 6153 6154 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6155 // divisors as a performance improvement, since rotating by 0 is a no-op. 6156 if (HadEvenDivisor) { 6157 // We need ROTR to do this. 6158 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6159 return SDValue(); 6160 // UREM: (rotr (mul N, P), K) 6161 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6162 Created.push_back(Op0.getNode()); 6163 } 6164 6165 // UREM: (setule/setugt (rotr (mul N, P), K), Q) 6166 SDValue NewCC = 6167 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 6168 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 6169 if (!HadTautologicalInvertedLanes) 6170 return NewCC; 6171 6172 // If any lanes previously compared always-false, the NewCC will give 6173 // always-true result for them, so we need to fixup those lanes. 6174 // Or the other way around for inequality predicate. 6175 assert(VT.isVector() && "Can/should only get here for vectors."); 6176 Created.push_back(NewCC.getNode()); 6177 6178 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6179 // if C2 is not less than C1, the comparison is always false. 6180 // But we have produced the comparison that will give the 6181 // opposive tautological answer. So these lanes would need to be fixed up. 6182 SDValue TautologicalInvertedChannels = 6183 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE); 6184 Created.push_back(TautologicalInvertedChannels.getNode()); 6185 6186 // NOTE: we avoid letting illegal types through even if we're before legalize 6187 // ops – legalization has a hard time producing good code for this. 6188 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) { 6189 // If we have a vector select, let's replace the comparison results in the 6190 // affected lanes with the correct tautological result. 6191 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true, 6192 DL, SETCCVT, SETCCVT); 6193 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels, 6194 Replacement, NewCC); 6195 } 6196 6197 // Else, we can just invert the comparison result in the appropriate lanes. 6198 // 6199 // NOTE: see the note above VSELECT above. 6200 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT)) 6201 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC, 6202 TautologicalInvertedChannels); 6203 6204 return SDValue(); // Don't know how to lower. 6205 } 6206 6207 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE 6208 /// where the divisor is constant and the comparison target is zero, 6209 /// return a DAG expression that will generate the same comparison result 6210 /// using only multiplications, additions and shifts/rotations. 6211 /// Ref: "Hacker's Delight" 10-17. 6212 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode, 6213 SDValue CompTargetNode, 6214 ISD::CondCode Cond, 6215 DAGCombinerInfo &DCI, 6216 const SDLoc &DL) const { 6217 SmallVector<SDNode *, 7> Built; 6218 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 6219 DCI, DL, Built)) { 6220 assert(Built.size() <= 7 && "Max size prediction failed."); 6221 for (SDNode *N : Built) 6222 DCI.AddToWorklist(N); 6223 return Folded; 6224 } 6225 6226 return SDValue(); 6227 } 6228 6229 SDValue 6230 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode, 6231 SDValue CompTargetNode, ISD::CondCode Cond, 6232 DAGCombinerInfo &DCI, const SDLoc &DL, 6233 SmallVectorImpl<SDNode *> &Created) const { 6234 // Fold: 6235 // (seteq/ne (srem N, D), 0) 6236 // To: 6237 // (setule/ugt (rotr (add (mul N, P), A), K), Q) 6238 // 6239 // - D must be constant, with D = D0 * 2^K where D0 is odd 6240 // - P is the multiplicative inverse of D0 modulo 2^W 6241 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k))) 6242 // - Q = floor((2 * A) / (2^K)) 6243 // where W is the width of the common type of N and D. 6244 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 6245 "Only applicable for (in)equality comparisons."); 6246 6247 SelectionDAG &DAG = DCI.DAG; 6248 6249 EVT VT = REMNode.getValueType(); 6250 EVT SVT = VT.getScalarType(); 6251 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize()); 6252 EVT ShSVT = ShVT.getScalarType(); 6253 6254 // If we are after ops legalization, and MUL is unavailable, we can not 6255 // proceed. 6256 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 6257 return SDValue(); 6258 6259 // TODO: Could support comparing with non-zero too. 6260 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode); 6261 if (!CompTarget || !CompTarget->isZero()) 6262 return SDValue(); 6263 6264 bool HadIntMinDivisor = false; 6265 bool HadOneDivisor = false; 6266 bool AllDivisorsAreOnes = true; 6267 bool HadEvenDivisor = false; 6268 bool NeedToApplyOffset = false; 6269 bool AllDivisorsArePowerOfTwo = true; 6270 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts; 6271 6272 auto BuildSREMPattern = [&](ConstantSDNode *C) { 6273 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6274 if (C->isZero()) 6275 return false; 6276 6277 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine. 6278 6279 // WARNING: this fold is only valid for positive divisors! 6280 APInt D = C->getAPIntValue(); 6281 if (D.isNegative()) 6282 D.negate(); // `rem %X, -C` is equivalent to `rem %X, C` 6283 6284 HadIntMinDivisor |= D.isMinSignedValue(); 6285 6286 // If all divisors are ones, we will prefer to avoid the fold. 6287 HadOneDivisor |= D.isOne(); 6288 AllDivisorsAreOnes &= D.isOne(); 6289 6290 // Decompose D into D0 * 2^K 6291 unsigned K = D.countTrailingZeros(); 6292 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 6293 APInt D0 = D.lshr(K); 6294 6295 if (!D.isMinSignedValue()) { 6296 // D is even if it has trailing zeros; unless it's INT_MIN, in which case 6297 // we don't care about this lane in this fold, we'll special-handle it. 6298 HadEvenDivisor |= (K != 0); 6299 } 6300 6301 // D is a power-of-two if D0 is one. This includes INT_MIN. 6302 // If all divisors are power-of-two, we will prefer to avoid the fold. 6303 AllDivisorsArePowerOfTwo &= D0.isOne(); 6304 6305 // P = inv(D0, 2^W) 6306 // 2^W requires W + 1 bits, so we have to extend and then truncate. 6307 unsigned W = D.getBitWidth(); 6308 APInt P = D0.zext(W + 1) 6309 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 6310 .trunc(W); 6311 assert(!P.isZero() && "No multiplicative inverse!"); // unreachable 6312 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 6313 6314 // A = floor((2^(W - 1) - 1) / D0) & -2^K 6315 APInt A = APInt::getSignedMaxValue(W).udiv(D0); 6316 A.clearLowBits(K); 6317 6318 if (!D.isMinSignedValue()) { 6319 // If divisor INT_MIN, then we don't care about this lane in this fold, 6320 // we'll special-handle it. 6321 NeedToApplyOffset |= A != 0; 6322 } 6323 6324 // Q = floor((2 * A) / (2^K)) 6325 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K)); 6326 6327 assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) && 6328 "We are expecting that A is always less than all-ones for SVT"); 6329 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 6330 "We are expecting that K is always less than all-ones for ShSVT"); 6331 6332 // If the divisor is 1 the result can be constant-folded. Likewise, we 6333 // don't care about INT_MIN lanes, those can be set to undef if appropriate. 6334 if (D.isOne()) { 6335 // Set P, A and K to a bogus values so we can try to splat them. 6336 P = 0; 6337 A = -1; 6338 K = -1; 6339 6340 // x ?% 1 == 0 <--> true <--> x u<= -1 6341 Q = -1; 6342 } 6343 6344 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 6345 AAmts.push_back(DAG.getConstant(A, DL, SVT)); 6346 KAmts.push_back( 6347 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 6348 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 6349 return true; 6350 }; 6351 6352 SDValue N = REMNode.getOperand(0); 6353 SDValue D = REMNode.getOperand(1); 6354 6355 // Collect the values from each element. 6356 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern)) 6357 return SDValue(); 6358 6359 // If this is a srem by a one, avoid the fold since it can be constant-folded. 6360 if (AllDivisorsAreOnes) 6361 return SDValue(); 6362 6363 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold 6364 // since it can be best implemented as a bit test. 6365 if (AllDivisorsArePowerOfTwo) 6366 return SDValue(); 6367 6368 SDValue PVal, AVal, KVal, QVal; 6369 if (D.getOpcode() == ISD::BUILD_VECTOR) { 6370 if (HadOneDivisor) { 6371 // Try to turn PAmts into a splat, since we don't care about the values 6372 // that are currently '0'. If we can't, just keep '0'`s. 6373 turnVectorIntoSplatVector(PAmts, isNullConstant); 6374 // Try to turn AAmts into a splat, since we don't care about the 6375 // values that are currently '-1'. If we can't, change them to '0'`s. 6376 turnVectorIntoSplatVector(AAmts, isAllOnesConstant, 6377 DAG.getConstant(0, DL, SVT)); 6378 // Try to turn KAmts into a splat, since we don't care about the values 6379 // that are currently '-1'. If we can't, change them to '0'`s. 6380 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 6381 DAG.getConstant(0, DL, ShSVT)); 6382 } 6383 6384 PVal = DAG.getBuildVector(VT, DL, PAmts); 6385 AVal = DAG.getBuildVector(VT, DL, AAmts); 6386 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 6387 QVal = DAG.getBuildVector(VT, DL, QAmts); 6388 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 6389 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 && 6390 QAmts.size() == 1 && 6391 "Expected matchUnaryPredicate to return one element for scalable " 6392 "vectors"); 6393 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 6394 AVal = DAG.getSplatVector(VT, DL, AAmts[0]); 6395 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 6396 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 6397 } else { 6398 assert(isa<ConstantSDNode>(D) && "Expected a constant"); 6399 PVal = PAmts[0]; 6400 AVal = AAmts[0]; 6401 KVal = KAmts[0]; 6402 QVal = QAmts[0]; 6403 } 6404 6405 // (mul N, P) 6406 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6407 Created.push_back(Op0.getNode()); 6408 6409 if (NeedToApplyOffset) { 6410 // We need ADD to do this. 6411 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT)) 6412 return SDValue(); 6413 6414 // (add (mul N, P), A) 6415 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal); 6416 Created.push_back(Op0.getNode()); 6417 } 6418 6419 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6420 // divisors as a performance improvement, since rotating by 0 is a no-op. 6421 if (HadEvenDivisor) { 6422 // We need ROTR to do this. 6423 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6424 return SDValue(); 6425 // SREM: (rotr (add (mul N, P), A), K) 6426 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6427 Created.push_back(Op0.getNode()); 6428 } 6429 6430 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q) 6431 SDValue Fold = 6432 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 6433 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 6434 6435 // If we didn't have lanes with INT_MIN divisor, then we're done. 6436 if (!HadIntMinDivisor) 6437 return Fold; 6438 6439 // That fold is only valid for positive divisors. Which effectively means, 6440 // it is invalid for INT_MIN divisors. So if we have such a lane, 6441 // we must fix-up results for said lanes. 6442 assert(VT.isVector() && "Can/should only get here for vectors."); 6443 6444 // NOTE: we avoid letting illegal types through even if we're before legalize 6445 // ops – legalization has a hard time producing good code for the code that 6446 // follows. 6447 if (!isOperationLegalOrCustom(ISD::SETEQ, VT) || 6448 !isOperationLegalOrCustom(ISD::AND, VT) || 6449 !isOperationLegalOrCustom(Cond, VT) || 6450 !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) 6451 return SDValue(); 6452 6453 Created.push_back(Fold.getNode()); 6454 6455 SDValue IntMin = DAG.getConstant( 6456 APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT); 6457 SDValue IntMax = DAG.getConstant( 6458 APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT); 6459 SDValue Zero = 6460 DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT); 6461 6462 // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded. 6463 SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ); 6464 Created.push_back(DivisorIsIntMin.getNode()); 6465 6466 // (N s% INT_MIN) ==/!= 0 <--> (N & INT_MAX) ==/!= 0 6467 SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax); 6468 Created.push_back(Masked.getNode()); 6469 SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond); 6470 Created.push_back(MaskedIsZero.getNode()); 6471 6472 // To produce final result we need to blend 2 vectors: 'SetCC' and 6473 // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick 6474 // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is 6475 // constant-folded, select can get lowered to a shuffle with constant mask. 6476 SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin, 6477 MaskedIsZero, Fold); 6478 6479 return Blended; 6480 } 6481 6482 bool TargetLowering:: 6483 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 6484 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 6485 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 6486 "be a constant integer"); 6487 return true; 6488 } 6489 6490 return false; 6491 } 6492 6493 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 6494 const DenormalMode &Mode) const { 6495 SDLoc DL(Op); 6496 EVT VT = Op.getValueType(); 6497 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6498 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 6499 // Testing it with denormal inputs to avoid wrong estimate. 6500 if (Mode.Input == DenormalMode::IEEE) { 6501 // This is specifically a check for the handling of denormal inputs, 6502 // not the result. 6503 6504 // Test = fabs(X) < SmallestNormal 6505 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 6506 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 6507 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 6508 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 6509 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 6510 } 6511 // Test = X == 0.0 6512 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 6513 } 6514 6515 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 6516 bool LegalOps, bool OptForSize, 6517 NegatibleCost &Cost, 6518 unsigned Depth) const { 6519 // fneg is removable even if it has multiple uses. 6520 if (Op.getOpcode() == ISD::FNEG) { 6521 Cost = NegatibleCost::Cheaper; 6522 return Op.getOperand(0); 6523 } 6524 6525 // Don't recurse exponentially. 6526 if (Depth > SelectionDAG::MaxRecursionDepth) 6527 return SDValue(); 6528 6529 // Pre-increment recursion depth for use in recursive calls. 6530 ++Depth; 6531 const SDNodeFlags Flags = Op->getFlags(); 6532 const TargetOptions &Options = DAG.getTarget().Options; 6533 EVT VT = Op.getValueType(); 6534 unsigned Opcode = Op.getOpcode(); 6535 6536 // Don't allow anything with multiple uses unless we know it is free. 6537 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) { 6538 bool IsFreeExtend = Opcode == ISD::FP_EXTEND && 6539 isFPExtFree(VT, Op.getOperand(0).getValueType()); 6540 if (!IsFreeExtend) 6541 return SDValue(); 6542 } 6543 6544 auto RemoveDeadNode = [&](SDValue N) { 6545 if (N && N.getNode()->use_empty()) 6546 DAG.RemoveDeadNode(N.getNode()); 6547 }; 6548 6549 SDLoc DL(Op); 6550 6551 // Because getNegatedExpression can delete nodes we need a handle to keep 6552 // temporary nodes alive in case the recursion manages to create an identical 6553 // node. 6554 std::list<HandleSDNode> Handles; 6555 6556 switch (Opcode) { 6557 case ISD::ConstantFP: { 6558 // Don't invert constant FP values after legalization unless the target says 6559 // the negated constant is legal. 6560 bool IsOpLegal = 6561 isOperationLegal(ISD::ConstantFP, VT) || 6562 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT, 6563 OptForSize); 6564 6565 if (LegalOps && !IsOpLegal) 6566 break; 6567 6568 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 6569 V.changeSign(); 6570 SDValue CFP = DAG.getConstantFP(V, DL, VT); 6571 6572 // If we already have the use of the negated floating constant, it is free 6573 // to negate it even it has multiple uses. 6574 if (!Op.hasOneUse() && CFP.use_empty()) 6575 break; 6576 Cost = NegatibleCost::Neutral; 6577 return CFP; 6578 } 6579 case ISD::BUILD_VECTOR: { 6580 // Only permit BUILD_VECTOR of constants. 6581 if (llvm::any_of(Op->op_values(), [&](SDValue N) { 6582 return !N.isUndef() && !isa<ConstantFPSDNode>(N); 6583 })) 6584 break; 6585 6586 bool IsOpLegal = 6587 (isOperationLegal(ISD::ConstantFP, VT) && 6588 isOperationLegal(ISD::BUILD_VECTOR, VT)) || 6589 llvm::all_of(Op->op_values(), [&](SDValue N) { 6590 return N.isUndef() || 6591 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT, 6592 OptForSize); 6593 }); 6594 6595 if (LegalOps && !IsOpLegal) 6596 break; 6597 6598 SmallVector<SDValue, 4> Ops; 6599 for (SDValue C : Op->op_values()) { 6600 if (C.isUndef()) { 6601 Ops.push_back(C); 6602 continue; 6603 } 6604 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF(); 6605 V.changeSign(); 6606 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType())); 6607 } 6608 Cost = NegatibleCost::Neutral; 6609 return DAG.getBuildVector(VT, DL, Ops); 6610 } 6611 case ISD::FADD: { 6612 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6613 break; 6614 6615 // After operation legalization, it might not be legal to create new FSUBs. 6616 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT)) 6617 break; 6618 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6619 6620 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y) 6621 NegatibleCost CostX = NegatibleCost::Expensive; 6622 SDValue NegX = 6623 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6624 // Prevent this node from being deleted by the next call. 6625 if (NegX) 6626 Handles.emplace_back(NegX); 6627 6628 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X) 6629 NegatibleCost CostY = NegatibleCost::Expensive; 6630 SDValue NegY = 6631 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6632 6633 // We're done with the handles. 6634 Handles.clear(); 6635 6636 // Negate the X if its cost is less or equal than Y. 6637 if (NegX && (CostX <= CostY)) { 6638 Cost = CostX; 6639 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags); 6640 if (NegY != N) 6641 RemoveDeadNode(NegY); 6642 return N; 6643 } 6644 6645 // Negate the Y if it is not expensive. 6646 if (NegY) { 6647 Cost = CostY; 6648 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags); 6649 if (NegX != N) 6650 RemoveDeadNode(NegX); 6651 return N; 6652 } 6653 break; 6654 } 6655 case ISD::FSUB: { 6656 // We can't turn -(A-B) into B-A when we honor signed zeros. 6657 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6658 break; 6659 6660 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6661 // fold (fneg (fsub 0, Y)) -> Y 6662 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true)) 6663 if (C->isZero()) { 6664 Cost = NegatibleCost::Cheaper; 6665 return Y; 6666 } 6667 6668 // fold (fneg (fsub X, Y)) -> (fsub Y, X) 6669 Cost = NegatibleCost::Neutral; 6670 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags); 6671 } 6672 case ISD::FMUL: 6673 case ISD::FDIV: { 6674 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6675 6676 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 6677 NegatibleCost CostX = NegatibleCost::Expensive; 6678 SDValue NegX = 6679 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6680 // Prevent this node from being deleted by the next call. 6681 if (NegX) 6682 Handles.emplace_back(NegX); 6683 6684 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 6685 NegatibleCost CostY = NegatibleCost::Expensive; 6686 SDValue NegY = 6687 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6688 6689 // We're done with the handles. 6690 Handles.clear(); 6691 6692 // Negate the X if its cost is less or equal than Y. 6693 if (NegX && (CostX <= CostY)) { 6694 Cost = CostX; 6695 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags); 6696 if (NegY != N) 6697 RemoveDeadNode(NegY); 6698 return N; 6699 } 6700 6701 // Ignore X * 2.0 because that is expected to be canonicalized to X + X. 6702 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1))) 6703 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL) 6704 break; 6705 6706 // Negate the Y if it is not expensive. 6707 if (NegY) { 6708 Cost = CostY; 6709 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags); 6710 if (NegX != N) 6711 RemoveDeadNode(NegX); 6712 return N; 6713 } 6714 break; 6715 } 6716 case ISD::FMA: 6717 case ISD::FMAD: { 6718 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6719 break; 6720 6721 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2); 6722 NegatibleCost CostZ = NegatibleCost::Expensive; 6723 SDValue NegZ = 6724 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth); 6725 // Give up if fail to negate the Z. 6726 if (!NegZ) 6727 break; 6728 6729 // Prevent this node from being deleted by the next two calls. 6730 Handles.emplace_back(NegZ); 6731 6732 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z)) 6733 NegatibleCost CostX = NegatibleCost::Expensive; 6734 SDValue NegX = 6735 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6736 // Prevent this node from being deleted by the next call. 6737 if (NegX) 6738 Handles.emplace_back(NegX); 6739 6740 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z)) 6741 NegatibleCost CostY = NegatibleCost::Expensive; 6742 SDValue NegY = 6743 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6744 6745 // We're done with the handles. 6746 Handles.clear(); 6747 6748 // Negate the X if its cost is less or equal than Y. 6749 if (NegX && (CostX <= CostY)) { 6750 Cost = std::min(CostX, CostZ); 6751 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags); 6752 if (NegY != N) 6753 RemoveDeadNode(NegY); 6754 return N; 6755 } 6756 6757 // Negate the Y if it is not expensive. 6758 if (NegY) { 6759 Cost = std::min(CostY, CostZ); 6760 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags); 6761 if (NegX != N) 6762 RemoveDeadNode(NegX); 6763 return N; 6764 } 6765 break; 6766 } 6767 6768 case ISD::FP_EXTEND: 6769 case ISD::FSIN: 6770 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6771 OptForSize, Cost, Depth)) 6772 return DAG.getNode(Opcode, DL, VT, NegV); 6773 break; 6774 case ISD::FP_ROUND: 6775 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6776 OptForSize, Cost, Depth)) 6777 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1)); 6778 break; 6779 } 6780 6781 return SDValue(); 6782 } 6783 6784 //===----------------------------------------------------------------------===// 6785 // Legalization Utilities 6786 //===----------------------------------------------------------------------===// 6787 6788 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, 6789 SDValue LHS, SDValue RHS, 6790 SmallVectorImpl<SDValue> &Result, 6791 EVT HiLoVT, SelectionDAG &DAG, 6792 MulExpansionKind Kind, SDValue LL, 6793 SDValue LH, SDValue RL, SDValue RH) const { 6794 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 6795 Opcode == ISD::SMUL_LOHI); 6796 6797 bool HasMULHS = (Kind == MulExpansionKind::Always) || 6798 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 6799 bool HasMULHU = (Kind == MulExpansionKind::Always) || 6800 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 6801 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 6802 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 6803 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 6804 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 6805 6806 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 6807 return false; 6808 6809 unsigned OuterBitSize = VT.getScalarSizeInBits(); 6810 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 6811 6812 // LL, LH, RL, and RH must be either all NULL or all set to a value. 6813 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 6814 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 6815 6816 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 6817 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 6818 bool Signed) -> bool { 6819 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 6820 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 6821 Hi = SDValue(Lo.getNode(), 1); 6822 return true; 6823 } 6824 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 6825 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 6826 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 6827 return true; 6828 } 6829 return false; 6830 }; 6831 6832 SDValue Lo, Hi; 6833 6834 if (!LL.getNode() && !RL.getNode() && 6835 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6836 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 6837 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 6838 } 6839 6840 if (!LL.getNode()) 6841 return false; 6842 6843 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 6844 if (DAG.MaskedValueIsZero(LHS, HighMask) && 6845 DAG.MaskedValueIsZero(RHS, HighMask)) { 6846 // The inputs are both zero-extended. 6847 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 6848 Result.push_back(Lo); 6849 Result.push_back(Hi); 6850 if (Opcode != ISD::MUL) { 6851 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6852 Result.push_back(Zero); 6853 Result.push_back(Zero); 6854 } 6855 return true; 6856 } 6857 } 6858 6859 if (!VT.isVector() && Opcode == ISD::MUL && 6860 DAG.ComputeNumSignBits(LHS) > InnerBitSize && 6861 DAG.ComputeNumSignBits(RHS) > InnerBitSize) { 6862 // The input values are both sign-extended. 6863 // TODO non-MUL case? 6864 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 6865 Result.push_back(Lo); 6866 Result.push_back(Hi); 6867 return true; 6868 } 6869 } 6870 6871 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 6872 EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout()); 6873 SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy); 6874 6875 if (!LH.getNode() && !RH.getNode() && 6876 isOperationLegalOrCustom(ISD::SRL, VT) && 6877 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6878 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 6879 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 6880 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 6881 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 6882 } 6883 6884 if (!LH.getNode()) 6885 return false; 6886 6887 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 6888 return false; 6889 6890 Result.push_back(Lo); 6891 6892 if (Opcode == ISD::MUL) { 6893 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 6894 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 6895 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 6896 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 6897 Result.push_back(Hi); 6898 return true; 6899 } 6900 6901 // Compute the full width result. 6902 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 6903 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 6904 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6905 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 6906 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 6907 }; 6908 6909 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6910 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 6911 return false; 6912 6913 // This is effectively the add part of a multiply-add of half-sized operands, 6914 // so it cannot overflow. 6915 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 6916 6917 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 6918 return false; 6919 6920 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6921 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6922 6923 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) && 6924 isOperationLegalOrCustom(ISD::ADDE, VT)); 6925 if (UseGlue) 6926 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 6927 Merge(Lo, Hi)); 6928 else 6929 Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next, 6930 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType)); 6931 6932 SDValue Carry = Next.getValue(1); 6933 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6934 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 6935 6936 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 6937 return false; 6938 6939 if (UseGlue) 6940 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 6941 Carry); 6942 else 6943 Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi, 6944 Zero, Carry); 6945 6946 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 6947 6948 if (Opcode == ISD::SMUL_LOHI) { 6949 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 6950 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 6951 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 6952 6953 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 6954 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 6955 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 6956 } 6957 6958 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6959 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 6960 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6961 return true; 6962 } 6963 6964 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 6965 SelectionDAG &DAG, MulExpansionKind Kind, 6966 SDValue LL, SDValue LH, SDValue RL, 6967 SDValue RH) const { 6968 SmallVector<SDValue, 2> Result; 6969 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N), 6970 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 6971 DAG, Kind, LL, LH, RL, RH); 6972 if (Ok) { 6973 assert(Result.size() == 2); 6974 Lo = Result[0]; 6975 Hi = Result[1]; 6976 } 6977 return Ok; 6978 } 6979 6980 // Check that (every element of) Z is undef or not an exact multiple of BW. 6981 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) { 6982 return ISD::matchUnaryPredicate( 6983 Z, 6984 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; }, 6985 true); 6986 } 6987 6988 SDValue TargetLowering::expandFunnelShift(SDNode *Node, 6989 SelectionDAG &DAG) const { 6990 EVT VT = Node->getValueType(0); 6991 6992 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 6993 !isOperationLegalOrCustom(ISD::SRL, VT) || 6994 !isOperationLegalOrCustom(ISD::SUB, VT) || 6995 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 6996 return SDValue(); 6997 6998 SDValue X = Node->getOperand(0); 6999 SDValue Y = Node->getOperand(1); 7000 SDValue Z = Node->getOperand(2); 7001 7002 unsigned BW = VT.getScalarSizeInBits(); 7003 bool IsFSHL = Node->getOpcode() == ISD::FSHL; 7004 SDLoc DL(SDValue(Node, 0)); 7005 7006 EVT ShVT = Z.getValueType(); 7007 7008 // If a funnel shift in the other direction is more supported, use it. 7009 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL; 7010 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 7011 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) { 7012 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 7013 // fshl X, Y, Z -> fshr X, Y, -Z 7014 // fshr X, Y, Z -> fshl X, Y, -Z 7015 SDValue Zero = DAG.getConstant(0, DL, ShVT); 7016 Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z); 7017 } else { 7018 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z 7019 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z 7020 SDValue One = DAG.getConstant(1, DL, ShVT); 7021 if (IsFSHL) { 7022 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 7023 X = DAG.getNode(ISD::SRL, DL, VT, X, One); 7024 } else { 7025 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 7026 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One); 7027 } 7028 Z = DAG.getNOT(DL, Z, ShVT); 7029 } 7030 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z); 7031 } 7032 7033 SDValue ShX, ShY; 7034 SDValue ShAmt, InvShAmt; 7035 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 7036 // fshl: X << C | Y >> (BW - C) 7037 // fshr: X << (BW - C) | Y >> C 7038 // where C = Z % BW is not zero 7039 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7040 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 7041 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt); 7042 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt); 7043 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt); 7044 } else { 7045 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW)) 7046 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW) 7047 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT); 7048 if (isPowerOf2_32(BW)) { 7049 // Z % BW -> Z & (BW - 1) 7050 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask); 7051 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1) 7052 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask); 7053 } else { 7054 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7055 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 7056 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt); 7057 } 7058 7059 SDValue One = DAG.getConstant(1, DL, ShVT); 7060 if (IsFSHL) { 7061 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt); 7062 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One); 7063 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt); 7064 } else { 7065 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One); 7066 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt); 7067 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt); 7068 } 7069 } 7070 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY); 7071 } 7072 7073 // TODO: Merge with expandFunnelShift. 7074 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps, 7075 SelectionDAG &DAG) const { 7076 EVT VT = Node->getValueType(0); 7077 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 7078 bool IsLeft = Node->getOpcode() == ISD::ROTL; 7079 SDValue Op0 = Node->getOperand(0); 7080 SDValue Op1 = Node->getOperand(1); 7081 SDLoc DL(SDValue(Node, 0)); 7082 7083 EVT ShVT = Op1.getValueType(); 7084 SDValue Zero = DAG.getConstant(0, DL, ShVT); 7085 7086 // If a rotate in the other direction is more supported, use it. 7087 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL; 7088 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 7089 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) { 7090 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 7091 return DAG.getNode(RevRot, DL, VT, Op0, Sub); 7092 } 7093 7094 if (!AllowVectorOps && VT.isVector() && 7095 (!isOperationLegalOrCustom(ISD::SHL, VT) || 7096 !isOperationLegalOrCustom(ISD::SRL, VT) || 7097 !isOperationLegalOrCustom(ISD::SUB, VT) || 7098 !isOperationLegalOrCustomOrPromote(ISD::OR, VT) || 7099 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 7100 return SDValue(); 7101 7102 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL; 7103 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL; 7104 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 7105 SDValue ShVal; 7106 SDValue HsVal; 7107 if (isPowerOf2_32(EltSizeInBits)) { 7108 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1)) 7109 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1)) 7110 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 7111 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC); 7112 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 7113 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC); 7114 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt); 7115 } else { 7116 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w)) 7117 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w)) 7118 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 7119 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC); 7120 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 7121 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt); 7122 SDValue One = DAG.getConstant(1, DL, ShVT); 7123 HsVal = 7124 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt); 7125 } 7126 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal); 7127 } 7128 7129 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi, 7130 SelectionDAG &DAG) const { 7131 assert(Node->getNumOperands() == 3 && "Not a double-shift!"); 7132 EVT VT = Node->getValueType(0); 7133 unsigned VTBits = VT.getScalarSizeInBits(); 7134 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected"); 7135 7136 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS; 7137 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS; 7138 SDValue ShOpLo = Node->getOperand(0); 7139 SDValue ShOpHi = Node->getOperand(1); 7140 SDValue ShAmt = Node->getOperand(2); 7141 EVT ShAmtVT = ShAmt.getValueType(); 7142 EVT ShAmtCCVT = 7143 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT); 7144 SDLoc dl(Node); 7145 7146 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and 7147 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized 7148 // away during isel. 7149 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 7150 DAG.getConstant(VTBits - 1, dl, ShAmtVT)); 7151 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 7152 DAG.getConstant(VTBits - 1, dl, ShAmtVT)) 7153 : DAG.getConstant(0, dl, VT); 7154 7155 SDValue Tmp2, Tmp3; 7156 if (IsSHL) { 7157 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt); 7158 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt); 7159 } else { 7160 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt); 7161 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt); 7162 } 7163 7164 // If the shift amount is larger or equal than the width of a part we don't 7165 // use the result from the FSHL/FSHR. Insert a test and select the appropriate 7166 // values for large shift amounts. 7167 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 7168 DAG.getConstant(VTBits, dl, ShAmtVT)); 7169 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode, 7170 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE); 7171 7172 if (IsSHL) { 7173 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 7174 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 7175 } else { 7176 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 7177 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 7178 } 7179 } 7180 7181 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 7182 SelectionDAG &DAG) const { 7183 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 7184 SDValue Src = Node->getOperand(OpNo); 7185 EVT SrcVT = Src.getValueType(); 7186 EVT DstVT = Node->getValueType(0); 7187 SDLoc dl(SDValue(Node, 0)); 7188 7189 // FIXME: Only f32 to i64 conversions are supported. 7190 if (SrcVT != MVT::f32 || DstVT != MVT::i64) 7191 return false; 7192 7193 if (Node->isStrictFPOpcode()) 7194 // When a NaN is converted to an integer a trap is allowed. We can't 7195 // use this expansion here because it would eliminate that trap. Other 7196 // traps are also allowed and cannot be eliminated. See 7197 // IEEE 754-2008 sec 5.8. 7198 return false; 7199 7200 // Expand f32 -> i64 conversion 7201 // This algorithm comes from compiler-rt's implementation of fixsfdi: 7202 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c 7203 unsigned SrcEltBits = SrcVT.getScalarSizeInBits(); 7204 EVT IntVT = SrcVT.changeTypeToInteger(); 7205 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout()); 7206 7207 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 7208 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 7209 SDValue Bias = DAG.getConstant(127, dl, IntVT); 7210 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT); 7211 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT); 7212 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 7213 7214 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src); 7215 7216 SDValue ExponentBits = DAG.getNode( 7217 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 7218 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT)); 7219 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 7220 7221 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT, 7222 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 7223 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT)); 7224 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT); 7225 7226 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 7227 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 7228 DAG.getConstant(0x00800000, dl, IntVT)); 7229 7230 R = DAG.getZExtOrTrunc(R, dl, DstVT); 7231 7232 R = DAG.getSelectCC( 7233 dl, Exponent, ExponentLoBit, 7234 DAG.getNode(ISD::SHL, dl, DstVT, R, 7235 DAG.getZExtOrTrunc( 7236 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 7237 dl, IntShVT)), 7238 DAG.getNode(ISD::SRL, dl, DstVT, R, 7239 DAG.getZExtOrTrunc( 7240 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 7241 dl, IntShVT)), 7242 ISD::SETGT); 7243 7244 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT, 7245 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign); 7246 7247 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 7248 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT); 7249 return true; 7250 } 7251 7252 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result, 7253 SDValue &Chain, 7254 SelectionDAG &DAG) const { 7255 SDLoc dl(SDValue(Node, 0)); 7256 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 7257 SDValue Src = Node->getOperand(OpNo); 7258 7259 EVT SrcVT = Src.getValueType(); 7260 EVT DstVT = Node->getValueType(0); 7261 EVT SetCCVT = 7262 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 7263 EVT DstSetCCVT = 7264 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 7265 7266 // Only expand vector types if we have the appropriate vector bit operations. 7267 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT : 7268 ISD::FP_TO_SINT; 7269 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) || 7270 !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT))) 7271 return false; 7272 7273 // If the maximum float value is smaller then the signed integer range, 7274 // the destination signmask can't be represented by the float, so we can 7275 // just use FP_TO_SINT directly. 7276 const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT); 7277 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits())); 7278 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits()); 7279 if (APFloat::opOverflow & 7280 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) { 7281 if (Node->isStrictFPOpcode()) { 7282 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 7283 { Node->getOperand(0), Src }); 7284 Chain = Result.getValue(1); 7285 } else 7286 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 7287 return true; 7288 } 7289 7290 // Don't expand it if there isn't cheap fsub instruction. 7291 if (!isOperationLegalOrCustom( 7292 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT)) 7293 return false; 7294 7295 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 7296 SDValue Sel; 7297 7298 if (Node->isStrictFPOpcode()) { 7299 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 7300 Node->getOperand(0), /*IsSignaling*/ true); 7301 Chain = Sel.getValue(1); 7302 } else { 7303 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT); 7304 } 7305 7306 bool Strict = Node->isStrictFPOpcode() || 7307 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false); 7308 7309 if (Strict) { 7310 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the 7311 // signmask then offset (the result of which should be fully representable). 7312 // Sel = Src < 0x8000000000000000 7313 // FltOfs = select Sel, 0, 0x8000000000000000 7314 // IntOfs = select Sel, 0, 0x8000000000000000 7315 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 7316 7317 // TODO: Should any fast-math-flags be set for the FSUB? 7318 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel, 7319 DAG.getConstantFP(0.0, dl, SrcVT), Cst); 7320 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 7321 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel, 7322 DAG.getConstant(0, dl, DstVT), 7323 DAG.getConstant(SignMask, dl, DstVT)); 7324 SDValue SInt; 7325 if (Node->isStrictFPOpcode()) { 7326 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other }, 7327 { Chain, Src, FltOfs }); 7328 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 7329 { Val.getValue(1), Val }); 7330 Chain = SInt.getValue(1); 7331 } else { 7332 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs); 7333 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val); 7334 } 7335 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 7336 } else { 7337 // Expand based on maximum range of FP_TO_SINT: 7338 // True = fp_to_sint(Src) 7339 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000) 7340 // Result = select (Src < 0x8000000000000000), True, False 7341 7342 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 7343 // TODO: Should any fast-math-flags be set for the FSUB? 7344 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, 7345 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 7346 False = DAG.getNode(ISD::XOR, dl, DstVT, False, 7347 DAG.getConstant(SignMask, dl, DstVT)); 7348 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 7349 Result = DAG.getSelect(dl, DstVT, Sel, True, False); 7350 } 7351 return true; 7352 } 7353 7354 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result, 7355 SDValue &Chain, 7356 SelectionDAG &DAG) const { 7357 // This transform is not correct for converting 0 when rounding mode is set 7358 // to round toward negative infinity which will produce -0.0. So disable under 7359 // strictfp. 7360 if (Node->isStrictFPOpcode()) 7361 return false; 7362 7363 SDValue Src = Node->getOperand(0); 7364 EVT SrcVT = Src.getValueType(); 7365 EVT DstVT = Node->getValueType(0); 7366 7367 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64) 7368 return false; 7369 7370 // Only expand vector types if we have the appropriate vector bit operations. 7371 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 7372 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 7373 !isOperationLegalOrCustom(ISD::FSUB, DstVT) || 7374 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 7375 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 7376 return false; 7377 7378 SDLoc dl(SDValue(Node, 0)); 7379 EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout()); 7380 7381 // Implementation of unsigned i64 to f64 following the algorithm in 7382 // __floatundidf in compiler_rt. This implementation performs rounding 7383 // correctly in all rounding modes with the exception of converting 0 7384 // when rounding toward negative infinity. In that case the fsub will produce 7385 // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect. 7386 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT); 7387 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP( 7388 BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT); 7389 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT); 7390 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT); 7391 SDValue HiShift = DAG.getConstant(32, dl, ShiftVT); 7392 7393 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask); 7394 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift); 7395 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52); 7396 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84); 7397 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr); 7398 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr); 7399 SDValue HiSub = 7400 DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52); 7401 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub); 7402 return true; 7403 } 7404 7405 SDValue 7406 TargetLowering::createSelectForFMINNUM_FMAXNUM(SDNode *Node, 7407 SelectionDAG &DAG) const { 7408 unsigned Opcode = Node->getOpcode(); 7409 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM || 7410 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) && 7411 "Wrong opcode"); 7412 7413 if (Node->getFlags().hasNoNaNs()) { 7414 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT; 7415 SDValue Op1 = Node->getOperand(0); 7416 SDValue Op2 = Node->getOperand(1); 7417 SDValue SelCC = DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred); 7418 // Copy FMF flags, but always set the no-signed-zeros flag 7419 // as this is implied by the FMINNUM/FMAXNUM semantics. 7420 SDNodeFlags Flags = Node->getFlags(); 7421 Flags.setNoSignedZeros(true); 7422 SelCC->setFlags(Flags); 7423 return SelCC; 7424 } 7425 7426 return SDValue(); 7427 } 7428 7429 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node, 7430 SelectionDAG &DAG) const { 7431 SDLoc dl(Node); 7432 unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ? 7433 ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 7434 EVT VT = Node->getValueType(0); 7435 7436 if (VT.isScalableVector()) 7437 report_fatal_error( 7438 "Expanding fminnum/fmaxnum for scalable vectors is undefined."); 7439 7440 if (isOperationLegalOrCustom(NewOp, VT)) { 7441 SDValue Quiet0 = Node->getOperand(0); 7442 SDValue Quiet1 = Node->getOperand(1); 7443 7444 if (!Node->getFlags().hasNoNaNs()) { 7445 // Insert canonicalizes if it's possible we need to quiet to get correct 7446 // sNaN behavior. 7447 if (!DAG.isKnownNeverSNaN(Quiet0)) { 7448 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0, 7449 Node->getFlags()); 7450 } 7451 if (!DAG.isKnownNeverSNaN(Quiet1)) { 7452 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1, 7453 Node->getFlags()); 7454 } 7455 } 7456 7457 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags()); 7458 } 7459 7460 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that 7461 // instead if there are no NaNs. 7462 if (Node->getFlags().hasNoNaNs()) { 7463 unsigned IEEE2018Op = 7464 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM; 7465 if (isOperationLegalOrCustom(IEEE2018Op, VT)) { 7466 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0), 7467 Node->getOperand(1), Node->getFlags()); 7468 } 7469 } 7470 7471 if (SDValue SelCC = createSelectForFMINNUM_FMAXNUM(Node, DAG)) 7472 return SelCC; 7473 7474 return SDValue(); 7475 } 7476 7477 SDValue TargetLowering::expandIS_FPCLASS(EVT ResultVT, SDValue Op, 7478 unsigned Test, SDNodeFlags Flags, 7479 const SDLoc &DL, 7480 SelectionDAG &DAG) const { 7481 EVT OperandVT = Op.getValueType(); 7482 assert(OperandVT.isFloatingPoint()); 7483 7484 // Degenerated cases. 7485 if (Test == 0) 7486 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT); 7487 if ((Test & fcAllFlags) == fcAllFlags) 7488 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT); 7489 7490 // PPC double double is a pair of doubles, of which the higher part determines 7491 // the value class. 7492 if (OperandVT == MVT::ppcf128) { 7493 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op, 7494 DAG.getConstant(1, DL, MVT::i32)); 7495 OperandVT = MVT::f64; 7496 } 7497 7498 // Some checks may be represented as inversion of simpler check, for example 7499 // "inf|normal|subnormal|zero" => !"nan". 7500 bool IsInverted = false; 7501 if (unsigned InvertedCheck = getInvertedFPClassTest(Test)) { 7502 IsInverted = true; 7503 Test = InvertedCheck; 7504 } 7505 7506 // Floating-point type properties. 7507 EVT ScalarFloatVT = OperandVT.getScalarType(); 7508 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext()); 7509 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics(); 7510 bool IsF80 = (ScalarFloatVT == MVT::f80); 7511 7512 // Some checks can be implemented using float comparisons, if floating point 7513 // exceptions are ignored. 7514 if (Flags.hasNoFPExcept() && 7515 isOperationLegalOrCustom(ISD::SETCC, OperandVT.getScalarType())) { 7516 if (Test == fcZero) 7517 return DAG.getSetCC(DL, ResultVT, Op, 7518 DAG.getConstantFP(0.0, DL, OperandVT), 7519 IsInverted ? ISD::SETUNE : ISD::SETOEQ); 7520 if (Test == fcNan) 7521 return DAG.getSetCC(DL, ResultVT, Op, Op, 7522 IsInverted ? ISD::SETO : ISD::SETUO); 7523 } 7524 7525 // In the general case use integer operations. 7526 unsigned BitSize = OperandVT.getScalarSizeInBits(); 7527 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), BitSize); 7528 if (OperandVT.isVector()) 7529 IntVT = EVT::getVectorVT(*DAG.getContext(), IntVT, 7530 OperandVT.getVectorElementCount()); 7531 SDValue OpAsInt = DAG.getBitcast(IntVT, Op); 7532 7533 // Various masks. 7534 APInt SignBit = APInt::getSignMask(BitSize); 7535 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign. 7536 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit. 7537 const unsigned ExplicitIntBitInF80 = 63; 7538 APInt ExpMask = Inf; 7539 if (IsF80) 7540 ExpMask.clearBit(ExplicitIntBitInF80); 7541 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf; 7542 APInt QNaNBitMask = 7543 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1); 7544 APInt InvertionMask = APInt::getAllOnesValue(ResultVT.getScalarSizeInBits()); 7545 7546 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT); 7547 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT); 7548 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT); 7549 SDValue ZeroV = DAG.getConstant(0, DL, IntVT); 7550 SDValue InfV = DAG.getConstant(Inf, DL, IntVT); 7551 SDValue ResultInvertionMask = DAG.getConstant(InvertionMask, DL, ResultVT); 7552 7553 SDValue Res; 7554 const auto appendResult = [&](SDValue PartialRes) { 7555 if (PartialRes) { 7556 if (Res) 7557 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes); 7558 else 7559 Res = PartialRes; 7560 } 7561 }; 7562 7563 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set. 7564 const auto getIntBitIsSet = [&]() -> SDValue { 7565 if (!IntBitIsSetV) { 7566 APInt IntBitMask(BitSize, 0); 7567 IntBitMask.setBit(ExplicitIntBitInF80); 7568 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT); 7569 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV); 7570 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE); 7571 } 7572 return IntBitIsSetV; 7573 }; 7574 7575 // Split the value into sign bit and absolute value. 7576 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV); 7577 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt, 7578 DAG.getConstant(0.0, DL, IntVT), ISD::SETLT); 7579 7580 // Tests that involve more than one class should be processed first. 7581 SDValue PartialRes; 7582 7583 if (IsF80) 7584 ; // Detect finite numbers of f80 by checking individual classes because 7585 // they have different settings of the explicit integer bit. 7586 else if ((Test & fcFinite) == fcFinite) { 7587 // finite(V) ==> abs(V) < exp_mask 7588 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 7589 Test &= ~fcFinite; 7590 } else if ((Test & fcFinite) == fcPosFinite) { 7591 // finite(V) && V > 0 ==> V < exp_mask 7592 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT); 7593 Test &= ~fcPosFinite; 7594 } else if ((Test & fcFinite) == fcNegFinite) { 7595 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1 7596 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 7597 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7598 Test &= ~fcNegFinite; 7599 } 7600 appendResult(PartialRes); 7601 7602 // Check for individual classes. 7603 7604 if (unsigned PartialCheck = Test & fcZero) { 7605 if (PartialCheck == fcPosZero) 7606 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ); 7607 else if (PartialCheck == fcZero) 7608 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ); 7609 else // ISD::fcNegZero 7610 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ); 7611 appendResult(PartialRes); 7612 } 7613 7614 if (unsigned PartialCheck = Test & fcInf) { 7615 if (PartialCheck == fcPosInf) 7616 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ); 7617 else if (PartialCheck == fcInf) 7618 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ); 7619 else { // ISD::fcNegInf 7620 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt(); 7621 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT); 7622 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ); 7623 } 7624 appendResult(PartialRes); 7625 } 7626 7627 if (unsigned PartialCheck = Test & fcNan) { 7628 APInt InfWithQnanBit = Inf | QNaNBitMask; 7629 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT); 7630 if (PartialCheck == fcNan) { 7631 // isnan(V) ==> abs(V) > int(inf) 7632 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 7633 if (IsF80) { 7634 // Recognize unsupported values as NaNs for compatibility with glibc. 7635 // In them (exp(V)==0) == int_bit. 7636 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV); 7637 SDValue ExpIsZero = 7638 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ); 7639 SDValue IsPseudo = 7640 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ); 7641 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo); 7642 } 7643 } else if (PartialCheck == fcQNan) { 7644 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit) 7645 PartialRes = 7646 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE); 7647 } else { // ISD::fcSNan 7648 // issignaling(V) ==> abs(V) > unsigned(Inf) && 7649 // abs(V) < (unsigned(Inf) | quiet_bit) 7650 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 7651 SDValue IsNotQnan = 7652 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT); 7653 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan); 7654 } 7655 appendResult(PartialRes); 7656 } 7657 7658 if (unsigned PartialCheck = Test & fcSubnormal) { 7659 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set) 7660 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set) 7661 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV; 7662 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT); 7663 SDValue VMinusOneV = 7664 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT)); 7665 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT); 7666 if (PartialCheck == fcNegSubnormal) 7667 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7668 appendResult(PartialRes); 7669 } 7670 7671 if (unsigned PartialCheck = Test & fcNormal) { 7672 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1)) 7673 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1)); 7674 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT); 7675 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV); 7676 APInt ExpLimit = ExpMask - ExpLSB; 7677 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT); 7678 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT); 7679 if (PartialCheck == fcNegNormal) 7680 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7681 else if (PartialCheck == fcPosNormal) { 7682 SDValue PosSignV = 7683 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInvertionMask); 7684 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV); 7685 } 7686 if (IsF80) 7687 PartialRes = 7688 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet()); 7689 appendResult(PartialRes); 7690 } 7691 7692 if (!Res) 7693 return DAG.getConstant(IsInverted, DL, ResultVT); 7694 if (IsInverted) 7695 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInvertionMask); 7696 return Res; 7697 } 7698 7699 // Only expand vector types if we have the appropriate vector bit operations. 7700 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) { 7701 assert(VT.isVector() && "Expected vector type"); 7702 unsigned Len = VT.getScalarSizeInBits(); 7703 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) && 7704 TLI.isOperationLegalOrCustom(ISD::SUB, VT) && 7705 TLI.isOperationLegalOrCustom(ISD::SRL, VT) && 7706 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) && 7707 TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT); 7708 } 7709 7710 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const { 7711 SDLoc dl(Node); 7712 EVT VT = Node->getValueType(0); 7713 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7714 SDValue Op = Node->getOperand(0); 7715 unsigned Len = VT.getScalarSizeInBits(); 7716 assert(VT.isInteger() && "CTPOP not implemented for this type."); 7717 7718 // TODO: Add support for irregular type lengths. 7719 if (!(Len <= 128 && Len % 8 == 0)) 7720 return SDValue(); 7721 7722 // Only expand vector types if we have the appropriate vector bit operations. 7723 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT)) 7724 return SDValue(); 7725 7726 // This is the "best" algorithm from 7727 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 7728 SDValue Mask55 = 7729 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 7730 SDValue Mask33 = 7731 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 7732 SDValue Mask0F = 7733 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 7734 7735 // v = v - ((v >> 1) & 0x55555555...) 7736 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 7737 DAG.getNode(ISD::AND, dl, VT, 7738 DAG.getNode(ISD::SRL, dl, VT, Op, 7739 DAG.getConstant(1, dl, ShVT)), 7740 Mask55)); 7741 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 7742 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 7743 DAG.getNode(ISD::AND, dl, VT, 7744 DAG.getNode(ISD::SRL, dl, VT, Op, 7745 DAG.getConstant(2, dl, ShVT)), 7746 Mask33)); 7747 // v = (v + (v >> 4)) & 0x0F0F0F0F... 7748 Op = DAG.getNode(ISD::AND, dl, VT, 7749 DAG.getNode(ISD::ADD, dl, VT, Op, 7750 DAG.getNode(ISD::SRL, dl, VT, Op, 7751 DAG.getConstant(4, dl, ShVT))), 7752 Mask0F); 7753 7754 if (Len <= 8) 7755 return Op; 7756 7757 // Avoid the multiply if we only have 2 bytes to add. 7758 // TODO: Only doing this for scalars because vectors weren't as obviously 7759 // improved. 7760 if (Len == 16 && !VT.isVector()) { 7761 // v = (v + (v >> 8)) & 0x00FF; 7762 return DAG.getNode(ISD::AND, dl, VT, 7763 DAG.getNode(ISD::ADD, dl, VT, Op, 7764 DAG.getNode(ISD::SRL, dl, VT, Op, 7765 DAG.getConstant(8, dl, ShVT))), 7766 DAG.getConstant(0xFF, dl, VT)); 7767 } 7768 7769 // v = (v * 0x01010101...) >> (Len - 8) 7770 SDValue Mask01 = 7771 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 7772 return DAG.getNode(ISD::SRL, dl, VT, 7773 DAG.getNode(ISD::MUL, dl, VT, Op, Mask01), 7774 DAG.getConstant(Len - 8, dl, ShVT)); 7775 } 7776 7777 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const { 7778 SDLoc dl(Node); 7779 EVT VT = Node->getValueType(0); 7780 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7781 SDValue Op = Node->getOperand(0); 7782 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 7783 7784 // If the non-ZERO_UNDEF version is supported we can use that instead. 7785 if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF && 7786 isOperationLegalOrCustom(ISD::CTLZ, VT)) 7787 return DAG.getNode(ISD::CTLZ, dl, VT, Op); 7788 7789 // If the ZERO_UNDEF version is supported use that and handle the zero case. 7790 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 7791 EVT SetCCVT = 7792 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7793 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 7794 SDValue Zero = DAG.getConstant(0, dl, VT); 7795 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 7796 return DAG.getSelect(dl, VT, SrcIsZero, 7797 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ); 7798 } 7799 7800 // Only expand vector types if we have the appropriate vector bit operations. 7801 // This includes the operations needed to expand CTPOP if it isn't supported. 7802 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 7803 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 7804 !canExpandVectorCTPOP(*this, VT)) || 7805 !isOperationLegalOrCustom(ISD::SRL, VT) || 7806 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 7807 return SDValue(); 7808 7809 // for now, we do this: 7810 // x = x | (x >> 1); 7811 // x = x | (x >> 2); 7812 // ... 7813 // x = x | (x >>16); 7814 // x = x | (x >>32); // for 64-bit input 7815 // return popcount(~x); 7816 // 7817 // Ref: "Hacker's Delight" by Henry Warren 7818 for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) { 7819 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 7820 Op = DAG.getNode(ISD::OR, dl, VT, Op, 7821 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp)); 7822 } 7823 Op = DAG.getNOT(dl, Op, VT); 7824 return DAG.getNode(ISD::CTPOP, dl, VT, Op); 7825 } 7826 7827 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const { 7828 SDLoc dl(Node); 7829 EVT VT = Node->getValueType(0); 7830 SDValue Op = Node->getOperand(0); 7831 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 7832 7833 // If the non-ZERO_UNDEF version is supported we can use that instead. 7834 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF && 7835 isOperationLegalOrCustom(ISD::CTTZ, VT)) 7836 return DAG.getNode(ISD::CTTZ, dl, VT, Op); 7837 7838 // If the ZERO_UNDEF version is supported use that and handle the zero case. 7839 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) { 7840 EVT SetCCVT = 7841 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7842 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op); 7843 SDValue Zero = DAG.getConstant(0, dl, VT); 7844 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 7845 return DAG.getSelect(dl, VT, SrcIsZero, 7846 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ); 7847 } 7848 7849 // Only expand vector types if we have the appropriate vector bit operations. 7850 // This includes the operations needed to expand CTPOP if it isn't supported. 7851 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 7852 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 7853 !isOperationLegalOrCustom(ISD::CTLZ, VT) && 7854 !canExpandVectorCTPOP(*this, VT)) || 7855 !isOperationLegalOrCustom(ISD::SUB, VT) || 7856 !isOperationLegalOrCustomOrPromote(ISD::AND, VT) || 7857 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 7858 return SDValue(); 7859 7860 // for now, we use: { return popcount(~x & (x - 1)); } 7861 // unless the target has ctlz but not ctpop, in which case we use: 7862 // { return 32 - nlz(~x & (x-1)); } 7863 // Ref: "Hacker's Delight" by Henry Warren 7864 SDValue Tmp = DAG.getNode( 7865 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT), 7866 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT))); 7867 7868 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 7869 if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) { 7870 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT), 7871 DAG.getNode(ISD::CTLZ, dl, VT, Tmp)); 7872 } 7873 7874 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp); 7875 } 7876 7877 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG, 7878 bool IsNegative) const { 7879 SDLoc dl(N); 7880 EVT VT = N->getValueType(0); 7881 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7882 SDValue Op = N->getOperand(0); 7883 7884 // abs(x) -> smax(x,sub(0,x)) 7885 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 7886 isOperationLegal(ISD::SMAX, VT)) { 7887 SDValue Zero = DAG.getConstant(0, dl, VT); 7888 return DAG.getNode(ISD::SMAX, dl, VT, Op, 7889 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7890 } 7891 7892 // abs(x) -> umin(x,sub(0,x)) 7893 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 7894 isOperationLegal(ISD::UMIN, VT)) { 7895 SDValue Zero = DAG.getConstant(0, dl, VT); 7896 Op = DAG.getFreeze(Op); 7897 return DAG.getNode(ISD::UMIN, dl, VT, Op, 7898 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7899 } 7900 7901 // 0 - abs(x) -> smin(x, sub(0,x)) 7902 if (IsNegative && isOperationLegal(ISD::SUB, VT) && 7903 isOperationLegal(ISD::SMIN, VT)) { 7904 Op = DAG.getFreeze(Op); 7905 SDValue Zero = DAG.getConstant(0, dl, VT); 7906 return DAG.getNode(ISD::SMIN, dl, VT, Op, 7907 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7908 } 7909 7910 // Only expand vector types if we have the appropriate vector operations. 7911 if (VT.isVector() && 7912 (!isOperationLegalOrCustom(ISD::SRA, VT) || 7913 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) || 7914 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) || 7915 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 7916 return SDValue(); 7917 7918 Op = DAG.getFreeze(Op); 7919 SDValue Shift = 7920 DAG.getNode(ISD::SRA, dl, VT, Op, 7921 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT)); 7922 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift); 7923 7924 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y) 7925 if (!IsNegative) 7926 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift); 7927 7928 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y)) 7929 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor); 7930 } 7931 7932 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const { 7933 SDLoc dl(N); 7934 EVT VT = N->getValueType(0); 7935 SDValue Op = N->getOperand(0); 7936 7937 if (!VT.isSimple()) 7938 return SDValue(); 7939 7940 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7941 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 7942 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 7943 default: 7944 return SDValue(); 7945 case MVT::i16: 7946 // Use a rotate by 8. This can be further expanded if necessary. 7947 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7948 case MVT::i32: 7949 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7950 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7951 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7952 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7953 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 7954 DAG.getConstant(0xFF0000, dl, VT)); 7955 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT)); 7956 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 7957 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 7958 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 7959 case MVT::i64: 7960 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 7961 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 7962 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7963 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7964 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7965 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7966 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 7967 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 7968 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, 7969 DAG.getConstant(255ULL<<48, dl, VT)); 7970 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, 7971 DAG.getConstant(255ULL<<40, dl, VT)); 7972 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, 7973 DAG.getConstant(255ULL<<32, dl, VT)); 7974 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, 7975 DAG.getConstant(255ULL<<24, dl, VT)); 7976 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 7977 DAG.getConstant(255ULL<<16, dl, VT)); 7978 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, 7979 DAG.getConstant(255ULL<<8 , dl, VT)); 7980 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7); 7981 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5); 7982 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 7983 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 7984 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6); 7985 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 7986 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4); 7987 } 7988 } 7989 7990 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const { 7991 SDLoc dl(N); 7992 EVT VT = N->getValueType(0); 7993 SDValue Op = N->getOperand(0); 7994 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7995 unsigned Sz = VT.getScalarSizeInBits(); 7996 7997 SDValue Tmp, Tmp2, Tmp3; 7998 7999 // If we can, perform BSWAP first and then the mask+swap the i4, then i2 8000 // and finally the i1 pairs. 8001 // TODO: We can easily support i4/i2 legal types if any target ever does. 8002 if (Sz >= 8 && isPowerOf2_32(Sz)) { 8003 // Create the masks - repeating the pattern every byte. 8004 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F)); 8005 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33)); 8006 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55)); 8007 8008 // BSWAP if the type is wider than a single byte. 8009 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op); 8010 8011 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4) 8012 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT)); 8013 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT)); 8014 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT)); 8015 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT)); 8016 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8017 8018 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2) 8019 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT)); 8020 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT)); 8021 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT)); 8022 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT)); 8023 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8024 8025 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1) 8026 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT)); 8027 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT)); 8028 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT)); 8029 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT)); 8030 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8031 return Tmp; 8032 } 8033 8034 Tmp = DAG.getConstant(0, dl, VT); 8035 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) { 8036 if (I < J) 8037 Tmp2 = 8038 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT)); 8039 else 8040 Tmp2 = 8041 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT)); 8042 8043 APInt Shift(Sz, 1); 8044 Shift <<= J; 8045 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT)); 8046 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2); 8047 } 8048 8049 return Tmp; 8050 } 8051 8052 std::pair<SDValue, SDValue> 8053 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 8054 SelectionDAG &DAG) const { 8055 SDLoc SL(LD); 8056 SDValue Chain = LD->getChain(); 8057 SDValue BasePTR = LD->getBasePtr(); 8058 EVT SrcVT = LD->getMemoryVT(); 8059 EVT DstVT = LD->getValueType(0); 8060 ISD::LoadExtType ExtType = LD->getExtensionType(); 8061 8062 if (SrcVT.isScalableVector()) 8063 report_fatal_error("Cannot scalarize scalable vector loads"); 8064 8065 unsigned NumElem = SrcVT.getVectorNumElements(); 8066 8067 EVT SrcEltVT = SrcVT.getScalarType(); 8068 EVT DstEltVT = DstVT.getScalarType(); 8069 8070 // A vector must always be stored in memory as-is, i.e. without any padding 8071 // between the elements, since various code depend on it, e.g. in the 8072 // handling of a bitcast of a vector type to int, which may be done with a 8073 // vector store followed by an integer load. A vector that does not have 8074 // elements that are byte-sized must therefore be stored as an integer 8075 // built out of the extracted vector elements. 8076 if (!SrcEltVT.isByteSized()) { 8077 unsigned NumLoadBits = SrcVT.getStoreSizeInBits(); 8078 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits); 8079 8080 unsigned NumSrcBits = SrcVT.getSizeInBits(); 8081 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits); 8082 8083 unsigned SrcEltBits = SrcEltVT.getSizeInBits(); 8084 SDValue SrcEltBitMask = DAG.getConstant( 8085 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT); 8086 8087 // Load the whole vector and avoid masking off the top bits as it makes 8088 // the codegen worse. 8089 SDValue Load = 8090 DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, 8091 LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(), 8092 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 8093 8094 SmallVector<SDValue, 8> Vals; 8095 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8096 unsigned ShiftIntoIdx = 8097 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 8098 SDValue ShiftAmount = 8099 DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(), 8100 LoadVT, SL, /*LegalTypes=*/false); 8101 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount); 8102 SDValue Elt = 8103 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask); 8104 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt); 8105 8106 if (ExtType != ISD::NON_EXTLOAD) { 8107 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType); 8108 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar); 8109 } 8110 8111 Vals.push_back(Scalar); 8112 } 8113 8114 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 8115 return std::make_pair(Value, Load.getValue(1)); 8116 } 8117 8118 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 8119 assert(SrcEltVT.isByteSized()); 8120 8121 SmallVector<SDValue, 8> Vals; 8122 SmallVector<SDValue, 8> LoadChains; 8123 8124 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8125 SDValue ScalarLoad = 8126 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 8127 LD->getPointerInfo().getWithOffset(Idx * Stride), 8128 SrcEltVT, LD->getOriginalAlign(), 8129 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 8130 8131 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride)); 8132 8133 Vals.push_back(ScalarLoad.getValue(0)); 8134 LoadChains.push_back(ScalarLoad.getValue(1)); 8135 } 8136 8137 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 8138 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 8139 8140 return std::make_pair(Value, NewChain); 8141 } 8142 8143 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 8144 SelectionDAG &DAG) const { 8145 SDLoc SL(ST); 8146 8147 SDValue Chain = ST->getChain(); 8148 SDValue BasePtr = ST->getBasePtr(); 8149 SDValue Value = ST->getValue(); 8150 EVT StVT = ST->getMemoryVT(); 8151 8152 if (StVT.isScalableVector()) 8153 report_fatal_error("Cannot scalarize scalable vector stores"); 8154 8155 // The type of the data we want to save 8156 EVT RegVT = Value.getValueType(); 8157 EVT RegSclVT = RegVT.getScalarType(); 8158 8159 // The type of data as saved in memory. 8160 EVT MemSclVT = StVT.getScalarType(); 8161 8162 unsigned NumElem = StVT.getVectorNumElements(); 8163 8164 // A vector must always be stored in memory as-is, i.e. without any padding 8165 // between the elements, since various code depend on it, e.g. in the 8166 // handling of a bitcast of a vector type to int, which may be done with a 8167 // vector store followed by an integer load. A vector that does not have 8168 // elements that are byte-sized must therefore be stored as an integer 8169 // built out of the extracted vector elements. 8170 if (!MemSclVT.isByteSized()) { 8171 unsigned NumBits = StVT.getSizeInBits(); 8172 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 8173 8174 SDValue CurrVal = DAG.getConstant(0, SL, IntVT); 8175 8176 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8177 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 8178 DAG.getVectorIdxConstant(Idx, SL)); 8179 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt); 8180 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc); 8181 unsigned ShiftIntoIdx = 8182 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 8183 SDValue ShiftAmount = 8184 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT); 8185 SDValue ShiftedElt = 8186 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount); 8187 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt); 8188 } 8189 8190 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(), 8191 ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 8192 ST->getAAInfo()); 8193 } 8194 8195 // Store Stride in bytes 8196 unsigned Stride = MemSclVT.getSizeInBits() / 8; 8197 assert(Stride && "Zero stride!"); 8198 // Extract each of the elements from the original vector and save them into 8199 // memory individually. 8200 SmallVector<SDValue, 8> Stores; 8201 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8202 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 8203 DAG.getVectorIdxConstant(Idx, SL)); 8204 8205 SDValue Ptr = 8206 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride)); 8207 8208 // This scalar TruncStore may be illegal, but we legalize it later. 8209 SDValue Store = DAG.getTruncStore( 8210 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 8211 MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 8212 ST->getAAInfo()); 8213 8214 Stores.push_back(Store); 8215 } 8216 8217 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 8218 } 8219 8220 std::pair<SDValue, SDValue> 8221 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 8222 assert(LD->getAddressingMode() == ISD::UNINDEXED && 8223 "unaligned indexed loads not implemented!"); 8224 SDValue Chain = LD->getChain(); 8225 SDValue Ptr = LD->getBasePtr(); 8226 EVT VT = LD->getValueType(0); 8227 EVT LoadedVT = LD->getMemoryVT(); 8228 SDLoc dl(LD); 8229 auto &MF = DAG.getMachineFunction(); 8230 8231 if (VT.isFloatingPoint() || VT.isVector()) { 8232 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 8233 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 8234 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) && 8235 LoadedVT.isVector()) { 8236 // Scalarize the load and let the individual components be handled. 8237 return scalarizeVectorLoad(LD, DAG); 8238 } 8239 8240 // Expand to a (misaligned) integer load of the same size, 8241 // then bitconvert to floating point or vector. 8242 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 8243 LD->getMemOperand()); 8244 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 8245 if (LoadedVT != VT) 8246 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 8247 ISD::ANY_EXTEND, dl, VT, Result); 8248 8249 return std::make_pair(Result, newLoad.getValue(1)); 8250 } 8251 8252 // Copy the value to a (aligned) stack slot using (unaligned) integer 8253 // loads and stores, then do a (aligned) load from the stack slot. 8254 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 8255 unsigned LoadedBytes = LoadedVT.getStoreSize(); 8256 unsigned RegBytes = RegVT.getSizeInBits() / 8; 8257 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 8258 8259 // Make sure the stack slot is also aligned for the register type. 8260 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 8261 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex(); 8262 SmallVector<SDValue, 8> Stores; 8263 SDValue StackPtr = StackBase; 8264 unsigned Offset = 0; 8265 8266 EVT PtrVT = Ptr.getValueType(); 8267 EVT StackPtrVT = StackPtr.getValueType(); 8268 8269 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 8270 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 8271 8272 // Do all but one copies using the full register width. 8273 for (unsigned i = 1; i < NumRegs; i++) { 8274 // Load one integer register's worth from the original location. 8275 SDValue Load = DAG.getLoad( 8276 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 8277 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 8278 LD->getAAInfo()); 8279 // Follow the load with a store to the stack slot. Remember the store. 8280 Stores.push_back(DAG.getStore( 8281 Load.getValue(1), dl, Load, StackPtr, 8282 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset))); 8283 // Increment the pointers. 8284 Offset += RegBytes; 8285 8286 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 8287 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 8288 } 8289 8290 // The last copy may be partial. Do an extending load. 8291 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 8292 8 * (LoadedBytes - Offset)); 8293 SDValue Load = 8294 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 8295 LD->getPointerInfo().getWithOffset(Offset), MemVT, 8296 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 8297 LD->getAAInfo()); 8298 // Follow the load with a store to the stack slot. Remember the store. 8299 // On big-endian machines this requires a truncating store to ensure 8300 // that the bits end up in the right place. 8301 Stores.push_back(DAG.getTruncStore( 8302 Load.getValue(1), dl, Load, StackPtr, 8303 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT)); 8304 8305 // The order of the stores doesn't matter - say it with a TokenFactor. 8306 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8307 8308 // Finally, perform the original load only redirected to the stack slot. 8309 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 8310 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), 8311 LoadedVT); 8312 8313 // Callers expect a MERGE_VALUES node. 8314 return std::make_pair(Load, TF); 8315 } 8316 8317 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 8318 "Unaligned load of unsupported type."); 8319 8320 // Compute the new VT that is half the size of the old one. This is an 8321 // integer MVT. 8322 unsigned NumBits = LoadedVT.getSizeInBits(); 8323 EVT NewLoadedVT; 8324 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 8325 NumBits >>= 1; 8326 8327 Align Alignment = LD->getOriginalAlign(); 8328 unsigned IncrementSize = NumBits / 8; 8329 ISD::LoadExtType HiExtType = LD->getExtensionType(); 8330 8331 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 8332 if (HiExtType == ISD::NON_EXTLOAD) 8333 HiExtType = ISD::ZEXTLOAD; 8334 8335 // Load the value in two parts 8336 SDValue Lo, Hi; 8337 if (DAG.getDataLayout().isLittleEndian()) { 8338 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 8339 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8340 LD->getAAInfo()); 8341 8342 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8343 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 8344 LD->getPointerInfo().getWithOffset(IncrementSize), 8345 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8346 LD->getAAInfo()); 8347 } else { 8348 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 8349 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8350 LD->getAAInfo()); 8351 8352 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8353 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 8354 LD->getPointerInfo().getWithOffset(IncrementSize), 8355 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8356 LD->getAAInfo()); 8357 } 8358 8359 // aggregate the two parts 8360 SDValue ShiftAmount = 8361 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(), 8362 DAG.getDataLayout())); 8363 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 8364 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 8365 8366 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 8367 Hi.getValue(1)); 8368 8369 return std::make_pair(Result, TF); 8370 } 8371 8372 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 8373 SelectionDAG &DAG) const { 8374 assert(ST->getAddressingMode() == ISD::UNINDEXED && 8375 "unaligned indexed stores not implemented!"); 8376 SDValue Chain = ST->getChain(); 8377 SDValue Ptr = ST->getBasePtr(); 8378 SDValue Val = ST->getValue(); 8379 EVT VT = Val.getValueType(); 8380 Align Alignment = ST->getOriginalAlign(); 8381 auto &MF = DAG.getMachineFunction(); 8382 EVT StoreMemVT = ST->getMemoryVT(); 8383 8384 SDLoc dl(ST); 8385 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) { 8386 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8387 if (isTypeLegal(intVT)) { 8388 if (!isOperationLegalOrCustom(ISD::STORE, intVT) && 8389 StoreMemVT.isVector()) { 8390 // Scalarize the store and let the individual components be handled. 8391 SDValue Result = scalarizeVectorStore(ST, DAG); 8392 return Result; 8393 } 8394 // Expand to a bitconvert of the value to the integer type of the 8395 // same size, then a (misaligned) int store. 8396 // FIXME: Does not handle truncating floating point stores! 8397 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 8398 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 8399 Alignment, ST->getMemOperand()->getFlags()); 8400 return Result; 8401 } 8402 // Do a (aligned) store to a stack slot, then copy from the stack slot 8403 // to the final destination using (unaligned) integer loads and stores. 8404 MVT RegVT = getRegisterType( 8405 *DAG.getContext(), 8406 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits())); 8407 EVT PtrVT = Ptr.getValueType(); 8408 unsigned StoredBytes = StoreMemVT.getStoreSize(); 8409 unsigned RegBytes = RegVT.getSizeInBits() / 8; 8410 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 8411 8412 // Make sure the stack slot is also aligned for the register type. 8413 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT); 8414 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 8415 8416 // Perform the original store, only redirected to the stack slot. 8417 SDValue Store = DAG.getTruncStore( 8418 Chain, dl, Val, StackPtr, 8419 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT); 8420 8421 EVT StackPtrVT = StackPtr.getValueType(); 8422 8423 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 8424 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 8425 SmallVector<SDValue, 8> Stores; 8426 unsigned Offset = 0; 8427 8428 // Do all but one copies using the full register width. 8429 for (unsigned i = 1; i < NumRegs; i++) { 8430 // Load one integer register's worth from the stack slot. 8431 SDValue Load = DAG.getLoad( 8432 RegVT, dl, Store, StackPtr, 8433 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)); 8434 // Store it to the final location. Remember the store. 8435 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 8436 ST->getPointerInfo().getWithOffset(Offset), 8437 ST->getOriginalAlign(), 8438 ST->getMemOperand()->getFlags())); 8439 // Increment the pointers. 8440 Offset += RegBytes; 8441 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 8442 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 8443 } 8444 8445 // The last store may be partial. Do a truncating store. On big-endian 8446 // machines this requires an extending load from the stack slot to ensure 8447 // that the bits are in the right place. 8448 EVT LoadMemVT = 8449 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset)); 8450 8451 // Load from the stack slot. 8452 SDValue Load = DAG.getExtLoad( 8453 ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 8454 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT); 8455 8456 Stores.push_back( 8457 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 8458 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT, 8459 ST->getOriginalAlign(), 8460 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 8461 // The order of the stores doesn't matter - say it with a TokenFactor. 8462 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8463 return Result; 8464 } 8465 8466 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() && 8467 "Unaligned store of unknown type."); 8468 // Get the half-size VT 8469 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext()); 8470 unsigned NumBits = NewStoredVT.getFixedSizeInBits(); 8471 unsigned IncrementSize = NumBits / 8; 8472 8473 // Divide the stored value in two parts. 8474 SDValue ShiftAmount = DAG.getConstant( 8475 NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout())); 8476 SDValue Lo = Val; 8477 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 8478 8479 // Store the two parts 8480 SDValue Store1, Store2; 8481 Store1 = DAG.getTruncStore(Chain, dl, 8482 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 8483 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 8484 ST->getMemOperand()->getFlags()); 8485 8486 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8487 Store2 = DAG.getTruncStore( 8488 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 8489 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 8490 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 8491 8492 SDValue Result = 8493 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 8494 return Result; 8495 } 8496 8497 SDValue 8498 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 8499 const SDLoc &DL, EVT DataVT, 8500 SelectionDAG &DAG, 8501 bool IsCompressedMemory) const { 8502 SDValue Increment; 8503 EVT AddrVT = Addr.getValueType(); 8504 EVT MaskVT = Mask.getValueType(); 8505 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() && 8506 "Incompatible types of Data and Mask"); 8507 if (IsCompressedMemory) { 8508 if (DataVT.isScalableVector()) 8509 report_fatal_error( 8510 "Cannot currently handle compressed memory with scalable vectors"); 8511 // Incrementing the pointer according to number of '1's in the mask. 8512 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 8513 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 8514 if (MaskIntVT.getSizeInBits() < 32) { 8515 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 8516 MaskIntVT = MVT::i32; 8517 } 8518 8519 // Count '1's with POPCNT. 8520 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 8521 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 8522 // Scale is an element size in bytes. 8523 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 8524 AddrVT); 8525 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 8526 } else if (DataVT.isScalableVector()) { 8527 Increment = DAG.getVScale(DL, AddrVT, 8528 APInt(AddrVT.getFixedSizeInBits(), 8529 DataVT.getStoreSize().getKnownMinSize())); 8530 } else 8531 Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT); 8532 8533 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 8534 } 8535 8536 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx, 8537 EVT VecVT, const SDLoc &dl, 8538 ElementCount SubEC) { 8539 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) && 8540 "Cannot index a scalable vector within a fixed-width vector"); 8541 8542 unsigned NElts = VecVT.getVectorMinNumElements(); 8543 unsigned NumSubElts = SubEC.getKnownMinValue(); 8544 EVT IdxVT = Idx.getValueType(); 8545 8546 if (VecVT.isScalableVector() && !SubEC.isScalable()) { 8547 // If this is a constant index and we know the value plus the number of the 8548 // elements in the subvector minus one is less than the minimum number of 8549 // elements then it's safe to return Idx. 8550 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx)) 8551 if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts) 8552 return Idx; 8553 SDValue VS = 8554 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts)); 8555 unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT; 8556 SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS, 8557 DAG.getConstant(NumSubElts, dl, IdxVT)); 8558 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub); 8559 } 8560 if (isPowerOf2_32(NElts) && NumSubElts == 1) { 8561 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts)); 8562 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 8563 DAG.getConstant(Imm, dl, IdxVT)); 8564 } 8565 unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0; 8566 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 8567 DAG.getConstant(MaxIndex, dl, IdxVT)); 8568 } 8569 8570 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 8571 SDValue VecPtr, EVT VecVT, 8572 SDValue Index) const { 8573 return getVectorSubVecPointer( 8574 DAG, VecPtr, VecVT, 8575 EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1), 8576 Index); 8577 } 8578 8579 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG, 8580 SDValue VecPtr, EVT VecVT, 8581 EVT SubVecVT, 8582 SDValue Index) const { 8583 SDLoc dl(Index); 8584 // Make sure the index type is big enough to compute in. 8585 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType()); 8586 8587 EVT EltVT = VecVT.getVectorElementType(); 8588 8589 // Calculate the element offset and add it to the pointer. 8590 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size. 8591 assert(EltSize * 8 == EltVT.getFixedSizeInBits() && 8592 "Converting bits to bytes lost precision"); 8593 assert(SubVecVT.getVectorElementType() == EltVT && 8594 "Sub-vector must be a vector with matching element type"); 8595 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl, 8596 SubVecVT.getVectorElementCount()); 8597 8598 EVT IdxVT = Index.getValueType(); 8599 if (SubVecVT.isScalableVector()) 8600 Index = 8601 DAG.getNode(ISD::MUL, dl, IdxVT, Index, 8602 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1))); 8603 8604 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 8605 DAG.getConstant(EltSize, dl, IdxVT)); 8606 return DAG.getMemBasePlusOffset(VecPtr, Index, dl); 8607 } 8608 8609 //===----------------------------------------------------------------------===// 8610 // Implementation of Emulated TLS Model 8611 //===----------------------------------------------------------------------===// 8612 8613 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 8614 SelectionDAG &DAG) const { 8615 // Access to address of TLS varialbe xyz is lowered to a function call: 8616 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 8617 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8618 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 8619 SDLoc dl(GA); 8620 8621 ArgListTy Args; 8622 ArgListEntry Entry; 8623 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 8624 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 8625 StringRef EmuTlsVarName(NameString); 8626 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 8627 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 8628 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 8629 Entry.Ty = VoidPtrType; 8630 Args.push_back(Entry); 8631 8632 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 8633 8634 TargetLowering::CallLoweringInfo CLI(DAG); 8635 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 8636 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 8637 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 8638 8639 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 8640 // At last for X86 targets, maybe good for other targets too? 8641 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8642 MFI.setAdjustsStack(true); // Is this only for X86 target? 8643 MFI.setHasCalls(true); 8644 8645 assert((GA->getOffset() == 0) && 8646 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 8647 return CallResult.first; 8648 } 8649 8650 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 8651 SelectionDAG &DAG) const { 8652 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 8653 if (!isCtlzFast()) 8654 return SDValue(); 8655 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8656 SDLoc dl(Op); 8657 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8658 if (C->isZero() && CC == ISD::SETEQ) { 8659 EVT VT = Op.getOperand(0).getValueType(); 8660 SDValue Zext = Op.getOperand(0); 8661 if (VT.bitsLT(MVT::i32)) { 8662 VT = MVT::i32; 8663 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 8664 } 8665 unsigned Log2b = Log2_32(VT.getSizeInBits()); 8666 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 8667 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 8668 DAG.getConstant(Log2b, dl, MVT::i32)); 8669 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 8670 } 8671 } 8672 return SDValue(); 8673 } 8674 8675 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const { 8676 SDValue Op0 = Node->getOperand(0); 8677 SDValue Op1 = Node->getOperand(1); 8678 EVT VT = Op0.getValueType(); 8679 unsigned Opcode = Node->getOpcode(); 8680 SDLoc DL(Node); 8681 8682 // umin(x,y) -> sub(x,usubsat(x,y)) 8683 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) && 8684 isOperationLegal(ISD::USUBSAT, VT)) { 8685 return DAG.getNode(ISD::SUB, DL, VT, Op0, 8686 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1)); 8687 } 8688 8689 // umax(x,y) -> add(x,usubsat(y,x)) 8690 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) && 8691 isOperationLegal(ISD::USUBSAT, VT)) { 8692 return DAG.getNode(ISD::ADD, DL, VT, Op0, 8693 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0)); 8694 } 8695 8696 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 8697 ISD::CondCode CC; 8698 switch (Opcode) { 8699 default: llvm_unreachable("How did we get here?"); 8700 case ISD::SMAX: CC = ISD::SETGT; break; 8701 case ISD::SMIN: CC = ISD::SETLT; break; 8702 case ISD::UMAX: CC = ISD::SETUGT; break; 8703 case ISD::UMIN: CC = ISD::SETULT; break; 8704 } 8705 8706 // FIXME: Should really try to split the vector in case it's legal on a 8707 // subvector. 8708 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8709 return DAG.UnrollVectorOp(Node); 8710 8711 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8712 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC); 8713 return DAG.getSelect(DL, VT, Cond, Op0, Op1); 8714 } 8715 8716 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const { 8717 unsigned Opcode = Node->getOpcode(); 8718 SDValue LHS = Node->getOperand(0); 8719 SDValue RHS = Node->getOperand(1); 8720 EVT VT = LHS.getValueType(); 8721 SDLoc dl(Node); 8722 8723 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 8724 assert(VT.isInteger() && "Expected operands to be integers"); 8725 8726 // usub.sat(a, b) -> umax(a, b) - b 8727 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) { 8728 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS); 8729 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS); 8730 } 8731 8732 // uadd.sat(a, b) -> umin(a, ~b) + b 8733 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) { 8734 SDValue InvRHS = DAG.getNOT(dl, RHS, VT); 8735 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS); 8736 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS); 8737 } 8738 8739 unsigned OverflowOp; 8740 switch (Opcode) { 8741 case ISD::SADDSAT: 8742 OverflowOp = ISD::SADDO; 8743 break; 8744 case ISD::UADDSAT: 8745 OverflowOp = ISD::UADDO; 8746 break; 8747 case ISD::SSUBSAT: 8748 OverflowOp = ISD::SSUBO; 8749 break; 8750 case ISD::USUBSAT: 8751 OverflowOp = ISD::USUBO; 8752 break; 8753 default: 8754 llvm_unreachable("Expected method to receive signed or unsigned saturation " 8755 "addition or subtraction node."); 8756 } 8757 8758 // FIXME: Should really try to split the vector in case it's legal on a 8759 // subvector. 8760 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8761 return DAG.UnrollVectorOp(Node); 8762 8763 unsigned BitWidth = LHS.getScalarValueSizeInBits(); 8764 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8765 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8766 SDValue SumDiff = Result.getValue(0); 8767 SDValue Overflow = Result.getValue(1); 8768 SDValue Zero = DAG.getConstant(0, dl, VT); 8769 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT); 8770 8771 if (Opcode == ISD::UADDSAT) { 8772 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 8773 // (LHS + RHS) | OverflowMask 8774 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 8775 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask); 8776 } 8777 // Overflow ? 0xffff.... : (LHS + RHS) 8778 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff); 8779 } 8780 8781 if (Opcode == ISD::USUBSAT) { 8782 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 8783 // (LHS - RHS) & ~OverflowMask 8784 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 8785 SDValue Not = DAG.getNOT(dl, OverflowMask, VT); 8786 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not); 8787 } 8788 // Overflow ? 0 : (LHS - RHS) 8789 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff); 8790 } 8791 8792 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff 8793 APInt MinVal = APInt::getSignedMinValue(BitWidth); 8794 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 8795 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff, 8796 DAG.getConstant(BitWidth - 1, dl, VT)); 8797 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin); 8798 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff); 8799 } 8800 8801 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const { 8802 unsigned Opcode = Node->getOpcode(); 8803 bool IsSigned = Opcode == ISD::SSHLSAT; 8804 SDValue LHS = Node->getOperand(0); 8805 SDValue RHS = Node->getOperand(1); 8806 EVT VT = LHS.getValueType(); 8807 SDLoc dl(Node); 8808 8809 assert((Node->getOpcode() == ISD::SSHLSAT || 8810 Node->getOpcode() == ISD::USHLSAT) && 8811 "Expected a SHLSAT opcode"); 8812 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 8813 assert(VT.isInteger() && "Expected operands to be integers"); 8814 8815 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate. 8816 8817 unsigned BW = VT.getScalarSizeInBits(); 8818 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS); 8819 SDValue Orig = 8820 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS); 8821 8822 SDValue SatVal; 8823 if (IsSigned) { 8824 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT); 8825 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT); 8826 SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT), 8827 SatMin, SatMax, ISD::SETLT); 8828 } else { 8829 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT); 8830 } 8831 Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE); 8832 8833 return Result; 8834 } 8835 8836 SDValue 8837 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const { 8838 assert((Node->getOpcode() == ISD::SMULFIX || 8839 Node->getOpcode() == ISD::UMULFIX || 8840 Node->getOpcode() == ISD::SMULFIXSAT || 8841 Node->getOpcode() == ISD::UMULFIXSAT) && 8842 "Expected a fixed point multiplication opcode"); 8843 8844 SDLoc dl(Node); 8845 SDValue LHS = Node->getOperand(0); 8846 SDValue RHS = Node->getOperand(1); 8847 EVT VT = LHS.getValueType(); 8848 unsigned Scale = Node->getConstantOperandVal(2); 8849 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT || 8850 Node->getOpcode() == ISD::UMULFIXSAT); 8851 bool Signed = (Node->getOpcode() == ISD::SMULFIX || 8852 Node->getOpcode() == ISD::SMULFIXSAT); 8853 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8854 unsigned VTSize = VT.getScalarSizeInBits(); 8855 8856 if (!Scale) { 8857 // [us]mul.fix(a, b, 0) -> mul(a, b) 8858 if (!Saturating) { 8859 if (isOperationLegalOrCustom(ISD::MUL, VT)) 8860 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8861 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) { 8862 SDValue Result = 8863 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8864 SDValue Product = Result.getValue(0); 8865 SDValue Overflow = Result.getValue(1); 8866 SDValue Zero = DAG.getConstant(0, dl, VT); 8867 8868 APInt MinVal = APInt::getSignedMinValue(VTSize); 8869 APInt MaxVal = APInt::getSignedMaxValue(VTSize); 8870 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 8871 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 8872 // Xor the inputs, if resulting sign bit is 0 the product will be 8873 // positive, else negative. 8874 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS); 8875 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT); 8876 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax); 8877 return DAG.getSelect(dl, VT, Overflow, Result, Product); 8878 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) { 8879 SDValue Result = 8880 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8881 SDValue Product = Result.getValue(0); 8882 SDValue Overflow = Result.getValue(1); 8883 8884 APInt MaxVal = APInt::getMaxValue(VTSize); 8885 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 8886 return DAG.getSelect(dl, VT, Overflow, SatMax, Product); 8887 } 8888 } 8889 8890 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) && 8891 "Expected scale to be less than the number of bits if signed or at " 8892 "most the number of bits if unsigned."); 8893 assert(LHS.getValueType() == RHS.getValueType() && 8894 "Expected both operands to be the same type"); 8895 8896 // Get the upper and lower bits of the result. 8897 SDValue Lo, Hi; 8898 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI; 8899 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU; 8900 if (isOperationLegalOrCustom(LoHiOp, VT)) { 8901 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS); 8902 Lo = Result.getValue(0); 8903 Hi = Result.getValue(1); 8904 } else if (isOperationLegalOrCustom(HiOp, VT)) { 8905 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8906 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS); 8907 } else if (VT.isVector()) { 8908 return SDValue(); 8909 } else { 8910 report_fatal_error("Unable to expand fixed point multiplication."); 8911 } 8912 8913 if (Scale == VTSize) 8914 // Result is just the top half since we'd be shifting by the width of the 8915 // operand. Overflow impossible so this works for both UMULFIX and 8916 // UMULFIXSAT. 8917 return Hi; 8918 8919 // The result will need to be shifted right by the scale since both operands 8920 // are scaled. The result is given to us in 2 halves, so we only want part of 8921 // both in the result. 8922 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 8923 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo, 8924 DAG.getConstant(Scale, dl, ShiftTy)); 8925 if (!Saturating) 8926 return Result; 8927 8928 if (!Signed) { 8929 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the 8930 // widened multiplication) aren't all zeroes. 8931 8932 // Saturate to max if ((Hi >> Scale) != 0), 8933 // which is the same as if (Hi > ((1 << Scale) - 1)) 8934 APInt MaxVal = APInt::getMaxValue(VTSize); 8935 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), 8936 dl, VT); 8937 Result = DAG.getSelectCC(dl, Hi, LowMask, 8938 DAG.getConstant(MaxVal, dl, VT), Result, 8939 ISD::SETUGT); 8940 8941 return Result; 8942 } 8943 8944 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the 8945 // widened multiplication) aren't all ones or all zeroes. 8946 8947 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT); 8948 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT); 8949 8950 if (Scale == 0) { 8951 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo, 8952 DAG.getConstant(VTSize - 1, dl, ShiftTy)); 8953 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE); 8954 // Saturated to SatMin if wide product is negative, and SatMax if wide 8955 // product is positive ... 8956 SDValue Zero = DAG.getConstant(0, dl, VT); 8957 SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax, 8958 ISD::SETLT); 8959 // ... but only if we overflowed. 8960 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result); 8961 } 8962 8963 // We handled Scale==0 above so all the bits to examine is in Hi. 8964 8965 // Saturate to max if ((Hi >> (Scale - 1)) > 0), 8966 // which is the same as if (Hi > (1 << (Scale - 1)) - 1) 8967 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), 8968 dl, VT); 8969 Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT); 8970 // Saturate to min if (Hi >> (Scale - 1)) < -1), 8971 // which is the same as if (HI < (-1 << (Scale - 1)) 8972 SDValue HighMask = 8973 DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), 8974 dl, VT); 8975 Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT); 8976 return Result; 8977 } 8978 8979 SDValue 8980 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, 8981 SDValue LHS, SDValue RHS, 8982 unsigned Scale, SelectionDAG &DAG) const { 8983 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT || 8984 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) && 8985 "Expected a fixed point division opcode"); 8986 8987 EVT VT = LHS.getValueType(); 8988 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 8989 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 8990 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8991 8992 // If there is enough room in the type to upscale the LHS or downscale the 8993 // RHS before the division, we can perform it in this type without having to 8994 // resize. For signed operations, the LHS headroom is the number of 8995 // redundant sign bits, and for unsigned ones it is the number of zeroes. 8996 // The headroom for the RHS is the number of trailing zeroes. 8997 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1 8998 : DAG.computeKnownBits(LHS).countMinLeadingZeros(); 8999 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros(); 9000 9001 // For signed saturating operations, we need to be able to detect true integer 9002 // division overflow; that is, when you have MIN / -EPS. However, this 9003 // is undefined behavior and if we emit divisions that could take such 9004 // values it may cause undesired behavior (arithmetic exceptions on x86, for 9005 // example). 9006 // Avoid this by requiring an extra bit so that we never get this case. 9007 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale 9008 // signed saturating division, we need to emit a whopping 32-bit division. 9009 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed)) 9010 return SDValue(); 9011 9012 unsigned LHSShift = std::min(LHSLead, Scale); 9013 unsigned RHSShift = Scale - LHSShift; 9014 9015 // At this point, we know that if we shift the LHS up by LHSShift and the 9016 // RHS down by RHSShift, we can emit a regular division with a final scaling 9017 // factor of Scale. 9018 9019 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 9020 if (LHSShift) 9021 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS, 9022 DAG.getConstant(LHSShift, dl, ShiftTy)); 9023 if (RHSShift) 9024 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS, 9025 DAG.getConstant(RHSShift, dl, ShiftTy)); 9026 9027 SDValue Quot; 9028 if (Signed) { 9029 // For signed operations, if the resulting quotient is negative and the 9030 // remainder is nonzero, subtract 1 from the quotient to round towards 9031 // negative infinity. 9032 SDValue Rem; 9033 // FIXME: Ideally we would always produce an SDIVREM here, but if the 9034 // type isn't legal, SDIVREM cannot be expanded. There is no reason why 9035 // we couldn't just form a libcall, but the type legalizer doesn't do it. 9036 if (isTypeLegal(VT) && 9037 isOperationLegalOrCustom(ISD::SDIVREM, VT)) { 9038 Quot = DAG.getNode(ISD::SDIVREM, dl, 9039 DAG.getVTList(VT, VT), 9040 LHS, RHS); 9041 Rem = Quot.getValue(1); 9042 Quot = Quot.getValue(0); 9043 } else { 9044 Quot = DAG.getNode(ISD::SDIV, dl, VT, 9045 LHS, RHS); 9046 Rem = DAG.getNode(ISD::SREM, dl, VT, 9047 LHS, RHS); 9048 } 9049 SDValue Zero = DAG.getConstant(0, dl, VT); 9050 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE); 9051 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT); 9052 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT); 9053 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg); 9054 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot, 9055 DAG.getConstant(1, dl, VT)); 9056 Quot = DAG.getSelect(dl, VT, 9057 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg), 9058 Sub1, Quot); 9059 } else 9060 Quot = DAG.getNode(ISD::UDIV, dl, VT, 9061 LHS, RHS); 9062 9063 return Quot; 9064 } 9065 9066 void TargetLowering::expandUADDSUBO( 9067 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 9068 SDLoc dl(Node); 9069 SDValue LHS = Node->getOperand(0); 9070 SDValue RHS = Node->getOperand(1); 9071 bool IsAdd = Node->getOpcode() == ISD::UADDO; 9072 9073 // If ADD/SUBCARRY is legal, use that instead. 9074 unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY; 9075 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) { 9076 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1)); 9077 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(), 9078 { LHS, RHS, CarryIn }); 9079 Result = SDValue(NodeCarry.getNode(), 0); 9080 Overflow = SDValue(NodeCarry.getNode(), 1); 9081 return; 9082 } 9083 9084 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 9085 LHS.getValueType(), LHS, RHS); 9086 9087 EVT ResultType = Node->getValueType(1); 9088 EVT SetCCType = getSetCCResultType( 9089 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 9090 SDValue SetCC; 9091 if (IsAdd && isOneConstant(RHS)) { 9092 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces 9093 // the live range of X. We assume comparing with 0 is cheap. 9094 // The general case (X + C) < C is not necessarily beneficial. Although we 9095 // reduce the live range of X, we may introduce the materialization of 9096 // constant C. 9097 SetCC = 9098 DAG.getSetCC(dl, SetCCType, Result, 9099 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ); 9100 } else { 9101 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 9102 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC); 9103 } 9104 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 9105 } 9106 9107 void TargetLowering::expandSADDSUBO( 9108 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 9109 SDLoc dl(Node); 9110 SDValue LHS = Node->getOperand(0); 9111 SDValue RHS = Node->getOperand(1); 9112 bool IsAdd = Node->getOpcode() == ISD::SADDO; 9113 9114 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 9115 LHS.getValueType(), LHS, RHS); 9116 9117 EVT ResultType = Node->getValueType(1); 9118 EVT OType = getSetCCResultType( 9119 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 9120 9121 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow. 9122 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT; 9123 if (isOperationLegal(OpcSat, LHS.getValueType())) { 9124 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS); 9125 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE); 9126 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 9127 return; 9128 } 9129 9130 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 9131 9132 // For an addition, the result should be less than one of the operands (LHS) 9133 // if and only if the other operand (RHS) is negative, otherwise there will 9134 // be overflow. 9135 // For a subtraction, the result should be less than one of the operands 9136 // (LHS) if and only if the other operand (RHS) is (non-zero) positive, 9137 // otherwise there will be overflow. 9138 SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT); 9139 SDValue ConditionRHS = 9140 DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT); 9141 9142 Overflow = DAG.getBoolExtOrTrunc( 9143 DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl, 9144 ResultType, ResultType); 9145 } 9146 9147 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result, 9148 SDValue &Overflow, SelectionDAG &DAG) const { 9149 SDLoc dl(Node); 9150 EVT VT = Node->getValueType(0); 9151 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9152 SDValue LHS = Node->getOperand(0); 9153 SDValue RHS = Node->getOperand(1); 9154 bool isSigned = Node->getOpcode() == ISD::SMULO; 9155 9156 // For power-of-two multiplications we can use a simpler shift expansion. 9157 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 9158 const APInt &C = RHSC->getAPIntValue(); 9159 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 9160 if (C.isPowerOf2()) { 9161 // smulo(x, signed_min) is same as umulo(x, signed_min). 9162 bool UseArithShift = isSigned && !C.isMinSignedValue(); 9163 EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout()); 9164 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy); 9165 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt); 9166 Overflow = DAG.getSetCC(dl, SetCCVT, 9167 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 9168 dl, VT, Result, ShiftAmt), 9169 LHS, ISD::SETNE); 9170 return true; 9171 } 9172 } 9173 9174 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2); 9175 if (VT.isVector()) 9176 WideVT = 9177 EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount()); 9178 9179 SDValue BottomHalf; 9180 SDValue TopHalf; 9181 static const unsigned Ops[2][3] = 9182 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 9183 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 9184 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 9185 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 9186 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 9187 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 9188 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 9189 RHS); 9190 TopHalf = BottomHalf.getValue(1); 9191 } else if (isTypeLegal(WideVT)) { 9192 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 9193 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 9194 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 9195 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul); 9196 SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl, 9197 getShiftAmountTy(WideVT, DAG.getDataLayout())); 9198 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, 9199 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt)); 9200 } else { 9201 if (VT.isVector()) 9202 return false; 9203 9204 // We can fall back to a libcall with an illegal type for the MUL if we 9205 // have a libcall big enough. 9206 // Also, we can fall back to a division in some cases, but that's a big 9207 // performance hit in the general case. 9208 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 9209 if (WideVT == MVT::i16) 9210 LC = RTLIB::MUL_I16; 9211 else if (WideVT == MVT::i32) 9212 LC = RTLIB::MUL_I32; 9213 else if (WideVT == MVT::i64) 9214 LC = RTLIB::MUL_I64; 9215 else if (WideVT == MVT::i128) 9216 LC = RTLIB::MUL_I128; 9217 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!"); 9218 9219 SDValue HiLHS; 9220 SDValue HiRHS; 9221 if (isSigned) { 9222 // The high part is obtained by SRA'ing all but one of the bits of low 9223 // part. 9224 unsigned LoSize = VT.getFixedSizeInBits(); 9225 HiLHS = 9226 DAG.getNode(ISD::SRA, dl, VT, LHS, 9227 DAG.getConstant(LoSize - 1, dl, 9228 getPointerTy(DAG.getDataLayout()))); 9229 HiRHS = 9230 DAG.getNode(ISD::SRA, dl, VT, RHS, 9231 DAG.getConstant(LoSize - 1, dl, 9232 getPointerTy(DAG.getDataLayout()))); 9233 } else { 9234 HiLHS = DAG.getConstant(0, dl, VT); 9235 HiRHS = DAG.getConstant(0, dl, VT); 9236 } 9237 9238 // Here we're passing the 2 arguments explicitly as 4 arguments that are 9239 // pre-lowered to the correct types. This all depends upon WideVT not 9240 // being a legal type for the architecture and thus has to be split to 9241 // two arguments. 9242 SDValue Ret; 9243 TargetLowering::MakeLibCallOptions CallOptions; 9244 CallOptions.setSExt(isSigned); 9245 CallOptions.setIsPostTypeLegalization(true); 9246 if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) { 9247 // Halves of WideVT are packed into registers in different order 9248 // depending on platform endianness. This is usually handled by 9249 // the C calling convention, but we can't defer to it in 9250 // the legalizer. 9251 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS }; 9252 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 9253 } else { 9254 SDValue Args[] = { HiLHS, LHS, HiRHS, RHS }; 9255 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 9256 } 9257 assert(Ret.getOpcode() == ISD::MERGE_VALUES && 9258 "Ret value is a collection of constituent nodes holding result."); 9259 if (DAG.getDataLayout().isLittleEndian()) { 9260 // Same as above. 9261 BottomHalf = Ret.getOperand(0); 9262 TopHalf = Ret.getOperand(1); 9263 } else { 9264 BottomHalf = Ret.getOperand(1); 9265 TopHalf = Ret.getOperand(0); 9266 } 9267 } 9268 9269 Result = BottomHalf; 9270 if (isSigned) { 9271 SDValue ShiftAmt = DAG.getConstant( 9272 VT.getScalarSizeInBits() - 1, dl, 9273 getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout())); 9274 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt); 9275 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE); 9276 } else { 9277 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, 9278 DAG.getConstant(0, dl, VT), ISD::SETNE); 9279 } 9280 9281 // Truncate the result if SetCC returns a larger type than needed. 9282 EVT RType = Node->getValueType(1); 9283 if (RType.bitsLT(Overflow.getValueType())) 9284 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow); 9285 9286 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() && 9287 "Unexpected result type for S/UMULO legalization"); 9288 return true; 9289 } 9290 9291 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const { 9292 SDLoc dl(Node); 9293 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 9294 SDValue Op = Node->getOperand(0); 9295 EVT VT = Op.getValueType(); 9296 9297 if (VT.isScalableVector()) 9298 report_fatal_error( 9299 "Expanding reductions for scalable vectors is undefined."); 9300 9301 // Try to use a shuffle reduction for power of two vectors. 9302 if (VT.isPow2VectorType()) { 9303 while (VT.getVectorNumElements() > 1) { 9304 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 9305 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) 9306 break; 9307 9308 SDValue Lo, Hi; 9309 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl); 9310 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi); 9311 VT = HalfVT; 9312 } 9313 } 9314 9315 EVT EltVT = VT.getVectorElementType(); 9316 unsigned NumElts = VT.getVectorNumElements(); 9317 9318 SmallVector<SDValue, 8> Ops; 9319 DAG.ExtractVectorElements(Op, Ops, 0, NumElts); 9320 9321 SDValue Res = Ops[0]; 9322 for (unsigned i = 1; i < NumElts; i++) 9323 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags()); 9324 9325 // Result type may be wider than element type. 9326 if (EltVT != Node->getValueType(0)) 9327 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res); 9328 return Res; 9329 } 9330 9331 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const { 9332 SDLoc dl(Node); 9333 SDValue AccOp = Node->getOperand(0); 9334 SDValue VecOp = Node->getOperand(1); 9335 SDNodeFlags Flags = Node->getFlags(); 9336 9337 EVT VT = VecOp.getValueType(); 9338 EVT EltVT = VT.getVectorElementType(); 9339 9340 if (VT.isScalableVector()) 9341 report_fatal_error( 9342 "Expanding reductions for scalable vectors is undefined."); 9343 9344 unsigned NumElts = VT.getVectorNumElements(); 9345 9346 SmallVector<SDValue, 8> Ops; 9347 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts); 9348 9349 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 9350 9351 SDValue Res = AccOp; 9352 for (unsigned i = 0; i < NumElts; i++) 9353 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags); 9354 9355 return Res; 9356 } 9357 9358 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result, 9359 SelectionDAG &DAG) const { 9360 EVT VT = Node->getValueType(0); 9361 SDLoc dl(Node); 9362 bool isSigned = Node->getOpcode() == ISD::SREM; 9363 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV; 9364 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 9365 SDValue Dividend = Node->getOperand(0); 9366 SDValue Divisor = Node->getOperand(1); 9367 if (isOperationLegalOrCustom(DivRemOpc, VT)) { 9368 SDVTList VTs = DAG.getVTList(VT, VT); 9369 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1); 9370 return true; 9371 } 9372 if (isOperationLegalOrCustom(DivOpc, VT)) { 9373 // X % Y -> X-X/Y*Y 9374 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor); 9375 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor); 9376 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 9377 return true; 9378 } 9379 return false; 9380 } 9381 9382 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node, 9383 SelectionDAG &DAG) const { 9384 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT; 9385 SDLoc dl(SDValue(Node, 0)); 9386 SDValue Src = Node->getOperand(0); 9387 9388 // DstVT is the result type, while SatVT is the size to which we saturate 9389 EVT SrcVT = Src.getValueType(); 9390 EVT DstVT = Node->getValueType(0); 9391 9392 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 9393 unsigned SatWidth = SatVT.getScalarSizeInBits(); 9394 unsigned DstWidth = DstVT.getScalarSizeInBits(); 9395 assert(SatWidth <= DstWidth && 9396 "Expected saturation width smaller than result width"); 9397 9398 // Determine minimum and maximum integer values and their corresponding 9399 // floating-point values. 9400 APInt MinInt, MaxInt; 9401 if (IsSigned) { 9402 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth); 9403 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth); 9404 } else { 9405 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth); 9406 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth); 9407 } 9408 9409 // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as 9410 // libcall emission cannot handle this. Large result types will fail. 9411 if (SrcVT == MVT::f16) { 9412 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src); 9413 SrcVT = Src.getValueType(); 9414 } 9415 9416 APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 9417 APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 9418 9419 APFloat::opStatus MinStatus = 9420 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero); 9421 APFloat::opStatus MaxStatus = 9422 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero); 9423 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) && 9424 !(MaxStatus & APFloat::opStatus::opInexact); 9425 9426 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT); 9427 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT); 9428 9429 // If the integer bounds are exactly representable as floats and min/max are 9430 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence 9431 // of comparisons and selects. 9432 bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) && 9433 isOperationLegal(ISD::FMAXNUM, SrcVT); 9434 if (AreExactFloatBounds && MinMaxLegal) { 9435 SDValue Clamped = Src; 9436 9437 // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat. 9438 Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode); 9439 // Clamp by MaxFloat from above. NaN cannot occur. 9440 Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode); 9441 // Convert clamped value to integer. 9442 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, 9443 dl, DstVT, Clamped); 9444 9445 // In the unsigned case we're done, because we mapped NaN to MinFloat, 9446 // which will cast to zero. 9447 if (!IsSigned) 9448 return FpToInt; 9449 9450 // Otherwise, select 0 if Src is NaN. 9451 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 9452 return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt, 9453 ISD::CondCode::SETUO); 9454 } 9455 9456 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT); 9457 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT); 9458 9459 // Result of direct conversion. The assumption here is that the operation is 9460 // non-trapping and it's fine to apply it to an out-of-range value if we 9461 // select it away later. 9462 SDValue FpToInt = 9463 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src); 9464 9465 SDValue Select = FpToInt; 9466 9467 // If Src ULT MinFloat, select MinInt. In particular, this also selects 9468 // MinInt if Src is NaN. 9469 Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select, 9470 ISD::CondCode::SETULT); 9471 // If Src OGT MaxFloat, select MaxInt. 9472 Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select, 9473 ISD::CondCode::SETOGT); 9474 9475 // In the unsigned case we are done, because we mapped NaN to MinInt, which 9476 // is already zero. 9477 if (!IsSigned) 9478 return Select; 9479 9480 // Otherwise, select 0 if Src is NaN. 9481 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 9482 return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO); 9483 } 9484 9485 SDValue TargetLowering::expandVectorSplice(SDNode *Node, 9486 SelectionDAG &DAG) const { 9487 assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!"); 9488 assert(Node->getValueType(0).isScalableVector() && 9489 "Fixed length vector types expected to use SHUFFLE_VECTOR!"); 9490 9491 EVT VT = Node->getValueType(0); 9492 SDValue V1 = Node->getOperand(0); 9493 SDValue V2 = Node->getOperand(1); 9494 int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue(); 9495 SDLoc DL(Node); 9496 9497 // Expand through memory thusly: 9498 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr 9499 // Store V1, Ptr 9500 // Store V2, Ptr + sizeof(V1) 9501 // If (Imm < 0) 9502 // TrailingElts = -Imm 9503 // Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt)) 9504 // else 9505 // Ptr = Ptr + (Imm * sizeof(VT.Elt)) 9506 // Res = Load Ptr 9507 9508 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false); 9509 9510 EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 9511 VT.getVectorElementCount() * 2); 9512 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment); 9513 EVT PtrVT = StackPtr.getValueType(); 9514 auto &MF = DAG.getMachineFunction(); 9515 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 9516 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex); 9517 9518 // Store the lo part of CONCAT_VECTORS(V1, V2) 9519 SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo); 9520 // Store the hi part of CONCAT_VECTORS(V1, V2) 9521 SDValue OffsetToV2 = DAG.getVScale( 9522 DL, PtrVT, 9523 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 9524 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2); 9525 SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo); 9526 9527 if (Imm >= 0) { 9528 // Load back the required element. getVectorElementPointer takes care of 9529 // clamping the index if it's out-of-bounds. 9530 StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2)); 9531 // Load the spliced result 9532 return DAG.getLoad(VT, DL, StoreV2, StackPtr, 9533 MachinePointerInfo::getUnknownStack(MF)); 9534 } 9535 9536 uint64_t TrailingElts = -Imm; 9537 9538 // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2. 9539 TypeSize EltByteSize = VT.getVectorElementType().getStoreSize(); 9540 SDValue TrailingBytes = 9541 DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT); 9542 9543 if (TrailingElts > VT.getVectorMinNumElements()) { 9544 SDValue VLBytes = DAG.getVScale( 9545 DL, PtrVT, 9546 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 9547 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes); 9548 } 9549 9550 // Calculate the start address of the spliced result. 9551 StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes); 9552 9553 // Load the spliced result 9554 return DAG.getLoad(VT, DL, StoreV2, StackPtr2, 9555 MachinePointerInfo::getUnknownStack(MF)); 9556 } 9557 9558 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, 9559 SDValue &LHS, SDValue &RHS, 9560 SDValue &CC, SDValue Mask, 9561 SDValue EVL, bool &NeedInvert, 9562 const SDLoc &dl, SDValue &Chain, 9563 bool IsSignaling) const { 9564 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9565 MVT OpVT = LHS.getSimpleValueType(); 9566 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get(); 9567 NeedInvert = false; 9568 assert(!EVL == !Mask && "VP Mask and EVL must either both be set or unset"); 9569 bool IsNonVP = !EVL; 9570 switch (TLI.getCondCodeAction(CCCode, OpVT)) { 9571 default: 9572 llvm_unreachable("Unknown condition code action!"); 9573 case TargetLowering::Legal: 9574 // Nothing to do. 9575 break; 9576 case TargetLowering::Expand: { 9577 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode); 9578 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9579 std::swap(LHS, RHS); 9580 CC = DAG.getCondCode(InvCC); 9581 return true; 9582 } 9583 // Swapping operands didn't work. Try inverting the condition. 9584 bool NeedSwap = false; 9585 InvCC = getSetCCInverse(CCCode, OpVT); 9586 if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9587 // If inverting the condition is not enough, try swapping operands 9588 // on top of it. 9589 InvCC = ISD::getSetCCSwappedOperands(InvCC); 9590 NeedSwap = true; 9591 } 9592 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9593 CC = DAG.getCondCode(InvCC); 9594 NeedInvert = true; 9595 if (NeedSwap) 9596 std::swap(LHS, RHS); 9597 return true; 9598 } 9599 9600 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID; 9601 unsigned Opc = 0; 9602 switch (CCCode) { 9603 default: 9604 llvm_unreachable("Don't know how to expand this condition!"); 9605 case ISD::SETUO: 9606 if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) { 9607 CC1 = ISD::SETUNE; 9608 CC2 = ISD::SETUNE; 9609 Opc = ISD::OR; 9610 break; 9611 } 9612 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 9613 "If SETUE is expanded, SETOEQ or SETUNE must be legal!"); 9614 NeedInvert = true; 9615 LLVM_FALLTHROUGH; 9616 case ISD::SETO: 9617 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 9618 "If SETO is expanded, SETOEQ must be legal!"); 9619 CC1 = ISD::SETOEQ; 9620 CC2 = ISD::SETOEQ; 9621 Opc = ISD::AND; 9622 break; 9623 case ISD::SETONE: 9624 case ISD::SETUEQ: 9625 // If the SETUO or SETO CC isn't legal, we might be able to use 9626 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one 9627 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping 9628 // the operands. 9629 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 9630 if (!TLI.isCondCodeLegal(CC2, OpVT) && 9631 (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) || 9632 TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) { 9633 CC1 = ISD::SETOGT; 9634 CC2 = ISD::SETOLT; 9635 Opc = ISD::OR; 9636 NeedInvert = ((unsigned)CCCode & 0x8U); 9637 break; 9638 } 9639 LLVM_FALLTHROUGH; 9640 case ISD::SETOEQ: 9641 case ISD::SETOGT: 9642 case ISD::SETOGE: 9643 case ISD::SETOLT: 9644 case ISD::SETOLE: 9645 case ISD::SETUNE: 9646 case ISD::SETUGT: 9647 case ISD::SETUGE: 9648 case ISD::SETULT: 9649 case ISD::SETULE: 9650 // If we are floating point, assign and break, otherwise fall through. 9651 if (!OpVT.isInteger()) { 9652 // We can use the 4th bit to tell if we are the unordered 9653 // or ordered version of the opcode. 9654 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 9655 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND; 9656 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10); 9657 break; 9658 } 9659 // Fallthrough if we are unsigned integer. 9660 LLVM_FALLTHROUGH; 9661 case ISD::SETLE: 9662 case ISD::SETGT: 9663 case ISD::SETGE: 9664 case ISD::SETLT: 9665 case ISD::SETNE: 9666 case ISD::SETEQ: 9667 // If all combinations of inverting the condition and swapping operands 9668 // didn't work then we have no means to expand the condition. 9669 llvm_unreachable("Don't know how to expand this condition!"); 9670 } 9671 9672 SDValue SetCC1, SetCC2; 9673 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) { 9674 // If we aren't the ordered or unorder operation, 9675 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS). 9676 if (IsNonVP) { 9677 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling); 9678 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling); 9679 } else { 9680 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC1, Mask, EVL); 9681 SetCC2 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC2, Mask, EVL); 9682 } 9683 } else { 9684 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS) 9685 if (IsNonVP) { 9686 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling); 9687 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling); 9688 } else { 9689 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, LHS, CC1, Mask, EVL); 9690 SetCC2 = DAG.getSetCCVP(dl, VT, RHS, RHS, CC2, Mask, EVL); 9691 } 9692 } 9693 if (Chain) 9694 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1), 9695 SetCC2.getValue(1)); 9696 if (IsNonVP) 9697 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2); 9698 else { 9699 // Transform the binary opcode to the VP equivalent. 9700 assert((Opc == ISD::OR || Opc == ISD::AND) && "Unexpected opcode"); 9701 Opc = Opc == ISD::OR ? ISD::VP_OR : ISD::VP_AND; 9702 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2, Mask, EVL); 9703 } 9704 RHS = SDValue(); 9705 CC = SDValue(); 9706 return true; 9707 } 9708 } 9709 return false; 9710 } 9711