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 // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I) 1366 // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits). 1367 if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR && 1368 (Op0.getOperand(0).isUndef() || 1369 ISD::isBuildVectorOfConstantSDNodes(Op0.getOperand(0).getNode())) && 1370 Op0->hasOneUse()) { 1371 unsigned NumSubElts = 1372 Op0.getOperand(1).getValueType().getVectorNumElements(); 1373 unsigned SubIdx = Op0.getConstantOperandVal(2); 1374 APInt DemandedSub = 1375 APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts); 1376 KnownBits KnownSubMask = 1377 TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1); 1378 if (DemandedBits.isSubsetOf(KnownSubMask.One)) { 1379 SDValue NewAnd = 1380 TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1); 1381 SDValue NewInsert = 1382 TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd, 1383 Op0.getOperand(1), Op0.getOperand(2)); 1384 return TLO.CombineTo(Op, NewInsert); 1385 } 1386 } 1387 1388 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1389 Depth + 1)) 1390 return true; 1391 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1392 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts, 1393 Known2, TLO, Depth + 1)) 1394 return true; 1395 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1396 1397 // If all of the demanded bits are known one on one side, return the other. 1398 // These bits cannot contribute to the result of the 'and'. 1399 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) 1400 return TLO.CombineTo(Op, Op0); 1401 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One)) 1402 return TLO.CombineTo(Op, Op1); 1403 // If all of the demanded bits in the inputs are known zeros, return zero. 1404 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1405 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT)); 1406 // If the RHS is a constant, see if we can simplify it. 1407 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts, 1408 TLO)) 1409 return true; 1410 // If the operation can be done in a smaller type, do so. 1411 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1412 return true; 1413 1414 // Attempt to avoid multi-use ops if we don't need anything from them. 1415 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1416 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1417 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1418 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1419 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1420 if (DemandedOp0 || DemandedOp1) { 1421 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1422 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1423 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1424 return TLO.CombineTo(Op, NewOp); 1425 } 1426 } 1427 1428 Known &= Known2; 1429 break; 1430 } 1431 case ISD::OR: { 1432 SDValue Op0 = Op.getOperand(0); 1433 SDValue Op1 = Op.getOperand(1); 1434 1435 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1436 Depth + 1)) 1437 return true; 1438 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1439 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts, 1440 Known2, TLO, Depth + 1)) 1441 return true; 1442 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1443 1444 // If all of the demanded bits are known zero on one side, return the other. 1445 // These bits cannot contribute to the result of the 'or'. 1446 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) 1447 return TLO.CombineTo(Op, Op0); 1448 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero)) 1449 return TLO.CombineTo(Op, Op1); 1450 // If the RHS is a constant, see if we can simplify it. 1451 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1452 return true; 1453 // If the operation can be done in a smaller type, do so. 1454 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1455 return true; 1456 1457 // Attempt to avoid multi-use ops if we don't need anything from them. 1458 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1459 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1460 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1461 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1462 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1463 if (DemandedOp0 || DemandedOp1) { 1464 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1465 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1466 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1467 return TLO.CombineTo(Op, NewOp); 1468 } 1469 } 1470 1471 Known |= Known2; 1472 break; 1473 } 1474 case ISD::XOR: { 1475 SDValue Op0 = Op.getOperand(0); 1476 SDValue Op1 = Op.getOperand(1); 1477 1478 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1479 Depth + 1)) 1480 return true; 1481 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1482 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO, 1483 Depth + 1)) 1484 return true; 1485 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1486 1487 // If all of the demanded bits are known zero on one side, return the other. 1488 // These bits cannot contribute to the result of the 'xor'. 1489 if (DemandedBits.isSubsetOf(Known.Zero)) 1490 return TLO.CombineTo(Op, Op0); 1491 if (DemandedBits.isSubsetOf(Known2.Zero)) 1492 return TLO.CombineTo(Op, Op1); 1493 // If the operation can be done in a smaller type, do so. 1494 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1495 return true; 1496 1497 // If all of the unknown bits are known to be zero on one side or the other 1498 // turn this into an *inclusive* or. 1499 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 1500 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1501 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1)); 1502 1503 ConstantSDNode* C = isConstOrConstSplat(Op1, DemandedElts); 1504 if (C) { 1505 // If one side is a constant, and all of the set bits in the constant are 1506 // also known set on the other side, turn this into an AND, as we know 1507 // the bits will be cleared. 1508 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 1509 // NB: it is okay if more bits are known than are requested 1510 if (C->getAPIntValue() == Known2.One) { 1511 SDValue ANDC = 1512 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT); 1513 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC)); 1514 } 1515 1516 // If the RHS is a constant, see if we can change it. Don't alter a -1 1517 // constant because that's a 'not' op, and that is better for combining 1518 // and codegen. 1519 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) { 1520 // We're flipping all demanded bits. Flip the undemanded bits too. 1521 SDValue New = TLO.DAG.getNOT(dl, Op0, VT); 1522 return TLO.CombineTo(Op, New); 1523 } 1524 } 1525 1526 // If we can't turn this into a 'not', try to shrink the constant. 1527 if (!C || !C->isAllOnes()) 1528 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1529 return true; 1530 1531 // Attempt to avoid multi-use ops if we don't need anything from them. 1532 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) { 1533 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1534 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1535 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1536 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1537 if (DemandedOp0 || DemandedOp1) { 1538 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1539 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1540 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1541 return TLO.CombineTo(Op, NewOp); 1542 } 1543 } 1544 1545 Known ^= Known2; 1546 break; 1547 } 1548 case ISD::SELECT: 1549 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO, 1550 Depth + 1)) 1551 return true; 1552 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO, 1553 Depth + 1)) 1554 return true; 1555 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1556 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1557 1558 // If the operands are constants, see if we can simplify them. 1559 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1560 return true; 1561 1562 // Only known if known in both the LHS and RHS. 1563 Known = KnownBits::commonBits(Known, Known2); 1564 break; 1565 case ISD::VSELECT: 1566 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts, 1567 Known, TLO, Depth + 1)) 1568 return true; 1569 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts, 1570 Known2, TLO, Depth + 1)) 1571 return true; 1572 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1573 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1574 1575 // Only known if known in both the LHS and RHS. 1576 Known = KnownBits::commonBits(Known, Known2); 1577 break; 1578 case ISD::SELECT_CC: 1579 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO, 1580 Depth + 1)) 1581 return true; 1582 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO, 1583 Depth + 1)) 1584 return true; 1585 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1586 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1587 1588 // If the operands are constants, see if we can simplify them. 1589 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1590 return true; 1591 1592 // Only known if known in both the LHS and RHS. 1593 Known = KnownBits::commonBits(Known, Known2); 1594 break; 1595 case ISD::SETCC: { 1596 SDValue Op0 = Op.getOperand(0); 1597 SDValue Op1 = Op.getOperand(1); 1598 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 1599 // If (1) we only need the sign-bit, (2) the setcc operands are the same 1600 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 1601 // -1, we may be able to bypass the setcc. 1602 if (DemandedBits.isSignMask() && 1603 Op0.getScalarValueSizeInBits() == BitWidth && 1604 getBooleanContents(Op0.getValueType()) == 1605 BooleanContent::ZeroOrNegativeOneBooleanContent) { 1606 // If we're testing X < 0, then this compare isn't needed - just use X! 1607 // FIXME: We're limiting to integer types here, but this should also work 1608 // if we don't care about FP signed-zero. The use of SETLT with FP means 1609 // that we don't care about NaNs. 1610 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 1611 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 1612 return TLO.CombineTo(Op, Op0); 1613 1614 // TODO: Should we check for other forms of sign-bit comparisons? 1615 // Examples: X <= -1, X >= 0 1616 } 1617 if (getBooleanContents(Op0.getValueType()) == 1618 TargetLowering::ZeroOrOneBooleanContent && 1619 BitWidth > 1) 1620 Known.Zero.setBitsFrom(1); 1621 break; 1622 } 1623 case ISD::SHL: { 1624 SDValue Op0 = Op.getOperand(0); 1625 SDValue Op1 = Op.getOperand(1); 1626 EVT ShiftVT = Op1.getValueType(); 1627 1628 if (const APInt *SA = 1629 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1630 unsigned ShAmt = SA->getZExtValue(); 1631 if (ShAmt == 0) 1632 return TLO.CombineTo(Op, Op0); 1633 1634 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 1635 // single shift. We can do this if the bottom bits (which are shifted 1636 // out) are never demanded. 1637 // TODO - support non-uniform vector amounts. 1638 if (Op0.getOpcode() == ISD::SRL) { 1639 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) { 1640 if (const APInt *SA2 = 1641 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1642 unsigned C1 = SA2->getZExtValue(); 1643 unsigned Opc = ISD::SHL; 1644 int Diff = ShAmt - C1; 1645 if (Diff < 0) { 1646 Diff = -Diff; 1647 Opc = ISD::SRL; 1648 } 1649 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1650 return TLO.CombineTo( 1651 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1652 } 1653 } 1654 } 1655 1656 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 1657 // are not demanded. This will likely allow the anyext to be folded away. 1658 // TODO - support non-uniform vector amounts. 1659 if (Op0.getOpcode() == ISD::ANY_EXTEND) { 1660 SDValue InnerOp = Op0.getOperand(0); 1661 EVT InnerVT = InnerOp.getValueType(); 1662 unsigned InnerBits = InnerVT.getScalarSizeInBits(); 1663 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits && 1664 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 1665 EVT ShTy = getShiftAmountTy(InnerVT, DL); 1666 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits())) 1667 ShTy = InnerVT; 1668 SDValue NarrowShl = 1669 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp, 1670 TLO.DAG.getConstant(ShAmt, dl, ShTy)); 1671 return TLO.CombineTo( 1672 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl)); 1673 } 1674 1675 // Repeat the SHL optimization above in cases where an extension 1676 // intervenes: (shl (anyext (shr x, c1)), c2) to 1677 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 1678 // aren't demanded (as above) and that the shifted upper c1 bits of 1679 // x aren't demanded. 1680 // TODO - support non-uniform vector amounts. 1681 if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL && 1682 InnerOp.hasOneUse()) { 1683 if (const APInt *SA2 = 1684 TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) { 1685 unsigned InnerShAmt = SA2->getZExtValue(); 1686 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits && 1687 DemandedBits.getActiveBits() <= 1688 (InnerBits - InnerShAmt + ShAmt) && 1689 DemandedBits.countTrailingZeros() >= ShAmt) { 1690 SDValue NewSA = 1691 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT); 1692 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 1693 InnerOp.getOperand(0)); 1694 return TLO.CombineTo( 1695 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA)); 1696 } 1697 } 1698 } 1699 } 1700 1701 APInt InDemandedMask = DemandedBits.lshr(ShAmt); 1702 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1703 Depth + 1)) 1704 return true; 1705 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1706 Known.Zero <<= ShAmt; 1707 Known.One <<= ShAmt; 1708 // low bits known zero. 1709 Known.Zero.setLowBits(ShAmt); 1710 1711 // Attempt to avoid multi-use ops if we don't need anything from them. 1712 if (!InDemandedMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1713 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1714 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1715 if (DemandedOp0) { 1716 SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1); 1717 return TLO.CombineTo(Op, NewOp); 1718 } 1719 } 1720 1721 // Try shrinking the operation as long as the shift amount will still be 1722 // in range. 1723 if ((ShAmt < DemandedBits.getActiveBits()) && 1724 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1725 return true; 1726 } else { 1727 // This is a variable shift, so we can't shift the demand mask by a known 1728 // amount. But if we are not demanding high bits, then we are not 1729 // demanding those bits from the pre-shifted operand either. 1730 if (unsigned CTLZ = DemandedBits.countLeadingZeros()) { 1731 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ)); 1732 if (SimplifyDemandedBits(Op0, DemandedFromOp, DemandedElts, Known, TLO, 1733 Depth + 1)) { 1734 SDNodeFlags Flags = Op.getNode()->getFlags(); 1735 if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) { 1736 // Disable the nsw and nuw flags. We can no longer guarantee that we 1737 // won't wrap after simplification. 1738 Flags.setNoSignedWrap(false); 1739 Flags.setNoUnsignedWrap(false); 1740 Op->setFlags(Flags); 1741 } 1742 return true; 1743 } 1744 Known.resetAll(); 1745 } 1746 } 1747 1748 // If we are only demanding sign bits then we can use the shift source 1749 // directly. 1750 if (const APInt *MaxSA = 1751 TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 1752 unsigned ShAmt = MaxSA->getZExtValue(); 1753 unsigned NumSignBits = 1754 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1755 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1756 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 1757 return TLO.CombineTo(Op, Op0); 1758 } 1759 break; 1760 } 1761 case ISD::SRL: { 1762 SDValue Op0 = Op.getOperand(0); 1763 SDValue Op1 = Op.getOperand(1); 1764 EVT ShiftVT = Op1.getValueType(); 1765 1766 // Try to match AVG patterns. 1767 if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits, 1768 DemandedElts, Depth + 1)) 1769 return TLO.CombineTo(Op, AVG); 1770 1771 if (const APInt *SA = 1772 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1773 unsigned ShAmt = SA->getZExtValue(); 1774 if (ShAmt == 0) 1775 return TLO.CombineTo(Op, Op0); 1776 1777 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 1778 // single shift. We can do this if the top bits (which are shifted out) 1779 // are never demanded. 1780 // TODO - support non-uniform vector amounts. 1781 if (Op0.getOpcode() == ISD::SHL) { 1782 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) { 1783 if (const APInt *SA2 = 1784 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1785 unsigned C1 = SA2->getZExtValue(); 1786 unsigned Opc = ISD::SRL; 1787 int Diff = ShAmt - C1; 1788 if (Diff < 0) { 1789 Diff = -Diff; 1790 Opc = ISD::SHL; 1791 } 1792 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1793 return TLO.CombineTo( 1794 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1795 } 1796 } 1797 } 1798 1799 APInt InDemandedMask = (DemandedBits << ShAmt); 1800 1801 // If the shift is exact, then it does demand the low bits (and knows that 1802 // they are zero). 1803 if (Op->getFlags().hasExact()) 1804 InDemandedMask.setLowBits(ShAmt); 1805 1806 // Compute the new bits that are at the top now. 1807 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1808 Depth + 1)) 1809 return true; 1810 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1811 Known.Zero.lshrInPlace(ShAmt); 1812 Known.One.lshrInPlace(ShAmt); 1813 // High bits known zero. 1814 Known.Zero.setHighBits(ShAmt); 1815 } 1816 break; 1817 } 1818 case ISD::SRA: { 1819 SDValue Op0 = Op.getOperand(0); 1820 SDValue Op1 = Op.getOperand(1); 1821 EVT ShiftVT = Op1.getValueType(); 1822 1823 // If we only want bits that already match the signbit then we don't need 1824 // to shift. 1825 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1826 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >= 1827 NumHiDemandedBits) 1828 return TLO.CombineTo(Op, Op0); 1829 1830 // If this is an arithmetic shift right and only the low-bit is set, we can 1831 // always convert this into a logical shr, even if the shift amount is 1832 // variable. The low bit of the shift cannot be an input sign bit unless 1833 // the shift amount is >= the size of the datatype, which is undefined. 1834 if (DemandedBits.isOne()) 1835 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 1836 1837 // Try to match AVG patterns. 1838 if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits, 1839 DemandedElts, Depth + 1)) 1840 return TLO.CombineTo(Op, AVG); 1841 1842 if (const APInt *SA = 1843 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1844 unsigned ShAmt = SA->getZExtValue(); 1845 if (ShAmt == 0) 1846 return TLO.CombineTo(Op, Op0); 1847 1848 APInt InDemandedMask = (DemandedBits << ShAmt); 1849 1850 // If the shift is exact, then it does demand the low bits (and knows that 1851 // they are zero). 1852 if (Op->getFlags().hasExact()) 1853 InDemandedMask.setLowBits(ShAmt); 1854 1855 // If any of the demanded bits are produced by the sign extension, we also 1856 // demand the input sign bit. 1857 if (DemandedBits.countLeadingZeros() < ShAmt) 1858 InDemandedMask.setSignBit(); 1859 1860 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1861 Depth + 1)) 1862 return true; 1863 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1864 Known.Zero.lshrInPlace(ShAmt); 1865 Known.One.lshrInPlace(ShAmt); 1866 1867 // If the input sign bit is known to be zero, or if none of the top bits 1868 // are demanded, turn this into an unsigned shift right. 1869 if (Known.Zero[BitWidth - ShAmt - 1] || 1870 DemandedBits.countLeadingZeros() >= ShAmt) { 1871 SDNodeFlags Flags; 1872 Flags.setExact(Op->getFlags().hasExact()); 1873 return TLO.CombineTo( 1874 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags)); 1875 } 1876 1877 int Log2 = DemandedBits.exactLogBase2(); 1878 if (Log2 >= 0) { 1879 // The bit must come from the sign. 1880 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT); 1881 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA)); 1882 } 1883 1884 if (Known.One[BitWidth - ShAmt - 1]) 1885 // New bits are known one. 1886 Known.One.setHighBits(ShAmt); 1887 1888 // Attempt to avoid multi-use ops if we don't need anything from them. 1889 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) { 1890 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1891 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1892 if (DemandedOp0) { 1893 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1); 1894 return TLO.CombineTo(Op, NewOp); 1895 } 1896 } 1897 } 1898 break; 1899 } 1900 case ISD::FSHL: 1901 case ISD::FSHR: { 1902 SDValue Op0 = Op.getOperand(0); 1903 SDValue Op1 = Op.getOperand(1); 1904 SDValue Op2 = Op.getOperand(2); 1905 bool IsFSHL = (Op.getOpcode() == ISD::FSHL); 1906 1907 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) { 1908 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 1909 1910 // For fshl, 0-shift returns the 1st arg. 1911 // For fshr, 0-shift returns the 2nd arg. 1912 if (Amt == 0) { 1913 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts, 1914 Known, TLO, Depth + 1)) 1915 return true; 1916 break; 1917 } 1918 1919 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt)) 1920 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt) 1921 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt)); 1922 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt); 1923 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 1924 Depth + 1)) 1925 return true; 1926 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO, 1927 Depth + 1)) 1928 return true; 1929 1930 Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1931 Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1932 Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1933 Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1934 Known.One |= Known2.One; 1935 Known.Zero |= Known2.Zero; 1936 1937 // Attempt to avoid multi-use ops if we don't need anything from them. 1938 if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() || 1939 !DemandedElts.isAllOnes()) { 1940 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1941 Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1); 1942 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1943 Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1); 1944 if (DemandedOp0 || DemandedOp1) { 1945 DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0; 1946 DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1; 1947 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0, 1948 DemandedOp1, Op2); 1949 return TLO.CombineTo(Op, NewOp); 1950 } 1951 } 1952 } 1953 1954 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1955 if (isPowerOf2_32(BitWidth)) { 1956 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1); 1957 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, 1958 Known2, TLO, Depth + 1)) 1959 return true; 1960 } 1961 break; 1962 } 1963 case ISD::ROTL: 1964 case ISD::ROTR: { 1965 SDValue Op0 = Op.getOperand(0); 1966 SDValue Op1 = Op.getOperand(1); 1967 bool IsROTL = (Op.getOpcode() == ISD::ROTL); 1968 1969 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 1970 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1)) 1971 return TLO.CombineTo(Op, Op0); 1972 1973 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) { 1974 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 1975 unsigned RevAmt = BitWidth - Amt; 1976 1977 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt)) 1978 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt) 1979 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt); 1980 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 1981 Depth + 1)) 1982 return true; 1983 1984 // rot*(x, 0) --> x 1985 if (Amt == 0) 1986 return TLO.CombineTo(Op, Op0); 1987 1988 // See if we don't demand either half of the rotated bits. 1989 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) && 1990 DemandedBits.countTrailingZeros() >= (IsROTL ? Amt : RevAmt)) { 1991 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType()); 1992 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1)); 1993 } 1994 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) && 1995 DemandedBits.countLeadingZeros() >= (IsROTL ? RevAmt : Amt)) { 1996 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType()); 1997 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 1998 } 1999 } 2000 2001 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 2002 if (isPowerOf2_32(BitWidth)) { 2003 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1); 2004 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO, 2005 Depth + 1)) 2006 return true; 2007 } 2008 break; 2009 } 2010 case ISD::UMIN: { 2011 // Check if one arg is always less than (or equal) to the other arg. 2012 SDValue Op0 = Op.getOperand(0); 2013 SDValue Op1 = Op.getOperand(1); 2014 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 2015 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 2016 Known = KnownBits::umin(Known0, Known1); 2017 if (Optional<bool> IsULE = KnownBits::ule(Known0, Known1)) 2018 return TLO.CombineTo(Op, IsULE.value() ? Op0 : Op1); 2019 if (Optional<bool> IsULT = KnownBits::ult(Known0, Known1)) 2020 return TLO.CombineTo(Op, IsULT.value() ? Op0 : Op1); 2021 break; 2022 } 2023 case ISD::UMAX: { 2024 // Check if one arg is always greater than (or equal) to the other arg. 2025 SDValue Op0 = Op.getOperand(0); 2026 SDValue Op1 = Op.getOperand(1); 2027 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 2028 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 2029 Known = KnownBits::umax(Known0, Known1); 2030 if (Optional<bool> IsUGE = KnownBits::uge(Known0, Known1)) 2031 return TLO.CombineTo(Op, IsUGE.value() ? Op0 : Op1); 2032 if (Optional<bool> IsUGT = KnownBits::ugt(Known0, Known1)) 2033 return TLO.CombineTo(Op, IsUGT.value() ? Op0 : Op1); 2034 break; 2035 } 2036 case ISD::BITREVERSE: { 2037 SDValue Src = Op.getOperand(0); 2038 APInt DemandedSrcBits = DemandedBits.reverseBits(); 2039 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 2040 Depth + 1)) 2041 return true; 2042 Known.One = Known2.One.reverseBits(); 2043 Known.Zero = Known2.Zero.reverseBits(); 2044 break; 2045 } 2046 case ISD::BSWAP: { 2047 SDValue Src = Op.getOperand(0); 2048 2049 // If the only bits demanded come from one byte of the bswap result, 2050 // just shift the input byte into position to eliminate the bswap. 2051 unsigned NLZ = DemandedBits.countLeadingZeros(); 2052 unsigned NTZ = DemandedBits.countTrailingZeros(); 2053 2054 // Round NTZ down to the next byte. If we have 11 trailing zeros, then 2055 // we need all the bits down to bit 8. Likewise, round NLZ. If we 2056 // have 14 leading zeros, round to 8. 2057 NLZ = alignDown(NLZ, 8); 2058 NTZ = alignDown(NTZ, 8); 2059 // If we need exactly one byte, we can do this transformation. 2060 if (BitWidth - NLZ - NTZ == 8) { 2061 // Replace this with either a left or right shift to get the byte into 2062 // the right place. 2063 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL; 2064 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) { 2065 EVT ShiftAmtTy = getShiftAmountTy(VT, DL); 2066 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ; 2067 SDValue ShAmt = TLO.DAG.getConstant(ShiftAmount, dl, ShiftAmtTy); 2068 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt); 2069 return TLO.CombineTo(Op, NewOp); 2070 } 2071 } 2072 2073 APInt DemandedSrcBits = DemandedBits.byteSwap(); 2074 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 2075 Depth + 1)) 2076 return true; 2077 Known.One = Known2.One.byteSwap(); 2078 Known.Zero = Known2.Zero.byteSwap(); 2079 break; 2080 } 2081 case ISD::CTPOP: { 2082 // If only 1 bit is demanded, replace with PARITY as long as we're before 2083 // op legalization. 2084 // FIXME: Limit to scalars for now. 2085 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector()) 2086 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT, 2087 Op.getOperand(0))); 2088 2089 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2090 break; 2091 } 2092 case ISD::SIGN_EXTEND_INREG: { 2093 SDValue Op0 = Op.getOperand(0); 2094 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2095 unsigned ExVTBits = ExVT.getScalarSizeInBits(); 2096 2097 // If we only care about the highest bit, don't bother shifting right. 2098 if (DemandedBits.isSignMask()) { 2099 unsigned MinSignedBits = 2100 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1); 2101 bool AlreadySignExtended = ExVTBits >= MinSignedBits; 2102 // However if the input is already sign extended we expect the sign 2103 // extension to be dropped altogether later and do not simplify. 2104 if (!AlreadySignExtended) { 2105 // Compute the correct shift amount type, which must be getShiftAmountTy 2106 // for scalar types after legalization. 2107 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ExVTBits, dl, 2108 getShiftAmountTy(VT, DL)); 2109 return TLO.CombineTo(Op, 2110 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt)); 2111 } 2112 } 2113 2114 // If none of the extended bits are demanded, eliminate the sextinreg. 2115 if (DemandedBits.getActiveBits() <= ExVTBits) 2116 return TLO.CombineTo(Op, Op0); 2117 2118 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits); 2119 2120 // Since the sign extended bits are demanded, we know that the sign 2121 // bit is demanded. 2122 InputDemandedBits.setBit(ExVTBits - 1); 2123 2124 if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO, 2125 Depth + 1)) 2126 return true; 2127 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2128 2129 // If the sign bit of the input is known set or clear, then we know the 2130 // top bits of the result. 2131 2132 // If the input sign bit is known zero, convert this into a zero extension. 2133 if (Known.Zero[ExVTBits - 1]) 2134 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT)); 2135 2136 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits); 2137 if (Known.One[ExVTBits - 1]) { // Input sign bit known set 2138 Known.One.setBitsFrom(ExVTBits); 2139 Known.Zero &= Mask; 2140 } else { // Input sign bit unknown 2141 Known.Zero &= Mask; 2142 Known.One &= Mask; 2143 } 2144 break; 2145 } 2146 case ISD::BUILD_PAIR: { 2147 EVT HalfVT = Op.getOperand(0).getValueType(); 2148 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 2149 2150 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 2151 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 2152 2153 KnownBits KnownLo, KnownHi; 2154 2155 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1)) 2156 return true; 2157 2158 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1)) 2159 return true; 2160 2161 Known.Zero = KnownLo.Zero.zext(BitWidth) | 2162 KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth); 2163 2164 Known.One = KnownLo.One.zext(BitWidth) | 2165 KnownHi.One.zext(BitWidth).shl(HalfBitWidth); 2166 break; 2167 } 2168 case ISD::ZERO_EXTEND: 2169 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2170 SDValue Src = Op.getOperand(0); 2171 EVT SrcVT = Src.getValueType(); 2172 unsigned InBits = SrcVT.getScalarSizeInBits(); 2173 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2174 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG; 2175 2176 // If none of the top bits are demanded, convert this into an any_extend. 2177 if (DemandedBits.getActiveBits() <= InBits) { 2178 // If we only need the non-extended bits of the bottom element 2179 // then we can just bitcast to the result. 2180 if (IsLE && IsVecInReg && DemandedElts == 1 && 2181 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2182 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2183 2184 unsigned Opc = 2185 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2186 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2187 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2188 } 2189 2190 APInt InDemandedBits = DemandedBits.trunc(InBits); 2191 APInt InDemandedElts = DemandedElts.zext(InElts); 2192 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2193 Depth + 1)) 2194 return true; 2195 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2196 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2197 Known = Known.zext(BitWidth); 2198 2199 // Attempt to avoid multi-use ops if we don't need anything from them. 2200 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2201 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2202 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2203 break; 2204 } 2205 case ISD::SIGN_EXTEND: 2206 case ISD::SIGN_EXTEND_VECTOR_INREG: { 2207 SDValue Src = Op.getOperand(0); 2208 EVT SrcVT = Src.getValueType(); 2209 unsigned InBits = SrcVT.getScalarSizeInBits(); 2210 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2211 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG; 2212 2213 // If none of the top bits are demanded, convert this into an any_extend. 2214 if (DemandedBits.getActiveBits() <= InBits) { 2215 // If we only need the non-extended bits of the bottom element 2216 // then we can just bitcast to the result. 2217 if (IsLE && IsVecInReg && DemandedElts == 1 && 2218 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2219 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2220 2221 unsigned Opc = 2222 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 2223 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2224 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2225 } 2226 2227 APInt InDemandedBits = DemandedBits.trunc(InBits); 2228 APInt InDemandedElts = DemandedElts.zext(InElts); 2229 2230 // Since some of the sign extended bits are demanded, we know that the sign 2231 // bit is demanded. 2232 InDemandedBits.setBit(InBits - 1); 2233 2234 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2235 Depth + 1)) 2236 return true; 2237 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2238 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2239 2240 // If the sign bit is known one, the top bits match. 2241 Known = Known.sext(BitWidth); 2242 2243 // If the sign bit is known zero, convert this to a zero extend. 2244 if (Known.isNonNegative()) { 2245 unsigned Opc = 2246 IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND; 2247 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 2248 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 2249 } 2250 2251 // Attempt to avoid multi-use ops if we don't need anything from them. 2252 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2253 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2254 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2255 break; 2256 } 2257 case ISD::ANY_EXTEND: 2258 case ISD::ANY_EXTEND_VECTOR_INREG: { 2259 SDValue Src = Op.getOperand(0); 2260 EVT SrcVT = Src.getValueType(); 2261 unsigned InBits = SrcVT.getScalarSizeInBits(); 2262 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2263 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG; 2264 2265 // If we only need the bottom element then we can just bitcast. 2266 // TODO: Handle ANY_EXTEND? 2267 if (IsLE && IsVecInReg && DemandedElts == 1 && 2268 VT.getSizeInBits() == SrcVT.getSizeInBits()) 2269 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2270 2271 APInt InDemandedBits = DemandedBits.trunc(InBits); 2272 APInt InDemandedElts = DemandedElts.zext(InElts); 2273 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 2274 Depth + 1)) 2275 return true; 2276 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2277 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 2278 Known = Known.anyext(BitWidth); 2279 2280 // Attempt to avoid multi-use ops if we don't need anything from them. 2281 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2282 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 2283 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 2284 break; 2285 } 2286 case ISD::TRUNCATE: { 2287 SDValue Src = Op.getOperand(0); 2288 2289 // Simplify the input, using demanded bit information, and compute the known 2290 // zero/one bits live out. 2291 unsigned OperandBitWidth = Src.getScalarValueSizeInBits(); 2292 APInt TruncMask = DemandedBits.zext(OperandBitWidth); 2293 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO, 2294 Depth + 1)) 2295 return true; 2296 Known = Known.trunc(BitWidth); 2297 2298 // Attempt to avoid multi-use ops if we don't need anything from them. 2299 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 2300 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1)) 2301 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc)); 2302 2303 // If the input is only used by this truncate, see if we can shrink it based 2304 // on the known demanded bits. 2305 if (Src.getNode()->hasOneUse()) { 2306 switch (Src.getOpcode()) { 2307 default: 2308 break; 2309 case ISD::SRL: 2310 // Shrink SRL by a constant if none of the high bits shifted in are 2311 // demanded. 2312 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT)) 2313 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 2314 // undesirable. 2315 break; 2316 2317 const APInt *ShAmtC = 2318 TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts); 2319 if (!ShAmtC || ShAmtC->uge(BitWidth)) 2320 break; 2321 uint64_t ShVal = ShAmtC->getZExtValue(); 2322 2323 APInt HighBits = 2324 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth); 2325 HighBits.lshrInPlace(ShVal); 2326 HighBits = HighBits.trunc(BitWidth); 2327 2328 if (!(HighBits & DemandedBits)) { 2329 // None of the shifted in bits are needed. Add a truncate of the 2330 // shift input, then shift it. 2331 SDValue NewShAmt = TLO.DAG.getConstant( 2332 ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes())); 2333 SDValue NewTrunc = 2334 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0)); 2335 return TLO.CombineTo( 2336 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt)); 2337 } 2338 break; 2339 } 2340 } 2341 2342 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2343 break; 2344 } 2345 case ISD::AssertZext: { 2346 // AssertZext demands all of the high bits, plus any of the low bits 2347 // demanded by its users. 2348 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2349 APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits()); 2350 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known, 2351 TLO, Depth + 1)) 2352 return true; 2353 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2354 2355 Known.Zero |= ~InMask; 2356 break; 2357 } 2358 case ISD::EXTRACT_VECTOR_ELT: { 2359 SDValue Src = Op.getOperand(0); 2360 SDValue Idx = Op.getOperand(1); 2361 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount(); 2362 unsigned EltBitWidth = Src.getScalarValueSizeInBits(); 2363 2364 if (SrcEltCnt.isScalable()) 2365 return false; 2366 2367 // Demand the bits from every vector element without a constant index. 2368 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2369 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 2370 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx)) 2371 if (CIdx->getAPIntValue().ult(NumSrcElts)) 2372 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue()); 2373 2374 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 2375 // anything about the extended bits. 2376 APInt DemandedSrcBits = DemandedBits; 2377 if (BitWidth > EltBitWidth) 2378 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth); 2379 2380 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO, 2381 Depth + 1)) 2382 return true; 2383 2384 // Attempt to avoid multi-use ops if we don't need anything from them. 2385 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) { 2386 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 2387 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) { 2388 SDValue NewOp = 2389 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx); 2390 return TLO.CombineTo(Op, NewOp); 2391 } 2392 } 2393 2394 Known = Known2; 2395 if (BitWidth > EltBitWidth) 2396 Known = Known.anyext(BitWidth); 2397 break; 2398 } 2399 case ISD::BITCAST: { 2400 SDValue Src = Op.getOperand(0); 2401 EVT SrcVT = Src.getValueType(); 2402 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 2403 2404 // If this is an FP->Int bitcast and if the sign bit is the only 2405 // thing demanded, turn this into a FGETSIGN. 2406 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() && 2407 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) && 2408 SrcVT.isFloatingPoint()) { 2409 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT); 2410 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 2411 if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 && 2412 SrcVT != MVT::f128) { 2413 // Cannot eliminate/lower SHL for f128 yet. 2414 EVT Ty = OpVTLegal ? VT : MVT::i32; 2415 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 2416 // place. We expect the SHL to be eliminated by other optimizations. 2417 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src); 2418 unsigned OpVTSizeInBits = Op.getValueSizeInBits(); 2419 if (!OpVTLegal && OpVTSizeInBits > 32) 2420 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign); 2421 unsigned ShVal = Op.getValueSizeInBits() - 1; 2422 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT); 2423 return TLO.CombineTo(Op, 2424 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt)); 2425 } 2426 } 2427 2428 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts. 2429 // Demand the elt/bit if any of the original elts/bits are demanded. 2430 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) { 2431 unsigned Scale = BitWidth / NumSrcEltBits; 2432 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2433 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2434 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2435 for (unsigned i = 0; i != Scale; ++i) { 2436 unsigned EltOffset = IsLE ? i : (Scale - 1 - i); 2437 unsigned BitOffset = EltOffset * NumSrcEltBits; 2438 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset); 2439 if (!Sub.isZero()) { 2440 DemandedSrcBits |= Sub; 2441 for (unsigned j = 0; j != NumElts; ++j) 2442 if (DemandedElts[j]) 2443 DemandedSrcElts.setBit((j * Scale) + i); 2444 } 2445 } 2446 2447 APInt KnownSrcUndef, KnownSrcZero; 2448 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2449 KnownSrcZero, TLO, Depth + 1)) 2450 return true; 2451 2452 KnownBits KnownSrcBits; 2453 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2454 KnownSrcBits, TLO, Depth + 1)) 2455 return true; 2456 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) { 2457 // TODO - bigendian once we have test coverage. 2458 unsigned Scale = NumSrcEltBits / BitWidth; 2459 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2460 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits); 2461 APInt DemandedSrcElts = APInt::getZero(NumSrcElts); 2462 for (unsigned i = 0; i != NumElts; ++i) 2463 if (DemandedElts[i]) { 2464 unsigned Offset = (i % Scale) * BitWidth; 2465 DemandedSrcBits.insertBits(DemandedBits, Offset); 2466 DemandedSrcElts.setBit(i / Scale); 2467 } 2468 2469 if (SrcVT.isVector()) { 2470 APInt KnownSrcUndef, KnownSrcZero; 2471 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2472 KnownSrcZero, TLO, Depth + 1)) 2473 return true; 2474 } 2475 2476 KnownBits KnownSrcBits; 2477 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2478 KnownSrcBits, TLO, Depth + 1)) 2479 return true; 2480 } 2481 2482 // If this is a bitcast, let computeKnownBits handle it. Only do this on a 2483 // recursive call where Known may be useful to the caller. 2484 if (Depth > 0) { 2485 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2486 return false; 2487 } 2488 break; 2489 } 2490 case ISD::MUL: 2491 if (DemandedBits.isPowerOf2()) { 2492 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1. 2493 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is 2494 // odd (has LSB set), then the left-shifted low bit of X is the answer. 2495 unsigned CTZ = DemandedBits.countTrailingZeros(); 2496 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts); 2497 if (C && C->getAPIntValue().countTrailingZeros() == CTZ) { 2498 EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout()); 2499 SDValue AmtC = TLO.DAG.getConstant(CTZ, dl, ShiftAmtTy); 2500 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC); 2501 return TLO.CombineTo(Op, Shl); 2502 } 2503 } 2504 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because: 2505 // X * X is odd iff X is odd. 2506 // 'Quadratic Reciprocity': X * X -> 0 for bit[1] 2507 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) { 2508 SDValue One = TLO.DAG.getConstant(1, dl, VT); 2509 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One); 2510 return TLO.CombineTo(Op, And1); 2511 } 2512 LLVM_FALLTHROUGH; 2513 case ISD::ADD: 2514 case ISD::SUB: { 2515 // Add, Sub, and Mul don't demand any bits in positions beyond that 2516 // of the highest bit demanded of them. 2517 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1); 2518 SDNodeFlags Flags = Op.getNode()->getFlags(); 2519 unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros(); 2520 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ); 2521 if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO, 2522 Depth + 1) || 2523 SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO, 2524 Depth + 1) || 2525 // See if the operation should be performed at a smaller bit width. 2526 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) { 2527 if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) { 2528 // Disable the nsw and nuw flags. We can no longer guarantee that we 2529 // won't wrap after simplification. 2530 Flags.setNoSignedWrap(false); 2531 Flags.setNoUnsignedWrap(false); 2532 Op->setFlags(Flags); 2533 } 2534 return true; 2535 } 2536 2537 // Attempt to avoid multi-use ops if we don't need anything from them. 2538 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) { 2539 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2540 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2541 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 2542 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2543 if (DemandedOp0 || DemandedOp1) { 2544 Flags.setNoSignedWrap(false); 2545 Flags.setNoUnsignedWrap(false); 2546 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 2547 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 2548 SDValue NewOp = 2549 TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags); 2550 return TLO.CombineTo(Op, NewOp); 2551 } 2552 } 2553 2554 // If we have a constant operand, we may be able to turn it into -1 if we 2555 // do not demand the high bits. This can make the constant smaller to 2556 // encode, allow more general folding, or match specialized instruction 2557 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that 2558 // is probably not useful (and could be detrimental). 2559 ConstantSDNode *C = isConstOrConstSplat(Op1); 2560 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ); 2561 if (C && !C->isAllOnes() && !C->isOne() && 2562 (C->getAPIntValue() | HighMask).isAllOnes()) { 2563 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT); 2564 // Disable the nsw and nuw flags. We can no longer guarantee that we 2565 // won't wrap after simplification. 2566 Flags.setNoSignedWrap(false); 2567 Flags.setNoUnsignedWrap(false); 2568 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags); 2569 return TLO.CombineTo(Op, NewOp); 2570 } 2571 2572 // Match a multiply with a disguised negated-power-of-2 and convert to a 2573 // an equivalent shift-left amount. 2574 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2575 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned { 2576 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse()) 2577 return 0; 2578 2579 // Don't touch opaque constants. Also, ignore zero and power-of-2 2580 // multiplies. Those will get folded later. 2581 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1)); 2582 if (MulC && !MulC->isOpaque() && !MulC->isZero() && 2583 !MulC->getAPIntValue().isPowerOf2()) { 2584 APInt UnmaskedC = MulC->getAPIntValue() | HighMask; 2585 if (UnmaskedC.isNegatedPowerOf2()) 2586 return (-UnmaskedC).logBase2(); 2587 } 2588 return 0; 2589 }; 2590 2591 auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y, unsigned ShlAmt) { 2592 EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout()); 2593 SDValue ShlAmtC = TLO.DAG.getConstant(ShlAmt, dl, ShiftAmtTy); 2594 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC); 2595 SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl); 2596 return TLO.CombineTo(Op, Res); 2597 }; 2598 2599 if (isOperationLegalOrCustom(ISD::SHL, VT)) { 2600 if (Op.getOpcode() == ISD::ADD) { 2601 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC)) 2602 if (unsigned ShAmt = getShiftLeftAmt(Op0)) 2603 return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt); 2604 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC)) 2605 if (unsigned ShAmt = getShiftLeftAmt(Op1)) 2606 return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt); 2607 } 2608 if (Op.getOpcode() == ISD::SUB) { 2609 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC)) 2610 if (unsigned ShAmt = getShiftLeftAmt(Op1)) 2611 return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt); 2612 } 2613 } 2614 2615 LLVM_FALLTHROUGH; 2616 } 2617 default: 2618 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 2619 if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts, 2620 Known, TLO, Depth)) 2621 return true; 2622 break; 2623 } 2624 2625 // Just use computeKnownBits to compute output bits. 2626 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2627 break; 2628 } 2629 2630 // If we know the value of all of the demanded bits, return this as a 2631 // constant. 2632 if (!isTargetCanonicalConstantNode(Op) && 2633 DemandedBits.isSubsetOf(Known.Zero | Known.One)) { 2634 // Avoid folding to a constant if any OpaqueConstant is involved. 2635 const SDNode *N = Op.getNode(); 2636 for (SDNode *Op : 2637 llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) { 2638 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 2639 if (C->isOpaque()) 2640 return false; 2641 } 2642 if (VT.isInteger()) 2643 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT)); 2644 if (VT.isFloatingPoint()) 2645 return TLO.CombineTo( 2646 Op, 2647 TLO.DAG.getConstantFP( 2648 APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT)); 2649 } 2650 2651 return false; 2652 } 2653 2654 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op, 2655 const APInt &DemandedElts, 2656 DAGCombinerInfo &DCI) const { 2657 SelectionDAG &DAG = DCI.DAG; 2658 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 2659 !DCI.isBeforeLegalizeOps()); 2660 2661 APInt KnownUndef, KnownZero; 2662 bool Simplified = 2663 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO); 2664 if (Simplified) { 2665 DCI.AddToWorklist(Op.getNode()); 2666 DCI.CommitTargetLoweringOpt(TLO); 2667 } 2668 2669 return Simplified; 2670 } 2671 2672 /// Given a vector binary operation and known undefined elements for each input 2673 /// operand, compute whether each element of the output is undefined. 2674 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG, 2675 const APInt &UndefOp0, 2676 const APInt &UndefOp1) { 2677 EVT VT = BO.getValueType(); 2678 assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() && 2679 "Vector binop only"); 2680 2681 EVT EltVT = VT.getVectorElementType(); 2682 unsigned NumElts = VT.getVectorNumElements(); 2683 assert(UndefOp0.getBitWidth() == NumElts && 2684 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis"); 2685 2686 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index, 2687 const APInt &UndefVals) { 2688 if (UndefVals[Index]) 2689 return DAG.getUNDEF(EltVT); 2690 2691 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 2692 // Try hard to make sure that the getNode() call is not creating temporary 2693 // nodes. Ignore opaque integers because they do not constant fold. 2694 SDValue Elt = BV->getOperand(Index); 2695 auto *C = dyn_cast<ConstantSDNode>(Elt); 2696 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque())) 2697 return Elt; 2698 } 2699 2700 return SDValue(); 2701 }; 2702 2703 APInt KnownUndef = APInt::getZero(NumElts); 2704 for (unsigned i = 0; i != NumElts; ++i) { 2705 // If both inputs for this element are either constant or undef and match 2706 // the element type, compute the constant/undef result for this element of 2707 // the vector. 2708 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does 2709 // not handle FP constants. The code within getNode() should be refactored 2710 // to avoid the danger of creating a bogus temporary node here. 2711 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0); 2712 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1); 2713 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT) 2714 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef()) 2715 KnownUndef.setBit(i); 2716 } 2717 return KnownUndef; 2718 } 2719 2720 bool TargetLowering::SimplifyDemandedVectorElts( 2721 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef, 2722 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth, 2723 bool AssumeSingleUse) const { 2724 EVT VT = Op.getValueType(); 2725 unsigned Opcode = Op.getOpcode(); 2726 APInt DemandedElts = OriginalDemandedElts; 2727 unsigned NumElts = DemandedElts.getBitWidth(); 2728 assert(VT.isVector() && "Expected vector op"); 2729 2730 KnownUndef = KnownZero = APInt::getZero(NumElts); 2731 2732 const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo(); 2733 if (!TLI.shouldSimplifyDemandedVectorElts(Op, TLO)) 2734 return false; 2735 2736 // TODO: For now we assume we know nothing about scalable vectors. 2737 if (VT.isScalableVector()) 2738 return false; 2739 2740 assert(VT.getVectorNumElements() == NumElts && 2741 "Mask size mismatches value type element count!"); 2742 2743 // Undef operand. 2744 if (Op.isUndef()) { 2745 KnownUndef.setAllBits(); 2746 return false; 2747 } 2748 2749 // If Op has other users, assume that all elements are needed. 2750 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) 2751 DemandedElts.setAllBits(); 2752 2753 // Not demanding any elements from Op. 2754 if (DemandedElts == 0) { 2755 KnownUndef.setAllBits(); 2756 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2757 } 2758 2759 // Limit search depth. 2760 if (Depth >= SelectionDAG::MaxRecursionDepth) 2761 return false; 2762 2763 SDLoc DL(Op); 2764 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 2765 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian(); 2766 2767 // Helper for demanding the specified elements and all the bits of both binary 2768 // operands. 2769 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) { 2770 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts, 2771 TLO.DAG, Depth + 1); 2772 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts, 2773 TLO.DAG, Depth + 1); 2774 if (NewOp0 || NewOp1) { 2775 SDValue NewOp = TLO.DAG.getNode( 2776 Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, NewOp1 ? NewOp1 : Op1); 2777 return TLO.CombineTo(Op, NewOp); 2778 } 2779 return false; 2780 }; 2781 2782 switch (Opcode) { 2783 case ISD::SCALAR_TO_VECTOR: { 2784 if (!DemandedElts[0]) { 2785 KnownUndef.setAllBits(); 2786 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2787 } 2788 SDValue ScalarSrc = Op.getOperand(0); 2789 if (ScalarSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 2790 SDValue Src = ScalarSrc.getOperand(0); 2791 SDValue Idx = ScalarSrc.getOperand(1); 2792 EVT SrcVT = Src.getValueType(); 2793 2794 ElementCount SrcEltCnt = SrcVT.getVectorElementCount(); 2795 2796 if (SrcEltCnt.isScalable()) 2797 return false; 2798 2799 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2800 if (isNullConstant(Idx)) { 2801 APInt SrcDemandedElts = APInt::getOneBitSet(NumSrcElts, 0); 2802 APInt SrcUndef = KnownUndef.zextOrTrunc(NumSrcElts); 2803 APInt SrcZero = KnownZero.zextOrTrunc(NumSrcElts); 2804 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2805 TLO, Depth + 1)) 2806 return true; 2807 } 2808 } 2809 KnownUndef.setHighBits(NumElts - 1); 2810 break; 2811 } 2812 case ISD::BITCAST: { 2813 SDValue Src = Op.getOperand(0); 2814 EVT SrcVT = Src.getValueType(); 2815 2816 // We only handle vectors here. 2817 // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits? 2818 if (!SrcVT.isVector()) 2819 break; 2820 2821 // Fast handling of 'identity' bitcasts. 2822 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2823 if (NumSrcElts == NumElts) 2824 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, 2825 KnownZero, TLO, Depth + 1); 2826 2827 APInt SrcDemandedElts, SrcZero, SrcUndef; 2828 2829 // Bitcast from 'large element' src vector to 'small element' vector, we 2830 // must demand a source element if any DemandedElt maps to it. 2831 if ((NumElts % NumSrcElts) == 0) { 2832 unsigned Scale = NumElts / NumSrcElts; 2833 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2834 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2835 TLO, Depth + 1)) 2836 return true; 2837 2838 // Try calling SimplifyDemandedBits, converting demanded elts to the bits 2839 // of the large element. 2840 // TODO - bigendian once we have test coverage. 2841 if (IsLE) { 2842 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits(); 2843 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits); 2844 for (unsigned i = 0; i != NumElts; ++i) 2845 if (DemandedElts[i]) { 2846 unsigned Ofs = (i % Scale) * EltSizeInBits; 2847 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits); 2848 } 2849 2850 KnownBits Known; 2851 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known, 2852 TLO, Depth + 1)) 2853 return true; 2854 2855 // The bitcast has split each wide element into a number of 2856 // narrow subelements. We have just computed the Known bits 2857 // for wide elements. See if element splitting results in 2858 // some subelements being zero. Only for demanded elements! 2859 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) { 2860 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits) 2861 .isAllOnes()) 2862 continue; 2863 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) { 2864 unsigned Elt = Scale * SrcElt + SubElt; 2865 if (DemandedElts[Elt]) 2866 KnownZero.setBit(Elt); 2867 } 2868 } 2869 } 2870 2871 // If the src element is zero/undef then all the output elements will be - 2872 // only demanded elements are guaranteed to be correct. 2873 for (unsigned i = 0; i != NumSrcElts; ++i) { 2874 if (SrcDemandedElts[i]) { 2875 if (SrcZero[i]) 2876 KnownZero.setBits(i * Scale, (i + 1) * Scale); 2877 if (SrcUndef[i]) 2878 KnownUndef.setBits(i * Scale, (i + 1) * Scale); 2879 } 2880 } 2881 } 2882 2883 // Bitcast from 'small element' src vector to 'large element' vector, we 2884 // demand all smaller source elements covered by the larger demanded element 2885 // of this vector. 2886 if ((NumSrcElts % NumElts) == 0) { 2887 unsigned Scale = NumSrcElts / NumElts; 2888 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2889 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2890 TLO, Depth + 1)) 2891 return true; 2892 2893 // If all the src elements covering an output element are zero/undef, then 2894 // the output element will be as well, assuming it was demanded. 2895 for (unsigned i = 0; i != NumElts; ++i) { 2896 if (DemandedElts[i]) { 2897 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes()) 2898 KnownZero.setBit(i); 2899 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes()) 2900 KnownUndef.setBit(i); 2901 } 2902 } 2903 } 2904 break; 2905 } 2906 case ISD::BUILD_VECTOR: { 2907 // Check all elements and simplify any unused elements with UNDEF. 2908 if (!DemandedElts.isAllOnes()) { 2909 // Don't simplify BROADCASTS. 2910 if (llvm::any_of(Op->op_values(), 2911 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) { 2912 SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end()); 2913 bool Updated = false; 2914 for (unsigned i = 0; i != NumElts; ++i) { 2915 if (!DemandedElts[i] && !Ops[i].isUndef()) { 2916 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType()); 2917 KnownUndef.setBit(i); 2918 Updated = true; 2919 } 2920 } 2921 if (Updated) 2922 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops)); 2923 } 2924 } 2925 for (unsigned i = 0; i != NumElts; ++i) { 2926 SDValue SrcOp = Op.getOperand(i); 2927 if (SrcOp.isUndef()) { 2928 KnownUndef.setBit(i); 2929 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() && 2930 (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) { 2931 KnownZero.setBit(i); 2932 } 2933 } 2934 break; 2935 } 2936 case ISD::CONCAT_VECTORS: { 2937 EVT SubVT = Op.getOperand(0).getValueType(); 2938 unsigned NumSubVecs = Op.getNumOperands(); 2939 unsigned NumSubElts = SubVT.getVectorNumElements(); 2940 for (unsigned i = 0; i != NumSubVecs; ++i) { 2941 SDValue SubOp = Op.getOperand(i); 2942 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 2943 APInt SubUndef, SubZero; 2944 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO, 2945 Depth + 1)) 2946 return true; 2947 KnownUndef.insertBits(SubUndef, i * NumSubElts); 2948 KnownZero.insertBits(SubZero, i * NumSubElts); 2949 } 2950 2951 // Attempt to avoid multi-use ops if we don't need anything from them. 2952 if (!DemandedElts.isAllOnes()) { 2953 bool FoundNewSub = false; 2954 SmallVector<SDValue, 2> DemandedSubOps; 2955 for (unsigned i = 0; i != NumSubVecs; ++i) { 2956 SDValue SubOp = Op.getOperand(i); 2957 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 2958 SDValue NewSubOp = SimplifyMultipleUseDemandedVectorElts( 2959 SubOp, SubElts, TLO.DAG, Depth + 1); 2960 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp); 2961 FoundNewSub = NewSubOp ? true : FoundNewSub; 2962 } 2963 if (FoundNewSub) { 2964 SDValue NewOp = 2965 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps); 2966 return TLO.CombineTo(Op, NewOp); 2967 } 2968 } 2969 break; 2970 } 2971 case ISD::INSERT_SUBVECTOR: { 2972 // Demand any elements from the subvector and the remainder from the src its 2973 // inserted into. 2974 SDValue Src = Op.getOperand(0); 2975 SDValue Sub = Op.getOperand(1); 2976 uint64_t Idx = Op.getConstantOperandVal(2); 2977 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2978 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2979 APInt DemandedSrcElts = DemandedElts; 2980 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 2981 2982 APInt SubUndef, SubZero; 2983 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO, 2984 Depth + 1)) 2985 return true; 2986 2987 // If none of the src operand elements are demanded, replace it with undef. 2988 if (!DemandedSrcElts && !Src.isUndef()) 2989 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 2990 TLO.DAG.getUNDEF(VT), Sub, 2991 Op.getOperand(2))); 2992 2993 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero, 2994 TLO, Depth + 1)) 2995 return true; 2996 KnownUndef.insertBits(SubUndef, Idx); 2997 KnownZero.insertBits(SubZero, Idx); 2998 2999 // Attempt to avoid multi-use ops if we don't need anything from them. 3000 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) { 3001 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 3002 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 3003 SDValue NewSub = SimplifyMultipleUseDemandedVectorElts( 3004 Sub, DemandedSubElts, TLO.DAG, Depth + 1); 3005 if (NewSrc || NewSub) { 3006 NewSrc = NewSrc ? NewSrc : Src; 3007 NewSub = NewSub ? NewSub : Sub; 3008 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 3009 NewSub, Op.getOperand(2)); 3010 return TLO.CombineTo(Op, NewOp); 3011 } 3012 } 3013 break; 3014 } 3015 case ISD::EXTRACT_SUBVECTOR: { 3016 // Offset the demanded elts by the subvector index. 3017 SDValue Src = Op.getOperand(0); 3018 if (Src.getValueType().isScalableVector()) 3019 break; 3020 uint64_t Idx = Op.getConstantOperandVal(1); 3021 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3022 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 3023 3024 APInt SrcUndef, SrcZero; 3025 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 3026 Depth + 1)) 3027 return true; 3028 KnownUndef = SrcUndef.extractBits(NumElts, Idx); 3029 KnownZero = SrcZero.extractBits(NumElts, Idx); 3030 3031 // Attempt to avoid multi-use ops if we don't need anything from them. 3032 if (!DemandedElts.isAllOnes()) { 3033 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 3034 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 3035 if (NewSrc) { 3036 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 3037 Op.getOperand(1)); 3038 return TLO.CombineTo(Op, NewOp); 3039 } 3040 } 3041 break; 3042 } 3043 case ISD::INSERT_VECTOR_ELT: { 3044 SDValue Vec = Op.getOperand(0); 3045 SDValue Scl = Op.getOperand(1); 3046 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 3047 3048 // For a legal, constant insertion index, if we don't need this insertion 3049 // then strip it, else remove it from the demanded elts. 3050 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) { 3051 unsigned Idx = CIdx->getZExtValue(); 3052 if (!DemandedElts[Idx]) 3053 return TLO.CombineTo(Op, Vec); 3054 3055 APInt DemandedVecElts(DemandedElts); 3056 DemandedVecElts.clearBit(Idx); 3057 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef, 3058 KnownZero, TLO, Depth + 1)) 3059 return true; 3060 3061 KnownUndef.setBitVal(Idx, Scl.isUndef()); 3062 3063 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl)); 3064 break; 3065 } 3066 3067 APInt VecUndef, VecZero; 3068 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO, 3069 Depth + 1)) 3070 return true; 3071 // Without knowing the insertion index we can't set KnownUndef/KnownZero. 3072 break; 3073 } 3074 case ISD::VSELECT: { 3075 SDValue Sel = Op.getOperand(0); 3076 SDValue LHS = Op.getOperand(1); 3077 SDValue RHS = Op.getOperand(2); 3078 3079 // Try to transform the select condition based on the current demanded 3080 // elements. 3081 APInt UndefSel, UndefZero; 3082 if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, UndefZero, TLO, 3083 Depth + 1)) 3084 return true; 3085 3086 // See if we can simplify either vselect operand. 3087 APInt DemandedLHS(DemandedElts); 3088 APInt DemandedRHS(DemandedElts); 3089 APInt UndefLHS, ZeroLHS; 3090 APInt UndefRHS, ZeroRHS; 3091 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO, 3092 Depth + 1)) 3093 return true; 3094 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO, 3095 Depth + 1)) 3096 return true; 3097 3098 KnownUndef = UndefLHS & UndefRHS; 3099 KnownZero = ZeroLHS & ZeroRHS; 3100 3101 // If we know that the selected element is always zero, we don't need the 3102 // select value element. 3103 APInt DemandedSel = DemandedElts & ~KnownZero; 3104 if (DemandedSel != DemandedElts) 3105 if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, UndefZero, TLO, 3106 Depth + 1)) 3107 return true; 3108 3109 break; 3110 } 3111 case ISD::VECTOR_SHUFFLE: { 3112 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 3113 3114 // Collect demanded elements from shuffle operands.. 3115 APInt DemandedLHS(NumElts, 0); 3116 APInt DemandedRHS(NumElts, 0); 3117 for (unsigned i = 0; i != NumElts; ++i) { 3118 int M = ShuffleMask[i]; 3119 if (M < 0 || !DemandedElts[i]) 3120 continue; 3121 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 3122 if (M < (int)NumElts) 3123 DemandedLHS.setBit(M); 3124 else 3125 DemandedRHS.setBit(M - NumElts); 3126 } 3127 3128 // See if we can simplify either shuffle operand. 3129 APInt UndefLHS, ZeroLHS; 3130 APInt UndefRHS, ZeroRHS; 3131 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS, 3132 ZeroLHS, TLO, Depth + 1)) 3133 return true; 3134 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS, 3135 ZeroRHS, TLO, Depth + 1)) 3136 return true; 3137 3138 // Simplify mask using undef elements from LHS/RHS. 3139 bool Updated = false; 3140 bool IdentityLHS = true, IdentityRHS = true; 3141 SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end()); 3142 for (unsigned i = 0; i != NumElts; ++i) { 3143 int &M = NewMask[i]; 3144 if (M < 0) 3145 continue; 3146 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) || 3147 (M >= (int)NumElts && UndefRHS[M - NumElts])) { 3148 Updated = true; 3149 M = -1; 3150 } 3151 IdentityLHS &= (M < 0) || (M == (int)i); 3152 IdentityRHS &= (M < 0) || ((M - NumElts) == i); 3153 } 3154 3155 // Update legal shuffle masks based on demanded elements if it won't reduce 3156 // to Identity which can cause premature removal of the shuffle mask. 3157 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) { 3158 SDValue LegalShuffle = 3159 buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1), 3160 NewMask, TLO.DAG); 3161 if (LegalShuffle) 3162 return TLO.CombineTo(Op, LegalShuffle); 3163 } 3164 3165 // Propagate undef/zero elements from LHS/RHS. 3166 for (unsigned i = 0; i != NumElts; ++i) { 3167 int M = ShuffleMask[i]; 3168 if (M < 0) { 3169 KnownUndef.setBit(i); 3170 } else if (M < (int)NumElts) { 3171 if (UndefLHS[M]) 3172 KnownUndef.setBit(i); 3173 if (ZeroLHS[M]) 3174 KnownZero.setBit(i); 3175 } else { 3176 if (UndefRHS[M - NumElts]) 3177 KnownUndef.setBit(i); 3178 if (ZeroRHS[M - NumElts]) 3179 KnownZero.setBit(i); 3180 } 3181 } 3182 break; 3183 } 3184 case ISD::ANY_EXTEND_VECTOR_INREG: 3185 case ISD::SIGN_EXTEND_VECTOR_INREG: 3186 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3187 APInt SrcUndef, SrcZero; 3188 SDValue Src = Op.getOperand(0); 3189 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3190 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts); 3191 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 3192 Depth + 1)) 3193 return true; 3194 KnownZero = SrcZero.zextOrTrunc(NumElts); 3195 KnownUndef = SrcUndef.zextOrTrunc(NumElts); 3196 3197 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG && 3198 Op.getValueSizeInBits() == Src.getValueSizeInBits() && 3199 DemandedSrcElts == 1) { 3200 // aext - if we just need the bottom element then we can bitcast. 3201 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 3202 } 3203 3204 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { 3205 // zext(undef) upper bits are guaranteed to be zero. 3206 if (DemandedElts.isSubsetOf(KnownUndef)) 3207 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3208 KnownUndef.clearAllBits(); 3209 3210 // zext - if we just need the bottom element then we can mask: 3211 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and. 3212 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND && 3213 Op->isOnlyUserOf(Src.getNode()) && 3214 Op.getValueSizeInBits() == Src.getValueSizeInBits()) { 3215 SDLoc DL(Op); 3216 EVT SrcVT = Src.getValueType(); 3217 EVT SrcSVT = SrcVT.getScalarType(); 3218 SmallVector<SDValue> MaskElts; 3219 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT)); 3220 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT)); 3221 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts); 3222 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic( 3223 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) { 3224 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold); 3225 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold)); 3226 } 3227 } 3228 } 3229 break; 3230 } 3231 3232 // TODO: There are more binop opcodes that could be handled here - MIN, 3233 // MAX, saturated math, etc. 3234 case ISD::ADD: { 3235 SDValue Op0 = Op.getOperand(0); 3236 SDValue Op1 = Op.getOperand(1); 3237 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) { 3238 APInt UndefLHS, ZeroLHS; 3239 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3240 Depth + 1, /*AssumeSingleUse*/ true)) 3241 return true; 3242 } 3243 LLVM_FALLTHROUGH; 3244 } 3245 case ISD::OR: 3246 case ISD::XOR: 3247 case ISD::SUB: 3248 case ISD::FADD: 3249 case ISD::FSUB: 3250 case ISD::FMUL: 3251 case ISD::FDIV: 3252 case ISD::FREM: { 3253 SDValue Op0 = Op.getOperand(0); 3254 SDValue Op1 = Op.getOperand(1); 3255 3256 APInt UndefRHS, ZeroRHS; 3257 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3258 Depth + 1)) 3259 return true; 3260 APInt UndefLHS, ZeroLHS; 3261 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3262 Depth + 1)) 3263 return true; 3264 3265 KnownZero = ZeroLHS & ZeroRHS; 3266 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS); 3267 3268 // Attempt to avoid multi-use ops if we don't need anything from them. 3269 // TODO - use KnownUndef to relax the demandedelts? 3270 if (!DemandedElts.isAllOnes()) 3271 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3272 return true; 3273 break; 3274 } 3275 case ISD::SHL: 3276 case ISD::SRL: 3277 case ISD::SRA: 3278 case ISD::ROTL: 3279 case ISD::ROTR: { 3280 SDValue Op0 = Op.getOperand(0); 3281 SDValue Op1 = Op.getOperand(1); 3282 3283 APInt UndefRHS, ZeroRHS; 3284 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 3285 Depth + 1)) 3286 return true; 3287 APInt UndefLHS, ZeroLHS; 3288 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 3289 Depth + 1)) 3290 return true; 3291 3292 KnownZero = ZeroLHS; 3293 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop? 3294 3295 // Attempt to avoid multi-use ops if we don't need anything from them. 3296 // TODO - use KnownUndef to relax the demandedelts? 3297 if (!DemandedElts.isAllOnes()) 3298 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3299 return true; 3300 break; 3301 } 3302 case ISD::MUL: 3303 case ISD::AND: { 3304 SDValue Op0 = Op.getOperand(0); 3305 SDValue Op1 = Op.getOperand(1); 3306 3307 APInt SrcUndef, SrcZero; 3308 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO, 3309 Depth + 1)) 3310 return true; 3311 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero, 3312 TLO, Depth + 1)) 3313 return true; 3314 3315 // If either side has a zero element, then the result element is zero, even 3316 // if the other is an UNDEF. 3317 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros 3318 // and then handle 'and' nodes with the rest of the binop opcodes. 3319 KnownZero |= SrcZero; 3320 KnownUndef &= SrcUndef; 3321 KnownUndef &= ~KnownZero; 3322 3323 // Attempt to avoid multi-use ops if we don't need anything from them. 3324 // TODO - use KnownUndef to relax the demandedelts? 3325 if (!DemandedElts.isAllOnes()) 3326 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 3327 return true; 3328 break; 3329 } 3330 case ISD::TRUNCATE: 3331 case ISD::SIGN_EXTEND: 3332 case ISD::ZERO_EXTEND: 3333 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 3334 KnownZero, TLO, Depth + 1)) 3335 return true; 3336 3337 if (Op.getOpcode() == ISD::ZERO_EXTEND) { 3338 // zext(undef) upper bits are guaranteed to be zero. 3339 if (DemandedElts.isSubsetOf(KnownUndef)) 3340 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 3341 KnownUndef.clearAllBits(); 3342 } 3343 break; 3344 default: { 3345 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 3346 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef, 3347 KnownZero, TLO, Depth)) 3348 return true; 3349 } else { 3350 KnownBits Known; 3351 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits); 3352 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known, 3353 TLO, Depth, AssumeSingleUse)) 3354 return true; 3355 } 3356 break; 3357 } 3358 } 3359 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero"); 3360 3361 // Constant fold all undef cases. 3362 // TODO: Handle zero cases as well. 3363 if (DemandedElts.isSubsetOf(KnownUndef)) 3364 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 3365 3366 return false; 3367 } 3368 3369 /// Determine which of the bits specified in Mask are known to be either zero or 3370 /// one and return them in the Known. 3371 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 3372 KnownBits &Known, 3373 const APInt &DemandedElts, 3374 const SelectionDAG &DAG, 3375 unsigned Depth) const { 3376 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3377 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3378 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3379 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3380 "Should use MaskedValueIsZero if you don't know whether Op" 3381 " is a target node!"); 3382 Known.resetAll(); 3383 } 3384 3385 void TargetLowering::computeKnownBitsForTargetInstr( 3386 GISelKnownBits &Analysis, Register R, KnownBits &Known, 3387 const APInt &DemandedElts, const MachineRegisterInfo &MRI, 3388 unsigned Depth) const { 3389 Known.resetAll(); 3390 } 3391 3392 void TargetLowering::computeKnownBitsForFrameIndex( 3393 const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const { 3394 // The low bits are known zero if the pointer is aligned. 3395 Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx))); 3396 } 3397 3398 Align TargetLowering::computeKnownAlignForTargetInstr( 3399 GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI, 3400 unsigned Depth) const { 3401 return Align(1); 3402 } 3403 3404 /// This method can be implemented by targets that want to expose additional 3405 /// information about sign bits to the DAG Combiner. 3406 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 3407 const APInt &, 3408 const SelectionDAG &, 3409 unsigned Depth) const { 3410 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3411 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3412 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3413 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3414 "Should use ComputeNumSignBits if you don't know whether Op" 3415 " is a target node!"); 3416 return 1; 3417 } 3418 3419 unsigned TargetLowering::computeNumSignBitsForTargetInstr( 3420 GISelKnownBits &Analysis, Register R, const APInt &DemandedElts, 3421 const MachineRegisterInfo &MRI, unsigned Depth) const { 3422 return 1; 3423 } 3424 3425 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode( 3426 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero, 3427 TargetLoweringOpt &TLO, unsigned Depth) const { 3428 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3429 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3430 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3431 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3432 "Should use SimplifyDemandedVectorElts if you don't know whether Op" 3433 " is a target node!"); 3434 return false; 3435 } 3436 3437 bool TargetLowering::SimplifyDemandedBitsForTargetNode( 3438 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3439 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const { 3440 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3441 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3442 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3443 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3444 "Should use SimplifyDemandedBits if you don't know whether Op" 3445 " is a target node!"); 3446 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth); 3447 return false; 3448 } 3449 3450 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode( 3451 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 3452 SelectionDAG &DAG, unsigned Depth) const { 3453 assert( 3454 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3455 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3456 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3457 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3458 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op" 3459 " is a target node!"); 3460 return SDValue(); 3461 } 3462 3463 SDValue 3464 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, 3465 SDValue N1, MutableArrayRef<int> Mask, 3466 SelectionDAG &DAG) const { 3467 bool LegalMask = isShuffleMaskLegal(Mask, VT); 3468 if (!LegalMask) { 3469 std::swap(N0, N1); 3470 ShuffleVectorSDNode::commuteMask(Mask); 3471 LegalMask = isShuffleMaskLegal(Mask, VT); 3472 } 3473 3474 if (!LegalMask) 3475 return SDValue(); 3476 3477 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask); 3478 } 3479 3480 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const { 3481 return nullptr; 3482 } 3483 3484 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode( 3485 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 3486 bool PoisonOnly, unsigned Depth) const { 3487 assert( 3488 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3489 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3490 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3491 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3492 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op" 3493 " is a target node!"); 3494 return false; 3495 } 3496 3497 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 3498 const SelectionDAG &DAG, 3499 bool SNaN, 3500 unsigned Depth) const { 3501 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3502 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3503 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3504 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3505 "Should use isKnownNeverNaN if you don't know whether Op" 3506 " is a target node!"); 3507 return false; 3508 } 3509 3510 bool TargetLowering::isSplatValueForTargetNode(SDValue Op, 3511 const APInt &DemandedElts, 3512 APInt &UndefElts, 3513 unsigned Depth) const { 3514 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3515 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3516 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3517 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3518 "Should use isSplatValue if you don't know whether Op" 3519 " is a target node!"); 3520 return false; 3521 } 3522 3523 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must 3524 // work with truncating build vectors and vectors with elements of less than 3525 // 8 bits. 3526 bool TargetLowering::isConstTrueVal(SDValue N) const { 3527 if (!N) 3528 return false; 3529 3530 unsigned EltWidth; 3531 APInt CVal; 3532 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false, 3533 /*AllowTruncation=*/true)) { 3534 CVal = CN->getAPIntValue(); 3535 EltWidth = N.getValueType().getScalarSizeInBits(); 3536 } else 3537 return false; 3538 3539 // If this is a truncating splat, truncate the splat value. 3540 // Otherwise, we may fail to match the expected values below. 3541 if (EltWidth < CVal.getBitWidth()) 3542 CVal = CVal.trunc(EltWidth); 3543 3544 switch (getBooleanContents(N.getValueType())) { 3545 case UndefinedBooleanContent: 3546 return CVal[0]; 3547 case ZeroOrOneBooleanContent: 3548 return CVal.isOne(); 3549 case ZeroOrNegativeOneBooleanContent: 3550 return CVal.isAllOnes(); 3551 } 3552 3553 llvm_unreachable("Invalid boolean contents"); 3554 } 3555 3556 bool TargetLowering::isConstFalseVal(SDValue N) const { 3557 if (!N) 3558 return false; 3559 3560 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 3561 if (!CN) { 3562 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 3563 if (!BV) 3564 return false; 3565 3566 // Only interested in constant splats, we don't care about undef 3567 // elements in identifying boolean constants and getConstantSplatNode 3568 // returns NULL if all ops are undef; 3569 CN = BV->getConstantSplatNode(); 3570 if (!CN) 3571 return false; 3572 } 3573 3574 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 3575 return !CN->getAPIntValue()[0]; 3576 3577 return CN->isZero(); 3578 } 3579 3580 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 3581 bool SExt) const { 3582 if (VT == MVT::i1) 3583 return N->isOne(); 3584 3585 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 3586 switch (Cnt) { 3587 case TargetLowering::ZeroOrOneBooleanContent: 3588 // An extended value of 1 is always true, unless its original type is i1, 3589 // in which case it will be sign extended to -1. 3590 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 3591 case TargetLowering::UndefinedBooleanContent: 3592 case TargetLowering::ZeroOrNegativeOneBooleanContent: 3593 return N->isAllOnes() && SExt; 3594 } 3595 llvm_unreachable("Unexpected enumeration."); 3596 } 3597 3598 /// This helper function of SimplifySetCC tries to optimize the comparison when 3599 /// either operand of the SetCC node is a bitwise-and instruction. 3600 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 3601 ISD::CondCode Cond, const SDLoc &DL, 3602 DAGCombinerInfo &DCI) const { 3603 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 3604 std::swap(N0, N1); 3605 3606 SelectionDAG &DAG = DCI.DAG; 3607 EVT OpVT = N0.getValueType(); 3608 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 3609 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 3610 return SDValue(); 3611 3612 // (X & Y) != 0 --> zextOrTrunc(X & Y) 3613 // iff everything but LSB is known zero: 3614 if (Cond == ISD::SETNE && isNullConstant(N1) && 3615 (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent || 3616 getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) { 3617 unsigned NumEltBits = OpVT.getScalarSizeInBits(); 3618 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1); 3619 if (DAG.MaskedValueIsZero(N0, UpperBits)) 3620 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT); 3621 } 3622 3623 // Match these patterns in any of their permutations: 3624 // (X & Y) == Y 3625 // (X & Y) != Y 3626 SDValue X, Y; 3627 if (N0.getOperand(0) == N1) { 3628 X = N0.getOperand(1); 3629 Y = N0.getOperand(0); 3630 } else if (N0.getOperand(1) == N1) { 3631 X = N0.getOperand(0); 3632 Y = N0.getOperand(1); 3633 } else { 3634 return SDValue(); 3635 } 3636 3637 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3638 if (DAG.isKnownToBeAPowerOfTwo(Y)) { 3639 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 3640 // Note that where Y is variable and is known to have at most one bit set 3641 // (for example, if it is Z & 1) we cannot do this; the expressions are not 3642 // equivalent when Y == 0. 3643 assert(OpVT.isInteger()); 3644 Cond = ISD::getSetCCInverse(Cond, OpVT); 3645 if (DCI.isBeforeLegalizeOps() || 3646 isCondCodeLegal(Cond, N0.getSimpleValueType())) 3647 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 3648 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 3649 // If the target supports an 'and-not' or 'and-complement' logic operation, 3650 // try to use that to make a comparison operation more efficient. 3651 // But don't do this transform if the mask is a single bit because there are 3652 // more efficient ways to deal with that case (for example, 'bt' on x86 or 3653 // 'rlwinm' on PPC). 3654 3655 // Bail out if the compare operand that we want to turn into a zero is 3656 // already a zero (otherwise, infinite loop). 3657 auto *YConst = dyn_cast<ConstantSDNode>(Y); 3658 if (YConst && YConst->isZero()) 3659 return SDValue(); 3660 3661 // Transform this into: ~X & Y == 0. 3662 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 3663 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 3664 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 3665 } 3666 3667 return SDValue(); 3668 } 3669 3670 /// There are multiple IR patterns that could be checking whether certain 3671 /// truncation of a signed number would be lossy or not. The pattern which is 3672 /// best at IR level, may not lower optimally. Thus, we want to unfold it. 3673 /// We are looking for the following pattern: (KeptBits is a constant) 3674 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits) 3675 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false. 3676 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0 3677 /// We will unfold it into the natural trunc+sext pattern: 3678 /// ((%x << C) a>> C) dstcond %x 3679 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x) 3680 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck( 3681 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI, 3682 const SDLoc &DL) const { 3683 // We must be comparing with a constant. 3684 ConstantSDNode *C1; 3685 if (!(C1 = dyn_cast<ConstantSDNode>(N1))) 3686 return SDValue(); 3687 3688 // N0 should be: add %x, (1 << (KeptBits-1)) 3689 if (N0->getOpcode() != ISD::ADD) 3690 return SDValue(); 3691 3692 // And we must be 'add'ing a constant. 3693 ConstantSDNode *C01; 3694 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1)))) 3695 return SDValue(); 3696 3697 SDValue X = N0->getOperand(0); 3698 EVT XVT = X.getValueType(); 3699 3700 // Validate constants ... 3701 3702 APInt I1 = C1->getAPIntValue(); 3703 3704 ISD::CondCode NewCond; 3705 if (Cond == ISD::CondCode::SETULT) { 3706 NewCond = ISD::CondCode::SETEQ; 3707 } else if (Cond == ISD::CondCode::SETULE) { 3708 NewCond = ISD::CondCode::SETEQ; 3709 // But need to 'canonicalize' the constant. 3710 I1 += 1; 3711 } else if (Cond == ISD::CondCode::SETUGT) { 3712 NewCond = ISD::CondCode::SETNE; 3713 // But need to 'canonicalize' the constant. 3714 I1 += 1; 3715 } else if (Cond == ISD::CondCode::SETUGE) { 3716 NewCond = ISD::CondCode::SETNE; 3717 } else 3718 return SDValue(); 3719 3720 APInt I01 = C01->getAPIntValue(); 3721 3722 auto checkConstants = [&I1, &I01]() -> bool { 3723 // Both of them must be power-of-two, and the constant from setcc is bigger. 3724 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2(); 3725 }; 3726 3727 if (checkConstants()) { 3728 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256 3729 } else { 3730 // What if we invert constants? (and the target predicate) 3731 I1.negate(); 3732 I01.negate(); 3733 assert(XVT.isInteger()); 3734 NewCond = getSetCCInverse(NewCond, XVT); 3735 if (!checkConstants()) 3736 return SDValue(); 3737 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256 3738 } 3739 3740 // They are power-of-two, so which bit is set? 3741 const unsigned KeptBits = I1.logBase2(); 3742 const unsigned KeptBitsMinusOne = I01.logBase2(); 3743 3744 // Magic! 3745 if (KeptBits != (KeptBitsMinusOne + 1)) 3746 return SDValue(); 3747 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable"); 3748 3749 // We don't want to do this in every single case. 3750 SelectionDAG &DAG = DCI.DAG; 3751 if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck( 3752 XVT, KeptBits)) 3753 return SDValue(); 3754 3755 const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits; 3756 assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable"); 3757 3758 // Unfold into: ((%x << C) a>> C) cond %x 3759 // Where 'cond' will be either 'eq' or 'ne'. 3760 SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT); 3761 SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt); 3762 SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt); 3763 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond); 3764 3765 return T2; 3766 } 3767 3768 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 3769 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift( 3770 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond, 3771 DAGCombinerInfo &DCI, const SDLoc &DL) const { 3772 assert(isConstOrConstSplat(N1C) && 3773 isConstOrConstSplat(N1C)->getAPIntValue().isZero() && 3774 "Should be a comparison with 0."); 3775 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3776 "Valid only for [in]equality comparisons."); 3777 3778 unsigned NewShiftOpcode; 3779 SDValue X, C, Y; 3780 3781 SelectionDAG &DAG = DCI.DAG; 3782 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3783 3784 // Look for '(C l>>/<< Y)'. 3785 auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) { 3786 // The shift should be one-use. 3787 if (!V.hasOneUse()) 3788 return false; 3789 unsigned OldShiftOpcode = V.getOpcode(); 3790 switch (OldShiftOpcode) { 3791 case ISD::SHL: 3792 NewShiftOpcode = ISD::SRL; 3793 break; 3794 case ISD::SRL: 3795 NewShiftOpcode = ISD::SHL; 3796 break; 3797 default: 3798 return false; // must be a logical shift. 3799 } 3800 // We should be shifting a constant. 3801 // FIXME: best to use isConstantOrConstantVector(). 3802 C = V.getOperand(0); 3803 ConstantSDNode *CC = 3804 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3805 if (!CC) 3806 return false; 3807 Y = V.getOperand(1); 3808 3809 ConstantSDNode *XC = 3810 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3811 return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 3812 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG); 3813 }; 3814 3815 // LHS of comparison should be an one-use 'and'. 3816 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 3817 return SDValue(); 3818 3819 X = N0.getOperand(0); 3820 SDValue Mask = N0.getOperand(1); 3821 3822 // 'and' is commutative! 3823 if (!Match(Mask)) { 3824 std::swap(X, Mask); 3825 if (!Match(Mask)) 3826 return SDValue(); 3827 } 3828 3829 EVT VT = X.getValueType(); 3830 3831 // Produce: 3832 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0 3833 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y); 3834 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C); 3835 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond); 3836 return T2; 3837 } 3838 3839 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as 3840 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to 3841 /// handle the commuted versions of these patterns. 3842 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, 3843 ISD::CondCode Cond, const SDLoc &DL, 3844 DAGCombinerInfo &DCI) const { 3845 unsigned BOpcode = N0.getOpcode(); 3846 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) && 3847 "Unexpected binop"); 3848 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode"); 3849 3850 // (X + Y) == X --> Y == 0 3851 // (X - Y) == X --> Y == 0 3852 // (X ^ Y) == X --> Y == 0 3853 SelectionDAG &DAG = DCI.DAG; 3854 EVT OpVT = N0.getValueType(); 3855 SDValue X = N0.getOperand(0); 3856 SDValue Y = N0.getOperand(1); 3857 if (X == N1) 3858 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond); 3859 3860 if (Y != N1) 3861 return SDValue(); 3862 3863 // (X + Y) == Y --> X == 0 3864 // (X ^ Y) == Y --> X == 0 3865 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR) 3866 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond); 3867 3868 // The shift would not be valid if the operands are boolean (i1). 3869 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1) 3870 return SDValue(); 3871 3872 // (X - Y) == Y --> X == Y << 1 3873 EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(), 3874 !DCI.isBeforeLegalize()); 3875 SDValue One = DAG.getConstant(1, DL, ShiftVT); 3876 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One); 3877 if (!DCI.isCalledByLegalizer()) 3878 DCI.AddToWorklist(YShl1.getNode()); 3879 return DAG.getSetCC(DL, VT, X, YShl1, Cond); 3880 } 3881 3882 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT, 3883 SDValue N0, const APInt &C1, 3884 ISD::CondCode Cond, const SDLoc &dl, 3885 SelectionDAG &DAG) { 3886 // Look through truncs that don't change the value of a ctpop. 3887 // FIXME: Add vector support? Need to be careful with setcc result type below. 3888 SDValue CTPOP = N0; 3889 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() && 3890 N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits())) 3891 CTPOP = N0.getOperand(0); 3892 3893 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse()) 3894 return SDValue(); 3895 3896 EVT CTVT = CTPOP.getValueType(); 3897 SDValue CTOp = CTPOP.getOperand(0); 3898 3899 // If this is a vector CTPOP, keep the CTPOP if it is legal. 3900 // TODO: Should we check if CTPOP is legal(or custom) for scalars? 3901 if (VT.isVector() && TLI.isOperationLegal(ISD::CTPOP, CTVT)) 3902 return SDValue(); 3903 3904 // (ctpop x) u< 2 -> (x & x-1) == 0 3905 // (ctpop x) u> 1 -> (x & x-1) != 0 3906 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) { 3907 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond); 3908 if (C1.ugt(CostLimit + (Cond == ISD::SETULT))) 3909 return SDValue(); 3910 if (C1 == 0 && (Cond == ISD::SETULT)) 3911 return SDValue(); // This is handled elsewhere. 3912 3913 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT); 3914 3915 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3916 SDValue Result = CTOp; 3917 for (unsigned i = 0; i < Passes; i++) { 3918 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne); 3919 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add); 3920 } 3921 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 3922 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC); 3923 } 3924 3925 // If ctpop is not supported, expand a power-of-2 comparison based on it. 3926 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) { 3927 // For scalars, keep CTPOP if it is legal or custom. 3928 if (!VT.isVector() && TLI.isOperationLegalOrCustom(ISD::CTPOP, CTVT)) 3929 return SDValue(); 3930 // This is based on X86's custom lowering for CTPOP which produces more 3931 // instructions than the expansion here. 3932 3933 // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0) 3934 // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0) 3935 SDValue Zero = DAG.getConstant(0, dl, CTVT); 3936 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3937 assert(CTVT.isInteger()); 3938 ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT); 3939 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne); 3940 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add); 3941 SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond); 3942 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond); 3943 unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR; 3944 return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS); 3945 } 3946 3947 return SDValue(); 3948 } 3949 3950 static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1, 3951 ISD::CondCode Cond, const SDLoc &dl, 3952 SelectionDAG &DAG) { 3953 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 3954 return SDValue(); 3955 3956 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 3957 if (!C1 || !(C1->isZero() || C1->isAllOnes())) 3958 return SDValue(); 3959 3960 auto getRotateSource = [](SDValue X) { 3961 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR) 3962 return X.getOperand(0); 3963 return SDValue(); 3964 }; 3965 3966 // Peek through a rotated value compared against 0 or -1: 3967 // (rot X, Y) == 0/-1 --> X == 0/-1 3968 // (rot X, Y) != 0/-1 --> X != 0/-1 3969 if (SDValue R = getRotateSource(N0)) 3970 return DAG.getSetCC(dl, VT, R, N1, Cond); 3971 3972 // Peek through an 'or' of a rotated value compared against 0: 3973 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0 3974 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0 3975 // 3976 // TODO: Add the 'and' with -1 sibling. 3977 // TODO: Recurse through a series of 'or' ops to find the rotate. 3978 EVT OpVT = N0.getValueType(); 3979 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) { 3980 if (SDValue R = getRotateSource(N0.getOperand(0))) { 3981 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1)); 3982 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 3983 } 3984 if (SDValue R = getRotateSource(N0.getOperand(1))) { 3985 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0)); 3986 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 3987 } 3988 } 3989 3990 return SDValue(); 3991 } 3992 3993 static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1, 3994 ISD::CondCode Cond, const SDLoc &dl, 3995 SelectionDAG &DAG) { 3996 // If we are testing for all-bits-clear, we might be able to do that with 3997 // less shifting since bit-order does not matter. 3998 if (Cond != ISD::SETEQ && Cond != ISD::SETNE) 3999 return SDValue(); 4000 4001 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true); 4002 if (!C1 || !C1->isZero()) 4003 return SDValue(); 4004 4005 if (!N0.hasOneUse() || 4006 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR)) 4007 return SDValue(); 4008 4009 unsigned BitWidth = N0.getScalarValueSizeInBits(); 4010 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2)); 4011 if (!ShAmtC || ShAmtC->getAPIntValue().uge(BitWidth)) 4012 return SDValue(); 4013 4014 // Canonicalize fshr as fshl to reduce pattern-matching. 4015 unsigned ShAmt = ShAmtC->getZExtValue(); 4016 if (N0.getOpcode() == ISD::FSHR) 4017 ShAmt = BitWidth - ShAmt; 4018 4019 // Match an 'or' with a specific operand 'Other' in either commuted variant. 4020 SDValue X, Y; 4021 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) { 4022 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse()) 4023 return false; 4024 if (Or.getOperand(0) == Other) { 4025 X = Or.getOperand(0); 4026 Y = Or.getOperand(1); 4027 return true; 4028 } 4029 if (Or.getOperand(1) == Other) { 4030 X = Or.getOperand(1); 4031 Y = Or.getOperand(0); 4032 return true; 4033 } 4034 return false; 4035 }; 4036 4037 EVT OpVT = N0.getValueType(); 4038 EVT ShAmtVT = N0.getOperand(2).getValueType(); 4039 SDValue F0 = N0.getOperand(0); 4040 SDValue F1 = N0.getOperand(1); 4041 if (matchOr(F0, F1)) { 4042 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0 4043 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT); 4044 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt); 4045 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 4046 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4047 } 4048 if (matchOr(F1, F0)) { 4049 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0 4050 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT); 4051 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt); 4052 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X); 4053 return DAG.getSetCC(dl, VT, NewOr, N1, Cond); 4054 } 4055 4056 return SDValue(); 4057 } 4058 4059 /// Try to simplify a setcc built with the specified operands and cc. If it is 4060 /// unable to simplify it, return a null SDValue. 4061 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 4062 ISD::CondCode Cond, bool foldBooleans, 4063 DAGCombinerInfo &DCI, 4064 const SDLoc &dl) const { 4065 SelectionDAG &DAG = DCI.DAG; 4066 const DataLayout &Layout = DAG.getDataLayout(); 4067 EVT OpVT = N0.getValueType(); 4068 4069 // Constant fold or commute setcc. 4070 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl)) 4071 return Fold; 4072 4073 bool N0ConstOrSplat = 4074 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 4075 bool N1ConstOrSplat = 4076 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true); 4077 4078 // Ensure that the constant occurs on the RHS and fold constant comparisons. 4079 // TODO: Handle non-splat vector constants. All undef causes trouble. 4080 // FIXME: We can't yet fold constant scalable vector splats, so avoid an 4081 // infinite loop here when we encounter one. 4082 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 4083 if (N0ConstOrSplat && (!OpVT.isScalableVector() || !N1ConstOrSplat) && 4084 (DCI.isBeforeLegalizeOps() || 4085 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 4086 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4087 4088 // If we have a subtract with the same 2 non-constant operands as this setcc 4089 // -- but in reverse order -- then try to commute the operands of this setcc 4090 // to match. A matching pair of setcc (cmp) and sub may be combined into 1 4091 // instruction on some targets. 4092 if (!N0ConstOrSplat && !N1ConstOrSplat && 4093 (DCI.isBeforeLegalizeOps() || 4094 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) && 4095 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) && 4096 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1})) 4097 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 4098 4099 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG)) 4100 return V; 4101 4102 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG)) 4103 return V; 4104 4105 if (auto *N1C = isConstOrConstSplat(N1)) { 4106 const APInt &C1 = N1C->getAPIntValue(); 4107 4108 // Optimize some CTPOP cases. 4109 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG)) 4110 return V; 4111 4112 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 4113 // equality comparison, then we're just comparing whether X itself is 4114 // zero. 4115 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) && 4116 N0.getOperand(0).getOpcode() == ISD::CTLZ && 4117 isPowerOf2_32(N0.getScalarValueSizeInBits())) { 4118 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) { 4119 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4120 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) { 4121 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 4122 // (srl (ctlz x), 5) == 0 -> X != 0 4123 // (srl (ctlz x), 5) != 1 -> X != 0 4124 Cond = ISD::SETNE; 4125 } else { 4126 // (srl (ctlz x), 5) != 0 -> X == 0 4127 // (srl (ctlz x), 5) == 1 -> X == 0 4128 Cond = ISD::SETEQ; 4129 } 4130 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 4131 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero, 4132 Cond); 4133 } 4134 } 4135 } 4136 } 4137 4138 // FIXME: Support vectors. 4139 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4140 const APInt &C1 = N1C->getAPIntValue(); 4141 4142 // (zext x) == C --> x == (trunc C) 4143 // (sext x) == C --> x == (trunc C) 4144 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4145 DCI.isBeforeLegalize() && N0->hasOneUse()) { 4146 unsigned MinBits = N0.getValueSizeInBits(); 4147 SDValue PreExt; 4148 bool Signed = false; 4149 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 4150 // ZExt 4151 MinBits = N0->getOperand(0).getValueSizeInBits(); 4152 PreExt = N0->getOperand(0); 4153 } else if (N0->getOpcode() == ISD::AND) { 4154 // DAGCombine turns costly ZExts into ANDs 4155 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 4156 if ((C->getAPIntValue()+1).isPowerOf2()) { 4157 MinBits = C->getAPIntValue().countTrailingOnes(); 4158 PreExt = N0->getOperand(0); 4159 } 4160 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 4161 // SExt 4162 MinBits = N0->getOperand(0).getValueSizeInBits(); 4163 PreExt = N0->getOperand(0); 4164 Signed = true; 4165 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 4166 // ZEXTLOAD / SEXTLOAD 4167 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 4168 MinBits = LN0->getMemoryVT().getSizeInBits(); 4169 PreExt = N0; 4170 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 4171 Signed = true; 4172 MinBits = LN0->getMemoryVT().getSizeInBits(); 4173 PreExt = N0; 4174 } 4175 } 4176 4177 // Figure out how many bits we need to preserve this constant. 4178 unsigned ReqdBits = Signed ? C1.getMinSignedBits() : C1.getActiveBits(); 4179 4180 // Make sure we're not losing bits from the constant. 4181 if (MinBits > 0 && 4182 MinBits < C1.getBitWidth() && 4183 MinBits >= ReqdBits) { 4184 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 4185 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 4186 // Will get folded away. 4187 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 4188 if (MinBits == 1 && C1 == 1) 4189 // Invert the condition. 4190 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 4191 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4192 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 4193 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 4194 } 4195 4196 // If truncating the setcc operands is not desirable, we can still 4197 // simplify the expression in some cases: 4198 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 4199 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 4200 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 4201 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 4202 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 4203 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 4204 SDValue TopSetCC = N0->getOperand(0); 4205 unsigned N0Opc = N0->getOpcode(); 4206 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 4207 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 4208 TopSetCC.getOpcode() == ISD::SETCC && 4209 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 4210 (isConstFalseVal(N1) || 4211 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 4212 4213 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) || 4214 (!N1C->isZero() && Cond == ISD::SETNE); 4215 4216 if (!Inverse) 4217 return TopSetCC; 4218 4219 ISD::CondCode InvCond = ISD::getSetCCInverse( 4220 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 4221 TopSetCC.getOperand(0).getValueType()); 4222 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 4223 TopSetCC.getOperand(1), 4224 InvCond); 4225 } 4226 } 4227 } 4228 4229 // If the LHS is '(and load, const)', the RHS is 0, the test is for 4230 // equality or unsigned, and all 1 bits of the const are in the same 4231 // partial word, see if we can shorten the load. 4232 if (DCI.isBeforeLegalize() && 4233 !ISD::isSignedIntSetCC(Cond) && 4234 N0.getOpcode() == ISD::AND && C1 == 0 && 4235 N0.getNode()->hasOneUse() && 4236 isa<LoadSDNode>(N0.getOperand(0)) && 4237 N0.getOperand(0).getNode()->hasOneUse() && 4238 isa<ConstantSDNode>(N0.getOperand(1))) { 4239 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 4240 APInt bestMask; 4241 unsigned bestWidth = 0, bestOffset = 0; 4242 if (Lod->isSimple() && Lod->isUnindexed()) { 4243 unsigned origWidth = N0.getValueSizeInBits(); 4244 unsigned maskWidth = origWidth; 4245 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 4246 // 8 bits, but have to be careful... 4247 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 4248 origWidth = Lod->getMemoryVT().getSizeInBits(); 4249 const APInt &Mask = N0.getConstantOperandAPInt(1); 4250 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 4251 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 4252 for (unsigned offset=0; offset<origWidth/width; offset++) { 4253 if (Mask.isSubsetOf(newMask)) { 4254 if (Layout.isLittleEndian()) 4255 bestOffset = (uint64_t)offset * (width/8); 4256 else 4257 bestOffset = (origWidth/width - offset - 1) * (width/8); 4258 bestMask = Mask.lshr(offset * (width/8) * 8); 4259 bestWidth = width; 4260 break; 4261 } 4262 newMask <<= width; 4263 } 4264 } 4265 } 4266 if (bestWidth) { 4267 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 4268 if (newVT.isRound() && 4269 shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) { 4270 SDValue Ptr = Lod->getBasePtr(); 4271 if (bestOffset != 0) 4272 Ptr = 4273 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(bestOffset), dl); 4274 SDValue NewLoad = 4275 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr, 4276 Lod->getPointerInfo().getWithOffset(bestOffset), 4277 Lod->getOriginalAlign()); 4278 return DAG.getSetCC(dl, VT, 4279 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 4280 DAG.getConstant(bestMask.trunc(bestWidth), 4281 dl, newVT)), 4282 DAG.getConstant(0LL, dl, newVT), Cond); 4283 } 4284 } 4285 } 4286 4287 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 4288 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 4289 unsigned InSize = N0.getOperand(0).getValueSizeInBits(); 4290 4291 // If the comparison constant has bits in the upper part, the 4292 // zero-extended value could never match. 4293 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 4294 C1.getBitWidth() - InSize))) { 4295 switch (Cond) { 4296 case ISD::SETUGT: 4297 case ISD::SETUGE: 4298 case ISD::SETEQ: 4299 return DAG.getConstant(0, dl, VT); 4300 case ISD::SETULT: 4301 case ISD::SETULE: 4302 case ISD::SETNE: 4303 return DAG.getConstant(1, dl, VT); 4304 case ISD::SETGT: 4305 case ISD::SETGE: 4306 // True if the sign bit of C1 is set. 4307 return DAG.getConstant(C1.isNegative(), dl, VT); 4308 case ISD::SETLT: 4309 case ISD::SETLE: 4310 // True if the sign bit of C1 isn't set. 4311 return DAG.getConstant(C1.isNonNegative(), dl, VT); 4312 default: 4313 break; 4314 } 4315 } 4316 4317 // Otherwise, we can perform the comparison with the low bits. 4318 switch (Cond) { 4319 case ISD::SETEQ: 4320 case ISD::SETNE: 4321 case ISD::SETUGT: 4322 case ISD::SETUGE: 4323 case ISD::SETULT: 4324 case ISD::SETULE: { 4325 EVT newVT = N0.getOperand(0).getValueType(); 4326 if (DCI.isBeforeLegalizeOps() || 4327 (isOperationLegal(ISD::SETCC, newVT) && 4328 isCondCodeLegal(Cond, newVT.getSimpleVT()))) { 4329 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT); 4330 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 4331 4332 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 4333 NewConst, Cond); 4334 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 4335 } 4336 break; 4337 } 4338 default: 4339 break; // todo, be more careful with signed comparisons 4340 } 4341 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 4342 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4343 !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(), 4344 OpVT)) { 4345 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 4346 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 4347 EVT ExtDstTy = N0.getValueType(); 4348 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 4349 4350 // If the constant doesn't fit into the number of bits for the source of 4351 // the sign extension, it is impossible for both sides to be equal. 4352 if (C1.getMinSignedBits() > ExtSrcTyBits) 4353 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT); 4354 4355 assert(ExtDstTy == N0.getOperand(0).getValueType() && 4356 ExtDstTy != ExtSrcTy && "Unexpected types!"); 4357 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 4358 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0), 4359 DAG.getConstant(Imm, dl, ExtDstTy)); 4360 if (!DCI.isCalledByLegalizer()) 4361 DCI.AddToWorklist(ZextOp.getNode()); 4362 // Otherwise, make this a use of a zext. 4363 return DAG.getSetCC(dl, VT, ZextOp, 4364 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond); 4365 } else if ((N1C->isZero() || N1C->isOne()) && 4366 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4367 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 4368 if (N0.getOpcode() == ISD::SETCC && 4369 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) && 4370 (N0.getValueType() == MVT::i1 || 4371 getBooleanContents(N0.getOperand(0).getValueType()) == 4372 ZeroOrOneBooleanContent)) { 4373 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne()); 4374 if (TrueWhenTrue) 4375 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 4376 // Invert the condition. 4377 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4378 CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType()); 4379 if (DCI.isBeforeLegalizeOps() || 4380 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 4381 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 4382 } 4383 4384 if ((N0.getOpcode() == ISD::XOR || 4385 (N0.getOpcode() == ISD::AND && 4386 N0.getOperand(0).getOpcode() == ISD::XOR && 4387 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 4388 isOneConstant(N0.getOperand(1))) { 4389 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 4390 // can only do this if the top bits are known zero. 4391 unsigned BitWidth = N0.getValueSizeInBits(); 4392 if (DAG.MaskedValueIsZero(N0, 4393 APInt::getHighBitsSet(BitWidth, 4394 BitWidth-1))) { 4395 // Okay, get the un-inverted input value. 4396 SDValue Val; 4397 if (N0.getOpcode() == ISD::XOR) { 4398 Val = N0.getOperand(0); 4399 } else { 4400 assert(N0.getOpcode() == ISD::AND && 4401 N0.getOperand(0).getOpcode() == ISD::XOR); 4402 // ((X^1)&1)^1 -> X & 1 4403 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 4404 N0.getOperand(0).getOperand(0), 4405 N0.getOperand(1)); 4406 } 4407 4408 return DAG.getSetCC(dl, VT, Val, N1, 4409 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4410 } 4411 } else if (N1C->isOne()) { 4412 SDValue Op0 = N0; 4413 if (Op0.getOpcode() == ISD::TRUNCATE) 4414 Op0 = Op0.getOperand(0); 4415 4416 if ((Op0.getOpcode() == ISD::XOR) && 4417 Op0.getOperand(0).getOpcode() == ISD::SETCC && 4418 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 4419 SDValue XorLHS = Op0.getOperand(0); 4420 SDValue XorRHS = Op0.getOperand(1); 4421 // Ensure that the input setccs return an i1 type or 0/1 value. 4422 if (Op0.getValueType() == MVT::i1 || 4423 (getBooleanContents(XorLHS.getOperand(0).getValueType()) == 4424 ZeroOrOneBooleanContent && 4425 getBooleanContents(XorRHS.getOperand(0).getValueType()) == 4426 ZeroOrOneBooleanContent)) { 4427 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 4428 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 4429 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond); 4430 } 4431 } 4432 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) { 4433 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 4434 if (Op0.getValueType().bitsGT(VT)) 4435 Op0 = DAG.getNode(ISD::AND, dl, VT, 4436 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 4437 DAG.getConstant(1, dl, VT)); 4438 else if (Op0.getValueType().bitsLT(VT)) 4439 Op0 = DAG.getNode(ISD::AND, dl, VT, 4440 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 4441 DAG.getConstant(1, dl, VT)); 4442 4443 return DAG.getSetCC(dl, VT, Op0, 4444 DAG.getConstant(0, dl, Op0.getValueType()), 4445 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4446 } 4447 if (Op0.getOpcode() == ISD::AssertZext && 4448 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 4449 return DAG.getSetCC(dl, VT, Op0, 4450 DAG.getConstant(0, dl, Op0.getValueType()), 4451 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 4452 } 4453 } 4454 4455 // Given: 4456 // icmp eq/ne (urem %x, %y), 0 4457 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem': 4458 // icmp eq/ne %x, 0 4459 if (N0.getOpcode() == ISD::UREM && N1C->isZero() && 4460 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4461 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0)); 4462 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1)); 4463 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2) 4464 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 4465 } 4466 4467 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0 4468 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0 4469 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4470 N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) && 4471 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 && 4472 N1C && N1C->isAllOnes()) { 4473 return DAG.getSetCC(dl, VT, N0.getOperand(0), 4474 DAG.getConstant(0, dl, OpVT), 4475 Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE); 4476 } 4477 4478 if (SDValue V = 4479 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl)) 4480 return V; 4481 } 4482 4483 // These simplifications apply to splat vectors as well. 4484 // TODO: Handle more splat vector cases. 4485 if (auto *N1C = isConstOrConstSplat(N1)) { 4486 const APInt &C1 = N1C->getAPIntValue(); 4487 4488 APInt MinVal, MaxVal; 4489 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits(); 4490 if (ISD::isSignedIntSetCC(Cond)) { 4491 MinVal = APInt::getSignedMinValue(OperandBitSize); 4492 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 4493 } else { 4494 MinVal = APInt::getMinValue(OperandBitSize); 4495 MaxVal = APInt::getMaxValue(OperandBitSize); 4496 } 4497 4498 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 4499 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 4500 // X >= MIN --> true 4501 if (C1 == MinVal) 4502 return DAG.getBoolConstant(true, dl, VT, OpVT); 4503 4504 if (!VT.isVector()) { // TODO: Support this for vectors. 4505 // X >= C0 --> X > (C0 - 1) 4506 APInt C = C1 - 1; 4507 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 4508 if ((DCI.isBeforeLegalizeOps() || 4509 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4510 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4511 isLegalICmpImmediate(C.getSExtValue())))) { 4512 return DAG.getSetCC(dl, VT, N0, 4513 DAG.getConstant(C, dl, N1.getValueType()), 4514 NewCC); 4515 } 4516 } 4517 } 4518 4519 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 4520 // X <= MAX --> true 4521 if (C1 == MaxVal) 4522 return DAG.getBoolConstant(true, dl, VT, OpVT); 4523 4524 // X <= C0 --> X < (C0 + 1) 4525 if (!VT.isVector()) { // TODO: Support this for vectors. 4526 APInt C = C1 + 1; 4527 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 4528 if ((DCI.isBeforeLegalizeOps() || 4529 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 4530 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 4531 isLegalICmpImmediate(C.getSExtValue())))) { 4532 return DAG.getSetCC(dl, VT, N0, 4533 DAG.getConstant(C, dl, N1.getValueType()), 4534 NewCC); 4535 } 4536 } 4537 } 4538 4539 if (Cond == ISD::SETLT || Cond == ISD::SETULT) { 4540 if (C1 == MinVal) 4541 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false 4542 4543 // TODO: Support this for vectors after legalize ops. 4544 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4545 // Canonicalize setlt X, Max --> setne X, Max 4546 if (C1 == MaxVal) 4547 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 4548 4549 // If we have setult X, 1, turn it into seteq X, 0 4550 if (C1 == MinVal+1) 4551 return DAG.getSetCC(dl, VT, N0, 4552 DAG.getConstant(MinVal, dl, N0.getValueType()), 4553 ISD::SETEQ); 4554 } 4555 } 4556 4557 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) { 4558 if (C1 == MaxVal) 4559 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false 4560 4561 // TODO: Support this for vectors after legalize ops. 4562 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4563 // Canonicalize setgt X, Min --> setne X, Min 4564 if (C1 == MinVal) 4565 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 4566 4567 // If we have setugt X, Max-1, turn it into seteq X, Max 4568 if (C1 == MaxVal-1) 4569 return DAG.getSetCC(dl, VT, N0, 4570 DAG.getConstant(MaxVal, dl, N0.getValueType()), 4571 ISD::SETEQ); 4572 } 4573 } 4574 4575 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) { 4576 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 4577 if (C1.isZero()) 4578 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift( 4579 VT, N0, N1, Cond, DCI, dl)) 4580 return CC; 4581 4582 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y). 4583 // For example, when high 32-bits of i64 X are known clear: 4584 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0 4585 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1 4586 bool CmpZero = N1C->getAPIntValue().isZero(); 4587 bool CmpNegOne = N1C->getAPIntValue().isAllOnes(); 4588 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) { 4589 // Match or(lo,shl(hi,bw/2)) pattern. 4590 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) { 4591 unsigned EltBits = V.getScalarValueSizeInBits(); 4592 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0) 4593 return false; 4594 SDValue LHS = V.getOperand(0); 4595 SDValue RHS = V.getOperand(1); 4596 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2); 4597 // Unshifted element must have zero upperbits. 4598 if (RHS.getOpcode() == ISD::SHL && 4599 isa<ConstantSDNode>(RHS.getOperand(1)) && 4600 RHS.getConstantOperandAPInt(1) == (EltBits / 2) && 4601 DAG.MaskedValueIsZero(LHS, HiBits)) { 4602 Lo = LHS; 4603 Hi = RHS.getOperand(0); 4604 return true; 4605 } 4606 if (LHS.getOpcode() == ISD::SHL && 4607 isa<ConstantSDNode>(LHS.getOperand(1)) && 4608 LHS.getConstantOperandAPInt(1) == (EltBits / 2) && 4609 DAG.MaskedValueIsZero(RHS, HiBits)) { 4610 Lo = RHS; 4611 Hi = LHS.getOperand(0); 4612 return true; 4613 } 4614 return false; 4615 }; 4616 4617 auto MergeConcat = [&](SDValue Lo, SDValue Hi) { 4618 unsigned EltBits = N0.getScalarValueSizeInBits(); 4619 unsigned HalfBits = EltBits / 2; 4620 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits); 4621 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT); 4622 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits); 4623 SDValue NewN0 = 4624 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask); 4625 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits; 4626 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond); 4627 }; 4628 4629 SDValue Lo, Hi; 4630 if (IsConcat(N0, Lo, Hi)) 4631 return MergeConcat(Lo, Hi); 4632 4633 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) { 4634 SDValue Lo0, Lo1, Hi0, Hi1; 4635 if (IsConcat(N0.getOperand(0), Lo0, Hi0) && 4636 IsConcat(N0.getOperand(1), Lo1, Hi1)) { 4637 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1), 4638 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1)); 4639 } 4640 } 4641 } 4642 } 4643 4644 // If we have "setcc X, C0", check to see if we can shrink the immediate 4645 // by changing cc. 4646 // TODO: Support this for vectors after legalize ops. 4647 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4648 // SETUGT X, SINTMAX -> SETLT X, 0 4649 // SETUGE X, SINTMIN -> SETLT X, 0 4650 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) || 4651 (Cond == ISD::SETUGE && C1.isMinSignedValue())) 4652 return DAG.getSetCC(dl, VT, N0, 4653 DAG.getConstant(0, dl, N1.getValueType()), 4654 ISD::SETLT); 4655 4656 // SETULT X, SINTMIN -> SETGT X, -1 4657 // SETULE X, SINTMAX -> SETGT X, -1 4658 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) || 4659 (Cond == ISD::SETULE && C1.isMaxSignedValue())) 4660 return DAG.getSetCC(dl, VT, N0, 4661 DAG.getAllOnesConstant(dl, N1.getValueType()), 4662 ISD::SETGT); 4663 } 4664 } 4665 4666 // Back to non-vector simplifications. 4667 // TODO: Can we do these for vector splats? 4668 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4669 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4670 const APInt &C1 = N1C->getAPIntValue(); 4671 EVT ShValTy = N0.getValueType(); 4672 4673 // Fold bit comparisons when we can. This will result in an 4674 // incorrect value when boolean false is negative one, unless 4675 // the bitsize is 1 in which case the false value is the same 4676 // in practice regardless of the representation. 4677 if ((VT.getSizeInBits() == 1 || 4678 getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) && 4679 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4680 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) && 4681 N0.getOpcode() == ISD::AND) { 4682 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4683 EVT ShiftTy = 4684 getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4685 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 4686 // Perform the xform if the AND RHS is a single bit. 4687 unsigned ShCt = AndRHS->getAPIntValue().logBase2(); 4688 if (AndRHS->getAPIntValue().isPowerOf2() && 4689 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4690 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4691 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4692 DAG.getConstant(ShCt, dl, ShiftTy))); 4693 } 4694 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 4695 // (X & 8) == 8 --> (X & 8) >> 3 4696 // Perform the xform if C1 is a single bit. 4697 unsigned ShCt = C1.logBase2(); 4698 if (C1.isPowerOf2() && 4699 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4700 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4701 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4702 DAG.getConstant(ShCt, dl, ShiftTy))); 4703 } 4704 } 4705 } 4706 } 4707 4708 if (C1.getMinSignedBits() <= 64 && 4709 !isLegalICmpImmediate(C1.getSExtValue())) { 4710 EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4711 // (X & -256) == 256 -> (X >> 8) == 1 4712 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4713 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 4714 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4715 const APInt &AndRHSC = AndRHS->getAPIntValue(); 4716 if (AndRHSC.isNegatedPowerOf2() && (AndRHSC & C1) == C1) { 4717 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 4718 if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4719 SDValue Shift = 4720 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0), 4721 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4722 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy); 4723 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 4724 } 4725 } 4726 } 4727 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 4728 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 4729 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 4730 // X < 0x100000000 -> (X >> 32) < 1 4731 // X >= 0x100000000 -> (X >> 32) >= 1 4732 // X <= 0x0ffffffff -> (X >> 32) < 1 4733 // X > 0x0ffffffff -> (X >> 32) >= 1 4734 unsigned ShiftBits; 4735 APInt NewC = C1; 4736 ISD::CondCode NewCond = Cond; 4737 if (AdjOne) { 4738 ShiftBits = C1.countTrailingOnes(); 4739 NewC = NewC + 1; 4740 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4741 } else { 4742 ShiftBits = C1.countTrailingZeros(); 4743 } 4744 NewC.lshrInPlace(ShiftBits); 4745 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 4746 isLegalICmpImmediate(NewC.getSExtValue()) && 4747 !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4748 SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4749 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4750 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy); 4751 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 4752 } 4753 } 4754 } 4755 } 4756 4757 if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) { 4758 auto *CFP = cast<ConstantFPSDNode>(N1); 4759 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value"); 4760 4761 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 4762 // constant if knowing that the operand is non-nan is enough. We prefer to 4763 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 4764 // materialize 0.0. 4765 if (Cond == ISD::SETO || Cond == ISD::SETUO) 4766 return DAG.getSetCC(dl, VT, N0, N0, Cond); 4767 4768 // setcc (fneg x), C -> setcc swap(pred) x, -C 4769 if (N0.getOpcode() == ISD::FNEG) { 4770 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 4771 if (DCI.isBeforeLegalizeOps() || 4772 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 4773 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 4774 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 4775 } 4776 } 4777 4778 // If the condition is not legal, see if we can find an equivalent one 4779 // which is legal. 4780 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 4781 // If the comparison was an awkward floating-point == or != and one of 4782 // the comparison operands is infinity or negative infinity, convert the 4783 // condition to a less-awkward <= or >=. 4784 if (CFP->getValueAPF().isInfinity()) { 4785 bool IsNegInf = CFP->getValueAPF().isNegative(); 4786 ISD::CondCode NewCond = ISD::SETCC_INVALID; 4787 switch (Cond) { 4788 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break; 4789 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break; 4790 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break; 4791 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break; 4792 default: break; 4793 } 4794 if (NewCond != ISD::SETCC_INVALID && 4795 isCondCodeLegal(NewCond, N0.getSimpleValueType())) 4796 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4797 } 4798 } 4799 } 4800 4801 if (N0 == N1) { 4802 // The sext(setcc()) => setcc() optimization relies on the appropriate 4803 // constant being emitted. 4804 assert(!N0.getValueType().isInteger() && 4805 "Integer types should be handled by FoldSetCC"); 4806 4807 bool EqTrue = ISD::isTrueWhenEqual(Cond); 4808 unsigned UOF = ISD::getUnorderedFlavor(Cond); 4809 if (UOF == 2) // FP operators that are undefined on NaNs. 4810 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4811 if (UOF == unsigned(EqTrue)) 4812 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4813 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 4814 // if it is not already. 4815 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 4816 if (NewCond != Cond && 4817 (DCI.isBeforeLegalizeOps() || 4818 isCondCodeLegal(NewCond, N0.getSimpleValueType()))) 4819 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4820 } 4821 4822 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4823 N0.getValueType().isInteger()) { 4824 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 4825 N0.getOpcode() == ISD::XOR) { 4826 // Simplify (X+Y) == (X+Z) --> Y == Z 4827 if (N0.getOpcode() == N1.getOpcode()) { 4828 if (N0.getOperand(0) == N1.getOperand(0)) 4829 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 4830 if (N0.getOperand(1) == N1.getOperand(1)) 4831 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 4832 if (isCommutativeBinOp(N0.getOpcode())) { 4833 // If X op Y == Y op X, try other combinations. 4834 if (N0.getOperand(0) == N1.getOperand(1)) 4835 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 4836 Cond); 4837 if (N0.getOperand(1) == N1.getOperand(0)) 4838 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 4839 Cond); 4840 } 4841 } 4842 4843 // If RHS is a legal immediate value for a compare instruction, we need 4844 // to be careful about increasing register pressure needlessly. 4845 bool LegalRHSImm = false; 4846 4847 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 4848 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4849 // Turn (X+C1) == C2 --> X == C2-C1 4850 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) 4851 return DAG.getSetCC( 4852 dl, VT, N0.getOperand(0), 4853 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(), 4854 dl, N0.getValueType()), 4855 Cond); 4856 4857 // Turn (X^C1) == C2 --> X == C1^C2 4858 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse()) 4859 return DAG.getSetCC( 4860 dl, VT, N0.getOperand(0), 4861 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(), 4862 dl, N0.getValueType()), 4863 Cond); 4864 } 4865 4866 // Turn (C1-X) == C2 --> X == C1-C2 4867 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 4868 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) 4869 return DAG.getSetCC( 4870 dl, VT, N0.getOperand(1), 4871 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(), 4872 dl, N0.getValueType()), 4873 Cond); 4874 4875 // Could RHSC fold directly into a compare? 4876 if (RHSC->getValueType(0).getSizeInBits() <= 64) 4877 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 4878 } 4879 4880 // (X+Y) == X --> Y == 0 and similar folds. 4881 // Don't do this if X is an immediate that can fold into a cmp 4882 // instruction and X+Y has other uses. It could be an induction variable 4883 // chain, and the transform would increase register pressure. 4884 if (!LegalRHSImm || N0.hasOneUse()) 4885 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI)) 4886 return V; 4887 } 4888 4889 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 4890 N1.getOpcode() == ISD::XOR) 4891 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI)) 4892 return V; 4893 4894 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI)) 4895 return V; 4896 } 4897 4898 // Fold remainder of division by a constant. 4899 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) && 4900 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4901 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4902 4903 // When division is cheap or optimizing for minimum size, 4904 // fall through to DIVREM creation by skipping this fold. 4905 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) { 4906 if (N0.getOpcode() == ISD::UREM) { 4907 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4908 return Folded; 4909 } else if (N0.getOpcode() == ISD::SREM) { 4910 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4911 return Folded; 4912 } 4913 } 4914 } 4915 4916 // Fold away ALL boolean setcc's. 4917 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) { 4918 SDValue Temp; 4919 switch (Cond) { 4920 default: llvm_unreachable("Unknown integer setcc!"); 4921 case ISD::SETEQ: // X == Y -> ~(X^Y) 4922 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4923 N0 = DAG.getNOT(dl, Temp, OpVT); 4924 if (!DCI.isCalledByLegalizer()) 4925 DCI.AddToWorklist(Temp.getNode()); 4926 break; 4927 case ISD::SETNE: // X != Y --> (X^Y) 4928 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4929 break; 4930 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 4931 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 4932 Temp = DAG.getNOT(dl, N0, OpVT); 4933 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp); 4934 if (!DCI.isCalledByLegalizer()) 4935 DCI.AddToWorklist(Temp.getNode()); 4936 break; 4937 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 4938 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 4939 Temp = DAG.getNOT(dl, N1, OpVT); 4940 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp); 4941 if (!DCI.isCalledByLegalizer()) 4942 DCI.AddToWorklist(Temp.getNode()); 4943 break; 4944 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 4945 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 4946 Temp = DAG.getNOT(dl, N0, OpVT); 4947 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp); 4948 if (!DCI.isCalledByLegalizer()) 4949 DCI.AddToWorklist(Temp.getNode()); 4950 break; 4951 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 4952 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 4953 Temp = DAG.getNOT(dl, N1, OpVT); 4954 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp); 4955 break; 4956 } 4957 if (VT.getScalarType() != MVT::i1) { 4958 if (!DCI.isCalledByLegalizer()) 4959 DCI.AddToWorklist(N0.getNode()); 4960 // FIXME: If running after legalize, we probably can't do this. 4961 ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT)); 4962 N0 = DAG.getNode(ExtendCode, dl, VT, N0); 4963 } 4964 return N0; 4965 } 4966 4967 // Could not fold it. 4968 return SDValue(); 4969 } 4970 4971 /// Returns true (and the GlobalValue and the offset) if the node is a 4972 /// GlobalAddress + offset. 4973 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA, 4974 int64_t &Offset) const { 4975 4976 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode(); 4977 4978 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 4979 GA = GASD->getGlobal(); 4980 Offset += GASD->getOffset(); 4981 return true; 4982 } 4983 4984 if (N->getOpcode() == ISD::ADD) { 4985 SDValue N1 = N->getOperand(0); 4986 SDValue N2 = N->getOperand(1); 4987 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 4988 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 4989 Offset += V->getSExtValue(); 4990 return true; 4991 } 4992 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 4993 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 4994 Offset += V->getSExtValue(); 4995 return true; 4996 } 4997 } 4998 } 4999 5000 return false; 5001 } 5002 5003 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 5004 DAGCombinerInfo &DCI) const { 5005 // Default implementation: no optimization. 5006 return SDValue(); 5007 } 5008 5009 //===----------------------------------------------------------------------===// 5010 // Inline Assembler Implementation Methods 5011 //===----------------------------------------------------------------------===// 5012 5013 TargetLowering::ConstraintType 5014 TargetLowering::getConstraintType(StringRef Constraint) const { 5015 unsigned S = Constraint.size(); 5016 5017 if (S == 1) { 5018 switch (Constraint[0]) { 5019 default: break; 5020 case 'r': 5021 return C_RegisterClass; 5022 case 'm': // memory 5023 case 'o': // offsetable 5024 case 'V': // not offsetable 5025 return C_Memory; 5026 case 'p': // Address. 5027 return C_Address; 5028 case 'n': // Simple Integer 5029 case 'E': // Floating Point Constant 5030 case 'F': // Floating Point Constant 5031 return C_Immediate; 5032 case 'i': // Simple Integer or Relocatable Constant 5033 case 's': // Relocatable Constant 5034 case 'X': // Allow ANY value. 5035 case 'I': // Target registers. 5036 case 'J': 5037 case 'K': 5038 case 'L': 5039 case 'M': 5040 case 'N': 5041 case 'O': 5042 case 'P': 5043 case '<': 5044 case '>': 5045 return C_Other; 5046 } 5047 } 5048 5049 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') { 5050 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 5051 return C_Memory; 5052 return C_Register; 5053 } 5054 return C_Unknown; 5055 } 5056 5057 /// Try to replace an X constraint, which matches anything, with another that 5058 /// has more specific requirements based on the type of the corresponding 5059 /// operand. 5060 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 5061 if (ConstraintVT.isInteger()) 5062 return "r"; 5063 if (ConstraintVT.isFloatingPoint()) 5064 return "f"; // works for many targets 5065 return nullptr; 5066 } 5067 5068 SDValue TargetLowering::LowerAsmOutputForConstraint( 5069 SDValue &Chain, SDValue &Flag, const SDLoc &DL, 5070 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const { 5071 return SDValue(); 5072 } 5073 5074 /// Lower the specified operand into the Ops vector. 5075 /// If it is invalid, don't add anything to Ops. 5076 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 5077 std::string &Constraint, 5078 std::vector<SDValue> &Ops, 5079 SelectionDAG &DAG) const { 5080 5081 if (Constraint.length() > 1) return; 5082 5083 char ConstraintLetter = Constraint[0]; 5084 switch (ConstraintLetter) { 5085 default: break; 5086 case 'X': // Allows any operand 5087 case 'i': // Simple Integer or Relocatable Constant 5088 case 'n': // Simple Integer 5089 case 's': { // Relocatable Constant 5090 5091 ConstantSDNode *C; 5092 uint64_t Offset = 0; 5093 5094 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C), 5095 // etc., since getelementpointer is variadic. We can't use 5096 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible 5097 // while in this case the GA may be furthest from the root node which is 5098 // likely an ISD::ADD. 5099 while (true) { 5100 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') { 5101 // gcc prints these as sign extended. Sign extend value to 64 bits 5102 // now; without this it would get ZExt'd later in 5103 // ScheduleDAGSDNodes::EmitNode, which is very generic. 5104 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1; 5105 BooleanContent BCont = getBooleanContents(MVT::i64); 5106 ISD::NodeType ExtOpc = 5107 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND; 5108 int64_t ExtVal = 5109 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue(); 5110 Ops.push_back( 5111 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64)); 5112 return; 5113 } 5114 if (ConstraintLetter != 'n') { 5115 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 5116 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 5117 GA->getValueType(0), 5118 Offset + GA->getOffset())); 5119 return; 5120 } 5121 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 5122 Ops.push_back(DAG.getTargetBlockAddress( 5123 BA->getBlockAddress(), BA->getValueType(0), 5124 Offset + BA->getOffset(), BA->getTargetFlags())); 5125 return; 5126 } 5127 if (isa<BasicBlockSDNode>(Op)) { 5128 Ops.push_back(Op); 5129 return; 5130 } 5131 } 5132 const unsigned OpCode = Op.getOpcode(); 5133 if (OpCode == ISD::ADD || OpCode == ISD::SUB) { 5134 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0)))) 5135 Op = Op.getOperand(1); 5136 // Subtraction is not commutative. 5137 else if (OpCode == ISD::ADD && 5138 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))) 5139 Op = Op.getOperand(0); 5140 else 5141 return; 5142 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue(); 5143 continue; 5144 } 5145 return; 5146 } 5147 break; 5148 } 5149 } 5150 } 5151 5152 std::pair<unsigned, const TargetRegisterClass *> 5153 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 5154 StringRef Constraint, 5155 MVT VT) const { 5156 if (Constraint.empty() || Constraint[0] != '{') 5157 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr)); 5158 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?"); 5159 5160 // Remove the braces from around the name. 5161 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 5162 5163 std::pair<unsigned, const TargetRegisterClass *> R = 5164 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr)); 5165 5166 // Figure out which register class contains this reg. 5167 for (const TargetRegisterClass *RC : RI->regclasses()) { 5168 // If none of the value types for this register class are valid, we 5169 // can't use it. For example, 64-bit reg classes on 32-bit targets. 5170 if (!isLegalRC(*RI, *RC)) 5171 continue; 5172 5173 for (const MCPhysReg &PR : *RC) { 5174 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) { 5175 std::pair<unsigned, const TargetRegisterClass *> S = 5176 std::make_pair(PR, RC); 5177 5178 // If this register class has the requested value type, return it, 5179 // otherwise keep searching and return the first class found 5180 // if no other is found which explicitly has the requested type. 5181 if (RI->isTypeLegalForClass(*RC, VT)) 5182 return S; 5183 if (!R.second) 5184 R = S; 5185 } 5186 } 5187 } 5188 5189 return R; 5190 } 5191 5192 //===----------------------------------------------------------------------===// 5193 // Constraint Selection. 5194 5195 /// Return true of this is an input operand that is a matching constraint like 5196 /// "4". 5197 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 5198 assert(!ConstraintCode.empty() && "No known constraint!"); 5199 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 5200 } 5201 5202 /// If this is an input matching constraint, this method returns the output 5203 /// operand it matches. 5204 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 5205 assert(!ConstraintCode.empty() && "No known constraint!"); 5206 return atoi(ConstraintCode.c_str()); 5207 } 5208 5209 /// Split up the constraint string from the inline assembly value into the 5210 /// specific constraints and their prefixes, and also tie in the associated 5211 /// operand values. 5212 /// If this returns an empty vector, and if the constraint string itself 5213 /// isn't empty, there was an error parsing. 5214 TargetLowering::AsmOperandInfoVector 5215 TargetLowering::ParseConstraints(const DataLayout &DL, 5216 const TargetRegisterInfo *TRI, 5217 const CallBase &Call) const { 5218 /// Information about all of the constraints. 5219 AsmOperandInfoVector ConstraintOperands; 5220 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 5221 unsigned maCount = 0; // Largest number of multiple alternative constraints. 5222 5223 // Do a prepass over the constraints, canonicalizing them, and building up the 5224 // ConstraintOperands list. 5225 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 5226 unsigned ResNo = 0; // ResNo - The result number of the next output. 5227 5228 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 5229 ConstraintOperands.emplace_back(std::move(CI)); 5230 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 5231 5232 // Update multiple alternative constraint count. 5233 if (OpInfo.multipleAlternatives.size() > maCount) 5234 maCount = OpInfo.multipleAlternatives.size(); 5235 5236 OpInfo.ConstraintVT = MVT::Other; 5237 5238 // Compute the value type for each operand. 5239 switch (OpInfo.Type) { 5240 case InlineAsm::isOutput: 5241 // Indirect outputs just consume an argument. 5242 if (OpInfo.isIndirect) { 5243 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5244 break; 5245 } 5246 5247 // The return value of the call is this value. As such, there is no 5248 // corresponding argument. 5249 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 5250 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 5251 OpInfo.ConstraintVT = 5252 getSimpleValueType(DL, STy->getElementType(ResNo)); 5253 } else { 5254 assert(ResNo == 0 && "Asm only has one result!"); 5255 OpInfo.ConstraintVT = 5256 getAsmOperandValueType(DL, Call.getType()).getSimpleVT(); 5257 } 5258 ++ResNo; 5259 break; 5260 case InlineAsm::isInput: 5261 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo); 5262 break; 5263 case InlineAsm::isClobber: 5264 // Nothing to do. 5265 break; 5266 } 5267 5268 if (OpInfo.CallOperandVal) { 5269 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 5270 if (OpInfo.isIndirect) { 5271 OpTy = Call.getParamElementType(ArgNo); 5272 assert(OpTy && "Indirect operand must have elementtype attribute"); 5273 } 5274 5275 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 5276 if (StructType *STy = dyn_cast<StructType>(OpTy)) 5277 if (STy->getNumElements() == 1) 5278 OpTy = STy->getElementType(0); 5279 5280 // If OpTy is not a single value, it may be a struct/union that we 5281 // can tile with integers. 5282 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 5283 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 5284 switch (BitSize) { 5285 default: break; 5286 case 1: 5287 case 8: 5288 case 16: 5289 case 32: 5290 case 64: 5291 case 128: 5292 OpTy = IntegerType::get(OpTy->getContext(), BitSize); 5293 break; 5294 } 5295 } 5296 5297 EVT VT = getAsmOperandValueType(DL, OpTy, true); 5298 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 5299 ArgNo++; 5300 } 5301 } 5302 5303 // If we have multiple alternative constraints, select the best alternative. 5304 if (!ConstraintOperands.empty()) { 5305 if (maCount) { 5306 unsigned bestMAIndex = 0; 5307 int bestWeight = -1; 5308 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 5309 int weight = -1; 5310 unsigned maIndex; 5311 // Compute the sums of the weights for each alternative, keeping track 5312 // of the best (highest weight) one so far. 5313 for (maIndex = 0; maIndex < maCount; ++maIndex) { 5314 int weightSum = 0; 5315 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5316 cIndex != eIndex; ++cIndex) { 5317 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5318 if (OpInfo.Type == InlineAsm::isClobber) 5319 continue; 5320 5321 // If this is an output operand with a matching input operand, 5322 // look up the matching input. If their types mismatch, e.g. one 5323 // is an integer, the other is floating point, or their sizes are 5324 // different, flag it as an maCantMatch. 5325 if (OpInfo.hasMatchingInput()) { 5326 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5327 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5328 if ((OpInfo.ConstraintVT.isInteger() != 5329 Input.ConstraintVT.isInteger()) || 5330 (OpInfo.ConstraintVT.getSizeInBits() != 5331 Input.ConstraintVT.getSizeInBits())) { 5332 weightSum = -1; // Can't match. 5333 break; 5334 } 5335 } 5336 } 5337 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 5338 if (weight == -1) { 5339 weightSum = -1; 5340 break; 5341 } 5342 weightSum += weight; 5343 } 5344 // Update best. 5345 if (weightSum > bestWeight) { 5346 bestWeight = weightSum; 5347 bestMAIndex = maIndex; 5348 } 5349 } 5350 5351 // Now select chosen alternative in each constraint. 5352 for (AsmOperandInfo &cInfo : ConstraintOperands) 5353 if (cInfo.Type != InlineAsm::isClobber) 5354 cInfo.selectAlternative(bestMAIndex); 5355 } 5356 } 5357 5358 // Check and hook up tied operands, choose constraint code to use. 5359 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 5360 cIndex != eIndex; ++cIndex) { 5361 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 5362 5363 // If this is an output operand with a matching input operand, look up the 5364 // matching input. If their types mismatch, e.g. one is an integer, the 5365 // other is floating point, or their sizes are different, flag it as an 5366 // error. 5367 if (OpInfo.hasMatchingInput()) { 5368 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5369 5370 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5371 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 5372 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 5373 OpInfo.ConstraintVT); 5374 std::pair<unsigned, const TargetRegisterClass *> InputRC = 5375 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 5376 Input.ConstraintVT); 5377 if ((OpInfo.ConstraintVT.isInteger() != 5378 Input.ConstraintVT.isInteger()) || 5379 (MatchRC.second != InputRC.second)) { 5380 report_fatal_error("Unsupported asm: input constraint" 5381 " with a matching output constraint of" 5382 " incompatible type!"); 5383 } 5384 } 5385 } 5386 } 5387 5388 return ConstraintOperands; 5389 } 5390 5391 /// Return an integer indicating how general CT is. 5392 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 5393 switch (CT) { 5394 case TargetLowering::C_Immediate: 5395 case TargetLowering::C_Other: 5396 case TargetLowering::C_Unknown: 5397 return 0; 5398 case TargetLowering::C_Register: 5399 return 1; 5400 case TargetLowering::C_RegisterClass: 5401 return 2; 5402 case TargetLowering::C_Memory: 5403 case TargetLowering::C_Address: 5404 return 3; 5405 } 5406 llvm_unreachable("Invalid constraint type"); 5407 } 5408 5409 /// Examine constraint type and operand type and determine a weight value. 5410 /// This object must already have been set up with the operand type 5411 /// and the current alternative constraint selected. 5412 TargetLowering::ConstraintWeight 5413 TargetLowering::getMultipleConstraintMatchWeight( 5414 AsmOperandInfo &info, int maIndex) const { 5415 InlineAsm::ConstraintCodeVector *rCodes; 5416 if (maIndex >= (int)info.multipleAlternatives.size()) 5417 rCodes = &info.Codes; 5418 else 5419 rCodes = &info.multipleAlternatives[maIndex].Codes; 5420 ConstraintWeight BestWeight = CW_Invalid; 5421 5422 // Loop over the options, keeping track of the most general one. 5423 for (const std::string &rCode : *rCodes) { 5424 ConstraintWeight weight = 5425 getSingleConstraintMatchWeight(info, rCode.c_str()); 5426 if (weight > BestWeight) 5427 BestWeight = weight; 5428 } 5429 5430 return BestWeight; 5431 } 5432 5433 /// Examine constraint type and operand type and determine a weight value. 5434 /// This object must already have been set up with the operand type 5435 /// and the current alternative constraint selected. 5436 TargetLowering::ConstraintWeight 5437 TargetLowering::getSingleConstraintMatchWeight( 5438 AsmOperandInfo &info, const char *constraint) const { 5439 ConstraintWeight weight = CW_Invalid; 5440 Value *CallOperandVal = info.CallOperandVal; 5441 // If we don't have a value, we can't do a match, 5442 // but allow it at the lowest weight. 5443 if (!CallOperandVal) 5444 return CW_Default; 5445 // Look at the constraint type. 5446 switch (*constraint) { 5447 case 'i': // immediate integer. 5448 case 'n': // immediate integer with a known value. 5449 if (isa<ConstantInt>(CallOperandVal)) 5450 weight = CW_Constant; 5451 break; 5452 case 's': // non-explicit intregal immediate. 5453 if (isa<GlobalValue>(CallOperandVal)) 5454 weight = CW_Constant; 5455 break; 5456 case 'E': // immediate float if host format. 5457 case 'F': // immediate float. 5458 if (isa<ConstantFP>(CallOperandVal)) 5459 weight = CW_Constant; 5460 break; 5461 case '<': // memory operand with autodecrement. 5462 case '>': // memory operand with autoincrement. 5463 case 'm': // memory operand. 5464 case 'o': // offsettable memory operand 5465 case 'V': // non-offsettable memory operand 5466 weight = CW_Memory; 5467 break; 5468 case 'r': // general register. 5469 case 'g': // general register, memory operand or immediate integer. 5470 // note: Clang converts "g" to "imr". 5471 if (CallOperandVal->getType()->isIntegerTy()) 5472 weight = CW_Register; 5473 break; 5474 case 'X': // any operand. 5475 default: 5476 weight = CW_Default; 5477 break; 5478 } 5479 return weight; 5480 } 5481 5482 /// If there are multiple different constraints that we could pick for this 5483 /// operand (e.g. "imr") try to pick the 'best' one. 5484 /// This is somewhat tricky: constraints fall into four classes: 5485 /// Other -> immediates and magic values 5486 /// Register -> one specific register 5487 /// RegisterClass -> a group of regs 5488 /// Memory -> memory 5489 /// Ideally, we would pick the most specific constraint possible: if we have 5490 /// something that fits into a register, we would pick it. The problem here 5491 /// is that if we have something that could either be in a register or in 5492 /// memory that use of the register could cause selection of *other* 5493 /// operands to fail: they might only succeed if we pick memory. Because of 5494 /// this the heuristic we use is: 5495 /// 5496 /// 1) If there is an 'other' constraint, and if the operand is valid for 5497 /// that constraint, use it. This makes us take advantage of 'i' 5498 /// constraints when available. 5499 /// 2) Otherwise, pick the most general constraint present. This prefers 5500 /// 'm' over 'r', for example. 5501 /// 5502 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 5503 const TargetLowering &TLI, 5504 SDValue Op, SelectionDAG *DAG) { 5505 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 5506 unsigned BestIdx = 0; 5507 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 5508 int BestGenerality = -1; 5509 5510 // Loop over the options, keeping track of the most general one. 5511 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 5512 TargetLowering::ConstraintType CType = 5513 TLI.getConstraintType(OpInfo.Codes[i]); 5514 5515 // Indirect 'other' or 'immediate' constraints are not allowed. 5516 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory || 5517 CType == TargetLowering::C_Register || 5518 CType == TargetLowering::C_RegisterClass)) 5519 continue; 5520 5521 // If this is an 'other' or 'immediate' constraint, see if the operand is 5522 // valid for it. For example, on X86 we might have an 'rI' constraint. If 5523 // the operand is an integer in the range [0..31] we want to use I (saving a 5524 // load of a register), otherwise we must use 'r'. 5525 if ((CType == TargetLowering::C_Other || 5526 CType == TargetLowering::C_Immediate) && Op.getNode()) { 5527 assert(OpInfo.Codes[i].size() == 1 && 5528 "Unhandled multi-letter 'other' constraint"); 5529 std::vector<SDValue> ResultOps; 5530 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 5531 ResultOps, *DAG); 5532 if (!ResultOps.empty()) { 5533 BestType = CType; 5534 BestIdx = i; 5535 break; 5536 } 5537 } 5538 5539 // Things with matching constraints can only be registers, per gcc 5540 // documentation. This mainly affects "g" constraints. 5541 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 5542 continue; 5543 5544 // This constraint letter is more general than the previous one, use it. 5545 int Generality = getConstraintGenerality(CType); 5546 if (Generality > BestGenerality) { 5547 BestType = CType; 5548 BestIdx = i; 5549 BestGenerality = Generality; 5550 } 5551 } 5552 5553 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 5554 OpInfo.ConstraintType = BestType; 5555 } 5556 5557 /// Determines the constraint code and constraint type to use for the specific 5558 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 5559 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 5560 SDValue Op, 5561 SelectionDAG *DAG) const { 5562 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 5563 5564 // Single-letter constraints ('r') are very common. 5565 if (OpInfo.Codes.size() == 1) { 5566 OpInfo.ConstraintCode = OpInfo.Codes[0]; 5567 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 5568 } else { 5569 ChooseConstraint(OpInfo, *this, Op, DAG); 5570 } 5571 5572 // 'X' matches anything. 5573 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 5574 // Constants are handled elsewhere. For Functions, the type here is the 5575 // type of the result, which is not what we want to look at; leave them 5576 // alone. 5577 Value *v = OpInfo.CallOperandVal; 5578 if (isa<ConstantInt>(v) || isa<Function>(v)) { 5579 return; 5580 } 5581 5582 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) { 5583 OpInfo.ConstraintCode = "i"; 5584 return; 5585 } 5586 5587 // Otherwise, try to resolve it to something we know about by looking at 5588 // the actual operand type. 5589 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 5590 OpInfo.ConstraintCode = Repl; 5591 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 5592 } 5593 } 5594 } 5595 5596 /// Given an exact SDIV by a constant, create a multiplication 5597 /// with the multiplicative inverse of the constant. 5598 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, 5599 const SDLoc &dl, SelectionDAG &DAG, 5600 SmallVectorImpl<SDNode *> &Created) { 5601 SDValue Op0 = N->getOperand(0); 5602 SDValue Op1 = N->getOperand(1); 5603 EVT VT = N->getValueType(0); 5604 EVT SVT = VT.getScalarType(); 5605 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 5606 EVT ShSVT = ShVT.getScalarType(); 5607 5608 bool UseSRA = false; 5609 SmallVector<SDValue, 16> Shifts, Factors; 5610 5611 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5612 if (C->isZero()) 5613 return false; 5614 APInt Divisor = C->getAPIntValue(); 5615 unsigned Shift = Divisor.countTrailingZeros(); 5616 if (Shift) { 5617 Divisor.ashrInPlace(Shift); 5618 UseSRA = true; 5619 } 5620 // Calculate the multiplicative inverse, using Newton's method. 5621 APInt t; 5622 APInt Factor = Divisor; 5623 while ((t = Divisor * Factor) != 1) 5624 Factor *= APInt(Divisor.getBitWidth(), 2) - t; 5625 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 5626 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 5627 return true; 5628 }; 5629 5630 // Collect all magic values from the build vector. 5631 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern)) 5632 return SDValue(); 5633 5634 SDValue Shift, Factor; 5635 if (Op1.getOpcode() == ISD::BUILD_VECTOR) { 5636 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5637 Factor = DAG.getBuildVector(VT, dl, Factors); 5638 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) { 5639 assert(Shifts.size() == 1 && Factors.size() == 1 && 5640 "Expected matchUnaryPredicate to return one element for scalable " 5641 "vectors"); 5642 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5643 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5644 } else { 5645 assert(isa<ConstantSDNode>(Op1) && "Expected a constant"); 5646 Shift = Shifts[0]; 5647 Factor = Factors[0]; 5648 } 5649 5650 SDValue Res = Op0; 5651 5652 // Shift the value upfront if it is even, so the LSB is one. 5653 if (UseSRA) { 5654 // TODO: For UDIV use SRL instead of SRA. 5655 SDNodeFlags Flags; 5656 Flags.setExact(true); 5657 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags); 5658 Created.push_back(Res.getNode()); 5659 } 5660 5661 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 5662 } 5663 5664 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 5665 SelectionDAG &DAG, 5666 SmallVectorImpl<SDNode *> &Created) const { 5667 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 5668 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5669 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 5670 return SDValue(N, 0); // Lower SDIV as SDIV 5671 return SDValue(); 5672 } 5673 5674 SDValue 5675 TargetLowering::BuildSREMPow2(SDNode *N, const APInt &Divisor, 5676 SelectionDAG &DAG, 5677 SmallVectorImpl<SDNode *> &Created) const { 5678 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 5679 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5680 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 5681 return SDValue(N, 0); // Lower SREM as SREM 5682 return SDValue(); 5683 } 5684 5685 /// Given an ISD::SDIV node expressing a divide by constant, 5686 /// return a DAG expression to select that will generate the same value by 5687 /// multiplying by a magic number. 5688 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5689 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 5690 bool IsAfterLegalization, 5691 SmallVectorImpl<SDNode *> &Created) const { 5692 SDLoc dl(N); 5693 EVT VT = N->getValueType(0); 5694 EVT SVT = VT.getScalarType(); 5695 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5696 EVT ShSVT = ShVT.getScalarType(); 5697 unsigned EltBits = VT.getScalarSizeInBits(); 5698 EVT MulVT; 5699 5700 // Check to see if we can do this. 5701 // FIXME: We should be more aggressive here. 5702 if (!isTypeLegal(VT)) { 5703 // Limit this to simple scalars for now. 5704 if (VT.isVector() || !VT.isSimple()) 5705 return SDValue(); 5706 5707 // If this type will be promoted to a large enough type with a legal 5708 // multiply operation, we can go ahead and do this transform. 5709 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5710 return SDValue(); 5711 5712 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5713 if (MulVT.getSizeInBits() < (2 * EltBits) || 5714 !isOperationLegal(ISD::MUL, MulVT)) 5715 return SDValue(); 5716 } 5717 5718 // If the sdiv has an 'exact' bit we can use a simpler lowering. 5719 if (N->getFlags().hasExact()) 5720 return BuildExactSDIV(*this, N, dl, DAG, Created); 5721 5722 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks; 5723 5724 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5725 if (C->isZero()) 5726 return false; 5727 5728 const APInt &Divisor = C->getAPIntValue(); 5729 SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor); 5730 int NumeratorFactor = 0; 5731 int ShiftMask = -1; 5732 5733 if (Divisor.isOne() || Divisor.isAllOnes()) { 5734 // If d is +1/-1, we just multiply the numerator by +1/-1. 5735 NumeratorFactor = Divisor.getSExtValue(); 5736 magics.Magic = 0; 5737 magics.ShiftAmount = 0; 5738 ShiftMask = 0; 5739 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) { 5740 // If d > 0 and m < 0, add the numerator. 5741 NumeratorFactor = 1; 5742 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) { 5743 // If d < 0 and m > 0, subtract the numerator. 5744 NumeratorFactor = -1; 5745 } 5746 5747 MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT)); 5748 Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT)); 5749 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT)); 5750 ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT)); 5751 return true; 5752 }; 5753 5754 SDValue N0 = N->getOperand(0); 5755 SDValue N1 = N->getOperand(1); 5756 5757 // Collect the shifts / magic values from each element. 5758 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern)) 5759 return SDValue(); 5760 5761 SDValue MagicFactor, Factor, Shift, ShiftMask; 5762 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5763 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5764 Factor = DAG.getBuildVector(VT, dl, Factors); 5765 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5766 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks); 5767 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5768 assert(MagicFactors.size() == 1 && Factors.size() == 1 && 5769 Shifts.size() == 1 && ShiftMasks.size() == 1 && 5770 "Expected matchUnaryPredicate to return one element for scalable " 5771 "vectors"); 5772 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5773 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5774 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5775 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]); 5776 } else { 5777 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 5778 MagicFactor = MagicFactors[0]; 5779 Factor = Factors[0]; 5780 Shift = Shifts[0]; 5781 ShiftMask = ShiftMasks[0]; 5782 } 5783 5784 // Multiply the numerator (operand 0) by the magic value. 5785 // FIXME: We should support doing a MUL in a wider type. 5786 auto GetMULHS = [&](SDValue X, SDValue Y) { 5787 // If the type isn't legal, use a wider mul of the the type calculated 5788 // earlier. 5789 if (!isTypeLegal(VT)) { 5790 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X); 5791 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y); 5792 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 5793 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 5794 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 5795 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 5796 } 5797 5798 if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization)) 5799 return DAG.getNode(ISD::MULHS, dl, VT, X, Y); 5800 if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) { 5801 SDValue LoHi = 5802 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5803 return SDValue(LoHi.getNode(), 1); 5804 } 5805 return SDValue(); 5806 }; 5807 5808 SDValue Q = GetMULHS(N0, MagicFactor); 5809 if (!Q) 5810 return SDValue(); 5811 5812 Created.push_back(Q.getNode()); 5813 5814 // (Optionally) Add/subtract the numerator using Factor. 5815 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor); 5816 Created.push_back(Factor.getNode()); 5817 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor); 5818 Created.push_back(Q.getNode()); 5819 5820 // Shift right algebraic by shift value. 5821 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift); 5822 Created.push_back(Q.getNode()); 5823 5824 // Extract the sign bit, mask it and add it to the quotient. 5825 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT); 5826 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift); 5827 Created.push_back(T.getNode()); 5828 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask); 5829 Created.push_back(T.getNode()); 5830 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 5831 } 5832 5833 /// Given an ISD::UDIV node expressing a divide by constant, 5834 /// return a DAG expression to select that will generate the same value by 5835 /// multiplying by a magic number. 5836 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5837 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG, 5838 bool IsAfterLegalization, 5839 SmallVectorImpl<SDNode *> &Created) const { 5840 SDLoc dl(N); 5841 EVT VT = N->getValueType(0); 5842 EVT SVT = VT.getScalarType(); 5843 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5844 EVT ShSVT = ShVT.getScalarType(); 5845 unsigned EltBits = VT.getScalarSizeInBits(); 5846 EVT MulVT; 5847 5848 // Check to see if we can do this. 5849 // FIXME: We should be more aggressive here. 5850 if (!isTypeLegal(VT)) { 5851 // Limit this to simple scalars for now. 5852 if (VT.isVector() || !VT.isSimple()) 5853 return SDValue(); 5854 5855 // If this type will be promoted to a large enough type with a legal 5856 // multiply operation, we can go ahead and do this transform. 5857 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5858 return SDValue(); 5859 5860 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5861 if (MulVT.getSizeInBits() < (2 * EltBits) || 5862 !isOperationLegal(ISD::MUL, MulVT)) 5863 return SDValue(); 5864 } 5865 5866 bool UseNPQ = false; 5867 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors; 5868 5869 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 5870 if (C->isZero()) 5871 return false; 5872 // FIXME: We should use a narrower constant when the upper 5873 // bits are known to be zero. 5874 const APInt& Divisor = C->getAPIntValue(); 5875 UnsignedDivisonByConstantInfo magics = UnsignedDivisonByConstantInfo::get(Divisor); 5876 unsigned PreShift = 0, PostShift = 0; 5877 5878 // If the divisor is even, we can avoid using the expensive fixup by 5879 // shifting the divided value upfront. 5880 if (magics.IsAdd != 0 && !Divisor[0]) { 5881 PreShift = Divisor.countTrailingZeros(); 5882 // Get magic number for the shifted divisor. 5883 magics = UnsignedDivisonByConstantInfo::get(Divisor.lshr(PreShift), PreShift); 5884 assert(magics.IsAdd == 0 && "Should use cheap fixup now"); 5885 } 5886 5887 APInt Magic = magics.Magic; 5888 5889 unsigned SelNPQ; 5890 if (magics.IsAdd == 0 || Divisor.isOne()) { 5891 assert(magics.ShiftAmount < Divisor.getBitWidth() && 5892 "We shouldn't generate an undefined shift!"); 5893 PostShift = magics.ShiftAmount; 5894 SelNPQ = false; 5895 } else { 5896 PostShift = magics.ShiftAmount - 1; 5897 SelNPQ = true; 5898 } 5899 5900 PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT)); 5901 MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT)); 5902 NPQFactors.push_back( 5903 DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1) 5904 : APInt::getZero(EltBits), 5905 dl, SVT)); 5906 PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT)); 5907 UseNPQ |= SelNPQ; 5908 return true; 5909 }; 5910 5911 SDValue N0 = N->getOperand(0); 5912 SDValue N1 = N->getOperand(1); 5913 5914 // Collect the shifts/magic values from each element. 5915 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern)) 5916 return SDValue(); 5917 5918 SDValue PreShift, PostShift, MagicFactor, NPQFactor; 5919 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5920 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts); 5921 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5922 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors); 5923 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts); 5924 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5925 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 && 5926 NPQFactors.size() == 1 && PostShifts.size() == 1 && 5927 "Expected matchUnaryPredicate to return one for scalable vectors"); 5928 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]); 5929 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5930 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]); 5931 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]); 5932 } else { 5933 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 5934 PreShift = PreShifts[0]; 5935 MagicFactor = MagicFactors[0]; 5936 PostShift = PostShifts[0]; 5937 } 5938 5939 SDValue Q = N0; 5940 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift); 5941 Created.push_back(Q.getNode()); 5942 5943 // FIXME: We should support doing a MUL in a wider type. 5944 auto GetMULHU = [&](SDValue X, SDValue Y) { 5945 // If the type isn't legal, use a wider mul of the the type calculated 5946 // earlier. 5947 if (!isTypeLegal(VT)) { 5948 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X); 5949 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y); 5950 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 5951 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 5952 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 5953 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 5954 } 5955 5956 if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization)) 5957 return DAG.getNode(ISD::MULHU, dl, VT, X, Y); 5958 if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) { 5959 SDValue LoHi = 5960 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5961 return SDValue(LoHi.getNode(), 1); 5962 } 5963 return SDValue(); // No mulhu or equivalent 5964 }; 5965 5966 // Multiply the numerator (operand 0) by the magic value. 5967 Q = GetMULHU(Q, MagicFactor); 5968 if (!Q) 5969 return SDValue(); 5970 5971 Created.push_back(Q.getNode()); 5972 5973 if (UseNPQ) { 5974 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q); 5975 Created.push_back(NPQ.getNode()); 5976 5977 // For vectors we might have a mix of non-NPQ/NPQ paths, so use 5978 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero. 5979 if (VT.isVector()) 5980 NPQ = GetMULHU(NPQ, NPQFactor); 5981 else 5982 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT)); 5983 5984 Created.push_back(NPQ.getNode()); 5985 5986 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 5987 Created.push_back(Q.getNode()); 5988 } 5989 5990 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift); 5991 Created.push_back(Q.getNode()); 5992 5993 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 5994 5995 SDValue One = DAG.getConstant(1, dl, VT); 5996 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ); 5997 return DAG.getSelect(dl, VT, IsOne, N0, Q); 5998 } 5999 6000 /// If all values in Values that *don't* match the predicate are same 'splat' 6001 /// value, then replace all values with that splat value. 6002 /// Else, if AlternativeReplacement was provided, then replace all values that 6003 /// do match predicate with AlternativeReplacement value. 6004 static void 6005 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values, 6006 std::function<bool(SDValue)> Predicate, 6007 SDValue AlternativeReplacement = SDValue()) { 6008 SDValue Replacement; 6009 // Is there a value for which the Predicate does *NOT* match? What is it? 6010 auto SplatValue = llvm::find_if_not(Values, Predicate); 6011 if (SplatValue != Values.end()) { 6012 // Does Values consist only of SplatValue's and values matching Predicate? 6013 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) { 6014 return Value == *SplatValue || Predicate(Value); 6015 })) // Then we shall replace values matching predicate with SplatValue. 6016 Replacement = *SplatValue; 6017 } 6018 if (!Replacement) { 6019 // Oops, we did not find the "baseline" splat value. 6020 if (!AlternativeReplacement) 6021 return; // Nothing to do. 6022 // Let's replace with provided value then. 6023 Replacement = AlternativeReplacement; 6024 } 6025 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement); 6026 } 6027 6028 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE 6029 /// where the divisor is constant and the comparison target is zero, 6030 /// return a DAG expression that will generate the same comparison result 6031 /// using only multiplications, additions and shifts/rotations. 6032 /// Ref: "Hacker's Delight" 10-17. 6033 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode, 6034 SDValue CompTargetNode, 6035 ISD::CondCode Cond, 6036 DAGCombinerInfo &DCI, 6037 const SDLoc &DL) const { 6038 SmallVector<SDNode *, 5> Built; 6039 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 6040 DCI, DL, Built)) { 6041 for (SDNode *N : Built) 6042 DCI.AddToWorklist(N); 6043 return Folded; 6044 } 6045 6046 return SDValue(); 6047 } 6048 6049 SDValue 6050 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode, 6051 SDValue CompTargetNode, ISD::CondCode Cond, 6052 DAGCombinerInfo &DCI, const SDLoc &DL, 6053 SmallVectorImpl<SDNode *> &Created) const { 6054 // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q) 6055 // - D must be constant, with D = D0 * 2^K where D0 is odd 6056 // - P is the multiplicative inverse of D0 modulo 2^W 6057 // - Q = floor(((2^W) - 1) / D) 6058 // where W is the width of the common type of N and D. 6059 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 6060 "Only applicable for (in)equality comparisons."); 6061 6062 SelectionDAG &DAG = DCI.DAG; 6063 6064 EVT VT = REMNode.getValueType(); 6065 EVT SVT = VT.getScalarType(); 6066 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize()); 6067 EVT ShSVT = ShVT.getScalarType(); 6068 6069 // If MUL is unavailable, we cannot proceed in any case. 6070 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 6071 return SDValue(); 6072 6073 bool ComparingWithAllZeros = true; 6074 bool AllComparisonsWithNonZerosAreTautological = true; 6075 bool HadTautologicalLanes = false; 6076 bool AllLanesAreTautological = true; 6077 bool HadEvenDivisor = false; 6078 bool AllDivisorsArePowerOfTwo = true; 6079 bool HadTautologicalInvertedLanes = false; 6080 SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts; 6081 6082 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) { 6083 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6084 if (CDiv->isZero()) 6085 return false; 6086 6087 const APInt &D = CDiv->getAPIntValue(); 6088 const APInt &Cmp = CCmp->getAPIntValue(); 6089 6090 ComparingWithAllZeros &= Cmp.isZero(); 6091 6092 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6093 // if C2 is not less than C1, the comparison is always false. 6094 // But we will only be able to produce the comparison that will give the 6095 // opposive tautological answer. So this lane would need to be fixed up. 6096 bool TautologicalInvertedLane = D.ule(Cmp); 6097 HadTautologicalInvertedLanes |= TautologicalInvertedLane; 6098 6099 // If all lanes are tautological (either all divisors are ones, or divisor 6100 // is not greater than the constant we are comparing with), 6101 // we will prefer to avoid the fold. 6102 bool TautologicalLane = D.isOne() || TautologicalInvertedLane; 6103 HadTautologicalLanes |= TautologicalLane; 6104 AllLanesAreTautological &= TautologicalLane; 6105 6106 // If we are comparing with non-zero, we need'll need to subtract said 6107 // comparison value from the LHS. But there is no point in doing that if 6108 // every lane where we are comparing with non-zero is tautological.. 6109 if (!Cmp.isZero()) 6110 AllComparisonsWithNonZerosAreTautological &= TautologicalLane; 6111 6112 // Decompose D into D0 * 2^K 6113 unsigned K = D.countTrailingZeros(); 6114 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 6115 APInt D0 = D.lshr(K); 6116 6117 // D is even if it has trailing zeros. 6118 HadEvenDivisor |= (K != 0); 6119 // D is a power-of-two if D0 is one. 6120 // If all divisors are power-of-two, we will prefer to avoid the fold. 6121 AllDivisorsArePowerOfTwo &= D0.isOne(); 6122 6123 // P = inv(D0, 2^W) 6124 // 2^W requires W + 1 bits, so we have to extend and then truncate. 6125 unsigned W = D.getBitWidth(); 6126 APInt P = D0.zext(W + 1) 6127 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 6128 .trunc(W); 6129 assert(!P.isZero() && "No multiplicative inverse!"); // unreachable 6130 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 6131 6132 // Q = floor((2^W - 1) u/ D) 6133 // R = ((2^W - 1) u% D) 6134 APInt Q, R; 6135 APInt::udivrem(APInt::getAllOnes(W), D, Q, R); 6136 6137 // If we are comparing with zero, then that comparison constant is okay, 6138 // else it may need to be one less than that. 6139 if (Cmp.ugt(R)) 6140 Q -= 1; 6141 6142 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 6143 "We are expecting that K is always less than all-ones for ShSVT"); 6144 6145 // If the lane is tautological the result can be constant-folded. 6146 if (TautologicalLane) { 6147 // Set P and K amount to a bogus values so we can try to splat them. 6148 P = 0; 6149 K = -1; 6150 // And ensure that comparison constant is tautological, 6151 // it will always compare true/false. 6152 Q = -1; 6153 } 6154 6155 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 6156 KAmts.push_back( 6157 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 6158 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 6159 return true; 6160 }; 6161 6162 SDValue N = REMNode.getOperand(0); 6163 SDValue D = REMNode.getOperand(1); 6164 6165 // Collect the values from each element. 6166 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern)) 6167 return SDValue(); 6168 6169 // If all lanes are tautological, the result can be constant-folded. 6170 if (AllLanesAreTautological) 6171 return SDValue(); 6172 6173 // If this is a urem by a powers-of-two, avoid the fold since it can be 6174 // best implemented as a bit test. 6175 if (AllDivisorsArePowerOfTwo) 6176 return SDValue(); 6177 6178 SDValue PVal, KVal, QVal; 6179 if (D.getOpcode() == ISD::BUILD_VECTOR) { 6180 if (HadTautologicalLanes) { 6181 // Try to turn PAmts into a splat, since we don't care about the values 6182 // that are currently '0'. If we can't, just keep '0'`s. 6183 turnVectorIntoSplatVector(PAmts, isNullConstant); 6184 // Try to turn KAmts into a splat, since we don't care about the values 6185 // that are currently '-1'. If we can't, change them to '0'`s. 6186 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 6187 DAG.getConstant(0, DL, ShSVT)); 6188 } 6189 6190 PVal = DAG.getBuildVector(VT, DL, PAmts); 6191 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 6192 QVal = DAG.getBuildVector(VT, DL, QAmts); 6193 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 6194 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 && 6195 "Expected matchBinaryPredicate to return one element for " 6196 "SPLAT_VECTORs"); 6197 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 6198 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 6199 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 6200 } else { 6201 PVal = PAmts[0]; 6202 KVal = KAmts[0]; 6203 QVal = QAmts[0]; 6204 } 6205 6206 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) { 6207 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT)) 6208 return SDValue(); // FIXME: Could/should use `ISD::ADD`? 6209 assert(CompTargetNode.getValueType() == N.getValueType() && 6210 "Expecting that the types on LHS and RHS of comparisons match."); 6211 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode); 6212 } 6213 6214 // (mul N, P) 6215 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6216 Created.push_back(Op0.getNode()); 6217 6218 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6219 // divisors as a performance improvement, since rotating by 0 is a no-op. 6220 if (HadEvenDivisor) { 6221 // We need ROTR to do this. 6222 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6223 return SDValue(); 6224 // UREM: (rotr (mul N, P), K) 6225 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6226 Created.push_back(Op0.getNode()); 6227 } 6228 6229 // UREM: (setule/setugt (rotr (mul N, P), K), Q) 6230 SDValue NewCC = 6231 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 6232 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 6233 if (!HadTautologicalInvertedLanes) 6234 return NewCC; 6235 6236 // If any lanes previously compared always-false, the NewCC will give 6237 // always-true result for them, so we need to fixup those lanes. 6238 // Or the other way around for inequality predicate. 6239 assert(VT.isVector() && "Can/should only get here for vectors."); 6240 Created.push_back(NewCC.getNode()); 6241 6242 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 6243 // if C2 is not less than C1, the comparison is always false. 6244 // But we have produced the comparison that will give the 6245 // opposive tautological answer. So these lanes would need to be fixed up. 6246 SDValue TautologicalInvertedChannels = 6247 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE); 6248 Created.push_back(TautologicalInvertedChannels.getNode()); 6249 6250 // NOTE: we avoid letting illegal types through even if we're before legalize 6251 // ops – legalization has a hard time producing good code for this. 6252 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) { 6253 // If we have a vector select, let's replace the comparison results in the 6254 // affected lanes with the correct tautological result. 6255 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true, 6256 DL, SETCCVT, SETCCVT); 6257 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels, 6258 Replacement, NewCC); 6259 } 6260 6261 // Else, we can just invert the comparison result in the appropriate lanes. 6262 // 6263 // NOTE: see the note above VSELECT above. 6264 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT)) 6265 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC, 6266 TautologicalInvertedChannels); 6267 6268 return SDValue(); // Don't know how to lower. 6269 } 6270 6271 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE 6272 /// where the divisor is constant and the comparison target is zero, 6273 /// return a DAG expression that will generate the same comparison result 6274 /// using only multiplications, additions and shifts/rotations. 6275 /// Ref: "Hacker's Delight" 10-17. 6276 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode, 6277 SDValue CompTargetNode, 6278 ISD::CondCode Cond, 6279 DAGCombinerInfo &DCI, 6280 const SDLoc &DL) const { 6281 SmallVector<SDNode *, 7> Built; 6282 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 6283 DCI, DL, Built)) { 6284 assert(Built.size() <= 7 && "Max size prediction failed."); 6285 for (SDNode *N : Built) 6286 DCI.AddToWorklist(N); 6287 return Folded; 6288 } 6289 6290 return SDValue(); 6291 } 6292 6293 SDValue 6294 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode, 6295 SDValue CompTargetNode, ISD::CondCode Cond, 6296 DAGCombinerInfo &DCI, const SDLoc &DL, 6297 SmallVectorImpl<SDNode *> &Created) const { 6298 // Fold: 6299 // (seteq/ne (srem N, D), 0) 6300 // To: 6301 // (setule/ugt (rotr (add (mul N, P), A), K), Q) 6302 // 6303 // - D must be constant, with D = D0 * 2^K where D0 is odd 6304 // - P is the multiplicative inverse of D0 modulo 2^W 6305 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k))) 6306 // - Q = floor((2 * A) / (2^K)) 6307 // where W is the width of the common type of N and D. 6308 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 6309 "Only applicable for (in)equality comparisons."); 6310 6311 SelectionDAG &DAG = DCI.DAG; 6312 6313 EVT VT = REMNode.getValueType(); 6314 EVT SVT = VT.getScalarType(); 6315 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize()); 6316 EVT ShSVT = ShVT.getScalarType(); 6317 6318 // If we are after ops legalization, and MUL is unavailable, we can not 6319 // proceed. 6320 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 6321 return SDValue(); 6322 6323 // TODO: Could support comparing with non-zero too. 6324 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode); 6325 if (!CompTarget || !CompTarget->isZero()) 6326 return SDValue(); 6327 6328 bool HadIntMinDivisor = false; 6329 bool HadOneDivisor = false; 6330 bool AllDivisorsAreOnes = true; 6331 bool HadEvenDivisor = false; 6332 bool NeedToApplyOffset = false; 6333 bool AllDivisorsArePowerOfTwo = true; 6334 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts; 6335 6336 auto BuildSREMPattern = [&](ConstantSDNode *C) { 6337 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 6338 if (C->isZero()) 6339 return false; 6340 6341 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine. 6342 6343 // WARNING: this fold is only valid for positive divisors! 6344 APInt D = C->getAPIntValue(); 6345 if (D.isNegative()) 6346 D.negate(); // `rem %X, -C` is equivalent to `rem %X, C` 6347 6348 HadIntMinDivisor |= D.isMinSignedValue(); 6349 6350 // If all divisors are ones, we will prefer to avoid the fold. 6351 HadOneDivisor |= D.isOne(); 6352 AllDivisorsAreOnes &= D.isOne(); 6353 6354 // Decompose D into D0 * 2^K 6355 unsigned K = D.countTrailingZeros(); 6356 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate."); 6357 APInt D0 = D.lshr(K); 6358 6359 if (!D.isMinSignedValue()) { 6360 // D is even if it has trailing zeros; unless it's INT_MIN, in which case 6361 // we don't care about this lane in this fold, we'll special-handle it. 6362 HadEvenDivisor |= (K != 0); 6363 } 6364 6365 // D is a power-of-two if D0 is one. This includes INT_MIN. 6366 // If all divisors are power-of-two, we will prefer to avoid the fold. 6367 AllDivisorsArePowerOfTwo &= D0.isOne(); 6368 6369 // P = inv(D0, 2^W) 6370 // 2^W requires W + 1 bits, so we have to extend and then truncate. 6371 unsigned W = D.getBitWidth(); 6372 APInt P = D0.zext(W + 1) 6373 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 6374 .trunc(W); 6375 assert(!P.isZero() && "No multiplicative inverse!"); // unreachable 6376 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed."); 6377 6378 // A = floor((2^(W - 1) - 1) / D0) & -2^K 6379 APInt A = APInt::getSignedMaxValue(W).udiv(D0); 6380 A.clearLowBits(K); 6381 6382 if (!D.isMinSignedValue()) { 6383 // If divisor INT_MIN, then we don't care about this lane in this fold, 6384 // we'll special-handle it. 6385 NeedToApplyOffset |= A != 0; 6386 } 6387 6388 // Q = floor((2 * A) / (2^K)) 6389 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K)); 6390 6391 assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) && 6392 "We are expecting that A is always less than all-ones for SVT"); 6393 assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) && 6394 "We are expecting that K is always less than all-ones for ShSVT"); 6395 6396 // If the divisor is 1 the result can be constant-folded. Likewise, we 6397 // don't care about INT_MIN lanes, those can be set to undef if appropriate. 6398 if (D.isOne()) { 6399 // Set P, A and K to a bogus values so we can try to splat them. 6400 P = 0; 6401 A = -1; 6402 K = -1; 6403 6404 // x ?% 1 == 0 <--> true <--> x u<= -1 6405 Q = -1; 6406 } 6407 6408 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 6409 AAmts.push_back(DAG.getConstant(A, DL, SVT)); 6410 KAmts.push_back( 6411 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 6412 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 6413 return true; 6414 }; 6415 6416 SDValue N = REMNode.getOperand(0); 6417 SDValue D = REMNode.getOperand(1); 6418 6419 // Collect the values from each element. 6420 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern)) 6421 return SDValue(); 6422 6423 // If this is a srem by a one, avoid the fold since it can be constant-folded. 6424 if (AllDivisorsAreOnes) 6425 return SDValue(); 6426 6427 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold 6428 // since it can be best implemented as a bit test. 6429 if (AllDivisorsArePowerOfTwo) 6430 return SDValue(); 6431 6432 SDValue PVal, AVal, KVal, QVal; 6433 if (D.getOpcode() == ISD::BUILD_VECTOR) { 6434 if (HadOneDivisor) { 6435 // Try to turn PAmts into a splat, since we don't care about the values 6436 // that are currently '0'. If we can't, just keep '0'`s. 6437 turnVectorIntoSplatVector(PAmts, isNullConstant); 6438 // Try to turn AAmts into a splat, since we don't care about the 6439 // values that are currently '-1'. If we can't, change them to '0'`s. 6440 turnVectorIntoSplatVector(AAmts, isAllOnesConstant, 6441 DAG.getConstant(0, DL, SVT)); 6442 // Try to turn KAmts into a splat, since we don't care about the values 6443 // that are currently '-1'. If we can't, change them to '0'`s. 6444 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 6445 DAG.getConstant(0, DL, ShSVT)); 6446 } 6447 6448 PVal = DAG.getBuildVector(VT, DL, PAmts); 6449 AVal = DAG.getBuildVector(VT, DL, AAmts); 6450 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 6451 QVal = DAG.getBuildVector(VT, DL, QAmts); 6452 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 6453 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 && 6454 QAmts.size() == 1 && 6455 "Expected matchUnaryPredicate to return one element for scalable " 6456 "vectors"); 6457 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 6458 AVal = DAG.getSplatVector(VT, DL, AAmts[0]); 6459 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 6460 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 6461 } else { 6462 assert(isa<ConstantSDNode>(D) && "Expected a constant"); 6463 PVal = PAmts[0]; 6464 AVal = AAmts[0]; 6465 KVal = KAmts[0]; 6466 QVal = QAmts[0]; 6467 } 6468 6469 // (mul N, P) 6470 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 6471 Created.push_back(Op0.getNode()); 6472 6473 if (NeedToApplyOffset) { 6474 // We need ADD to do this. 6475 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT)) 6476 return SDValue(); 6477 6478 // (add (mul N, P), A) 6479 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal); 6480 Created.push_back(Op0.getNode()); 6481 } 6482 6483 // Rotate right only if any divisor was even. We avoid rotates for all-odd 6484 // divisors as a performance improvement, since rotating by 0 is a no-op. 6485 if (HadEvenDivisor) { 6486 // We need ROTR to do this. 6487 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 6488 return SDValue(); 6489 // SREM: (rotr (add (mul N, P), A), K) 6490 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal); 6491 Created.push_back(Op0.getNode()); 6492 } 6493 6494 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q) 6495 SDValue Fold = 6496 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 6497 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 6498 6499 // If we didn't have lanes with INT_MIN divisor, then we're done. 6500 if (!HadIntMinDivisor) 6501 return Fold; 6502 6503 // That fold is only valid for positive divisors. Which effectively means, 6504 // it is invalid for INT_MIN divisors. So if we have such a lane, 6505 // we must fix-up results for said lanes. 6506 assert(VT.isVector() && "Can/should only get here for vectors."); 6507 6508 // NOTE: we avoid letting illegal types through even if we're before legalize 6509 // ops – legalization has a hard time producing good code for the code that 6510 // follows. 6511 if (!isOperationLegalOrCustom(ISD::SETEQ, VT) || 6512 !isOperationLegalOrCustom(ISD::AND, VT) || 6513 !isOperationLegalOrCustom(Cond, VT) || 6514 !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) 6515 return SDValue(); 6516 6517 Created.push_back(Fold.getNode()); 6518 6519 SDValue IntMin = DAG.getConstant( 6520 APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT); 6521 SDValue IntMax = DAG.getConstant( 6522 APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT); 6523 SDValue Zero = 6524 DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT); 6525 6526 // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded. 6527 SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ); 6528 Created.push_back(DivisorIsIntMin.getNode()); 6529 6530 // (N s% INT_MIN) ==/!= 0 <--> (N & INT_MAX) ==/!= 0 6531 SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax); 6532 Created.push_back(Masked.getNode()); 6533 SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond); 6534 Created.push_back(MaskedIsZero.getNode()); 6535 6536 // To produce final result we need to blend 2 vectors: 'SetCC' and 6537 // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick 6538 // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is 6539 // constant-folded, select can get lowered to a shuffle with constant mask. 6540 SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin, 6541 MaskedIsZero, Fold); 6542 6543 return Blended; 6544 } 6545 6546 bool TargetLowering:: 6547 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 6548 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 6549 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 6550 "be a constant integer"); 6551 return true; 6552 } 6553 6554 return false; 6555 } 6556 6557 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 6558 const DenormalMode &Mode) const { 6559 SDLoc DL(Op); 6560 EVT VT = Op.getValueType(); 6561 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6562 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 6563 // Testing it with denormal inputs to avoid wrong estimate. 6564 if (Mode.Input == DenormalMode::IEEE) { 6565 // This is specifically a check for the handling of denormal inputs, 6566 // not the result. 6567 6568 // Test = fabs(X) < SmallestNormal 6569 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 6570 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 6571 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 6572 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 6573 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 6574 } 6575 // Test = X == 0.0 6576 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 6577 } 6578 6579 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 6580 bool LegalOps, bool OptForSize, 6581 NegatibleCost &Cost, 6582 unsigned Depth) const { 6583 // fneg is removable even if it has multiple uses. 6584 if (Op.getOpcode() == ISD::FNEG) { 6585 Cost = NegatibleCost::Cheaper; 6586 return Op.getOperand(0); 6587 } 6588 6589 // Don't recurse exponentially. 6590 if (Depth > SelectionDAG::MaxRecursionDepth) 6591 return SDValue(); 6592 6593 // Pre-increment recursion depth for use in recursive calls. 6594 ++Depth; 6595 const SDNodeFlags Flags = Op->getFlags(); 6596 const TargetOptions &Options = DAG.getTarget().Options; 6597 EVT VT = Op.getValueType(); 6598 unsigned Opcode = Op.getOpcode(); 6599 6600 // Don't allow anything with multiple uses unless we know it is free. 6601 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) { 6602 bool IsFreeExtend = Opcode == ISD::FP_EXTEND && 6603 isFPExtFree(VT, Op.getOperand(0).getValueType()); 6604 if (!IsFreeExtend) 6605 return SDValue(); 6606 } 6607 6608 auto RemoveDeadNode = [&](SDValue N) { 6609 if (N && N.getNode()->use_empty()) 6610 DAG.RemoveDeadNode(N.getNode()); 6611 }; 6612 6613 SDLoc DL(Op); 6614 6615 // Because getNegatedExpression can delete nodes we need a handle to keep 6616 // temporary nodes alive in case the recursion manages to create an identical 6617 // node. 6618 std::list<HandleSDNode> Handles; 6619 6620 switch (Opcode) { 6621 case ISD::ConstantFP: { 6622 // Don't invert constant FP values after legalization unless the target says 6623 // the negated constant is legal. 6624 bool IsOpLegal = 6625 isOperationLegal(ISD::ConstantFP, VT) || 6626 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT, 6627 OptForSize); 6628 6629 if (LegalOps && !IsOpLegal) 6630 break; 6631 6632 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 6633 V.changeSign(); 6634 SDValue CFP = DAG.getConstantFP(V, DL, VT); 6635 6636 // If we already have the use of the negated floating constant, it is free 6637 // to negate it even it has multiple uses. 6638 if (!Op.hasOneUse() && CFP.use_empty()) 6639 break; 6640 Cost = NegatibleCost::Neutral; 6641 return CFP; 6642 } 6643 case ISD::BUILD_VECTOR: { 6644 // Only permit BUILD_VECTOR of constants. 6645 if (llvm::any_of(Op->op_values(), [&](SDValue N) { 6646 return !N.isUndef() && !isa<ConstantFPSDNode>(N); 6647 })) 6648 break; 6649 6650 bool IsOpLegal = 6651 (isOperationLegal(ISD::ConstantFP, VT) && 6652 isOperationLegal(ISD::BUILD_VECTOR, VT)) || 6653 llvm::all_of(Op->op_values(), [&](SDValue N) { 6654 return N.isUndef() || 6655 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT, 6656 OptForSize); 6657 }); 6658 6659 if (LegalOps && !IsOpLegal) 6660 break; 6661 6662 SmallVector<SDValue, 4> Ops; 6663 for (SDValue C : Op->op_values()) { 6664 if (C.isUndef()) { 6665 Ops.push_back(C); 6666 continue; 6667 } 6668 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF(); 6669 V.changeSign(); 6670 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType())); 6671 } 6672 Cost = NegatibleCost::Neutral; 6673 return DAG.getBuildVector(VT, DL, Ops); 6674 } 6675 case ISD::FADD: { 6676 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6677 break; 6678 6679 // After operation legalization, it might not be legal to create new FSUBs. 6680 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT)) 6681 break; 6682 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6683 6684 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y) 6685 NegatibleCost CostX = NegatibleCost::Expensive; 6686 SDValue NegX = 6687 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6688 // Prevent this node from being deleted by the next call. 6689 if (NegX) 6690 Handles.emplace_back(NegX); 6691 6692 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X) 6693 NegatibleCost CostY = NegatibleCost::Expensive; 6694 SDValue NegY = 6695 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6696 6697 // We're done with the handles. 6698 Handles.clear(); 6699 6700 // Negate the X if its cost is less or equal than Y. 6701 if (NegX && (CostX <= CostY)) { 6702 Cost = CostX; 6703 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags); 6704 if (NegY != N) 6705 RemoveDeadNode(NegY); 6706 return N; 6707 } 6708 6709 // Negate the Y if it is not expensive. 6710 if (NegY) { 6711 Cost = CostY; 6712 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags); 6713 if (NegX != N) 6714 RemoveDeadNode(NegX); 6715 return N; 6716 } 6717 break; 6718 } 6719 case ISD::FSUB: { 6720 // We can't turn -(A-B) into B-A when we honor signed zeros. 6721 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6722 break; 6723 6724 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6725 // fold (fneg (fsub 0, Y)) -> Y 6726 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true)) 6727 if (C->isZero()) { 6728 Cost = NegatibleCost::Cheaper; 6729 return Y; 6730 } 6731 6732 // fold (fneg (fsub X, Y)) -> (fsub Y, X) 6733 Cost = NegatibleCost::Neutral; 6734 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags); 6735 } 6736 case ISD::FMUL: 6737 case ISD::FDIV: { 6738 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6739 6740 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 6741 NegatibleCost CostX = NegatibleCost::Expensive; 6742 SDValue NegX = 6743 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6744 // Prevent this node from being deleted by the next call. 6745 if (NegX) 6746 Handles.emplace_back(NegX); 6747 6748 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 6749 NegatibleCost CostY = NegatibleCost::Expensive; 6750 SDValue NegY = 6751 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6752 6753 // We're done with the handles. 6754 Handles.clear(); 6755 6756 // Negate the X if its cost is less or equal than Y. 6757 if (NegX && (CostX <= CostY)) { 6758 Cost = CostX; 6759 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags); 6760 if (NegY != N) 6761 RemoveDeadNode(NegY); 6762 return N; 6763 } 6764 6765 // Ignore X * 2.0 because that is expected to be canonicalized to X + X. 6766 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1))) 6767 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL) 6768 break; 6769 6770 // Negate the Y if it is not expensive. 6771 if (NegY) { 6772 Cost = CostY; 6773 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags); 6774 if (NegX != N) 6775 RemoveDeadNode(NegX); 6776 return N; 6777 } 6778 break; 6779 } 6780 case ISD::FMA: 6781 case ISD::FMAD: { 6782 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6783 break; 6784 6785 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2); 6786 NegatibleCost CostZ = NegatibleCost::Expensive; 6787 SDValue NegZ = 6788 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth); 6789 // Give up if fail to negate the Z. 6790 if (!NegZ) 6791 break; 6792 6793 // Prevent this node from being deleted by the next two calls. 6794 Handles.emplace_back(NegZ); 6795 6796 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z)) 6797 NegatibleCost CostX = NegatibleCost::Expensive; 6798 SDValue NegX = 6799 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6800 // Prevent this node from being deleted by the next call. 6801 if (NegX) 6802 Handles.emplace_back(NegX); 6803 6804 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z)) 6805 NegatibleCost CostY = NegatibleCost::Expensive; 6806 SDValue NegY = 6807 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6808 6809 // We're done with the handles. 6810 Handles.clear(); 6811 6812 // Negate the X if its cost is less or equal than Y. 6813 if (NegX && (CostX <= CostY)) { 6814 Cost = std::min(CostX, CostZ); 6815 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags); 6816 if (NegY != N) 6817 RemoveDeadNode(NegY); 6818 return N; 6819 } 6820 6821 // Negate the Y if it is not expensive. 6822 if (NegY) { 6823 Cost = std::min(CostY, CostZ); 6824 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags); 6825 if (NegX != N) 6826 RemoveDeadNode(NegX); 6827 return N; 6828 } 6829 break; 6830 } 6831 6832 case ISD::FP_EXTEND: 6833 case ISD::FSIN: 6834 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6835 OptForSize, Cost, Depth)) 6836 return DAG.getNode(Opcode, DL, VT, NegV); 6837 break; 6838 case ISD::FP_ROUND: 6839 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6840 OptForSize, Cost, Depth)) 6841 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1)); 6842 break; 6843 } 6844 6845 return SDValue(); 6846 } 6847 6848 //===----------------------------------------------------------------------===// 6849 // Legalization Utilities 6850 //===----------------------------------------------------------------------===// 6851 6852 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, 6853 SDValue LHS, SDValue RHS, 6854 SmallVectorImpl<SDValue> &Result, 6855 EVT HiLoVT, SelectionDAG &DAG, 6856 MulExpansionKind Kind, SDValue LL, 6857 SDValue LH, SDValue RL, SDValue RH) const { 6858 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 6859 Opcode == ISD::SMUL_LOHI); 6860 6861 bool HasMULHS = (Kind == MulExpansionKind::Always) || 6862 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 6863 bool HasMULHU = (Kind == MulExpansionKind::Always) || 6864 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 6865 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 6866 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 6867 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 6868 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 6869 6870 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 6871 return false; 6872 6873 unsigned OuterBitSize = VT.getScalarSizeInBits(); 6874 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 6875 6876 // LL, LH, RL, and RH must be either all NULL or all set to a value. 6877 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 6878 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 6879 6880 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 6881 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 6882 bool Signed) -> bool { 6883 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 6884 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 6885 Hi = SDValue(Lo.getNode(), 1); 6886 return true; 6887 } 6888 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 6889 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 6890 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 6891 return true; 6892 } 6893 return false; 6894 }; 6895 6896 SDValue Lo, Hi; 6897 6898 if (!LL.getNode() && !RL.getNode() && 6899 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6900 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 6901 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 6902 } 6903 6904 if (!LL.getNode()) 6905 return false; 6906 6907 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 6908 if (DAG.MaskedValueIsZero(LHS, HighMask) && 6909 DAG.MaskedValueIsZero(RHS, HighMask)) { 6910 // The inputs are both zero-extended. 6911 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 6912 Result.push_back(Lo); 6913 Result.push_back(Hi); 6914 if (Opcode != ISD::MUL) { 6915 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6916 Result.push_back(Zero); 6917 Result.push_back(Zero); 6918 } 6919 return true; 6920 } 6921 } 6922 6923 if (!VT.isVector() && Opcode == ISD::MUL && 6924 DAG.ComputeNumSignBits(LHS) > InnerBitSize && 6925 DAG.ComputeNumSignBits(RHS) > InnerBitSize) { 6926 // The input values are both sign-extended. 6927 // TODO non-MUL case? 6928 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 6929 Result.push_back(Lo); 6930 Result.push_back(Hi); 6931 return true; 6932 } 6933 } 6934 6935 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 6936 EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout()); 6937 SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy); 6938 6939 if (!LH.getNode() && !RH.getNode() && 6940 isOperationLegalOrCustom(ISD::SRL, VT) && 6941 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6942 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 6943 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 6944 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 6945 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 6946 } 6947 6948 if (!LH.getNode()) 6949 return false; 6950 6951 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 6952 return false; 6953 6954 Result.push_back(Lo); 6955 6956 if (Opcode == ISD::MUL) { 6957 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 6958 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 6959 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 6960 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 6961 Result.push_back(Hi); 6962 return true; 6963 } 6964 6965 // Compute the full width result. 6966 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 6967 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 6968 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6969 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 6970 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 6971 }; 6972 6973 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6974 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 6975 return false; 6976 6977 // This is effectively the add part of a multiply-add of half-sized operands, 6978 // so it cannot overflow. 6979 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 6980 6981 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 6982 return false; 6983 6984 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6985 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6986 6987 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) && 6988 isOperationLegalOrCustom(ISD::ADDE, VT)); 6989 if (UseGlue) 6990 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 6991 Merge(Lo, Hi)); 6992 else 6993 Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next, 6994 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType)); 6995 6996 SDValue Carry = Next.getValue(1); 6997 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6998 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 6999 7000 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 7001 return false; 7002 7003 if (UseGlue) 7004 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 7005 Carry); 7006 else 7007 Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi, 7008 Zero, Carry); 7009 7010 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 7011 7012 if (Opcode == ISD::SMUL_LOHI) { 7013 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 7014 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 7015 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 7016 7017 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 7018 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 7019 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 7020 } 7021 7022 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7023 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 7024 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 7025 return true; 7026 } 7027 7028 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 7029 SelectionDAG &DAG, MulExpansionKind Kind, 7030 SDValue LL, SDValue LH, SDValue RL, 7031 SDValue RH) const { 7032 SmallVector<SDValue, 2> Result; 7033 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N), 7034 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 7035 DAG, Kind, LL, LH, RL, RH); 7036 if (Ok) { 7037 assert(Result.size() == 2); 7038 Lo = Result[0]; 7039 Hi = Result[1]; 7040 } 7041 return Ok; 7042 } 7043 7044 // Check that (every element of) Z is undef or not an exact multiple of BW. 7045 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) { 7046 return ISD::matchUnaryPredicate( 7047 Z, 7048 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; }, 7049 true); 7050 } 7051 7052 SDValue TargetLowering::expandFunnelShift(SDNode *Node, 7053 SelectionDAG &DAG) const { 7054 EVT VT = Node->getValueType(0); 7055 7056 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 7057 !isOperationLegalOrCustom(ISD::SRL, VT) || 7058 !isOperationLegalOrCustom(ISD::SUB, VT) || 7059 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 7060 return SDValue(); 7061 7062 SDValue X = Node->getOperand(0); 7063 SDValue Y = Node->getOperand(1); 7064 SDValue Z = Node->getOperand(2); 7065 7066 unsigned BW = VT.getScalarSizeInBits(); 7067 bool IsFSHL = Node->getOpcode() == ISD::FSHL; 7068 SDLoc DL(SDValue(Node, 0)); 7069 7070 EVT ShVT = Z.getValueType(); 7071 7072 // If a funnel shift in the other direction is more supported, use it. 7073 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL; 7074 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 7075 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) { 7076 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 7077 // fshl X, Y, Z -> fshr X, Y, -Z 7078 // fshr X, Y, Z -> fshl X, Y, -Z 7079 SDValue Zero = DAG.getConstant(0, DL, ShVT); 7080 Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z); 7081 } else { 7082 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z 7083 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z 7084 SDValue One = DAG.getConstant(1, DL, ShVT); 7085 if (IsFSHL) { 7086 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 7087 X = DAG.getNode(ISD::SRL, DL, VT, X, One); 7088 } else { 7089 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 7090 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One); 7091 } 7092 Z = DAG.getNOT(DL, Z, ShVT); 7093 } 7094 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z); 7095 } 7096 7097 SDValue ShX, ShY; 7098 SDValue ShAmt, InvShAmt; 7099 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 7100 // fshl: X << C | Y >> (BW - C) 7101 // fshr: X << (BW - C) | Y >> C 7102 // where C = Z % BW is not zero 7103 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7104 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 7105 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt); 7106 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt); 7107 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt); 7108 } else { 7109 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW)) 7110 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW) 7111 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT); 7112 if (isPowerOf2_32(BW)) { 7113 // Z % BW -> Z & (BW - 1) 7114 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask); 7115 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1) 7116 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask); 7117 } else { 7118 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 7119 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 7120 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt); 7121 } 7122 7123 SDValue One = DAG.getConstant(1, DL, ShVT); 7124 if (IsFSHL) { 7125 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt); 7126 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One); 7127 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt); 7128 } else { 7129 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One); 7130 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt); 7131 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt); 7132 } 7133 } 7134 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY); 7135 } 7136 7137 // TODO: Merge with expandFunnelShift. 7138 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps, 7139 SelectionDAG &DAG) const { 7140 EVT VT = Node->getValueType(0); 7141 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 7142 bool IsLeft = Node->getOpcode() == ISD::ROTL; 7143 SDValue Op0 = Node->getOperand(0); 7144 SDValue Op1 = Node->getOperand(1); 7145 SDLoc DL(SDValue(Node, 0)); 7146 7147 EVT ShVT = Op1.getValueType(); 7148 SDValue Zero = DAG.getConstant(0, DL, ShVT); 7149 7150 // If a rotate in the other direction is more supported, use it. 7151 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL; 7152 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 7153 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) { 7154 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 7155 return DAG.getNode(RevRot, DL, VT, Op0, Sub); 7156 } 7157 7158 if (!AllowVectorOps && VT.isVector() && 7159 (!isOperationLegalOrCustom(ISD::SHL, VT) || 7160 !isOperationLegalOrCustom(ISD::SRL, VT) || 7161 !isOperationLegalOrCustom(ISD::SUB, VT) || 7162 !isOperationLegalOrCustomOrPromote(ISD::OR, VT) || 7163 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 7164 return SDValue(); 7165 7166 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL; 7167 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL; 7168 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 7169 SDValue ShVal; 7170 SDValue HsVal; 7171 if (isPowerOf2_32(EltSizeInBits)) { 7172 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1)) 7173 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1)) 7174 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 7175 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC); 7176 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 7177 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC); 7178 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt); 7179 } else { 7180 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w)) 7181 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w)) 7182 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 7183 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC); 7184 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 7185 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt); 7186 SDValue One = DAG.getConstant(1, DL, ShVT); 7187 HsVal = 7188 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt); 7189 } 7190 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal); 7191 } 7192 7193 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi, 7194 SelectionDAG &DAG) const { 7195 assert(Node->getNumOperands() == 3 && "Not a double-shift!"); 7196 EVT VT = Node->getValueType(0); 7197 unsigned VTBits = VT.getScalarSizeInBits(); 7198 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected"); 7199 7200 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS; 7201 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS; 7202 SDValue ShOpLo = Node->getOperand(0); 7203 SDValue ShOpHi = Node->getOperand(1); 7204 SDValue ShAmt = Node->getOperand(2); 7205 EVT ShAmtVT = ShAmt.getValueType(); 7206 EVT ShAmtCCVT = 7207 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT); 7208 SDLoc dl(Node); 7209 7210 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and 7211 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized 7212 // away during isel. 7213 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 7214 DAG.getConstant(VTBits - 1, dl, ShAmtVT)); 7215 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 7216 DAG.getConstant(VTBits - 1, dl, ShAmtVT)) 7217 : DAG.getConstant(0, dl, VT); 7218 7219 SDValue Tmp2, Tmp3; 7220 if (IsSHL) { 7221 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt); 7222 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt); 7223 } else { 7224 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt); 7225 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt); 7226 } 7227 7228 // If the shift amount is larger or equal than the width of a part we don't 7229 // use the result from the FSHL/FSHR. Insert a test and select the appropriate 7230 // values for large shift amounts. 7231 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt, 7232 DAG.getConstant(VTBits, dl, ShAmtVT)); 7233 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode, 7234 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE); 7235 7236 if (IsSHL) { 7237 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 7238 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 7239 } else { 7240 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2); 7241 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3); 7242 } 7243 } 7244 7245 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 7246 SelectionDAG &DAG) const { 7247 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 7248 SDValue Src = Node->getOperand(OpNo); 7249 EVT SrcVT = Src.getValueType(); 7250 EVT DstVT = Node->getValueType(0); 7251 SDLoc dl(SDValue(Node, 0)); 7252 7253 // FIXME: Only f32 to i64 conversions are supported. 7254 if (SrcVT != MVT::f32 || DstVT != MVT::i64) 7255 return false; 7256 7257 if (Node->isStrictFPOpcode()) 7258 // When a NaN is converted to an integer a trap is allowed. We can't 7259 // use this expansion here because it would eliminate that trap. Other 7260 // traps are also allowed and cannot be eliminated. See 7261 // IEEE 754-2008 sec 5.8. 7262 return false; 7263 7264 // Expand f32 -> i64 conversion 7265 // This algorithm comes from compiler-rt's implementation of fixsfdi: 7266 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c 7267 unsigned SrcEltBits = SrcVT.getScalarSizeInBits(); 7268 EVT IntVT = SrcVT.changeTypeToInteger(); 7269 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout()); 7270 7271 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 7272 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 7273 SDValue Bias = DAG.getConstant(127, dl, IntVT); 7274 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT); 7275 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT); 7276 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 7277 7278 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src); 7279 7280 SDValue ExponentBits = DAG.getNode( 7281 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 7282 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT)); 7283 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 7284 7285 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT, 7286 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 7287 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT)); 7288 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT); 7289 7290 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 7291 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 7292 DAG.getConstant(0x00800000, dl, IntVT)); 7293 7294 R = DAG.getZExtOrTrunc(R, dl, DstVT); 7295 7296 R = DAG.getSelectCC( 7297 dl, Exponent, ExponentLoBit, 7298 DAG.getNode(ISD::SHL, dl, DstVT, R, 7299 DAG.getZExtOrTrunc( 7300 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 7301 dl, IntShVT)), 7302 DAG.getNode(ISD::SRL, dl, DstVT, R, 7303 DAG.getZExtOrTrunc( 7304 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 7305 dl, IntShVT)), 7306 ISD::SETGT); 7307 7308 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT, 7309 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign); 7310 7311 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 7312 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT); 7313 return true; 7314 } 7315 7316 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result, 7317 SDValue &Chain, 7318 SelectionDAG &DAG) const { 7319 SDLoc dl(SDValue(Node, 0)); 7320 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 7321 SDValue Src = Node->getOperand(OpNo); 7322 7323 EVT SrcVT = Src.getValueType(); 7324 EVT DstVT = Node->getValueType(0); 7325 EVT SetCCVT = 7326 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 7327 EVT DstSetCCVT = 7328 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 7329 7330 // Only expand vector types if we have the appropriate vector bit operations. 7331 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT : 7332 ISD::FP_TO_SINT; 7333 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) || 7334 !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT))) 7335 return false; 7336 7337 // If the maximum float value is smaller then the signed integer range, 7338 // the destination signmask can't be represented by the float, so we can 7339 // just use FP_TO_SINT directly. 7340 const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT); 7341 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits())); 7342 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits()); 7343 if (APFloat::opOverflow & 7344 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) { 7345 if (Node->isStrictFPOpcode()) { 7346 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 7347 { Node->getOperand(0), Src }); 7348 Chain = Result.getValue(1); 7349 } else 7350 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 7351 return true; 7352 } 7353 7354 // Don't expand it if there isn't cheap fsub instruction. 7355 if (!isOperationLegalOrCustom( 7356 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT)) 7357 return false; 7358 7359 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 7360 SDValue Sel; 7361 7362 if (Node->isStrictFPOpcode()) { 7363 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 7364 Node->getOperand(0), /*IsSignaling*/ true); 7365 Chain = Sel.getValue(1); 7366 } else { 7367 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT); 7368 } 7369 7370 bool Strict = Node->isStrictFPOpcode() || 7371 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false); 7372 7373 if (Strict) { 7374 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the 7375 // signmask then offset (the result of which should be fully representable). 7376 // Sel = Src < 0x8000000000000000 7377 // FltOfs = select Sel, 0, 0x8000000000000000 7378 // IntOfs = select Sel, 0, 0x8000000000000000 7379 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 7380 7381 // TODO: Should any fast-math-flags be set for the FSUB? 7382 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel, 7383 DAG.getConstantFP(0.0, dl, SrcVT), Cst); 7384 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 7385 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel, 7386 DAG.getConstant(0, dl, DstVT), 7387 DAG.getConstant(SignMask, dl, DstVT)); 7388 SDValue SInt; 7389 if (Node->isStrictFPOpcode()) { 7390 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other }, 7391 { Chain, Src, FltOfs }); 7392 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 7393 { Val.getValue(1), Val }); 7394 Chain = SInt.getValue(1); 7395 } else { 7396 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs); 7397 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val); 7398 } 7399 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 7400 } else { 7401 // Expand based on maximum range of FP_TO_SINT: 7402 // True = fp_to_sint(Src) 7403 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000) 7404 // Result = select (Src < 0x8000000000000000), True, False 7405 7406 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 7407 // TODO: Should any fast-math-flags be set for the FSUB? 7408 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, 7409 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 7410 False = DAG.getNode(ISD::XOR, dl, DstVT, False, 7411 DAG.getConstant(SignMask, dl, DstVT)); 7412 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 7413 Result = DAG.getSelect(dl, DstVT, Sel, True, False); 7414 } 7415 return true; 7416 } 7417 7418 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result, 7419 SDValue &Chain, 7420 SelectionDAG &DAG) const { 7421 // This transform is not correct for converting 0 when rounding mode is set 7422 // to round toward negative infinity which will produce -0.0. So disable under 7423 // strictfp. 7424 if (Node->isStrictFPOpcode()) 7425 return false; 7426 7427 SDValue Src = Node->getOperand(0); 7428 EVT SrcVT = Src.getValueType(); 7429 EVT DstVT = Node->getValueType(0); 7430 7431 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64) 7432 return false; 7433 7434 // Only expand vector types if we have the appropriate vector bit operations. 7435 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 7436 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 7437 !isOperationLegalOrCustom(ISD::FSUB, DstVT) || 7438 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 7439 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 7440 return false; 7441 7442 SDLoc dl(SDValue(Node, 0)); 7443 EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout()); 7444 7445 // Implementation of unsigned i64 to f64 following the algorithm in 7446 // __floatundidf in compiler_rt. This implementation performs rounding 7447 // correctly in all rounding modes with the exception of converting 0 7448 // when rounding toward negative infinity. In that case the fsub will produce 7449 // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect. 7450 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT); 7451 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP( 7452 BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT); 7453 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT); 7454 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT); 7455 SDValue HiShift = DAG.getConstant(32, dl, ShiftVT); 7456 7457 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask); 7458 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift); 7459 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52); 7460 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84); 7461 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr); 7462 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr); 7463 SDValue HiSub = 7464 DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52); 7465 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub); 7466 return true; 7467 } 7468 7469 SDValue 7470 TargetLowering::createSelectForFMINNUM_FMAXNUM(SDNode *Node, 7471 SelectionDAG &DAG) const { 7472 unsigned Opcode = Node->getOpcode(); 7473 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM || 7474 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) && 7475 "Wrong opcode"); 7476 7477 if (Node->getFlags().hasNoNaNs()) { 7478 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT; 7479 SDValue Op1 = Node->getOperand(0); 7480 SDValue Op2 = Node->getOperand(1); 7481 SDValue SelCC = DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred); 7482 // Copy FMF flags, but always set the no-signed-zeros flag 7483 // as this is implied by the FMINNUM/FMAXNUM semantics. 7484 SDNodeFlags Flags = Node->getFlags(); 7485 Flags.setNoSignedZeros(true); 7486 SelCC->setFlags(Flags); 7487 return SelCC; 7488 } 7489 7490 return SDValue(); 7491 } 7492 7493 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node, 7494 SelectionDAG &DAG) const { 7495 SDLoc dl(Node); 7496 unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ? 7497 ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 7498 EVT VT = Node->getValueType(0); 7499 7500 if (VT.isScalableVector()) 7501 report_fatal_error( 7502 "Expanding fminnum/fmaxnum for scalable vectors is undefined."); 7503 7504 if (isOperationLegalOrCustom(NewOp, VT)) { 7505 SDValue Quiet0 = Node->getOperand(0); 7506 SDValue Quiet1 = Node->getOperand(1); 7507 7508 if (!Node->getFlags().hasNoNaNs()) { 7509 // Insert canonicalizes if it's possible we need to quiet to get correct 7510 // sNaN behavior. 7511 if (!DAG.isKnownNeverSNaN(Quiet0)) { 7512 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0, 7513 Node->getFlags()); 7514 } 7515 if (!DAG.isKnownNeverSNaN(Quiet1)) { 7516 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1, 7517 Node->getFlags()); 7518 } 7519 } 7520 7521 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags()); 7522 } 7523 7524 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that 7525 // instead if there are no NaNs. 7526 if (Node->getFlags().hasNoNaNs()) { 7527 unsigned IEEE2018Op = 7528 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM; 7529 if (isOperationLegalOrCustom(IEEE2018Op, VT)) { 7530 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0), 7531 Node->getOperand(1), Node->getFlags()); 7532 } 7533 } 7534 7535 if (SDValue SelCC = createSelectForFMINNUM_FMAXNUM(Node, DAG)) 7536 return SelCC; 7537 7538 return SDValue(); 7539 } 7540 7541 SDValue TargetLowering::expandIS_FPCLASS(EVT ResultVT, SDValue Op, 7542 unsigned Test, SDNodeFlags Flags, 7543 const SDLoc &DL, 7544 SelectionDAG &DAG) const { 7545 EVT OperandVT = Op.getValueType(); 7546 assert(OperandVT.isFloatingPoint()); 7547 7548 // Degenerated cases. 7549 if (Test == 0) 7550 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT); 7551 if ((Test & fcAllFlags) == fcAllFlags) 7552 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT); 7553 7554 // PPC double double is a pair of doubles, of which the higher part determines 7555 // the value class. 7556 if (OperandVT == MVT::ppcf128) { 7557 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op, 7558 DAG.getConstant(1, DL, MVT::i32)); 7559 OperandVT = MVT::f64; 7560 } 7561 7562 // Some checks may be represented as inversion of simpler check, for example 7563 // "inf|normal|subnormal|zero" => !"nan". 7564 bool IsInverted = false; 7565 if (unsigned InvertedCheck = getInvertedFPClassTest(Test)) { 7566 IsInverted = true; 7567 Test = InvertedCheck; 7568 } 7569 7570 // Floating-point type properties. 7571 EVT ScalarFloatVT = OperandVT.getScalarType(); 7572 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext()); 7573 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics(); 7574 bool IsF80 = (ScalarFloatVT == MVT::f80); 7575 7576 // Some checks can be implemented using float comparisons, if floating point 7577 // exceptions are ignored. 7578 if (Flags.hasNoFPExcept() && 7579 isOperationLegalOrCustom(ISD::SETCC, OperandVT.getScalarType())) { 7580 if (Test == fcZero) 7581 return DAG.getSetCC(DL, ResultVT, Op, 7582 DAG.getConstantFP(0.0, DL, OperandVT), 7583 IsInverted ? ISD::SETUNE : ISD::SETOEQ); 7584 if (Test == fcNan) 7585 return DAG.getSetCC(DL, ResultVT, Op, Op, 7586 IsInverted ? ISD::SETO : ISD::SETUO); 7587 } 7588 7589 // In the general case use integer operations. 7590 unsigned BitSize = OperandVT.getScalarSizeInBits(); 7591 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), BitSize); 7592 if (OperandVT.isVector()) 7593 IntVT = EVT::getVectorVT(*DAG.getContext(), IntVT, 7594 OperandVT.getVectorElementCount()); 7595 SDValue OpAsInt = DAG.getBitcast(IntVT, Op); 7596 7597 // Various masks. 7598 APInt SignBit = APInt::getSignMask(BitSize); 7599 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign. 7600 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit. 7601 const unsigned ExplicitIntBitInF80 = 63; 7602 APInt ExpMask = Inf; 7603 if (IsF80) 7604 ExpMask.clearBit(ExplicitIntBitInF80); 7605 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf; 7606 APInt QNaNBitMask = 7607 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1); 7608 APInt InvertionMask = APInt::getAllOnesValue(ResultVT.getScalarSizeInBits()); 7609 7610 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT); 7611 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT); 7612 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT); 7613 SDValue ZeroV = DAG.getConstant(0, DL, IntVT); 7614 SDValue InfV = DAG.getConstant(Inf, DL, IntVT); 7615 SDValue ResultInvertionMask = DAG.getConstant(InvertionMask, DL, ResultVT); 7616 7617 SDValue Res; 7618 const auto appendResult = [&](SDValue PartialRes) { 7619 if (PartialRes) { 7620 if (Res) 7621 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes); 7622 else 7623 Res = PartialRes; 7624 } 7625 }; 7626 7627 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set. 7628 const auto getIntBitIsSet = [&]() -> SDValue { 7629 if (!IntBitIsSetV) { 7630 APInt IntBitMask(BitSize, 0); 7631 IntBitMask.setBit(ExplicitIntBitInF80); 7632 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT); 7633 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV); 7634 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE); 7635 } 7636 return IntBitIsSetV; 7637 }; 7638 7639 // Split the value into sign bit and absolute value. 7640 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV); 7641 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt, 7642 DAG.getConstant(0.0, DL, IntVT), ISD::SETLT); 7643 7644 // Tests that involve more than one class should be processed first. 7645 SDValue PartialRes; 7646 7647 if (IsF80) 7648 ; // Detect finite numbers of f80 by checking individual classes because 7649 // they have different settings of the explicit integer bit. 7650 else if ((Test & fcFinite) == fcFinite) { 7651 // finite(V) ==> abs(V) < exp_mask 7652 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 7653 Test &= ~fcFinite; 7654 } else if ((Test & fcFinite) == fcPosFinite) { 7655 // finite(V) && V > 0 ==> V < exp_mask 7656 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT); 7657 Test &= ~fcPosFinite; 7658 } else if ((Test & fcFinite) == fcNegFinite) { 7659 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1 7660 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT); 7661 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7662 Test &= ~fcNegFinite; 7663 } 7664 appendResult(PartialRes); 7665 7666 // Check for individual classes. 7667 7668 if (unsigned PartialCheck = Test & fcZero) { 7669 if (PartialCheck == fcPosZero) 7670 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ); 7671 else if (PartialCheck == fcZero) 7672 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ); 7673 else // ISD::fcNegZero 7674 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ); 7675 appendResult(PartialRes); 7676 } 7677 7678 if (unsigned PartialCheck = Test & fcInf) { 7679 if (PartialCheck == fcPosInf) 7680 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ); 7681 else if (PartialCheck == fcInf) 7682 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ); 7683 else { // ISD::fcNegInf 7684 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt(); 7685 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT); 7686 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ); 7687 } 7688 appendResult(PartialRes); 7689 } 7690 7691 if (unsigned PartialCheck = Test & fcNan) { 7692 APInt InfWithQnanBit = Inf | QNaNBitMask; 7693 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT); 7694 if (PartialCheck == fcNan) { 7695 // isnan(V) ==> abs(V) > int(inf) 7696 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 7697 if (IsF80) { 7698 // Recognize unsupported values as NaNs for compatibility with glibc. 7699 // In them (exp(V)==0) == int_bit. 7700 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV); 7701 SDValue ExpIsZero = 7702 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ); 7703 SDValue IsPseudo = 7704 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ); 7705 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo); 7706 } 7707 } else if (PartialCheck == fcQNan) { 7708 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit) 7709 PartialRes = 7710 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE); 7711 } else { // ISD::fcSNan 7712 // issignaling(V) ==> abs(V) > unsigned(Inf) && 7713 // abs(V) < (unsigned(Inf) | quiet_bit) 7714 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT); 7715 SDValue IsNotQnan = 7716 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT); 7717 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan); 7718 } 7719 appendResult(PartialRes); 7720 } 7721 7722 if (unsigned PartialCheck = Test & fcSubnormal) { 7723 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set) 7724 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set) 7725 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV; 7726 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT); 7727 SDValue VMinusOneV = 7728 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT)); 7729 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT); 7730 if (PartialCheck == fcNegSubnormal) 7731 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7732 appendResult(PartialRes); 7733 } 7734 7735 if (unsigned PartialCheck = Test & fcNormal) { 7736 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1)) 7737 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1)); 7738 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT); 7739 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV); 7740 APInt ExpLimit = ExpMask - ExpLSB; 7741 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT); 7742 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT); 7743 if (PartialCheck == fcNegNormal) 7744 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV); 7745 else if (PartialCheck == fcPosNormal) { 7746 SDValue PosSignV = 7747 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInvertionMask); 7748 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV); 7749 } 7750 if (IsF80) 7751 PartialRes = 7752 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet()); 7753 appendResult(PartialRes); 7754 } 7755 7756 if (!Res) 7757 return DAG.getConstant(IsInverted, DL, ResultVT); 7758 if (IsInverted) 7759 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInvertionMask); 7760 return Res; 7761 } 7762 7763 // Only expand vector types if we have the appropriate vector bit operations. 7764 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) { 7765 assert(VT.isVector() && "Expected vector type"); 7766 unsigned Len = VT.getScalarSizeInBits(); 7767 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) && 7768 TLI.isOperationLegalOrCustom(ISD::SUB, VT) && 7769 TLI.isOperationLegalOrCustom(ISD::SRL, VT) && 7770 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) && 7771 TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT); 7772 } 7773 7774 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const { 7775 SDLoc dl(Node); 7776 EVT VT = Node->getValueType(0); 7777 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7778 SDValue Op = Node->getOperand(0); 7779 unsigned Len = VT.getScalarSizeInBits(); 7780 assert(VT.isInteger() && "CTPOP not implemented for this type."); 7781 7782 // TODO: Add support for irregular type lengths. 7783 if (!(Len <= 128 && Len % 8 == 0)) 7784 return SDValue(); 7785 7786 // Only expand vector types if we have the appropriate vector bit operations. 7787 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT)) 7788 return SDValue(); 7789 7790 // This is the "best" algorithm from 7791 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 7792 SDValue Mask55 = 7793 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 7794 SDValue Mask33 = 7795 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 7796 SDValue Mask0F = 7797 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 7798 7799 // v = v - ((v >> 1) & 0x55555555...) 7800 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 7801 DAG.getNode(ISD::AND, dl, VT, 7802 DAG.getNode(ISD::SRL, dl, VT, Op, 7803 DAG.getConstant(1, dl, ShVT)), 7804 Mask55)); 7805 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 7806 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 7807 DAG.getNode(ISD::AND, dl, VT, 7808 DAG.getNode(ISD::SRL, dl, VT, Op, 7809 DAG.getConstant(2, dl, ShVT)), 7810 Mask33)); 7811 // v = (v + (v >> 4)) & 0x0F0F0F0F... 7812 Op = DAG.getNode(ISD::AND, dl, VT, 7813 DAG.getNode(ISD::ADD, dl, VT, Op, 7814 DAG.getNode(ISD::SRL, dl, VT, Op, 7815 DAG.getConstant(4, dl, ShVT))), 7816 Mask0F); 7817 7818 if (Len <= 8) 7819 return Op; 7820 7821 // Avoid the multiply if we only have 2 bytes to add. 7822 // TODO: Only doing this for scalars because vectors weren't as obviously 7823 // improved. 7824 if (Len == 16 && !VT.isVector()) { 7825 // v = (v + (v >> 8)) & 0x00FF; 7826 return DAG.getNode(ISD::AND, dl, VT, 7827 DAG.getNode(ISD::ADD, dl, VT, Op, 7828 DAG.getNode(ISD::SRL, dl, VT, Op, 7829 DAG.getConstant(8, dl, ShVT))), 7830 DAG.getConstant(0xFF, dl, VT)); 7831 } 7832 7833 // v = (v * 0x01010101...) >> (Len - 8) 7834 SDValue Mask01 = 7835 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 7836 return DAG.getNode(ISD::SRL, dl, VT, 7837 DAG.getNode(ISD::MUL, dl, VT, Op, Mask01), 7838 DAG.getConstant(Len - 8, dl, ShVT)); 7839 } 7840 7841 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const { 7842 SDLoc dl(Node); 7843 EVT VT = Node->getValueType(0); 7844 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7845 SDValue Op = Node->getOperand(0); 7846 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 7847 7848 // If the non-ZERO_UNDEF version is supported we can use that instead. 7849 if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF && 7850 isOperationLegalOrCustom(ISD::CTLZ, VT)) 7851 return DAG.getNode(ISD::CTLZ, dl, VT, Op); 7852 7853 // If the ZERO_UNDEF version is supported use that and handle the zero case. 7854 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 7855 EVT SetCCVT = 7856 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7857 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 7858 SDValue Zero = DAG.getConstant(0, dl, VT); 7859 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 7860 return DAG.getSelect(dl, VT, SrcIsZero, 7861 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ); 7862 } 7863 7864 // Only expand vector types if we have the appropriate vector bit operations. 7865 // This includes the operations needed to expand CTPOP if it isn't supported. 7866 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 7867 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 7868 !canExpandVectorCTPOP(*this, VT)) || 7869 !isOperationLegalOrCustom(ISD::SRL, VT) || 7870 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 7871 return SDValue(); 7872 7873 // for now, we do this: 7874 // x = x | (x >> 1); 7875 // x = x | (x >> 2); 7876 // ... 7877 // x = x | (x >>16); 7878 // x = x | (x >>32); // for 64-bit input 7879 // return popcount(~x); 7880 // 7881 // Ref: "Hacker's Delight" by Henry Warren 7882 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) { 7883 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 7884 Op = DAG.getNode(ISD::OR, dl, VT, Op, 7885 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp)); 7886 } 7887 Op = DAG.getNOT(dl, Op, VT); 7888 return DAG.getNode(ISD::CTPOP, dl, VT, Op); 7889 } 7890 7891 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const { 7892 SDLoc dl(Node); 7893 EVT VT = Node->getValueType(0); 7894 SDValue Op = Node->getOperand(0); 7895 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 7896 7897 // If the non-ZERO_UNDEF version is supported we can use that instead. 7898 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF && 7899 isOperationLegalOrCustom(ISD::CTTZ, VT)) 7900 return DAG.getNode(ISD::CTTZ, dl, VT, Op); 7901 7902 // If the ZERO_UNDEF version is supported use that and handle the zero case. 7903 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) { 7904 EVT SetCCVT = 7905 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7906 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op); 7907 SDValue Zero = DAG.getConstant(0, dl, VT); 7908 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 7909 return DAG.getSelect(dl, VT, SrcIsZero, 7910 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ); 7911 } 7912 7913 // Only expand vector types if we have the appropriate vector bit operations. 7914 // This includes the operations needed to expand CTPOP if it isn't supported. 7915 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 7916 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 7917 !isOperationLegalOrCustom(ISD::CTLZ, VT) && 7918 !canExpandVectorCTPOP(*this, VT)) || 7919 !isOperationLegalOrCustom(ISD::SUB, VT) || 7920 !isOperationLegalOrCustomOrPromote(ISD::AND, VT) || 7921 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 7922 return SDValue(); 7923 7924 // for now, we use: { return popcount(~x & (x - 1)); } 7925 // unless the target has ctlz but not ctpop, in which case we use: 7926 // { return 32 - nlz(~x & (x-1)); } 7927 // Ref: "Hacker's Delight" by Henry Warren 7928 SDValue Tmp = DAG.getNode( 7929 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT), 7930 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT))); 7931 7932 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 7933 if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) { 7934 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT), 7935 DAG.getNode(ISD::CTLZ, dl, VT, Tmp)); 7936 } 7937 7938 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp); 7939 } 7940 7941 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG, 7942 bool IsNegative) const { 7943 SDLoc dl(N); 7944 EVT VT = N->getValueType(0); 7945 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7946 SDValue Op = N->getOperand(0); 7947 7948 // abs(x) -> smax(x,sub(0,x)) 7949 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 7950 isOperationLegal(ISD::SMAX, VT)) { 7951 SDValue Zero = DAG.getConstant(0, dl, VT); 7952 return DAG.getNode(ISD::SMAX, dl, VT, Op, 7953 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7954 } 7955 7956 // abs(x) -> umin(x,sub(0,x)) 7957 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 7958 isOperationLegal(ISD::UMIN, VT)) { 7959 SDValue Zero = DAG.getConstant(0, dl, VT); 7960 Op = DAG.getFreeze(Op); 7961 return DAG.getNode(ISD::UMIN, dl, VT, Op, 7962 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7963 } 7964 7965 // 0 - abs(x) -> smin(x, sub(0,x)) 7966 if (IsNegative && isOperationLegal(ISD::SUB, VT) && 7967 isOperationLegal(ISD::SMIN, VT)) { 7968 Op = DAG.getFreeze(Op); 7969 SDValue Zero = DAG.getConstant(0, dl, VT); 7970 return DAG.getNode(ISD::SMIN, dl, VT, Op, 7971 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7972 } 7973 7974 // Only expand vector types if we have the appropriate vector operations. 7975 if (VT.isVector() && 7976 (!isOperationLegalOrCustom(ISD::SRA, VT) || 7977 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) || 7978 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) || 7979 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 7980 return SDValue(); 7981 7982 Op = DAG.getFreeze(Op); 7983 SDValue Shift = 7984 DAG.getNode(ISD::SRA, dl, VT, Op, 7985 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT)); 7986 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift); 7987 7988 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y) 7989 if (!IsNegative) 7990 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift); 7991 7992 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y)) 7993 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor); 7994 } 7995 7996 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const { 7997 SDLoc dl(N); 7998 EVT VT = N->getValueType(0); 7999 SDValue Op = N->getOperand(0); 8000 8001 if (!VT.isSimple()) 8002 return SDValue(); 8003 8004 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 8005 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 8006 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 8007 default: 8008 return SDValue(); 8009 case MVT::i16: 8010 // Use a rotate by 8. This can be further expanded if necessary. 8011 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 8012 case MVT::i32: 8013 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 8014 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 8015 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 8016 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 8017 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 8018 DAG.getConstant(0xFF0000, dl, VT)); 8019 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT)); 8020 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 8021 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 8022 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 8023 case MVT::i64: 8024 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 8025 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 8026 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 8027 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 8028 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 8029 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 8030 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 8031 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 8032 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, 8033 DAG.getConstant(255ULL<<48, dl, VT)); 8034 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, 8035 DAG.getConstant(255ULL<<40, dl, VT)); 8036 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, 8037 DAG.getConstant(255ULL<<32, dl, VT)); 8038 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, 8039 DAG.getConstant(255ULL<<24, dl, VT)); 8040 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 8041 DAG.getConstant(255ULL<<16, dl, VT)); 8042 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, 8043 DAG.getConstant(255ULL<<8 , dl, VT)); 8044 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7); 8045 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5); 8046 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 8047 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 8048 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6); 8049 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 8050 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4); 8051 } 8052 } 8053 8054 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const { 8055 SDLoc dl(N); 8056 EVT VT = N->getValueType(0); 8057 SDValue Op = N->getOperand(0); 8058 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 8059 unsigned Sz = VT.getScalarSizeInBits(); 8060 8061 SDValue Tmp, Tmp2, Tmp3; 8062 8063 // If we can, perform BSWAP first and then the mask+swap the i4, then i2 8064 // and finally the i1 pairs. 8065 // TODO: We can easily support i4/i2 legal types if any target ever does. 8066 if (Sz >= 8 && isPowerOf2_32(Sz)) { 8067 // Create the masks - repeating the pattern every byte. 8068 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F)); 8069 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33)); 8070 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55)); 8071 8072 // BSWAP if the type is wider than a single byte. 8073 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op); 8074 8075 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4) 8076 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT)); 8077 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT)); 8078 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT)); 8079 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT)); 8080 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8081 8082 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2) 8083 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT)); 8084 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT)); 8085 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT)); 8086 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT)); 8087 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8088 8089 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1) 8090 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT)); 8091 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT)); 8092 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT)); 8093 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT)); 8094 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8095 return Tmp; 8096 } 8097 8098 Tmp = DAG.getConstant(0, dl, VT); 8099 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) { 8100 if (I < J) 8101 Tmp2 = 8102 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT)); 8103 else 8104 Tmp2 = 8105 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT)); 8106 8107 APInt Shift(Sz, 1); 8108 Shift <<= J; 8109 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT)); 8110 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2); 8111 } 8112 8113 return Tmp; 8114 } 8115 8116 std::pair<SDValue, SDValue> 8117 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 8118 SelectionDAG &DAG) const { 8119 SDLoc SL(LD); 8120 SDValue Chain = LD->getChain(); 8121 SDValue BasePTR = LD->getBasePtr(); 8122 EVT SrcVT = LD->getMemoryVT(); 8123 EVT DstVT = LD->getValueType(0); 8124 ISD::LoadExtType ExtType = LD->getExtensionType(); 8125 8126 if (SrcVT.isScalableVector()) 8127 report_fatal_error("Cannot scalarize scalable vector loads"); 8128 8129 unsigned NumElem = SrcVT.getVectorNumElements(); 8130 8131 EVT SrcEltVT = SrcVT.getScalarType(); 8132 EVT DstEltVT = DstVT.getScalarType(); 8133 8134 // A vector must always be stored in memory as-is, i.e. without any padding 8135 // between the elements, since various code depend on it, e.g. in the 8136 // handling of a bitcast of a vector type to int, which may be done with a 8137 // vector store followed by an integer load. A vector that does not have 8138 // elements that are byte-sized must therefore be stored as an integer 8139 // built out of the extracted vector elements. 8140 if (!SrcEltVT.isByteSized()) { 8141 unsigned NumLoadBits = SrcVT.getStoreSizeInBits(); 8142 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits); 8143 8144 unsigned NumSrcBits = SrcVT.getSizeInBits(); 8145 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits); 8146 8147 unsigned SrcEltBits = SrcEltVT.getSizeInBits(); 8148 SDValue SrcEltBitMask = DAG.getConstant( 8149 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT); 8150 8151 // Load the whole vector and avoid masking off the top bits as it makes 8152 // the codegen worse. 8153 SDValue Load = 8154 DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, 8155 LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(), 8156 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 8157 8158 SmallVector<SDValue, 8> Vals; 8159 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8160 unsigned ShiftIntoIdx = 8161 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 8162 SDValue ShiftAmount = 8163 DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(), 8164 LoadVT, SL, /*LegalTypes=*/false); 8165 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount); 8166 SDValue Elt = 8167 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask); 8168 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt); 8169 8170 if (ExtType != ISD::NON_EXTLOAD) { 8171 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType); 8172 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar); 8173 } 8174 8175 Vals.push_back(Scalar); 8176 } 8177 8178 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 8179 return std::make_pair(Value, Load.getValue(1)); 8180 } 8181 8182 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 8183 assert(SrcEltVT.isByteSized()); 8184 8185 SmallVector<SDValue, 8> Vals; 8186 SmallVector<SDValue, 8> LoadChains; 8187 8188 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8189 SDValue ScalarLoad = 8190 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 8191 LD->getPointerInfo().getWithOffset(Idx * Stride), 8192 SrcEltVT, LD->getOriginalAlign(), 8193 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 8194 8195 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride)); 8196 8197 Vals.push_back(ScalarLoad.getValue(0)); 8198 LoadChains.push_back(ScalarLoad.getValue(1)); 8199 } 8200 8201 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 8202 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 8203 8204 return std::make_pair(Value, NewChain); 8205 } 8206 8207 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 8208 SelectionDAG &DAG) const { 8209 SDLoc SL(ST); 8210 8211 SDValue Chain = ST->getChain(); 8212 SDValue BasePtr = ST->getBasePtr(); 8213 SDValue Value = ST->getValue(); 8214 EVT StVT = ST->getMemoryVT(); 8215 8216 if (StVT.isScalableVector()) 8217 report_fatal_error("Cannot scalarize scalable vector stores"); 8218 8219 // The type of the data we want to save 8220 EVT RegVT = Value.getValueType(); 8221 EVT RegSclVT = RegVT.getScalarType(); 8222 8223 // The type of data as saved in memory. 8224 EVT MemSclVT = StVT.getScalarType(); 8225 8226 unsigned NumElem = StVT.getVectorNumElements(); 8227 8228 // A vector must always be stored in memory as-is, i.e. without any padding 8229 // between the elements, since various code depend on it, e.g. in the 8230 // handling of a bitcast of a vector type to int, which may be done with a 8231 // vector store followed by an integer load. A vector that does not have 8232 // elements that are byte-sized must therefore be stored as an integer 8233 // built out of the extracted vector elements. 8234 if (!MemSclVT.isByteSized()) { 8235 unsigned NumBits = StVT.getSizeInBits(); 8236 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 8237 8238 SDValue CurrVal = DAG.getConstant(0, SL, IntVT); 8239 8240 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8241 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 8242 DAG.getVectorIdxConstant(Idx, SL)); 8243 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt); 8244 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc); 8245 unsigned ShiftIntoIdx = 8246 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 8247 SDValue ShiftAmount = 8248 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT); 8249 SDValue ShiftedElt = 8250 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount); 8251 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt); 8252 } 8253 8254 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(), 8255 ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 8256 ST->getAAInfo()); 8257 } 8258 8259 // Store Stride in bytes 8260 unsigned Stride = MemSclVT.getSizeInBits() / 8; 8261 assert(Stride && "Zero stride!"); 8262 // Extract each of the elements from the original vector and save them into 8263 // memory individually. 8264 SmallVector<SDValue, 8> Stores; 8265 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 8266 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 8267 DAG.getVectorIdxConstant(Idx, SL)); 8268 8269 SDValue Ptr = 8270 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride)); 8271 8272 // This scalar TruncStore may be illegal, but we legalize it later. 8273 SDValue Store = DAG.getTruncStore( 8274 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 8275 MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 8276 ST->getAAInfo()); 8277 8278 Stores.push_back(Store); 8279 } 8280 8281 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 8282 } 8283 8284 std::pair<SDValue, SDValue> 8285 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 8286 assert(LD->getAddressingMode() == ISD::UNINDEXED && 8287 "unaligned indexed loads not implemented!"); 8288 SDValue Chain = LD->getChain(); 8289 SDValue Ptr = LD->getBasePtr(); 8290 EVT VT = LD->getValueType(0); 8291 EVT LoadedVT = LD->getMemoryVT(); 8292 SDLoc dl(LD); 8293 auto &MF = DAG.getMachineFunction(); 8294 8295 if (VT.isFloatingPoint() || VT.isVector()) { 8296 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 8297 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 8298 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) && 8299 LoadedVT.isVector()) { 8300 // Scalarize the load and let the individual components be handled. 8301 return scalarizeVectorLoad(LD, DAG); 8302 } 8303 8304 // Expand to a (misaligned) integer load of the same size, 8305 // then bitconvert to floating point or vector. 8306 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 8307 LD->getMemOperand()); 8308 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 8309 if (LoadedVT != VT) 8310 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 8311 ISD::ANY_EXTEND, dl, VT, Result); 8312 8313 return std::make_pair(Result, newLoad.getValue(1)); 8314 } 8315 8316 // Copy the value to a (aligned) stack slot using (unaligned) integer 8317 // loads and stores, then do a (aligned) load from the stack slot. 8318 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 8319 unsigned LoadedBytes = LoadedVT.getStoreSize(); 8320 unsigned RegBytes = RegVT.getSizeInBits() / 8; 8321 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 8322 8323 // Make sure the stack slot is also aligned for the register type. 8324 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 8325 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex(); 8326 SmallVector<SDValue, 8> Stores; 8327 SDValue StackPtr = StackBase; 8328 unsigned Offset = 0; 8329 8330 EVT PtrVT = Ptr.getValueType(); 8331 EVT StackPtrVT = StackPtr.getValueType(); 8332 8333 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 8334 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 8335 8336 // Do all but one copies using the full register width. 8337 for (unsigned i = 1; i < NumRegs; i++) { 8338 // Load one integer register's worth from the original location. 8339 SDValue Load = DAG.getLoad( 8340 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 8341 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 8342 LD->getAAInfo()); 8343 // Follow the load with a store to the stack slot. Remember the store. 8344 Stores.push_back(DAG.getStore( 8345 Load.getValue(1), dl, Load, StackPtr, 8346 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset))); 8347 // Increment the pointers. 8348 Offset += RegBytes; 8349 8350 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 8351 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 8352 } 8353 8354 // The last copy may be partial. Do an extending load. 8355 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 8356 8 * (LoadedBytes - Offset)); 8357 SDValue Load = 8358 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 8359 LD->getPointerInfo().getWithOffset(Offset), MemVT, 8360 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 8361 LD->getAAInfo()); 8362 // Follow the load with a store to the stack slot. Remember the store. 8363 // On big-endian machines this requires a truncating store to ensure 8364 // that the bits end up in the right place. 8365 Stores.push_back(DAG.getTruncStore( 8366 Load.getValue(1), dl, Load, StackPtr, 8367 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT)); 8368 8369 // The order of the stores doesn't matter - say it with a TokenFactor. 8370 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8371 8372 // Finally, perform the original load only redirected to the stack slot. 8373 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 8374 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), 8375 LoadedVT); 8376 8377 // Callers expect a MERGE_VALUES node. 8378 return std::make_pair(Load, TF); 8379 } 8380 8381 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 8382 "Unaligned load of unsupported type."); 8383 8384 // Compute the new VT that is half the size of the old one. This is an 8385 // integer MVT. 8386 unsigned NumBits = LoadedVT.getSizeInBits(); 8387 EVT NewLoadedVT; 8388 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 8389 NumBits >>= 1; 8390 8391 Align Alignment = LD->getOriginalAlign(); 8392 unsigned IncrementSize = NumBits / 8; 8393 ISD::LoadExtType HiExtType = LD->getExtensionType(); 8394 8395 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 8396 if (HiExtType == ISD::NON_EXTLOAD) 8397 HiExtType = ISD::ZEXTLOAD; 8398 8399 // Load the value in two parts 8400 SDValue Lo, Hi; 8401 if (DAG.getDataLayout().isLittleEndian()) { 8402 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 8403 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8404 LD->getAAInfo()); 8405 8406 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8407 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 8408 LD->getPointerInfo().getWithOffset(IncrementSize), 8409 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8410 LD->getAAInfo()); 8411 } else { 8412 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 8413 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8414 LD->getAAInfo()); 8415 8416 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8417 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 8418 LD->getPointerInfo().getWithOffset(IncrementSize), 8419 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 8420 LD->getAAInfo()); 8421 } 8422 8423 // aggregate the two parts 8424 SDValue ShiftAmount = 8425 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(), 8426 DAG.getDataLayout())); 8427 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 8428 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 8429 8430 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 8431 Hi.getValue(1)); 8432 8433 return std::make_pair(Result, TF); 8434 } 8435 8436 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 8437 SelectionDAG &DAG) const { 8438 assert(ST->getAddressingMode() == ISD::UNINDEXED && 8439 "unaligned indexed stores not implemented!"); 8440 SDValue Chain = ST->getChain(); 8441 SDValue Ptr = ST->getBasePtr(); 8442 SDValue Val = ST->getValue(); 8443 EVT VT = Val.getValueType(); 8444 Align Alignment = ST->getOriginalAlign(); 8445 auto &MF = DAG.getMachineFunction(); 8446 EVT StoreMemVT = ST->getMemoryVT(); 8447 8448 SDLoc dl(ST); 8449 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) { 8450 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8451 if (isTypeLegal(intVT)) { 8452 if (!isOperationLegalOrCustom(ISD::STORE, intVT) && 8453 StoreMemVT.isVector()) { 8454 // Scalarize the store and let the individual components be handled. 8455 SDValue Result = scalarizeVectorStore(ST, DAG); 8456 return Result; 8457 } 8458 // Expand to a bitconvert of the value to the integer type of the 8459 // same size, then a (misaligned) int store. 8460 // FIXME: Does not handle truncating floating point stores! 8461 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 8462 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 8463 Alignment, ST->getMemOperand()->getFlags()); 8464 return Result; 8465 } 8466 // Do a (aligned) store to a stack slot, then copy from the stack slot 8467 // to the final destination using (unaligned) integer loads and stores. 8468 MVT RegVT = getRegisterType( 8469 *DAG.getContext(), 8470 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits())); 8471 EVT PtrVT = Ptr.getValueType(); 8472 unsigned StoredBytes = StoreMemVT.getStoreSize(); 8473 unsigned RegBytes = RegVT.getSizeInBits() / 8; 8474 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 8475 8476 // Make sure the stack slot is also aligned for the register type. 8477 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT); 8478 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 8479 8480 // Perform the original store, only redirected to the stack slot. 8481 SDValue Store = DAG.getTruncStore( 8482 Chain, dl, Val, StackPtr, 8483 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT); 8484 8485 EVT StackPtrVT = StackPtr.getValueType(); 8486 8487 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 8488 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 8489 SmallVector<SDValue, 8> Stores; 8490 unsigned Offset = 0; 8491 8492 // Do all but one copies using the full register width. 8493 for (unsigned i = 1; i < NumRegs; i++) { 8494 // Load one integer register's worth from the stack slot. 8495 SDValue Load = DAG.getLoad( 8496 RegVT, dl, Store, StackPtr, 8497 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)); 8498 // Store it to the final location. Remember the store. 8499 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 8500 ST->getPointerInfo().getWithOffset(Offset), 8501 ST->getOriginalAlign(), 8502 ST->getMemOperand()->getFlags())); 8503 // Increment the pointers. 8504 Offset += RegBytes; 8505 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 8506 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 8507 } 8508 8509 // The last store may be partial. Do a truncating store. On big-endian 8510 // machines this requires an extending load from the stack slot to ensure 8511 // that the bits are in the right place. 8512 EVT LoadMemVT = 8513 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset)); 8514 8515 // Load from the stack slot. 8516 SDValue Load = DAG.getExtLoad( 8517 ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 8518 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT); 8519 8520 Stores.push_back( 8521 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 8522 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT, 8523 ST->getOriginalAlign(), 8524 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 8525 // The order of the stores doesn't matter - say it with a TokenFactor. 8526 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8527 return Result; 8528 } 8529 8530 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() && 8531 "Unaligned store of unknown type."); 8532 // Get the half-size VT 8533 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext()); 8534 unsigned NumBits = NewStoredVT.getFixedSizeInBits(); 8535 unsigned IncrementSize = NumBits / 8; 8536 8537 // Divide the stored value in two parts. 8538 SDValue ShiftAmount = DAG.getConstant( 8539 NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout())); 8540 SDValue Lo = Val; 8541 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 8542 8543 // Store the two parts 8544 SDValue Store1, Store2; 8545 Store1 = DAG.getTruncStore(Chain, dl, 8546 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 8547 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 8548 ST->getMemOperand()->getFlags()); 8549 8550 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 8551 Store2 = DAG.getTruncStore( 8552 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 8553 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 8554 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 8555 8556 SDValue Result = 8557 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 8558 return Result; 8559 } 8560 8561 SDValue 8562 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 8563 const SDLoc &DL, EVT DataVT, 8564 SelectionDAG &DAG, 8565 bool IsCompressedMemory) const { 8566 SDValue Increment; 8567 EVT AddrVT = Addr.getValueType(); 8568 EVT MaskVT = Mask.getValueType(); 8569 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() && 8570 "Incompatible types of Data and Mask"); 8571 if (IsCompressedMemory) { 8572 if (DataVT.isScalableVector()) 8573 report_fatal_error( 8574 "Cannot currently handle compressed memory with scalable vectors"); 8575 // Incrementing the pointer according to number of '1's in the mask. 8576 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 8577 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 8578 if (MaskIntVT.getSizeInBits() < 32) { 8579 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 8580 MaskIntVT = MVT::i32; 8581 } 8582 8583 // Count '1's with POPCNT. 8584 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 8585 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 8586 // Scale is an element size in bytes. 8587 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 8588 AddrVT); 8589 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 8590 } else if (DataVT.isScalableVector()) { 8591 Increment = DAG.getVScale(DL, AddrVT, 8592 APInt(AddrVT.getFixedSizeInBits(), 8593 DataVT.getStoreSize().getKnownMinSize())); 8594 } else 8595 Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT); 8596 8597 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 8598 } 8599 8600 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx, 8601 EVT VecVT, const SDLoc &dl, 8602 ElementCount SubEC) { 8603 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) && 8604 "Cannot index a scalable vector within a fixed-width vector"); 8605 8606 unsigned NElts = VecVT.getVectorMinNumElements(); 8607 unsigned NumSubElts = SubEC.getKnownMinValue(); 8608 EVT IdxVT = Idx.getValueType(); 8609 8610 if (VecVT.isScalableVector() && !SubEC.isScalable()) { 8611 // If this is a constant index and we know the value plus the number of the 8612 // elements in the subvector minus one is less than the minimum number of 8613 // elements then it's safe to return Idx. 8614 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx)) 8615 if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts) 8616 return Idx; 8617 SDValue VS = 8618 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts)); 8619 unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT; 8620 SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS, 8621 DAG.getConstant(NumSubElts, dl, IdxVT)); 8622 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub); 8623 } 8624 if (isPowerOf2_32(NElts) && NumSubElts == 1) { 8625 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts)); 8626 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 8627 DAG.getConstant(Imm, dl, IdxVT)); 8628 } 8629 unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0; 8630 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 8631 DAG.getConstant(MaxIndex, dl, IdxVT)); 8632 } 8633 8634 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 8635 SDValue VecPtr, EVT VecVT, 8636 SDValue Index) const { 8637 return getVectorSubVecPointer( 8638 DAG, VecPtr, VecVT, 8639 EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1), 8640 Index); 8641 } 8642 8643 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG, 8644 SDValue VecPtr, EVT VecVT, 8645 EVT SubVecVT, 8646 SDValue Index) const { 8647 SDLoc dl(Index); 8648 // Make sure the index type is big enough to compute in. 8649 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType()); 8650 8651 EVT EltVT = VecVT.getVectorElementType(); 8652 8653 // Calculate the element offset and add it to the pointer. 8654 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size. 8655 assert(EltSize * 8 == EltVT.getFixedSizeInBits() && 8656 "Converting bits to bytes lost precision"); 8657 assert(SubVecVT.getVectorElementType() == EltVT && 8658 "Sub-vector must be a vector with matching element type"); 8659 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl, 8660 SubVecVT.getVectorElementCount()); 8661 8662 EVT IdxVT = Index.getValueType(); 8663 if (SubVecVT.isScalableVector()) 8664 Index = 8665 DAG.getNode(ISD::MUL, dl, IdxVT, Index, 8666 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1))); 8667 8668 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 8669 DAG.getConstant(EltSize, dl, IdxVT)); 8670 return DAG.getMemBasePlusOffset(VecPtr, Index, dl); 8671 } 8672 8673 //===----------------------------------------------------------------------===// 8674 // Implementation of Emulated TLS Model 8675 //===----------------------------------------------------------------------===// 8676 8677 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 8678 SelectionDAG &DAG) const { 8679 // Access to address of TLS varialbe xyz is lowered to a function call: 8680 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 8681 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8682 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 8683 SDLoc dl(GA); 8684 8685 ArgListTy Args; 8686 ArgListEntry Entry; 8687 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 8688 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 8689 StringRef EmuTlsVarName(NameString); 8690 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 8691 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 8692 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 8693 Entry.Ty = VoidPtrType; 8694 Args.push_back(Entry); 8695 8696 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 8697 8698 TargetLowering::CallLoweringInfo CLI(DAG); 8699 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 8700 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 8701 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 8702 8703 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 8704 // At last for X86 targets, maybe good for other targets too? 8705 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8706 MFI.setAdjustsStack(true); // Is this only for X86 target? 8707 MFI.setHasCalls(true); 8708 8709 assert((GA->getOffset() == 0) && 8710 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 8711 return CallResult.first; 8712 } 8713 8714 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 8715 SelectionDAG &DAG) const { 8716 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 8717 if (!isCtlzFast()) 8718 return SDValue(); 8719 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8720 SDLoc dl(Op); 8721 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 8722 if (C->isZero() && CC == ISD::SETEQ) { 8723 EVT VT = Op.getOperand(0).getValueType(); 8724 SDValue Zext = Op.getOperand(0); 8725 if (VT.bitsLT(MVT::i32)) { 8726 VT = MVT::i32; 8727 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 8728 } 8729 unsigned Log2b = Log2_32(VT.getSizeInBits()); 8730 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 8731 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 8732 DAG.getConstant(Log2b, dl, MVT::i32)); 8733 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 8734 } 8735 } 8736 return SDValue(); 8737 } 8738 8739 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const { 8740 SDValue Op0 = Node->getOperand(0); 8741 SDValue Op1 = Node->getOperand(1); 8742 EVT VT = Op0.getValueType(); 8743 unsigned Opcode = Node->getOpcode(); 8744 SDLoc DL(Node); 8745 8746 // umin(x,y) -> sub(x,usubsat(x,y)) 8747 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) && 8748 isOperationLegal(ISD::USUBSAT, VT)) { 8749 return DAG.getNode(ISD::SUB, DL, VT, Op0, 8750 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1)); 8751 } 8752 8753 // umax(x,y) -> add(x,usubsat(y,x)) 8754 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) && 8755 isOperationLegal(ISD::USUBSAT, VT)) { 8756 return DAG.getNode(ISD::ADD, DL, VT, Op0, 8757 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0)); 8758 } 8759 8760 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 8761 ISD::CondCode CC; 8762 switch (Opcode) { 8763 default: llvm_unreachable("How did we get here?"); 8764 case ISD::SMAX: CC = ISD::SETGT; break; 8765 case ISD::SMIN: CC = ISD::SETLT; break; 8766 case ISD::UMAX: CC = ISD::SETUGT; break; 8767 case ISD::UMIN: CC = ISD::SETULT; break; 8768 } 8769 8770 // FIXME: Should really try to split the vector in case it's legal on a 8771 // subvector. 8772 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8773 return DAG.UnrollVectorOp(Node); 8774 8775 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8776 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC); 8777 return DAG.getSelect(DL, VT, Cond, Op0, Op1); 8778 } 8779 8780 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const { 8781 unsigned Opcode = Node->getOpcode(); 8782 SDValue LHS = Node->getOperand(0); 8783 SDValue RHS = Node->getOperand(1); 8784 EVT VT = LHS.getValueType(); 8785 SDLoc dl(Node); 8786 8787 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 8788 assert(VT.isInteger() && "Expected operands to be integers"); 8789 8790 // usub.sat(a, b) -> umax(a, b) - b 8791 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) { 8792 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS); 8793 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS); 8794 } 8795 8796 // uadd.sat(a, b) -> umin(a, ~b) + b 8797 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) { 8798 SDValue InvRHS = DAG.getNOT(dl, RHS, VT); 8799 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS); 8800 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS); 8801 } 8802 8803 unsigned OverflowOp; 8804 switch (Opcode) { 8805 case ISD::SADDSAT: 8806 OverflowOp = ISD::SADDO; 8807 break; 8808 case ISD::UADDSAT: 8809 OverflowOp = ISD::UADDO; 8810 break; 8811 case ISD::SSUBSAT: 8812 OverflowOp = ISD::SSUBO; 8813 break; 8814 case ISD::USUBSAT: 8815 OverflowOp = ISD::USUBO; 8816 break; 8817 default: 8818 llvm_unreachable("Expected method to receive signed or unsigned saturation " 8819 "addition or subtraction node."); 8820 } 8821 8822 // FIXME: Should really try to split the vector in case it's legal on a 8823 // subvector. 8824 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 8825 return DAG.UnrollVectorOp(Node); 8826 8827 unsigned BitWidth = LHS.getScalarValueSizeInBits(); 8828 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8829 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8830 SDValue SumDiff = Result.getValue(0); 8831 SDValue Overflow = Result.getValue(1); 8832 SDValue Zero = DAG.getConstant(0, dl, VT); 8833 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT); 8834 8835 if (Opcode == ISD::UADDSAT) { 8836 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 8837 // (LHS + RHS) | OverflowMask 8838 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 8839 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask); 8840 } 8841 // Overflow ? 0xffff.... : (LHS + RHS) 8842 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff); 8843 } 8844 8845 if (Opcode == ISD::USUBSAT) { 8846 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 8847 // (LHS - RHS) & ~OverflowMask 8848 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 8849 SDValue Not = DAG.getNOT(dl, OverflowMask, VT); 8850 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not); 8851 } 8852 // Overflow ? 0 : (LHS - RHS) 8853 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff); 8854 } 8855 8856 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff 8857 APInt MinVal = APInt::getSignedMinValue(BitWidth); 8858 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 8859 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff, 8860 DAG.getConstant(BitWidth - 1, dl, VT)); 8861 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin); 8862 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff); 8863 } 8864 8865 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const { 8866 unsigned Opcode = Node->getOpcode(); 8867 bool IsSigned = Opcode == ISD::SSHLSAT; 8868 SDValue LHS = Node->getOperand(0); 8869 SDValue RHS = Node->getOperand(1); 8870 EVT VT = LHS.getValueType(); 8871 SDLoc dl(Node); 8872 8873 assert((Node->getOpcode() == ISD::SSHLSAT || 8874 Node->getOpcode() == ISD::USHLSAT) && 8875 "Expected a SHLSAT opcode"); 8876 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 8877 assert(VT.isInteger() && "Expected operands to be integers"); 8878 8879 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate. 8880 8881 unsigned BW = VT.getScalarSizeInBits(); 8882 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS); 8883 SDValue Orig = 8884 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS); 8885 8886 SDValue SatVal; 8887 if (IsSigned) { 8888 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT); 8889 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT); 8890 SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT), 8891 SatMin, SatMax, ISD::SETLT); 8892 } else { 8893 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT); 8894 } 8895 Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE); 8896 8897 return Result; 8898 } 8899 8900 SDValue 8901 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const { 8902 assert((Node->getOpcode() == ISD::SMULFIX || 8903 Node->getOpcode() == ISD::UMULFIX || 8904 Node->getOpcode() == ISD::SMULFIXSAT || 8905 Node->getOpcode() == ISD::UMULFIXSAT) && 8906 "Expected a fixed point multiplication opcode"); 8907 8908 SDLoc dl(Node); 8909 SDValue LHS = Node->getOperand(0); 8910 SDValue RHS = Node->getOperand(1); 8911 EVT VT = LHS.getValueType(); 8912 unsigned Scale = Node->getConstantOperandVal(2); 8913 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT || 8914 Node->getOpcode() == ISD::UMULFIXSAT); 8915 bool Signed = (Node->getOpcode() == ISD::SMULFIX || 8916 Node->getOpcode() == ISD::SMULFIXSAT); 8917 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8918 unsigned VTSize = VT.getScalarSizeInBits(); 8919 8920 if (!Scale) { 8921 // [us]mul.fix(a, b, 0) -> mul(a, b) 8922 if (!Saturating) { 8923 if (isOperationLegalOrCustom(ISD::MUL, VT)) 8924 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8925 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) { 8926 SDValue Result = 8927 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8928 SDValue Product = Result.getValue(0); 8929 SDValue Overflow = Result.getValue(1); 8930 SDValue Zero = DAG.getConstant(0, dl, VT); 8931 8932 APInt MinVal = APInt::getSignedMinValue(VTSize); 8933 APInt MaxVal = APInt::getSignedMaxValue(VTSize); 8934 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 8935 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 8936 // Xor the inputs, if resulting sign bit is 0 the product will be 8937 // positive, else negative. 8938 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS); 8939 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT); 8940 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax); 8941 return DAG.getSelect(dl, VT, Overflow, Result, Product); 8942 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) { 8943 SDValue Result = 8944 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8945 SDValue Product = Result.getValue(0); 8946 SDValue Overflow = Result.getValue(1); 8947 8948 APInt MaxVal = APInt::getMaxValue(VTSize); 8949 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 8950 return DAG.getSelect(dl, VT, Overflow, SatMax, Product); 8951 } 8952 } 8953 8954 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) && 8955 "Expected scale to be less than the number of bits if signed or at " 8956 "most the number of bits if unsigned."); 8957 assert(LHS.getValueType() == RHS.getValueType() && 8958 "Expected both operands to be the same type"); 8959 8960 // Get the upper and lower bits of the result. 8961 SDValue Lo, Hi; 8962 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI; 8963 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU; 8964 if (isOperationLegalOrCustom(LoHiOp, VT)) { 8965 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS); 8966 Lo = Result.getValue(0); 8967 Hi = Result.getValue(1); 8968 } else if (isOperationLegalOrCustom(HiOp, VT)) { 8969 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8970 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS); 8971 } else if (VT.isVector()) { 8972 return SDValue(); 8973 } else { 8974 report_fatal_error("Unable to expand fixed point multiplication."); 8975 } 8976 8977 if (Scale == VTSize) 8978 // Result is just the top half since we'd be shifting by the width of the 8979 // operand. Overflow impossible so this works for both UMULFIX and 8980 // UMULFIXSAT. 8981 return Hi; 8982 8983 // The result will need to be shifted right by the scale since both operands 8984 // are scaled. The result is given to us in 2 halves, so we only want part of 8985 // both in the result. 8986 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 8987 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo, 8988 DAG.getConstant(Scale, dl, ShiftTy)); 8989 if (!Saturating) 8990 return Result; 8991 8992 if (!Signed) { 8993 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the 8994 // widened multiplication) aren't all zeroes. 8995 8996 // Saturate to max if ((Hi >> Scale) != 0), 8997 // which is the same as if (Hi > ((1 << Scale) - 1)) 8998 APInt MaxVal = APInt::getMaxValue(VTSize); 8999 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), 9000 dl, VT); 9001 Result = DAG.getSelectCC(dl, Hi, LowMask, 9002 DAG.getConstant(MaxVal, dl, VT), Result, 9003 ISD::SETUGT); 9004 9005 return Result; 9006 } 9007 9008 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the 9009 // widened multiplication) aren't all ones or all zeroes. 9010 9011 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT); 9012 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT); 9013 9014 if (Scale == 0) { 9015 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo, 9016 DAG.getConstant(VTSize - 1, dl, ShiftTy)); 9017 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE); 9018 // Saturated to SatMin if wide product is negative, and SatMax if wide 9019 // product is positive ... 9020 SDValue Zero = DAG.getConstant(0, dl, VT); 9021 SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax, 9022 ISD::SETLT); 9023 // ... but only if we overflowed. 9024 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result); 9025 } 9026 9027 // We handled Scale==0 above so all the bits to examine is in Hi. 9028 9029 // Saturate to max if ((Hi >> (Scale - 1)) > 0), 9030 // which is the same as if (Hi > (1 << (Scale - 1)) - 1) 9031 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), 9032 dl, VT); 9033 Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT); 9034 // Saturate to min if (Hi >> (Scale - 1)) < -1), 9035 // which is the same as if (HI < (-1 << (Scale - 1)) 9036 SDValue HighMask = 9037 DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), 9038 dl, VT); 9039 Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT); 9040 return Result; 9041 } 9042 9043 SDValue 9044 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, 9045 SDValue LHS, SDValue RHS, 9046 unsigned Scale, SelectionDAG &DAG) const { 9047 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT || 9048 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) && 9049 "Expected a fixed point division opcode"); 9050 9051 EVT VT = LHS.getValueType(); 9052 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 9053 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 9054 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9055 9056 // If there is enough room in the type to upscale the LHS or downscale the 9057 // RHS before the division, we can perform it in this type without having to 9058 // resize. For signed operations, the LHS headroom is the number of 9059 // redundant sign bits, and for unsigned ones it is the number of zeroes. 9060 // The headroom for the RHS is the number of trailing zeroes. 9061 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1 9062 : DAG.computeKnownBits(LHS).countMinLeadingZeros(); 9063 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros(); 9064 9065 // For signed saturating operations, we need to be able to detect true integer 9066 // division overflow; that is, when you have MIN / -EPS. However, this 9067 // is undefined behavior and if we emit divisions that could take such 9068 // values it may cause undesired behavior (arithmetic exceptions on x86, for 9069 // example). 9070 // Avoid this by requiring an extra bit so that we never get this case. 9071 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale 9072 // signed saturating division, we need to emit a whopping 32-bit division. 9073 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed)) 9074 return SDValue(); 9075 9076 unsigned LHSShift = std::min(LHSLead, Scale); 9077 unsigned RHSShift = Scale - LHSShift; 9078 9079 // At this point, we know that if we shift the LHS up by LHSShift and the 9080 // RHS down by RHSShift, we can emit a regular division with a final scaling 9081 // factor of Scale. 9082 9083 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 9084 if (LHSShift) 9085 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS, 9086 DAG.getConstant(LHSShift, dl, ShiftTy)); 9087 if (RHSShift) 9088 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS, 9089 DAG.getConstant(RHSShift, dl, ShiftTy)); 9090 9091 SDValue Quot; 9092 if (Signed) { 9093 // For signed operations, if the resulting quotient is negative and the 9094 // remainder is nonzero, subtract 1 from the quotient to round towards 9095 // negative infinity. 9096 SDValue Rem; 9097 // FIXME: Ideally we would always produce an SDIVREM here, but if the 9098 // type isn't legal, SDIVREM cannot be expanded. There is no reason why 9099 // we couldn't just form a libcall, but the type legalizer doesn't do it. 9100 if (isTypeLegal(VT) && 9101 isOperationLegalOrCustom(ISD::SDIVREM, VT)) { 9102 Quot = DAG.getNode(ISD::SDIVREM, dl, 9103 DAG.getVTList(VT, VT), 9104 LHS, RHS); 9105 Rem = Quot.getValue(1); 9106 Quot = Quot.getValue(0); 9107 } else { 9108 Quot = DAG.getNode(ISD::SDIV, dl, VT, 9109 LHS, RHS); 9110 Rem = DAG.getNode(ISD::SREM, dl, VT, 9111 LHS, RHS); 9112 } 9113 SDValue Zero = DAG.getConstant(0, dl, VT); 9114 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE); 9115 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT); 9116 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT); 9117 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg); 9118 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot, 9119 DAG.getConstant(1, dl, VT)); 9120 Quot = DAG.getSelect(dl, VT, 9121 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg), 9122 Sub1, Quot); 9123 } else 9124 Quot = DAG.getNode(ISD::UDIV, dl, VT, 9125 LHS, RHS); 9126 9127 return Quot; 9128 } 9129 9130 void TargetLowering::expandUADDSUBO( 9131 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 9132 SDLoc dl(Node); 9133 SDValue LHS = Node->getOperand(0); 9134 SDValue RHS = Node->getOperand(1); 9135 bool IsAdd = Node->getOpcode() == ISD::UADDO; 9136 9137 // If ADD/SUBCARRY is legal, use that instead. 9138 unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY; 9139 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) { 9140 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1)); 9141 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(), 9142 { LHS, RHS, CarryIn }); 9143 Result = SDValue(NodeCarry.getNode(), 0); 9144 Overflow = SDValue(NodeCarry.getNode(), 1); 9145 return; 9146 } 9147 9148 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 9149 LHS.getValueType(), LHS, RHS); 9150 9151 EVT ResultType = Node->getValueType(1); 9152 EVT SetCCType = getSetCCResultType( 9153 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 9154 SDValue SetCC; 9155 if (IsAdd && isOneConstant(RHS)) { 9156 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces 9157 // the live range of X. We assume comparing with 0 is cheap. 9158 // The general case (X + C) < C is not necessarily beneficial. Although we 9159 // reduce the live range of X, we may introduce the materialization of 9160 // constant C. 9161 SetCC = 9162 DAG.getSetCC(dl, SetCCType, Result, 9163 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ); 9164 } else { 9165 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 9166 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC); 9167 } 9168 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 9169 } 9170 9171 void TargetLowering::expandSADDSUBO( 9172 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 9173 SDLoc dl(Node); 9174 SDValue LHS = Node->getOperand(0); 9175 SDValue RHS = Node->getOperand(1); 9176 bool IsAdd = Node->getOpcode() == ISD::SADDO; 9177 9178 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 9179 LHS.getValueType(), LHS, RHS); 9180 9181 EVT ResultType = Node->getValueType(1); 9182 EVT OType = getSetCCResultType( 9183 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 9184 9185 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow. 9186 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT; 9187 if (isOperationLegal(OpcSat, LHS.getValueType())) { 9188 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS); 9189 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE); 9190 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 9191 return; 9192 } 9193 9194 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 9195 9196 // For an addition, the result should be less than one of the operands (LHS) 9197 // if and only if the other operand (RHS) is negative, otherwise there will 9198 // be overflow. 9199 // For a subtraction, the result should be less than one of the operands 9200 // (LHS) if and only if the other operand (RHS) is (non-zero) positive, 9201 // otherwise there will be overflow. 9202 SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT); 9203 SDValue ConditionRHS = 9204 DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT); 9205 9206 Overflow = DAG.getBoolExtOrTrunc( 9207 DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl, 9208 ResultType, ResultType); 9209 } 9210 9211 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result, 9212 SDValue &Overflow, SelectionDAG &DAG) const { 9213 SDLoc dl(Node); 9214 EVT VT = Node->getValueType(0); 9215 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 9216 SDValue LHS = Node->getOperand(0); 9217 SDValue RHS = Node->getOperand(1); 9218 bool isSigned = Node->getOpcode() == ISD::SMULO; 9219 9220 // For power-of-two multiplications we can use a simpler shift expansion. 9221 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 9222 const APInt &C = RHSC->getAPIntValue(); 9223 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 9224 if (C.isPowerOf2()) { 9225 // smulo(x, signed_min) is same as umulo(x, signed_min). 9226 bool UseArithShift = isSigned && !C.isMinSignedValue(); 9227 EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout()); 9228 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy); 9229 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt); 9230 Overflow = DAG.getSetCC(dl, SetCCVT, 9231 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 9232 dl, VT, Result, ShiftAmt), 9233 LHS, ISD::SETNE); 9234 return true; 9235 } 9236 } 9237 9238 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2); 9239 if (VT.isVector()) 9240 WideVT = 9241 EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount()); 9242 9243 SDValue BottomHalf; 9244 SDValue TopHalf; 9245 static const unsigned Ops[2][3] = 9246 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 9247 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 9248 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 9249 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 9250 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 9251 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 9252 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 9253 RHS); 9254 TopHalf = BottomHalf.getValue(1); 9255 } else if (isTypeLegal(WideVT)) { 9256 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 9257 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 9258 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 9259 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul); 9260 SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl, 9261 getShiftAmountTy(WideVT, DAG.getDataLayout())); 9262 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, 9263 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt)); 9264 } else { 9265 if (VT.isVector()) 9266 return false; 9267 9268 // We can fall back to a libcall with an illegal type for the MUL if we 9269 // have a libcall big enough. 9270 // Also, we can fall back to a division in some cases, but that's a big 9271 // performance hit in the general case. 9272 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 9273 if (WideVT == MVT::i16) 9274 LC = RTLIB::MUL_I16; 9275 else if (WideVT == MVT::i32) 9276 LC = RTLIB::MUL_I32; 9277 else if (WideVT == MVT::i64) 9278 LC = RTLIB::MUL_I64; 9279 else if (WideVT == MVT::i128) 9280 LC = RTLIB::MUL_I128; 9281 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!"); 9282 9283 SDValue HiLHS; 9284 SDValue HiRHS; 9285 if (isSigned) { 9286 // The high part is obtained by SRA'ing all but one of the bits of low 9287 // part. 9288 unsigned LoSize = VT.getFixedSizeInBits(); 9289 HiLHS = 9290 DAG.getNode(ISD::SRA, dl, VT, LHS, 9291 DAG.getConstant(LoSize - 1, dl, 9292 getPointerTy(DAG.getDataLayout()))); 9293 HiRHS = 9294 DAG.getNode(ISD::SRA, dl, VT, RHS, 9295 DAG.getConstant(LoSize - 1, dl, 9296 getPointerTy(DAG.getDataLayout()))); 9297 } else { 9298 HiLHS = DAG.getConstant(0, dl, VT); 9299 HiRHS = DAG.getConstant(0, dl, VT); 9300 } 9301 9302 // Here we're passing the 2 arguments explicitly as 4 arguments that are 9303 // pre-lowered to the correct types. This all depends upon WideVT not 9304 // being a legal type for the architecture and thus has to be split to 9305 // two arguments. 9306 SDValue Ret; 9307 TargetLowering::MakeLibCallOptions CallOptions; 9308 CallOptions.setSExt(isSigned); 9309 CallOptions.setIsPostTypeLegalization(true); 9310 if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) { 9311 // Halves of WideVT are packed into registers in different order 9312 // depending on platform endianness. This is usually handled by 9313 // the C calling convention, but we can't defer to it in 9314 // the legalizer. 9315 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS }; 9316 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 9317 } else { 9318 SDValue Args[] = { HiLHS, LHS, HiRHS, RHS }; 9319 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 9320 } 9321 assert(Ret.getOpcode() == ISD::MERGE_VALUES && 9322 "Ret value is a collection of constituent nodes holding result."); 9323 if (DAG.getDataLayout().isLittleEndian()) { 9324 // Same as above. 9325 BottomHalf = Ret.getOperand(0); 9326 TopHalf = Ret.getOperand(1); 9327 } else { 9328 BottomHalf = Ret.getOperand(1); 9329 TopHalf = Ret.getOperand(0); 9330 } 9331 } 9332 9333 Result = BottomHalf; 9334 if (isSigned) { 9335 SDValue ShiftAmt = DAG.getConstant( 9336 VT.getScalarSizeInBits() - 1, dl, 9337 getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout())); 9338 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt); 9339 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE); 9340 } else { 9341 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, 9342 DAG.getConstant(0, dl, VT), ISD::SETNE); 9343 } 9344 9345 // Truncate the result if SetCC returns a larger type than needed. 9346 EVT RType = Node->getValueType(1); 9347 if (RType.bitsLT(Overflow.getValueType())) 9348 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow); 9349 9350 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() && 9351 "Unexpected result type for S/UMULO legalization"); 9352 return true; 9353 } 9354 9355 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const { 9356 SDLoc dl(Node); 9357 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 9358 SDValue Op = Node->getOperand(0); 9359 EVT VT = Op.getValueType(); 9360 9361 if (VT.isScalableVector()) 9362 report_fatal_error( 9363 "Expanding reductions for scalable vectors is undefined."); 9364 9365 // Try to use a shuffle reduction for power of two vectors. 9366 if (VT.isPow2VectorType()) { 9367 while (VT.getVectorNumElements() > 1) { 9368 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 9369 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) 9370 break; 9371 9372 SDValue Lo, Hi; 9373 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl); 9374 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi); 9375 VT = HalfVT; 9376 } 9377 } 9378 9379 EVT EltVT = VT.getVectorElementType(); 9380 unsigned NumElts = VT.getVectorNumElements(); 9381 9382 SmallVector<SDValue, 8> Ops; 9383 DAG.ExtractVectorElements(Op, Ops, 0, NumElts); 9384 9385 SDValue Res = Ops[0]; 9386 for (unsigned i = 1; i < NumElts; i++) 9387 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags()); 9388 9389 // Result type may be wider than element type. 9390 if (EltVT != Node->getValueType(0)) 9391 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res); 9392 return Res; 9393 } 9394 9395 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const { 9396 SDLoc dl(Node); 9397 SDValue AccOp = Node->getOperand(0); 9398 SDValue VecOp = Node->getOperand(1); 9399 SDNodeFlags Flags = Node->getFlags(); 9400 9401 EVT VT = VecOp.getValueType(); 9402 EVT EltVT = VT.getVectorElementType(); 9403 9404 if (VT.isScalableVector()) 9405 report_fatal_error( 9406 "Expanding reductions for scalable vectors is undefined."); 9407 9408 unsigned NumElts = VT.getVectorNumElements(); 9409 9410 SmallVector<SDValue, 8> Ops; 9411 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts); 9412 9413 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 9414 9415 SDValue Res = AccOp; 9416 for (unsigned i = 0; i < NumElts; i++) 9417 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags); 9418 9419 return Res; 9420 } 9421 9422 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result, 9423 SelectionDAG &DAG) const { 9424 EVT VT = Node->getValueType(0); 9425 SDLoc dl(Node); 9426 bool isSigned = Node->getOpcode() == ISD::SREM; 9427 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV; 9428 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 9429 SDValue Dividend = Node->getOperand(0); 9430 SDValue Divisor = Node->getOperand(1); 9431 if (isOperationLegalOrCustom(DivRemOpc, VT)) { 9432 SDVTList VTs = DAG.getVTList(VT, VT); 9433 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1); 9434 return true; 9435 } 9436 if (isOperationLegalOrCustom(DivOpc, VT)) { 9437 // X % Y -> X-X/Y*Y 9438 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor); 9439 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor); 9440 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 9441 return true; 9442 } 9443 return false; 9444 } 9445 9446 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node, 9447 SelectionDAG &DAG) const { 9448 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT; 9449 SDLoc dl(SDValue(Node, 0)); 9450 SDValue Src = Node->getOperand(0); 9451 9452 // DstVT is the result type, while SatVT is the size to which we saturate 9453 EVT SrcVT = Src.getValueType(); 9454 EVT DstVT = Node->getValueType(0); 9455 9456 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 9457 unsigned SatWidth = SatVT.getScalarSizeInBits(); 9458 unsigned DstWidth = DstVT.getScalarSizeInBits(); 9459 assert(SatWidth <= DstWidth && 9460 "Expected saturation width smaller than result width"); 9461 9462 // Determine minimum and maximum integer values and their corresponding 9463 // floating-point values. 9464 APInt MinInt, MaxInt; 9465 if (IsSigned) { 9466 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth); 9467 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth); 9468 } else { 9469 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth); 9470 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth); 9471 } 9472 9473 // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as 9474 // libcall emission cannot handle this. Large result types will fail. 9475 if (SrcVT == MVT::f16) { 9476 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src); 9477 SrcVT = Src.getValueType(); 9478 } 9479 9480 APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 9481 APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 9482 9483 APFloat::opStatus MinStatus = 9484 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero); 9485 APFloat::opStatus MaxStatus = 9486 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero); 9487 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) && 9488 !(MaxStatus & APFloat::opStatus::opInexact); 9489 9490 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT); 9491 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT); 9492 9493 // If the integer bounds are exactly representable as floats and min/max are 9494 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence 9495 // of comparisons and selects. 9496 bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) && 9497 isOperationLegal(ISD::FMAXNUM, SrcVT); 9498 if (AreExactFloatBounds && MinMaxLegal) { 9499 SDValue Clamped = Src; 9500 9501 // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat. 9502 Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode); 9503 // Clamp by MaxFloat from above. NaN cannot occur. 9504 Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode); 9505 // Convert clamped value to integer. 9506 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, 9507 dl, DstVT, Clamped); 9508 9509 // In the unsigned case we're done, because we mapped NaN to MinFloat, 9510 // which will cast to zero. 9511 if (!IsSigned) 9512 return FpToInt; 9513 9514 // Otherwise, select 0 if Src is NaN. 9515 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 9516 return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt, 9517 ISD::CondCode::SETUO); 9518 } 9519 9520 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT); 9521 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT); 9522 9523 // Result of direct conversion. The assumption here is that the operation is 9524 // non-trapping and it's fine to apply it to an out-of-range value if we 9525 // select it away later. 9526 SDValue FpToInt = 9527 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src); 9528 9529 SDValue Select = FpToInt; 9530 9531 // If Src ULT MinFloat, select MinInt. In particular, this also selects 9532 // MinInt if Src is NaN. 9533 Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select, 9534 ISD::CondCode::SETULT); 9535 // If Src OGT MaxFloat, select MaxInt. 9536 Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select, 9537 ISD::CondCode::SETOGT); 9538 9539 // In the unsigned case we are done, because we mapped NaN to MinInt, which 9540 // is already zero. 9541 if (!IsSigned) 9542 return Select; 9543 9544 // Otherwise, select 0 if Src is NaN. 9545 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 9546 return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO); 9547 } 9548 9549 SDValue TargetLowering::expandVectorSplice(SDNode *Node, 9550 SelectionDAG &DAG) const { 9551 assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!"); 9552 assert(Node->getValueType(0).isScalableVector() && 9553 "Fixed length vector types expected to use SHUFFLE_VECTOR!"); 9554 9555 EVT VT = Node->getValueType(0); 9556 SDValue V1 = Node->getOperand(0); 9557 SDValue V2 = Node->getOperand(1); 9558 int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue(); 9559 SDLoc DL(Node); 9560 9561 // Expand through memory thusly: 9562 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr 9563 // Store V1, Ptr 9564 // Store V2, Ptr + sizeof(V1) 9565 // If (Imm < 0) 9566 // TrailingElts = -Imm 9567 // Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt)) 9568 // else 9569 // Ptr = Ptr + (Imm * sizeof(VT.Elt)) 9570 // Res = Load Ptr 9571 9572 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false); 9573 9574 EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 9575 VT.getVectorElementCount() * 2); 9576 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment); 9577 EVT PtrVT = StackPtr.getValueType(); 9578 auto &MF = DAG.getMachineFunction(); 9579 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 9580 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex); 9581 9582 // Store the lo part of CONCAT_VECTORS(V1, V2) 9583 SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo); 9584 // Store the hi part of CONCAT_VECTORS(V1, V2) 9585 SDValue OffsetToV2 = DAG.getVScale( 9586 DL, PtrVT, 9587 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 9588 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2); 9589 SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo); 9590 9591 if (Imm >= 0) { 9592 // Load back the required element. getVectorElementPointer takes care of 9593 // clamping the index if it's out-of-bounds. 9594 StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2)); 9595 // Load the spliced result 9596 return DAG.getLoad(VT, DL, StoreV2, StackPtr, 9597 MachinePointerInfo::getUnknownStack(MF)); 9598 } 9599 9600 uint64_t TrailingElts = -Imm; 9601 9602 // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2. 9603 TypeSize EltByteSize = VT.getVectorElementType().getStoreSize(); 9604 SDValue TrailingBytes = 9605 DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT); 9606 9607 if (TrailingElts > VT.getVectorMinNumElements()) { 9608 SDValue VLBytes = DAG.getVScale( 9609 DL, PtrVT, 9610 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 9611 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes); 9612 } 9613 9614 // Calculate the start address of the spliced result. 9615 StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes); 9616 9617 // Load the spliced result 9618 return DAG.getLoad(VT, DL, StoreV2, StackPtr2, 9619 MachinePointerInfo::getUnknownStack(MF)); 9620 } 9621 9622 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, 9623 SDValue &LHS, SDValue &RHS, 9624 SDValue &CC, SDValue Mask, 9625 SDValue EVL, bool &NeedInvert, 9626 const SDLoc &dl, SDValue &Chain, 9627 bool IsSignaling) const { 9628 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9629 MVT OpVT = LHS.getSimpleValueType(); 9630 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get(); 9631 NeedInvert = false; 9632 assert(!EVL == !Mask && "VP Mask and EVL must either both be set or unset"); 9633 bool IsNonVP = !EVL; 9634 switch (TLI.getCondCodeAction(CCCode, OpVT)) { 9635 default: 9636 llvm_unreachable("Unknown condition code action!"); 9637 case TargetLowering::Legal: 9638 // Nothing to do. 9639 break; 9640 case TargetLowering::Expand: { 9641 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode); 9642 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9643 std::swap(LHS, RHS); 9644 CC = DAG.getCondCode(InvCC); 9645 return true; 9646 } 9647 // Swapping operands didn't work. Try inverting the condition. 9648 bool NeedSwap = false; 9649 InvCC = getSetCCInverse(CCCode, OpVT); 9650 if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9651 // If inverting the condition is not enough, try swapping operands 9652 // on top of it. 9653 InvCC = ISD::getSetCCSwappedOperands(InvCC); 9654 NeedSwap = true; 9655 } 9656 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 9657 CC = DAG.getCondCode(InvCC); 9658 NeedInvert = true; 9659 if (NeedSwap) 9660 std::swap(LHS, RHS); 9661 return true; 9662 } 9663 9664 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID; 9665 unsigned Opc = 0; 9666 switch (CCCode) { 9667 default: 9668 llvm_unreachable("Don't know how to expand this condition!"); 9669 case ISD::SETUO: 9670 if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) { 9671 CC1 = ISD::SETUNE; 9672 CC2 = ISD::SETUNE; 9673 Opc = ISD::OR; 9674 break; 9675 } 9676 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 9677 "If SETUE is expanded, SETOEQ or SETUNE must be legal!"); 9678 NeedInvert = true; 9679 LLVM_FALLTHROUGH; 9680 case ISD::SETO: 9681 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 9682 "If SETO is expanded, SETOEQ must be legal!"); 9683 CC1 = ISD::SETOEQ; 9684 CC2 = ISD::SETOEQ; 9685 Opc = ISD::AND; 9686 break; 9687 case ISD::SETONE: 9688 case ISD::SETUEQ: 9689 // If the SETUO or SETO CC isn't legal, we might be able to use 9690 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one 9691 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping 9692 // the operands. 9693 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 9694 if (!TLI.isCondCodeLegal(CC2, OpVT) && 9695 (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) || 9696 TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) { 9697 CC1 = ISD::SETOGT; 9698 CC2 = ISD::SETOLT; 9699 Opc = ISD::OR; 9700 NeedInvert = ((unsigned)CCCode & 0x8U); 9701 break; 9702 } 9703 LLVM_FALLTHROUGH; 9704 case ISD::SETOEQ: 9705 case ISD::SETOGT: 9706 case ISD::SETOGE: 9707 case ISD::SETOLT: 9708 case ISD::SETOLE: 9709 case ISD::SETUNE: 9710 case ISD::SETUGT: 9711 case ISD::SETUGE: 9712 case ISD::SETULT: 9713 case ISD::SETULE: 9714 // If we are floating point, assign and break, otherwise fall through. 9715 if (!OpVT.isInteger()) { 9716 // We can use the 4th bit to tell if we are the unordered 9717 // or ordered version of the opcode. 9718 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 9719 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND; 9720 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10); 9721 break; 9722 } 9723 // Fallthrough if we are unsigned integer. 9724 LLVM_FALLTHROUGH; 9725 case ISD::SETLE: 9726 case ISD::SETGT: 9727 case ISD::SETGE: 9728 case ISD::SETLT: 9729 case ISD::SETNE: 9730 case ISD::SETEQ: 9731 // If all combinations of inverting the condition and swapping operands 9732 // didn't work then we have no means to expand the condition. 9733 llvm_unreachable("Don't know how to expand this condition!"); 9734 } 9735 9736 SDValue SetCC1, SetCC2; 9737 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) { 9738 // If we aren't the ordered or unorder operation, 9739 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS). 9740 if (IsNonVP) { 9741 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling); 9742 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling); 9743 } else { 9744 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC1, Mask, EVL); 9745 SetCC2 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC2, Mask, EVL); 9746 } 9747 } else { 9748 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS) 9749 if (IsNonVP) { 9750 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling); 9751 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling); 9752 } else { 9753 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, LHS, CC1, Mask, EVL); 9754 SetCC2 = DAG.getSetCCVP(dl, VT, RHS, RHS, CC2, Mask, EVL); 9755 } 9756 } 9757 if (Chain) 9758 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1), 9759 SetCC2.getValue(1)); 9760 if (IsNonVP) 9761 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2); 9762 else { 9763 // Transform the binary opcode to the VP equivalent. 9764 assert((Opc == ISD::OR || Opc == ISD::AND) && "Unexpected opcode"); 9765 Opc = Opc == ISD::OR ? ISD::VP_OR : ISD::VP_AND; 9766 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2, Mask, EVL); 9767 } 9768 RHS = SDValue(); 9769 CC = SDValue(); 9770 return true; 9771 } 9772 } 9773 return false; 9774 } 9775