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/MachineFrameInfo.h" 17 #include "llvm/CodeGen/MachineFunction.h" 18 #include "llvm/CodeGen/MachineJumpTableInfo.h" 19 #include "llvm/CodeGen/MachineRegisterInfo.h" 20 #include "llvm/CodeGen/SelectionDAG.h" 21 #include "llvm/CodeGen/TargetRegisterInfo.h" 22 #include "llvm/CodeGen/TargetSubtargetInfo.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/ErrorHandling.h" 30 #include "llvm/Support/KnownBits.h" 31 #include "llvm/Support/MathExtras.h" 32 #include "llvm/Target/TargetLoweringObjectFile.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 NoAlias and NonNull because they don't affect the 61 // call sequence. 62 AttributeList CallerAttrs = F.getAttributes(); 63 if (AttrBuilder(CallerAttrs, AttributeList::ReturnIndex) 64 .removeAttribute(Attribute::NoAlias) 65 .removeAttribute(Attribute::NonNull) 66 .hasAttributes()) 67 return false; 68 69 // It's not safe to eliminate the sign / zero extension of the return value. 70 if (CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt) || 71 CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt)) 72 return false; 73 74 // Check if the only use is a function return node. 75 return isUsedByReturnOnly(Node, Chain); 76 } 77 78 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI, 79 const uint32_t *CallerPreservedMask, 80 const SmallVectorImpl<CCValAssign> &ArgLocs, 81 const SmallVectorImpl<SDValue> &OutVals) const { 82 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 83 const CCValAssign &ArgLoc = ArgLocs[I]; 84 if (!ArgLoc.isRegLoc()) 85 continue; 86 MCRegister Reg = ArgLoc.getLocReg(); 87 // Only look at callee saved registers. 88 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg)) 89 continue; 90 // Check that we pass the value used for the caller. 91 // (We look for a CopyFromReg reading a virtual register that is used 92 // for the function live-in value of register Reg) 93 SDValue Value = OutVals[I]; 94 if (Value->getOpcode() != ISD::CopyFromReg) 95 return false; 96 Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg(); 97 if (MRI.getLiveInPhysReg(ArgReg) != Reg) 98 return false; 99 } 100 return true; 101 } 102 103 /// Set CallLoweringInfo attribute flags based on a call instruction 104 /// and called function attributes. 105 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call, 106 unsigned ArgIdx) { 107 IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt); 108 IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt); 109 IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg); 110 IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet); 111 IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest); 112 IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal); 113 IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated); 114 IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca); 115 IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned); 116 IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf); 117 IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError); 118 Alignment = Call->getParamStackAlign(ArgIdx); 119 ByValType = nullptr; 120 if (IsByVal) { 121 ByValType = Call->getParamByValType(ArgIdx); 122 if (!Alignment) 123 Alignment = Call->getParamAlign(ArgIdx); 124 } 125 PreallocatedType = nullptr; 126 if (IsPreallocated) 127 PreallocatedType = Call->getParamPreallocatedType(ArgIdx); 128 } 129 130 /// Generate a libcall taking the given operands as arguments and returning a 131 /// result of type RetVT. 132 std::pair<SDValue, SDValue> 133 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, 134 ArrayRef<SDValue> Ops, 135 MakeLibCallOptions CallOptions, 136 const SDLoc &dl, 137 SDValue InChain) const { 138 if (!InChain) 139 InChain = DAG.getEntryNode(); 140 141 TargetLowering::ArgListTy Args; 142 Args.reserve(Ops.size()); 143 144 TargetLowering::ArgListEntry Entry; 145 for (unsigned i = 0; i < Ops.size(); ++i) { 146 SDValue NewOp = Ops[i]; 147 Entry.Node = NewOp; 148 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 149 Entry.IsSExt = shouldSignExtendTypeInLibCall(NewOp.getValueType(), 150 CallOptions.IsSExt); 151 Entry.IsZExt = !Entry.IsSExt; 152 153 if (CallOptions.IsSoften && 154 !shouldExtendTypeInLibCall(CallOptions.OpsVTBeforeSoften[i])) { 155 Entry.IsSExt = Entry.IsZExt = false; 156 } 157 Args.push_back(Entry); 158 } 159 160 if (LC == RTLIB::UNKNOWN_LIBCALL) 161 report_fatal_error("Unsupported library call operation!"); 162 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 163 getPointerTy(DAG.getDataLayout())); 164 165 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 166 TargetLowering::CallLoweringInfo CLI(DAG); 167 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, CallOptions.IsSExt); 168 bool zeroExtend = !signExtend; 169 170 if (CallOptions.IsSoften && 171 !shouldExtendTypeInLibCall(CallOptions.RetVTBeforeSoften)) { 172 signExtend = zeroExtend = false; 173 } 174 175 CLI.setDebugLoc(dl) 176 .setChain(InChain) 177 .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 178 .setNoReturn(CallOptions.DoesNotReturn) 179 .setDiscardResult(!CallOptions.IsReturnValueUsed) 180 .setIsPostTypeLegalization(CallOptions.IsPostTypeLegalization) 181 .setSExtResult(signExtend) 182 .setZExtResult(zeroExtend); 183 return LowerCallTo(CLI); 184 } 185 186 bool TargetLowering::findOptimalMemOpLowering( 187 std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, 188 unsigned SrcAS, const AttributeList &FuncAttributes) const { 189 if (Op.isMemcpyWithFixedDstAlign() && Op.getSrcAlign() < Op.getDstAlign()) 190 return false; 191 192 EVT VT = getOptimalMemOpType(Op, FuncAttributes); 193 194 if (VT == MVT::Other) { 195 // Use the largest integer type whose alignment constraints are satisfied. 196 // We only need to check DstAlign here as SrcAlign is always greater or 197 // equal to DstAlign (or zero). 198 VT = MVT::i64; 199 if (Op.isFixedDstAlign()) 200 while (Op.getDstAlign() < (VT.getSizeInBits() / 8) && 201 !allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign())) 202 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1); 203 assert(VT.isInteger()); 204 205 // Find the largest legal integer type. 206 MVT LVT = MVT::i64; 207 while (!isTypeLegal(LVT)) 208 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1); 209 assert(LVT.isInteger()); 210 211 // If the type we've chosen is larger than the largest legal integer type 212 // then use that instead. 213 if (VT.bitsGT(LVT)) 214 VT = LVT; 215 } 216 217 unsigned NumMemOps = 0; 218 uint64_t Size = Op.size(); 219 while (Size) { 220 unsigned VTSize = VT.getSizeInBits() / 8; 221 while (VTSize > Size) { 222 // For now, only use non-vector load / store's for the left-over pieces. 223 EVT NewVT = VT; 224 unsigned NewVTSize; 225 226 bool Found = false; 227 if (VT.isVector() || VT.isFloatingPoint()) { 228 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32; 229 if (isOperationLegalOrCustom(ISD::STORE, NewVT) && 230 isSafeMemOpType(NewVT.getSimpleVT())) 231 Found = true; 232 else if (NewVT == MVT::i64 && 233 isOperationLegalOrCustom(ISD::STORE, MVT::f64) && 234 isSafeMemOpType(MVT::f64)) { 235 // i64 is usually not legal on 32-bit targets, but f64 may be. 236 NewVT = MVT::f64; 237 Found = true; 238 } 239 } 240 241 if (!Found) { 242 do { 243 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1); 244 if (NewVT == MVT::i8) 245 break; 246 } while (!isSafeMemOpType(NewVT.getSimpleVT())); 247 } 248 NewVTSize = NewVT.getSizeInBits() / 8; 249 250 // If the new VT cannot cover all of the remaining bits, then consider 251 // issuing a (or a pair of) unaligned and overlapping load / store. 252 bool Fast; 253 if (NumMemOps && Op.allowOverlap() && NewVTSize < Size && 254 allowsMisalignedMemoryAccesses( 255 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1), 256 MachineMemOperand::MONone, &Fast) && 257 Fast) 258 VTSize = Size; 259 else { 260 VT = NewVT; 261 VTSize = NewVTSize; 262 } 263 } 264 265 if (++NumMemOps > Limit) 266 return false; 267 268 MemOps.push_back(VT); 269 Size -= VTSize; 270 } 271 272 return true; 273 } 274 275 /// Soften the operands of a comparison. This code is shared among BR_CC, 276 /// SELECT_CC, and SETCC handlers. 277 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 278 SDValue &NewLHS, SDValue &NewRHS, 279 ISD::CondCode &CCCode, 280 const SDLoc &dl, const SDValue OldLHS, 281 const SDValue OldRHS) const { 282 SDValue Chain; 283 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS, 284 OldRHS, Chain); 285 } 286 287 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 288 SDValue &NewLHS, SDValue &NewRHS, 289 ISD::CondCode &CCCode, 290 const SDLoc &dl, const SDValue OldLHS, 291 const SDValue OldRHS, 292 SDValue &Chain, 293 bool IsSignaling) const { 294 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc 295 // not supporting it. We can update this code when libgcc provides such 296 // functions. 297 298 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128) 299 && "Unsupported setcc type!"); 300 301 // Expand into one or more soft-fp libcall(s). 302 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL; 303 bool ShouldInvertCC = false; 304 switch (CCCode) { 305 case ISD::SETEQ: 306 case ISD::SETOEQ: 307 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 308 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 309 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 310 break; 311 case ISD::SETNE: 312 case ISD::SETUNE: 313 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : 314 (VT == MVT::f64) ? RTLIB::UNE_F64 : 315 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128; 316 break; 317 case ISD::SETGE: 318 case ISD::SETOGE: 319 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 320 (VT == MVT::f64) ? RTLIB::OGE_F64 : 321 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 322 break; 323 case ISD::SETLT: 324 case ISD::SETOLT: 325 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 326 (VT == MVT::f64) ? RTLIB::OLT_F64 : 327 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 328 break; 329 case ISD::SETLE: 330 case ISD::SETOLE: 331 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 332 (VT == MVT::f64) ? RTLIB::OLE_F64 : 333 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 334 break; 335 case ISD::SETGT: 336 case ISD::SETOGT: 337 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 338 (VT == MVT::f64) ? RTLIB::OGT_F64 : 339 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 340 break; 341 case ISD::SETO: 342 ShouldInvertCC = true; 343 LLVM_FALLTHROUGH; 344 case ISD::SETUO: 345 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 346 (VT == MVT::f64) ? RTLIB::UO_F64 : 347 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 348 break; 349 case ISD::SETONE: 350 // SETONE = O && UNE 351 ShouldInvertCC = true; 352 LLVM_FALLTHROUGH; 353 case ISD::SETUEQ: 354 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 355 (VT == MVT::f64) ? RTLIB::UO_F64 : 356 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 357 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 358 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 359 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 360 break; 361 default: 362 // Invert CC for unordered comparisons 363 ShouldInvertCC = true; 364 switch (CCCode) { 365 case ISD::SETULT: 366 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 367 (VT == MVT::f64) ? RTLIB::OGE_F64 : 368 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 369 break; 370 case ISD::SETULE: 371 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 372 (VT == MVT::f64) ? RTLIB::OGT_F64 : 373 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 374 break; 375 case ISD::SETUGT: 376 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 377 (VT == MVT::f64) ? RTLIB::OLE_F64 : 378 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 379 break; 380 case ISD::SETUGE: 381 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 382 (VT == MVT::f64) ? RTLIB::OLT_F64 : 383 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 384 break; 385 default: llvm_unreachable("Do not know how to soften this setcc!"); 386 } 387 } 388 389 // Use the target specific return value for comparions lib calls. 390 EVT RetVT = getCmpLibcallReturnType(); 391 SDValue Ops[2] = {NewLHS, NewRHS}; 392 TargetLowering::MakeLibCallOptions CallOptions; 393 EVT OpsVT[2] = { OldLHS.getValueType(), 394 OldRHS.getValueType() }; 395 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT, true); 396 auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain); 397 NewLHS = Call.first; 398 NewRHS = DAG.getConstant(0, dl, RetVT); 399 400 CCCode = getCmpLibcallCC(LC1); 401 if (ShouldInvertCC) { 402 assert(RetVT.isInteger()); 403 CCCode = getSetCCInverse(CCCode, RetVT); 404 } 405 406 if (LC2 == RTLIB::UNKNOWN_LIBCALL) { 407 // Update Chain. 408 Chain = Call.second; 409 } else { 410 EVT SetCCVT = 411 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT); 412 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode); 413 auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain); 414 CCCode = getCmpLibcallCC(LC2); 415 if (ShouldInvertCC) 416 CCCode = getSetCCInverse(CCCode, RetVT); 417 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode); 418 if (Chain) 419 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second, 420 Call2.second); 421 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl, 422 Tmp.getValueType(), Tmp, NewLHS); 423 NewRHS = SDValue(); 424 } 425 } 426 427 /// Return the entry encoding for a jump table in the current function. The 428 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum. 429 unsigned TargetLowering::getJumpTableEncoding() const { 430 // In non-pic modes, just use the address of a block. 431 if (!isPositionIndependent()) 432 return MachineJumpTableInfo::EK_BlockAddress; 433 434 // In PIC mode, if the target supports a GPRel32 directive, use it. 435 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr) 436 return MachineJumpTableInfo::EK_GPRel32BlockAddress; 437 438 // Otherwise, use a label difference. 439 return MachineJumpTableInfo::EK_LabelDifference32; 440 } 441 442 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table, 443 SelectionDAG &DAG) const { 444 // If our PIC model is GP relative, use the global offset table as the base. 445 unsigned JTEncoding = getJumpTableEncoding(); 446 447 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) || 448 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress)) 449 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout())); 450 451 return Table; 452 } 453 454 /// This returns the relocation base for the given PIC jumptable, the same as 455 /// getPICJumpTableRelocBase, but as an MCExpr. 456 const MCExpr * 457 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 458 unsigned JTI,MCContext &Ctx) const{ 459 // The normal PIC reloc base is the label at the start of the jump table. 460 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx); 461 } 462 463 bool 464 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 465 const TargetMachine &TM = getTargetMachine(); 466 const GlobalValue *GV = GA->getGlobal(); 467 468 // If the address is not even local to this DSO we will have to load it from 469 // a got and then add the offset. 470 if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 471 return false; 472 473 // If the code is position independent we will have to add a base register. 474 if (isPositionIndependent()) 475 return false; 476 477 // Otherwise we can do it. 478 return true; 479 } 480 481 //===----------------------------------------------------------------------===// 482 // Optimization Methods 483 //===----------------------------------------------------------------------===// 484 485 /// If the specified instruction has a constant integer operand and there are 486 /// bits set in that constant that are not demanded, then clear those bits and 487 /// return true. 488 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 489 const APInt &DemandedBits, 490 const APInt &DemandedElts, 491 TargetLoweringOpt &TLO) const { 492 SDLoc DL(Op); 493 unsigned Opcode = Op.getOpcode(); 494 495 // Do target-specific constant optimization. 496 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 497 return TLO.New.getNode(); 498 499 // FIXME: ISD::SELECT, ISD::SELECT_CC 500 switch (Opcode) { 501 default: 502 break; 503 case ISD::XOR: 504 case ISD::AND: 505 case ISD::OR: { 506 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 507 if (!Op1C) 508 return false; 509 510 // If this is a 'not' op, don't touch it because that's a canonical form. 511 const APInt &C = Op1C->getAPIntValue(); 512 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C)) 513 return false; 514 515 if (!C.isSubsetOf(DemandedBits)) { 516 EVT VT = Op.getValueType(); 517 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT); 518 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC); 519 return TLO.CombineTo(Op, NewOp); 520 } 521 522 break; 523 } 524 } 525 526 return false; 527 } 528 529 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 530 const APInt &DemandedBits, 531 TargetLoweringOpt &TLO) const { 532 EVT VT = Op.getValueType(); 533 APInt DemandedElts = VT.isVector() 534 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 535 : APInt(1, 1); 536 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO); 537 } 538 539 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. 540 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be 541 /// generalized for targets with other types of implicit widening casts. 542 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth, 543 const APInt &Demanded, 544 TargetLoweringOpt &TLO) const { 545 assert(Op.getNumOperands() == 2 && 546 "ShrinkDemandedOp only supports binary operators!"); 547 assert(Op.getNode()->getNumValues() == 1 && 548 "ShrinkDemandedOp only supports nodes with one result!"); 549 550 SelectionDAG &DAG = TLO.DAG; 551 SDLoc dl(Op); 552 553 // Early return, as this function cannot handle vector types. 554 if (Op.getValueType().isVector()) 555 return false; 556 557 // Don't do this if the node has another user, which may require the 558 // full value. 559 if (!Op.getNode()->hasOneUse()) 560 return false; 561 562 // Search for the smallest integer type with free casts to and from 563 // Op's type. For expedience, just check power-of-2 integer types. 564 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 565 unsigned DemandedSize = Demanded.getActiveBits(); 566 unsigned SmallVTBits = DemandedSize; 567 if (!isPowerOf2_32(SmallVTBits)) 568 SmallVTBits = NextPowerOf2(SmallVTBits); 569 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) { 570 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits); 571 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) && 572 TLI.isZExtFree(SmallVT, Op.getValueType())) { 573 // We found a type with free casts. 574 SDValue X = DAG.getNode( 575 Op.getOpcode(), dl, SmallVT, 576 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)), 577 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1))); 578 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?"); 579 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X); 580 return TLO.CombineTo(Op, Z); 581 } 582 } 583 return false; 584 } 585 586 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 587 DAGCombinerInfo &DCI) const { 588 SelectionDAG &DAG = DCI.DAG; 589 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 590 !DCI.isBeforeLegalizeOps()); 591 KnownBits Known; 592 593 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO); 594 if (Simplified) { 595 DCI.AddToWorklist(Op.getNode()); 596 DCI.CommitTargetLoweringOpt(TLO); 597 } 598 return Simplified; 599 } 600 601 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 602 KnownBits &Known, 603 TargetLoweringOpt &TLO, 604 unsigned Depth, 605 bool AssumeSingleUse) const { 606 EVT VT = Op.getValueType(); 607 608 // TODO: We can probably do more work on calculating the known bits and 609 // simplifying the operations for scalable vectors, but for now we just 610 // bail out. 611 if (VT.isScalableVector()) { 612 // Pretend we don't know anything for now. 613 Known = KnownBits(DemandedBits.getBitWidth()); 614 return false; 615 } 616 617 APInt DemandedElts = VT.isVector() 618 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 619 : APInt(1, 1); 620 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth, 621 AssumeSingleUse); 622 } 623 624 // TODO: Can we merge SelectionDAG::GetDemandedBits into this? 625 // TODO: Under what circumstances can we create nodes? Constant folding? 626 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 627 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 628 SelectionDAG &DAG, unsigned Depth) const { 629 // Limit search depth. 630 if (Depth >= SelectionDAG::MaxRecursionDepth) 631 return SDValue(); 632 633 // Ignore UNDEFs. 634 if (Op.isUndef()) 635 return SDValue(); 636 637 // Not demanding any bits/elts from Op. 638 if (DemandedBits == 0 || DemandedElts == 0) 639 return DAG.getUNDEF(Op.getValueType()); 640 641 unsigned NumElts = DemandedElts.getBitWidth(); 642 unsigned BitWidth = DemandedBits.getBitWidth(); 643 KnownBits LHSKnown, RHSKnown; 644 switch (Op.getOpcode()) { 645 case ISD::BITCAST: { 646 SDValue Src = peekThroughBitcasts(Op.getOperand(0)); 647 EVT SrcVT = Src.getValueType(); 648 EVT DstVT = Op.getValueType(); 649 if (SrcVT == DstVT) 650 return Src; 651 652 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 653 unsigned NumDstEltBits = DstVT.getScalarSizeInBits(); 654 if (NumSrcEltBits == NumDstEltBits) 655 if (SDValue V = SimplifyMultipleUseDemandedBits( 656 Src, DemandedBits, DemandedElts, DAG, Depth + 1)) 657 return DAG.getBitcast(DstVT, V); 658 659 // TODO - bigendian once we have test coverage. 660 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0 && 661 DAG.getDataLayout().isLittleEndian()) { 662 unsigned Scale = NumDstEltBits / NumSrcEltBits; 663 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 664 APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits); 665 APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts); 666 for (unsigned i = 0; i != Scale; ++i) { 667 unsigned Offset = i * NumSrcEltBits; 668 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, Offset); 669 if (!Sub.isNullValue()) { 670 DemandedSrcBits |= Sub; 671 for (unsigned j = 0; j != NumElts; ++j) 672 if (DemandedElts[j]) 673 DemandedSrcElts.setBit((j * Scale) + i); 674 } 675 } 676 677 if (SDValue V = SimplifyMultipleUseDemandedBits( 678 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 679 return DAG.getBitcast(DstVT, V); 680 } 681 682 // TODO - bigendian once we have test coverage. 683 if ((NumSrcEltBits % NumDstEltBits) == 0 && 684 DAG.getDataLayout().isLittleEndian()) { 685 unsigned Scale = NumSrcEltBits / NumDstEltBits; 686 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 687 APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits); 688 APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts); 689 for (unsigned i = 0; i != NumElts; ++i) 690 if (DemandedElts[i]) { 691 unsigned Offset = (i % Scale) * NumDstEltBits; 692 DemandedSrcBits.insertBits(DemandedBits, Offset); 693 DemandedSrcElts.setBit(i / Scale); 694 } 695 696 if (SDValue V = SimplifyMultipleUseDemandedBits( 697 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 698 return DAG.getBitcast(DstVT, V); 699 } 700 701 break; 702 } 703 case ISD::AND: { 704 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 705 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 706 707 // If all of the demanded bits are known 1 on one side, return the other. 708 // These bits cannot contribute to the result of the 'and' in this 709 // context. 710 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) 711 return Op.getOperand(0); 712 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One)) 713 return Op.getOperand(1); 714 break; 715 } 716 case ISD::OR: { 717 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 718 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 719 720 // If all of the demanded bits are known zero on one side, return the 721 // other. These bits cannot contribute to the result of the 'or' in this 722 // context. 723 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero)) 724 return Op.getOperand(0); 725 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero)) 726 return Op.getOperand(1); 727 break; 728 } 729 case ISD::XOR: { 730 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 731 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 732 733 // If all of the demanded bits are known zero on one side, return the 734 // other. 735 if (DemandedBits.isSubsetOf(RHSKnown.Zero)) 736 return Op.getOperand(0); 737 if (DemandedBits.isSubsetOf(LHSKnown.Zero)) 738 return Op.getOperand(1); 739 break; 740 } 741 case ISD::SHL: { 742 // If we are only demanding sign bits then we can use the shift source 743 // directly. 744 if (const APInt *MaxSA = 745 DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 746 SDValue Op0 = Op.getOperand(0); 747 unsigned ShAmt = MaxSA->getZExtValue(); 748 unsigned NumSignBits = 749 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 750 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 751 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 752 return Op0; 753 } 754 break; 755 } 756 case ISD::SETCC: { 757 SDValue Op0 = Op.getOperand(0); 758 SDValue Op1 = Op.getOperand(1); 759 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 760 // If (1) we only need the sign-bit, (2) the setcc operands are the same 761 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 762 // -1, we may be able to bypass the setcc. 763 if (DemandedBits.isSignMask() && 764 Op0.getScalarValueSizeInBits() == BitWidth && 765 getBooleanContents(Op0.getValueType()) == 766 BooleanContent::ZeroOrNegativeOneBooleanContent) { 767 // If we're testing X < 0, then this compare isn't needed - just use X! 768 // FIXME: We're limiting to integer types here, but this should also work 769 // if we don't care about FP signed-zero. The use of SETLT with FP means 770 // that we don't care about NaNs. 771 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 772 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 773 return Op0; 774 } 775 break; 776 } 777 case ISD::SIGN_EXTEND_INREG: { 778 // If none of the extended bits are demanded, eliminate the sextinreg. 779 SDValue Op0 = Op.getOperand(0); 780 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 781 unsigned ExBits = ExVT.getScalarSizeInBits(); 782 if (DemandedBits.getActiveBits() <= ExBits) 783 return Op0; 784 // If the input is already sign extended, just drop the extension. 785 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 786 if (NumSignBits >= (BitWidth - ExBits + 1)) 787 return Op0; 788 break; 789 } 790 case ISD::ANY_EXTEND_VECTOR_INREG: 791 case ISD::SIGN_EXTEND_VECTOR_INREG: 792 case ISD::ZERO_EXTEND_VECTOR_INREG: { 793 // If we only want the lowest element and none of extended bits, then we can 794 // return the bitcasted source vector. 795 SDValue Src = Op.getOperand(0); 796 EVT SrcVT = Src.getValueType(); 797 EVT DstVT = Op.getValueType(); 798 if (DemandedElts == 1 && DstVT.getSizeInBits() == SrcVT.getSizeInBits() && 799 DAG.getDataLayout().isLittleEndian() && 800 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) { 801 return DAG.getBitcast(DstVT, Src); 802 } 803 break; 804 } 805 case ISD::INSERT_VECTOR_ELT: { 806 // If we don't demand the inserted element, return the base vector. 807 SDValue Vec = Op.getOperand(0); 808 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 809 EVT VecVT = Vec.getValueType(); 810 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) && 811 !DemandedElts[CIdx->getZExtValue()]) 812 return Vec; 813 break; 814 } 815 case ISD::INSERT_SUBVECTOR: { 816 // If we don't demand the inserted subvector, return the base vector. 817 SDValue Vec = Op.getOperand(0); 818 SDValue Sub = Op.getOperand(1); 819 uint64_t Idx = Op.getConstantOperandVal(2); 820 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 821 if (DemandedElts.extractBits(NumSubElts, Idx) == 0) 822 return Vec; 823 break; 824 } 825 case ISD::VECTOR_SHUFFLE: { 826 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 827 828 // If all the demanded elts are from one operand and are inline, 829 // then we can use the operand directly. 830 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true; 831 for (unsigned i = 0; i != NumElts; ++i) { 832 int M = ShuffleMask[i]; 833 if (M < 0 || !DemandedElts[i]) 834 continue; 835 AllUndef = false; 836 IdentityLHS &= (M == (int)i); 837 IdentityRHS &= ((M - NumElts) == i); 838 } 839 840 if (AllUndef) 841 return DAG.getUNDEF(Op.getValueType()); 842 if (IdentityLHS) 843 return Op.getOperand(0); 844 if (IdentityRHS) 845 return Op.getOperand(1); 846 break; 847 } 848 default: 849 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) 850 if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode( 851 Op, DemandedBits, DemandedElts, DAG, Depth)) 852 return V; 853 break; 854 } 855 return SDValue(); 856 } 857 858 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 859 SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG, 860 unsigned Depth) const { 861 EVT VT = Op.getValueType(); 862 APInt DemandedElts = VT.isVector() 863 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 864 : APInt(1, 1); 865 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 866 Depth); 867 } 868 869 SDValue TargetLowering::SimplifyMultipleUseDemandedVectorElts( 870 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG, 871 unsigned Depth) const { 872 APInt DemandedBits = APInt::getAllOnesValue(Op.getScalarValueSizeInBits()); 873 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 874 Depth); 875 } 876 877 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the 878 /// result of Op are ever used downstream. If we can use this information to 879 /// simplify Op, create a new simplified DAG node and return true, returning the 880 /// original and new nodes in Old and New. Otherwise, analyze the expression and 881 /// return a mask of Known bits for the expression (used to simplify the 882 /// caller). The Known bits may only be accurate for those bits in the 883 /// OriginalDemandedBits and OriginalDemandedElts. 884 bool TargetLowering::SimplifyDemandedBits( 885 SDValue Op, const APInt &OriginalDemandedBits, 886 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 887 unsigned Depth, bool AssumeSingleUse) const { 888 unsigned BitWidth = OriginalDemandedBits.getBitWidth(); 889 assert(Op.getScalarValueSizeInBits() == BitWidth && 890 "Mask size mismatches value type size!"); 891 892 // Don't know anything. 893 Known = KnownBits(BitWidth); 894 895 // TODO: We can probably do more work on calculating the known bits and 896 // simplifying the operations for scalable vectors, but for now we just 897 // bail out. 898 if (Op.getValueType().isScalableVector()) 899 return false; 900 901 unsigned NumElts = OriginalDemandedElts.getBitWidth(); 902 assert((!Op.getValueType().isVector() || 903 NumElts == Op.getValueType().getVectorNumElements()) && 904 "Unexpected vector size"); 905 906 APInt DemandedBits = OriginalDemandedBits; 907 APInt DemandedElts = OriginalDemandedElts; 908 SDLoc dl(Op); 909 auto &DL = TLO.DAG.getDataLayout(); 910 911 // Undef operand. 912 if (Op.isUndef()) 913 return false; 914 915 if (Op.getOpcode() == ISD::Constant) { 916 // We know all of the bits for a constant! 917 Known = KnownBits::makeConstant(cast<ConstantSDNode>(Op)->getAPIntValue()); 918 return false; 919 } 920 921 if (Op.getOpcode() == ISD::ConstantFP) { 922 // We know all of the bits for a floating point constant! 923 Known = KnownBits::makeConstant( 924 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()); 925 return false; 926 } 927 928 // Other users may use these bits. 929 EVT VT = Op.getValueType(); 930 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) { 931 if (Depth != 0) { 932 // If not at the root, Just compute the Known bits to 933 // simplify things downstream. 934 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 935 return false; 936 } 937 // If this is the root being simplified, allow it to have multiple uses, 938 // just set the DemandedBits/Elts to all bits. 939 DemandedBits = APInt::getAllOnesValue(BitWidth); 940 DemandedElts = APInt::getAllOnesValue(NumElts); 941 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) { 942 // Not demanding any bits/elts from Op. 943 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 944 } else if (Depth >= SelectionDAG::MaxRecursionDepth) { 945 // Limit search depth. 946 return false; 947 } 948 949 KnownBits Known2; 950 switch (Op.getOpcode()) { 951 case ISD::TargetConstant: 952 llvm_unreachable("Can't simplify this node"); 953 case ISD::SCALAR_TO_VECTOR: { 954 if (!DemandedElts[0]) 955 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 956 957 KnownBits SrcKnown; 958 SDValue Src = Op.getOperand(0); 959 unsigned SrcBitWidth = Src.getScalarValueSizeInBits(); 960 APInt SrcDemandedBits = DemandedBits.zextOrSelf(SrcBitWidth); 961 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1)) 962 return true; 963 964 // Upper elements are undef, so only get the knownbits if we just demand 965 // the bottom element. 966 if (DemandedElts == 1) 967 Known = SrcKnown.anyextOrTrunc(BitWidth); 968 break; 969 } 970 case ISD::BUILD_VECTOR: 971 // Collect the known bits that are shared by every demanded element. 972 // TODO: Call SimplifyDemandedBits for non-constant demanded elements. 973 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 974 return false; // Don't fall through, will infinitely loop. 975 case ISD::LOAD: { 976 LoadSDNode *LD = cast<LoadSDNode>(Op); 977 if (getTargetConstantFromLoad(LD)) { 978 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 979 return false; // Don't fall through, will infinitely loop. 980 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 981 // If this is a ZEXTLoad and we are looking at the loaded value. 982 EVT MemVT = LD->getMemoryVT(); 983 unsigned MemBits = MemVT.getScalarSizeInBits(); 984 Known.Zero.setBitsFrom(MemBits); 985 return false; // Don't fall through, will infinitely loop. 986 } 987 break; 988 } 989 case ISD::INSERT_VECTOR_ELT: { 990 SDValue Vec = Op.getOperand(0); 991 SDValue Scl = Op.getOperand(1); 992 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 993 EVT VecVT = Vec.getValueType(); 994 995 // If index isn't constant, assume we need all vector elements AND the 996 // inserted element. 997 APInt DemandedVecElts(DemandedElts); 998 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) { 999 unsigned Idx = CIdx->getZExtValue(); 1000 DemandedVecElts.clearBit(Idx); 1001 1002 // Inserted element is not required. 1003 if (!DemandedElts[Idx]) 1004 return TLO.CombineTo(Op, Vec); 1005 } 1006 1007 KnownBits KnownScl; 1008 unsigned NumSclBits = Scl.getScalarValueSizeInBits(); 1009 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits); 1010 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1)) 1011 return true; 1012 1013 Known = KnownScl.anyextOrTrunc(BitWidth); 1014 1015 KnownBits KnownVec; 1016 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO, 1017 Depth + 1)) 1018 return true; 1019 1020 if (!!DemandedVecElts) 1021 Known = KnownBits::commonBits(Known, KnownVec); 1022 1023 return false; 1024 } 1025 case ISD::INSERT_SUBVECTOR: { 1026 // Demand any elements from the subvector and the remainder from the src its 1027 // inserted into. 1028 SDValue Src = Op.getOperand(0); 1029 SDValue Sub = Op.getOperand(1); 1030 uint64_t Idx = Op.getConstantOperandVal(2); 1031 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 1032 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 1033 APInt DemandedSrcElts = DemandedElts; 1034 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 1035 1036 KnownBits KnownSub, KnownSrc; 1037 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO, 1038 Depth + 1)) 1039 return true; 1040 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO, 1041 Depth + 1)) 1042 return true; 1043 1044 Known.Zero.setAllBits(); 1045 Known.One.setAllBits(); 1046 if (!!DemandedSubElts) 1047 Known = KnownBits::commonBits(Known, KnownSub); 1048 if (!!DemandedSrcElts) 1049 Known = KnownBits::commonBits(Known, KnownSrc); 1050 1051 // Attempt to avoid multi-use src if we don't need anything from it. 1052 if (!DemandedBits.isAllOnesValue() || !DemandedSubElts.isAllOnesValue() || 1053 !DemandedSrcElts.isAllOnesValue()) { 1054 SDValue NewSub = SimplifyMultipleUseDemandedBits( 1055 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1); 1056 SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1057 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1058 if (NewSub || NewSrc) { 1059 NewSub = NewSub ? NewSub : Sub; 1060 NewSrc = NewSrc ? NewSrc : Src; 1061 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub, 1062 Op.getOperand(2)); 1063 return TLO.CombineTo(Op, NewOp); 1064 } 1065 } 1066 break; 1067 } 1068 case ISD::EXTRACT_SUBVECTOR: { 1069 // Offset the demanded elts by the subvector index. 1070 SDValue Src = Op.getOperand(0); 1071 if (Src.getValueType().isScalableVector()) 1072 break; 1073 uint64_t Idx = Op.getConstantOperandVal(1); 1074 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 1075 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 1076 1077 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO, 1078 Depth + 1)) 1079 return true; 1080 1081 // Attempt to avoid multi-use src if we don't need anything from it. 1082 if (!DemandedBits.isAllOnesValue() || !DemandedSrcElts.isAllOnesValue()) { 1083 SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 1084 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1085 if (DemandedSrc) { 1086 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, 1087 Op.getOperand(1)); 1088 return TLO.CombineTo(Op, NewOp); 1089 } 1090 } 1091 break; 1092 } 1093 case ISD::CONCAT_VECTORS: { 1094 Known.Zero.setAllBits(); 1095 Known.One.setAllBits(); 1096 EVT SubVT = Op.getOperand(0).getValueType(); 1097 unsigned NumSubVecs = Op.getNumOperands(); 1098 unsigned NumSubElts = SubVT.getVectorNumElements(); 1099 for (unsigned i = 0; i != NumSubVecs; ++i) { 1100 APInt DemandedSubElts = 1101 DemandedElts.extractBits(NumSubElts, i * NumSubElts); 1102 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts, 1103 Known2, TLO, Depth + 1)) 1104 return true; 1105 // Known bits are shared by every demanded subvector element. 1106 if (!!DemandedSubElts) 1107 Known = KnownBits::commonBits(Known, Known2); 1108 } 1109 break; 1110 } 1111 case ISD::VECTOR_SHUFFLE: { 1112 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 1113 1114 // Collect demanded elements from shuffle operands.. 1115 APInt DemandedLHS(NumElts, 0); 1116 APInt DemandedRHS(NumElts, 0); 1117 for (unsigned i = 0; i != NumElts; ++i) { 1118 if (!DemandedElts[i]) 1119 continue; 1120 int M = ShuffleMask[i]; 1121 if (M < 0) { 1122 // For UNDEF elements, we don't know anything about the common state of 1123 // the shuffle result. 1124 DemandedLHS.clearAllBits(); 1125 DemandedRHS.clearAllBits(); 1126 break; 1127 } 1128 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 1129 if (M < (int)NumElts) 1130 DemandedLHS.setBit(M); 1131 else 1132 DemandedRHS.setBit(M - NumElts); 1133 } 1134 1135 if (!!DemandedLHS || !!DemandedRHS) { 1136 SDValue Op0 = Op.getOperand(0); 1137 SDValue Op1 = Op.getOperand(1); 1138 1139 Known.Zero.setAllBits(); 1140 Known.One.setAllBits(); 1141 if (!!DemandedLHS) { 1142 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO, 1143 Depth + 1)) 1144 return true; 1145 Known = KnownBits::commonBits(Known, Known2); 1146 } 1147 if (!!DemandedRHS) { 1148 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO, 1149 Depth + 1)) 1150 return true; 1151 Known = KnownBits::commonBits(Known, Known2); 1152 } 1153 1154 // Attempt to avoid multi-use ops if we don't need anything from them. 1155 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1156 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1); 1157 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1158 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1); 1159 if (DemandedOp0 || DemandedOp1) { 1160 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1161 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1162 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask); 1163 return TLO.CombineTo(Op, NewOp); 1164 } 1165 } 1166 break; 1167 } 1168 case ISD::AND: { 1169 SDValue Op0 = Op.getOperand(0); 1170 SDValue Op1 = Op.getOperand(1); 1171 1172 // If the RHS is a constant, check to see if the LHS would be zero without 1173 // using the bits from the RHS. Below, we use knowledge about the RHS to 1174 // simplify the LHS, here we're using information from the LHS to simplify 1175 // the RHS. 1176 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) { 1177 // Do not increment Depth here; that can cause an infinite loop. 1178 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth); 1179 // If the LHS already has zeros where RHSC does, this 'and' is dead. 1180 if ((LHSKnown.Zero & DemandedBits) == 1181 (~RHSC->getAPIntValue() & DemandedBits)) 1182 return TLO.CombineTo(Op, Op0); 1183 1184 // If any of the set bits in the RHS are known zero on the LHS, shrink 1185 // the constant. 1186 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits, 1187 DemandedElts, TLO)) 1188 return true; 1189 1190 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its 1191 // constant, but if this 'and' is only clearing bits that were just set by 1192 // the xor, then this 'and' can be eliminated by shrinking the mask of 1193 // the xor. For example, for a 32-bit X: 1194 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1 1195 if (isBitwiseNot(Op0) && Op0.hasOneUse() && 1196 LHSKnown.One == ~RHSC->getAPIntValue()) { 1197 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1); 1198 return TLO.CombineTo(Op, Xor); 1199 } 1200 } 1201 1202 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1203 Depth + 1)) 1204 return true; 1205 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1206 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts, 1207 Known2, TLO, Depth + 1)) 1208 return true; 1209 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1210 1211 // Attempt to avoid multi-use ops if we don't need anything from them. 1212 if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1213 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1214 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1215 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1216 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1217 if (DemandedOp0 || DemandedOp1) { 1218 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1219 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1220 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1221 return TLO.CombineTo(Op, NewOp); 1222 } 1223 } 1224 1225 // If all of the demanded bits are known one on one side, return the other. 1226 // These bits cannot contribute to the result of the 'and'. 1227 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) 1228 return TLO.CombineTo(Op, Op0); 1229 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One)) 1230 return TLO.CombineTo(Op, Op1); 1231 // If all of the demanded bits in the inputs are known zeros, return zero. 1232 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1233 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT)); 1234 // If the RHS is a constant, see if we can simplify it. 1235 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts, 1236 TLO)) 1237 return true; 1238 // If the operation can be done in a smaller type, do so. 1239 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1240 return true; 1241 1242 Known &= Known2; 1243 break; 1244 } 1245 case ISD::OR: { 1246 SDValue Op0 = Op.getOperand(0); 1247 SDValue Op1 = Op.getOperand(1); 1248 1249 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1250 Depth + 1)) 1251 return true; 1252 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1253 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts, 1254 Known2, TLO, Depth + 1)) 1255 return true; 1256 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1257 1258 // Attempt to avoid multi-use ops if we don't need anything from them. 1259 if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1260 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1261 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1262 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1263 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1264 if (DemandedOp0 || DemandedOp1) { 1265 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1266 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1267 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1268 return TLO.CombineTo(Op, NewOp); 1269 } 1270 } 1271 1272 // If all of the demanded bits are known zero on one side, return the other. 1273 // These bits cannot contribute to the result of the 'or'. 1274 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) 1275 return TLO.CombineTo(Op, Op0); 1276 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero)) 1277 return TLO.CombineTo(Op, Op1); 1278 // If the RHS is a constant, see if we can simplify it. 1279 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1280 return true; 1281 // If the operation can be done in a smaller type, do so. 1282 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1283 return true; 1284 1285 Known |= Known2; 1286 break; 1287 } 1288 case ISD::XOR: { 1289 SDValue Op0 = Op.getOperand(0); 1290 SDValue Op1 = Op.getOperand(1); 1291 1292 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1293 Depth + 1)) 1294 return true; 1295 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1296 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO, 1297 Depth + 1)) 1298 return true; 1299 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1300 1301 // Attempt to avoid multi-use ops if we don't need anything from them. 1302 if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1303 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1304 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1305 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1306 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1307 if (DemandedOp0 || DemandedOp1) { 1308 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1309 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1310 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1311 return TLO.CombineTo(Op, NewOp); 1312 } 1313 } 1314 1315 // If all of the demanded bits are known zero on one side, return the other. 1316 // These bits cannot contribute to the result of the 'xor'. 1317 if (DemandedBits.isSubsetOf(Known.Zero)) 1318 return TLO.CombineTo(Op, Op0); 1319 if (DemandedBits.isSubsetOf(Known2.Zero)) 1320 return TLO.CombineTo(Op, Op1); 1321 // If the operation can be done in a smaller type, do so. 1322 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1323 return true; 1324 1325 // If all of the unknown bits are known to be zero on one side or the other 1326 // turn this into an *inclusive* or. 1327 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 1328 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1329 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1)); 1330 1331 ConstantSDNode* C = isConstOrConstSplat(Op1, DemandedElts); 1332 if (C) { 1333 // If one side is a constant, and all of the set bits in the constant are 1334 // also known set on the other side, turn this into an AND, as we know 1335 // the bits will be cleared. 1336 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 1337 // NB: it is okay if more bits are known than are requested 1338 if (C->getAPIntValue() == Known2.One) { 1339 SDValue ANDC = 1340 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT); 1341 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC)); 1342 } 1343 1344 // If the RHS is a constant, see if we can change it. Don't alter a -1 1345 // constant because that's a 'not' op, and that is better for combining 1346 // and codegen. 1347 if (!C->isAllOnesValue() && 1348 DemandedBits.isSubsetOf(C->getAPIntValue())) { 1349 // We're flipping all demanded bits. Flip the undemanded bits too. 1350 SDValue New = TLO.DAG.getNOT(dl, Op0, VT); 1351 return TLO.CombineTo(Op, New); 1352 } 1353 } 1354 1355 // If we can't turn this into a 'not', try to shrink the constant. 1356 if (!C || !C->isAllOnesValue()) 1357 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1358 return true; 1359 1360 Known ^= Known2; 1361 break; 1362 } 1363 case ISD::SELECT: 1364 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO, 1365 Depth + 1)) 1366 return true; 1367 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO, 1368 Depth + 1)) 1369 return true; 1370 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1371 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1372 1373 // If the operands are constants, see if we can simplify them. 1374 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1375 return true; 1376 1377 // Only known if known in both the LHS and RHS. 1378 Known = KnownBits::commonBits(Known, Known2); 1379 break; 1380 case ISD::SELECT_CC: 1381 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO, 1382 Depth + 1)) 1383 return true; 1384 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO, 1385 Depth + 1)) 1386 return true; 1387 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1388 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1389 1390 // If the operands are constants, see if we can simplify them. 1391 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1392 return true; 1393 1394 // Only known if known in both the LHS and RHS. 1395 Known = KnownBits::commonBits(Known, Known2); 1396 break; 1397 case ISD::SETCC: { 1398 SDValue Op0 = Op.getOperand(0); 1399 SDValue Op1 = Op.getOperand(1); 1400 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 1401 // If (1) we only need the sign-bit, (2) the setcc operands are the same 1402 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 1403 // -1, we may be able to bypass the setcc. 1404 if (DemandedBits.isSignMask() && 1405 Op0.getScalarValueSizeInBits() == BitWidth && 1406 getBooleanContents(Op0.getValueType()) == 1407 BooleanContent::ZeroOrNegativeOneBooleanContent) { 1408 // If we're testing X < 0, then this compare isn't needed - just use X! 1409 // FIXME: We're limiting to integer types here, but this should also work 1410 // if we don't care about FP signed-zero. The use of SETLT with FP means 1411 // that we don't care about NaNs. 1412 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 1413 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 1414 return TLO.CombineTo(Op, Op0); 1415 1416 // TODO: Should we check for other forms of sign-bit comparisons? 1417 // Examples: X <= -1, X >= 0 1418 } 1419 if (getBooleanContents(Op0.getValueType()) == 1420 TargetLowering::ZeroOrOneBooleanContent && 1421 BitWidth > 1) 1422 Known.Zero.setBitsFrom(1); 1423 break; 1424 } 1425 case ISD::SHL: { 1426 SDValue Op0 = Op.getOperand(0); 1427 SDValue Op1 = Op.getOperand(1); 1428 EVT ShiftVT = Op1.getValueType(); 1429 1430 if (const APInt *SA = 1431 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1432 unsigned ShAmt = SA->getZExtValue(); 1433 if (ShAmt == 0) 1434 return TLO.CombineTo(Op, Op0); 1435 1436 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 1437 // single shift. We can do this if the bottom bits (which are shifted 1438 // out) are never demanded. 1439 // TODO - support non-uniform vector amounts. 1440 if (Op0.getOpcode() == ISD::SRL) { 1441 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) { 1442 if (const APInt *SA2 = 1443 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1444 unsigned C1 = SA2->getZExtValue(); 1445 unsigned Opc = ISD::SHL; 1446 int Diff = ShAmt - C1; 1447 if (Diff < 0) { 1448 Diff = -Diff; 1449 Opc = ISD::SRL; 1450 } 1451 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1452 return TLO.CombineTo( 1453 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1454 } 1455 } 1456 } 1457 1458 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 1459 // are not demanded. This will likely allow the anyext to be folded away. 1460 // TODO - support non-uniform vector amounts. 1461 if (Op0.getOpcode() == ISD::ANY_EXTEND) { 1462 SDValue InnerOp = Op0.getOperand(0); 1463 EVT InnerVT = InnerOp.getValueType(); 1464 unsigned InnerBits = InnerVT.getScalarSizeInBits(); 1465 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits && 1466 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 1467 EVT ShTy = getShiftAmountTy(InnerVT, DL); 1468 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits())) 1469 ShTy = InnerVT; 1470 SDValue NarrowShl = 1471 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp, 1472 TLO.DAG.getConstant(ShAmt, dl, ShTy)); 1473 return TLO.CombineTo( 1474 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl)); 1475 } 1476 1477 // Repeat the SHL optimization above in cases where an extension 1478 // intervenes: (shl (anyext (shr x, c1)), c2) to 1479 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 1480 // aren't demanded (as above) and that the shifted upper c1 bits of 1481 // x aren't demanded. 1482 // TODO - support non-uniform vector amounts. 1483 if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL && 1484 InnerOp.hasOneUse()) { 1485 if (const APInt *SA2 = 1486 TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) { 1487 unsigned InnerShAmt = SA2->getZExtValue(); 1488 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits && 1489 DemandedBits.getActiveBits() <= 1490 (InnerBits - InnerShAmt + ShAmt) && 1491 DemandedBits.countTrailingZeros() >= ShAmt) { 1492 SDValue NewSA = 1493 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT); 1494 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 1495 InnerOp.getOperand(0)); 1496 return TLO.CombineTo( 1497 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA)); 1498 } 1499 } 1500 } 1501 } 1502 1503 APInt InDemandedMask = DemandedBits.lshr(ShAmt); 1504 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1505 Depth + 1)) 1506 return true; 1507 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1508 Known.Zero <<= ShAmt; 1509 Known.One <<= ShAmt; 1510 // low bits known zero. 1511 Known.Zero.setLowBits(ShAmt); 1512 1513 // Try shrinking the operation as long as the shift amount will still be 1514 // in range. 1515 if ((ShAmt < DemandedBits.getActiveBits()) && 1516 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1517 return true; 1518 } 1519 1520 // If we are only demanding sign bits then we can use the shift source 1521 // directly. 1522 if (const APInt *MaxSA = 1523 TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 1524 unsigned ShAmt = MaxSA->getZExtValue(); 1525 unsigned NumSignBits = 1526 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1527 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1528 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 1529 return TLO.CombineTo(Op, Op0); 1530 } 1531 break; 1532 } 1533 case ISD::SRL: { 1534 SDValue Op0 = Op.getOperand(0); 1535 SDValue Op1 = Op.getOperand(1); 1536 EVT ShiftVT = Op1.getValueType(); 1537 1538 if (const APInt *SA = 1539 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1540 unsigned ShAmt = SA->getZExtValue(); 1541 if (ShAmt == 0) 1542 return TLO.CombineTo(Op, Op0); 1543 1544 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 1545 // single shift. We can do this if the top bits (which are shifted out) 1546 // are never demanded. 1547 // TODO - support non-uniform vector amounts. 1548 if (Op0.getOpcode() == ISD::SHL) { 1549 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) { 1550 if (const APInt *SA2 = 1551 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1552 unsigned C1 = SA2->getZExtValue(); 1553 unsigned Opc = ISD::SRL; 1554 int Diff = ShAmt - C1; 1555 if (Diff < 0) { 1556 Diff = -Diff; 1557 Opc = ISD::SHL; 1558 } 1559 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1560 return TLO.CombineTo( 1561 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1562 } 1563 } 1564 } 1565 1566 APInt InDemandedMask = (DemandedBits << ShAmt); 1567 1568 // If the shift is exact, then it does demand the low bits (and knows that 1569 // they are zero). 1570 if (Op->getFlags().hasExact()) 1571 InDemandedMask.setLowBits(ShAmt); 1572 1573 // Compute the new bits that are at the top now. 1574 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1575 Depth + 1)) 1576 return true; 1577 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1578 Known.Zero.lshrInPlace(ShAmt); 1579 Known.One.lshrInPlace(ShAmt); 1580 // High bits known zero. 1581 Known.Zero.setHighBits(ShAmt); 1582 } 1583 break; 1584 } 1585 case ISD::SRA: { 1586 SDValue Op0 = Op.getOperand(0); 1587 SDValue Op1 = Op.getOperand(1); 1588 EVT ShiftVT = Op1.getValueType(); 1589 1590 // If we only want bits that already match the signbit then we don't need 1591 // to shift. 1592 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1593 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >= 1594 NumHiDemandedBits) 1595 return TLO.CombineTo(Op, Op0); 1596 1597 // If this is an arithmetic shift right and only the low-bit is set, we can 1598 // always convert this into a logical shr, even if the shift amount is 1599 // variable. The low bit of the shift cannot be an input sign bit unless 1600 // the shift amount is >= the size of the datatype, which is undefined. 1601 if (DemandedBits.isOneValue()) 1602 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 1603 1604 if (const APInt *SA = 1605 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1606 unsigned ShAmt = SA->getZExtValue(); 1607 if (ShAmt == 0) 1608 return TLO.CombineTo(Op, Op0); 1609 1610 APInt InDemandedMask = (DemandedBits << ShAmt); 1611 1612 // If the shift is exact, then it does demand the low bits (and knows that 1613 // they are zero). 1614 if (Op->getFlags().hasExact()) 1615 InDemandedMask.setLowBits(ShAmt); 1616 1617 // If any of the demanded bits are produced by the sign extension, we also 1618 // demand the input sign bit. 1619 if (DemandedBits.countLeadingZeros() < ShAmt) 1620 InDemandedMask.setSignBit(); 1621 1622 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1623 Depth + 1)) 1624 return true; 1625 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1626 Known.Zero.lshrInPlace(ShAmt); 1627 Known.One.lshrInPlace(ShAmt); 1628 1629 // If the input sign bit is known to be zero, or if none of the top bits 1630 // are demanded, turn this into an unsigned shift right. 1631 if (Known.Zero[BitWidth - ShAmt - 1] || 1632 DemandedBits.countLeadingZeros() >= ShAmt) { 1633 SDNodeFlags Flags; 1634 Flags.setExact(Op->getFlags().hasExact()); 1635 return TLO.CombineTo( 1636 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags)); 1637 } 1638 1639 int Log2 = DemandedBits.exactLogBase2(); 1640 if (Log2 >= 0) { 1641 // The bit must come from the sign. 1642 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT); 1643 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA)); 1644 } 1645 1646 if (Known.One[BitWidth - ShAmt - 1]) 1647 // New bits are known one. 1648 Known.One.setHighBits(ShAmt); 1649 1650 // Attempt to avoid multi-use ops if we don't need anything from them. 1651 if (!InDemandedMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1652 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1653 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1654 if (DemandedOp0) { 1655 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1); 1656 return TLO.CombineTo(Op, NewOp); 1657 } 1658 } 1659 } 1660 break; 1661 } 1662 case ISD::FSHL: 1663 case ISD::FSHR: { 1664 SDValue Op0 = Op.getOperand(0); 1665 SDValue Op1 = Op.getOperand(1); 1666 SDValue Op2 = Op.getOperand(2); 1667 bool IsFSHL = (Op.getOpcode() == ISD::FSHL); 1668 1669 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) { 1670 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 1671 1672 // For fshl, 0-shift returns the 1st arg. 1673 // For fshr, 0-shift returns the 2nd arg. 1674 if (Amt == 0) { 1675 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts, 1676 Known, TLO, Depth + 1)) 1677 return true; 1678 break; 1679 } 1680 1681 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt)) 1682 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt) 1683 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt)); 1684 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt); 1685 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 1686 Depth + 1)) 1687 return true; 1688 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO, 1689 Depth + 1)) 1690 return true; 1691 1692 Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1693 Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1694 Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1695 Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1696 Known.One |= Known2.One; 1697 Known.Zero |= Known2.Zero; 1698 } 1699 1700 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1701 if (isPowerOf2_32(BitWidth)) { 1702 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1); 1703 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, 1704 Known2, TLO, Depth + 1)) 1705 return true; 1706 } 1707 break; 1708 } 1709 case ISD::ROTL: 1710 case ISD::ROTR: { 1711 SDValue Op0 = Op.getOperand(0); 1712 SDValue Op1 = Op.getOperand(1); 1713 1714 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 1715 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1)) 1716 return TLO.CombineTo(Op, Op0); 1717 1718 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1719 if (isPowerOf2_32(BitWidth)) { 1720 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1); 1721 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO, 1722 Depth + 1)) 1723 return true; 1724 } 1725 break; 1726 } 1727 case ISD::UMIN: { 1728 // Check if one arg is always less than (or equal) to the other arg. 1729 SDValue Op0 = Op.getOperand(0); 1730 SDValue Op1 = Op.getOperand(1); 1731 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 1732 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 1733 Known = KnownBits::umin(Known0, Known1); 1734 if (Optional<bool> IsULE = KnownBits::ule(Known0, Known1)) 1735 return TLO.CombineTo(Op, IsULE.getValue() ? Op0 : Op1); 1736 if (Optional<bool> IsULT = KnownBits::ult(Known0, Known1)) 1737 return TLO.CombineTo(Op, IsULT.getValue() ? Op0 : Op1); 1738 break; 1739 } 1740 case ISD::UMAX: { 1741 // Check if one arg is always greater than (or equal) to the other arg. 1742 SDValue Op0 = Op.getOperand(0); 1743 SDValue Op1 = Op.getOperand(1); 1744 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 1745 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 1746 Known = KnownBits::umax(Known0, Known1); 1747 if (Optional<bool> IsUGE = KnownBits::uge(Known0, Known1)) 1748 return TLO.CombineTo(Op, IsUGE.getValue() ? Op0 : Op1); 1749 if (Optional<bool> IsUGT = KnownBits::ugt(Known0, Known1)) 1750 return TLO.CombineTo(Op, IsUGT.getValue() ? Op0 : Op1); 1751 break; 1752 } 1753 case ISD::BITREVERSE: { 1754 SDValue Src = Op.getOperand(0); 1755 APInt DemandedSrcBits = DemandedBits.reverseBits(); 1756 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 1757 Depth + 1)) 1758 return true; 1759 Known.One = Known2.One.reverseBits(); 1760 Known.Zero = Known2.Zero.reverseBits(); 1761 break; 1762 } 1763 case ISD::BSWAP: { 1764 SDValue Src = Op.getOperand(0); 1765 APInt DemandedSrcBits = DemandedBits.byteSwap(); 1766 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 1767 Depth + 1)) 1768 return true; 1769 Known.One = Known2.One.byteSwap(); 1770 Known.Zero = Known2.Zero.byteSwap(); 1771 break; 1772 } 1773 case ISD::CTPOP: { 1774 // If only 1 bit is demanded, replace with PARITY as long as we're before 1775 // op legalization. 1776 // FIXME: Limit to scalars for now. 1777 if (DemandedBits.isOneValue() && !TLO.LegalOps && !VT.isVector()) 1778 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT, 1779 Op.getOperand(0))); 1780 1781 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1782 break; 1783 } 1784 case ISD::SIGN_EXTEND_INREG: { 1785 SDValue Op0 = Op.getOperand(0); 1786 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1787 unsigned ExVTBits = ExVT.getScalarSizeInBits(); 1788 1789 // If we only care about the highest bit, don't bother shifting right. 1790 if (DemandedBits.isSignMask()) { 1791 unsigned NumSignBits = 1792 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1793 bool AlreadySignExtended = NumSignBits >= BitWidth - ExVTBits + 1; 1794 // However if the input is already sign extended we expect the sign 1795 // extension to be dropped altogether later and do not simplify. 1796 if (!AlreadySignExtended) { 1797 // Compute the correct shift amount type, which must be getShiftAmountTy 1798 // for scalar types after legalization. 1799 EVT ShiftAmtTy = VT; 1800 if (TLO.LegalTypes() && !ShiftAmtTy.isVector()) 1801 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL); 1802 1803 SDValue ShiftAmt = 1804 TLO.DAG.getConstant(BitWidth - ExVTBits, dl, ShiftAmtTy); 1805 return TLO.CombineTo(Op, 1806 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt)); 1807 } 1808 } 1809 1810 // If none of the extended bits are demanded, eliminate the sextinreg. 1811 if (DemandedBits.getActiveBits() <= ExVTBits) 1812 return TLO.CombineTo(Op, Op0); 1813 1814 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits); 1815 1816 // Since the sign extended bits are demanded, we know that the sign 1817 // bit is demanded. 1818 InputDemandedBits.setBit(ExVTBits - 1); 1819 1820 if (SimplifyDemandedBits(Op0, InputDemandedBits, Known, TLO, Depth + 1)) 1821 return true; 1822 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1823 1824 // If the sign bit of the input is known set or clear, then we know the 1825 // top bits of the result. 1826 1827 // If the input sign bit is known zero, convert this into a zero extension. 1828 if (Known.Zero[ExVTBits - 1]) 1829 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT)); 1830 1831 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits); 1832 if (Known.One[ExVTBits - 1]) { // Input sign bit known set 1833 Known.One.setBitsFrom(ExVTBits); 1834 Known.Zero &= Mask; 1835 } else { // Input sign bit unknown 1836 Known.Zero &= Mask; 1837 Known.One &= Mask; 1838 } 1839 break; 1840 } 1841 case ISD::BUILD_PAIR: { 1842 EVT HalfVT = Op.getOperand(0).getValueType(); 1843 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 1844 1845 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 1846 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 1847 1848 KnownBits KnownLo, KnownHi; 1849 1850 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1)) 1851 return true; 1852 1853 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1)) 1854 return true; 1855 1856 Known.Zero = KnownLo.Zero.zext(BitWidth) | 1857 KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth); 1858 1859 Known.One = KnownLo.One.zext(BitWidth) | 1860 KnownHi.One.zext(BitWidth).shl(HalfBitWidth); 1861 break; 1862 } 1863 case ISD::ZERO_EXTEND: 1864 case ISD::ZERO_EXTEND_VECTOR_INREG: { 1865 SDValue Src = Op.getOperand(0); 1866 EVT SrcVT = Src.getValueType(); 1867 unsigned InBits = SrcVT.getScalarSizeInBits(); 1868 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 1869 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG; 1870 1871 // If none of the top bits are demanded, convert this into an any_extend. 1872 if (DemandedBits.getActiveBits() <= InBits) { 1873 // If we only need the non-extended bits of the bottom element 1874 // then we can just bitcast to the result. 1875 if (IsVecInReg && DemandedElts == 1 && 1876 VT.getSizeInBits() == SrcVT.getSizeInBits() && 1877 TLO.DAG.getDataLayout().isLittleEndian()) 1878 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 1879 1880 unsigned Opc = 1881 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 1882 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 1883 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 1884 } 1885 1886 APInt InDemandedBits = DemandedBits.trunc(InBits); 1887 APInt InDemandedElts = DemandedElts.zextOrSelf(InElts); 1888 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 1889 Depth + 1)) 1890 return true; 1891 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1892 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 1893 Known = Known.zext(BitWidth); 1894 1895 // Attempt to avoid multi-use ops if we don't need anything from them. 1896 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1897 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 1898 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 1899 break; 1900 } 1901 case ISD::SIGN_EXTEND: 1902 case ISD::SIGN_EXTEND_VECTOR_INREG: { 1903 SDValue Src = Op.getOperand(0); 1904 EVT SrcVT = Src.getValueType(); 1905 unsigned InBits = SrcVT.getScalarSizeInBits(); 1906 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 1907 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG; 1908 1909 // If none of the top bits are demanded, convert this into an any_extend. 1910 if (DemandedBits.getActiveBits() <= InBits) { 1911 // If we only need the non-extended bits of the bottom element 1912 // then we can just bitcast to the result. 1913 if (IsVecInReg && DemandedElts == 1 && 1914 VT.getSizeInBits() == SrcVT.getSizeInBits() && 1915 TLO.DAG.getDataLayout().isLittleEndian()) 1916 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 1917 1918 unsigned Opc = 1919 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 1920 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 1921 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 1922 } 1923 1924 APInt InDemandedBits = DemandedBits.trunc(InBits); 1925 APInt InDemandedElts = DemandedElts.zextOrSelf(InElts); 1926 1927 // Since some of the sign extended bits are demanded, we know that the sign 1928 // bit is demanded. 1929 InDemandedBits.setBit(InBits - 1); 1930 1931 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 1932 Depth + 1)) 1933 return true; 1934 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1935 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 1936 1937 // If the sign bit is known one, the top bits match. 1938 Known = Known.sext(BitWidth); 1939 1940 // If the sign bit is known zero, convert this to a zero extend. 1941 if (Known.isNonNegative()) { 1942 unsigned Opc = 1943 IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND; 1944 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 1945 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 1946 } 1947 1948 // Attempt to avoid multi-use ops if we don't need anything from them. 1949 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1950 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 1951 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 1952 break; 1953 } 1954 case ISD::ANY_EXTEND: 1955 case ISD::ANY_EXTEND_VECTOR_INREG: { 1956 SDValue Src = Op.getOperand(0); 1957 EVT SrcVT = Src.getValueType(); 1958 unsigned InBits = SrcVT.getScalarSizeInBits(); 1959 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 1960 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG; 1961 1962 // If we only need the bottom element then we can just bitcast. 1963 // TODO: Handle ANY_EXTEND? 1964 if (IsVecInReg && DemandedElts == 1 && 1965 VT.getSizeInBits() == SrcVT.getSizeInBits() && 1966 TLO.DAG.getDataLayout().isLittleEndian()) 1967 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 1968 1969 APInt InDemandedBits = DemandedBits.trunc(InBits); 1970 APInt InDemandedElts = DemandedElts.zextOrSelf(InElts); 1971 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 1972 Depth + 1)) 1973 return true; 1974 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1975 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 1976 Known = Known.anyext(BitWidth); 1977 1978 // Attempt to avoid multi-use ops if we don't need anything from them. 1979 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1980 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 1981 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 1982 break; 1983 } 1984 case ISD::TRUNCATE: { 1985 SDValue Src = Op.getOperand(0); 1986 1987 // Simplify the input, using demanded bit information, and compute the known 1988 // zero/one bits live out. 1989 unsigned OperandBitWidth = Src.getScalarValueSizeInBits(); 1990 APInt TruncMask = DemandedBits.zext(OperandBitWidth); 1991 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO, 1992 Depth + 1)) 1993 return true; 1994 Known = Known.trunc(BitWidth); 1995 1996 // Attempt to avoid multi-use ops if we don't need anything from them. 1997 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1998 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1)) 1999 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc)); 2000 2001 // If the input is only used by this truncate, see if we can shrink it based 2002 // on the known demanded bits. 2003 if (Src.getNode()->hasOneUse()) { 2004 switch (Src.getOpcode()) { 2005 default: 2006 break; 2007 case ISD::SRL: 2008 // Shrink SRL by a constant if none of the high bits shifted in are 2009 // demanded. 2010 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT)) 2011 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 2012 // undesirable. 2013 break; 2014 2015 const APInt *ShAmtC = 2016 TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts); 2017 if (!ShAmtC || ShAmtC->uge(BitWidth)) 2018 break; 2019 uint64_t ShVal = ShAmtC->getZExtValue(); 2020 2021 APInt HighBits = 2022 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth); 2023 HighBits.lshrInPlace(ShVal); 2024 HighBits = HighBits.trunc(BitWidth); 2025 2026 if (!(HighBits & DemandedBits)) { 2027 // None of the shifted in bits are needed. Add a truncate of the 2028 // shift input, then shift it. 2029 SDValue NewShAmt = TLO.DAG.getConstant( 2030 ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes())); 2031 SDValue NewTrunc = 2032 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0)); 2033 return TLO.CombineTo( 2034 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt)); 2035 } 2036 break; 2037 } 2038 } 2039 2040 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2041 break; 2042 } 2043 case ISD::AssertZext: { 2044 // AssertZext demands all of the high bits, plus any of the low bits 2045 // demanded by its users. 2046 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2047 APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits()); 2048 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known, 2049 TLO, Depth + 1)) 2050 return true; 2051 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 2052 2053 Known.Zero |= ~InMask; 2054 break; 2055 } 2056 case ISD::EXTRACT_VECTOR_ELT: { 2057 SDValue Src = Op.getOperand(0); 2058 SDValue Idx = Op.getOperand(1); 2059 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount(); 2060 unsigned EltBitWidth = Src.getScalarValueSizeInBits(); 2061 2062 if (SrcEltCnt.isScalable()) 2063 return false; 2064 2065 // Demand the bits from every vector element without a constant index. 2066 unsigned NumSrcElts = SrcEltCnt.getFixedValue(); 2067 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts); 2068 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx)) 2069 if (CIdx->getAPIntValue().ult(NumSrcElts)) 2070 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue()); 2071 2072 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 2073 // anything about the extended bits. 2074 APInt DemandedSrcBits = DemandedBits; 2075 if (BitWidth > EltBitWidth) 2076 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth); 2077 2078 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO, 2079 Depth + 1)) 2080 return true; 2081 2082 // Attempt to avoid multi-use ops if we don't need anything from them. 2083 if (!DemandedSrcBits.isAllOnesValue() || 2084 !DemandedSrcElts.isAllOnesValue()) { 2085 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 2086 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) { 2087 SDValue NewOp = 2088 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx); 2089 return TLO.CombineTo(Op, NewOp); 2090 } 2091 } 2092 2093 Known = Known2; 2094 if (BitWidth > EltBitWidth) 2095 Known = Known.anyext(BitWidth); 2096 break; 2097 } 2098 case ISD::BITCAST: { 2099 SDValue Src = Op.getOperand(0); 2100 EVT SrcVT = Src.getValueType(); 2101 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 2102 2103 // If this is an FP->Int bitcast and if the sign bit is the only 2104 // thing demanded, turn this into a FGETSIGN. 2105 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() && 2106 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) && 2107 SrcVT.isFloatingPoint()) { 2108 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT); 2109 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 2110 if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 && 2111 SrcVT != MVT::f128) { 2112 // Cannot eliminate/lower SHL for f128 yet. 2113 EVT Ty = OpVTLegal ? VT : MVT::i32; 2114 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 2115 // place. We expect the SHL to be eliminated by other optimizations. 2116 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src); 2117 unsigned OpVTSizeInBits = Op.getValueSizeInBits(); 2118 if (!OpVTLegal && OpVTSizeInBits > 32) 2119 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign); 2120 unsigned ShVal = Op.getValueSizeInBits() - 1; 2121 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT); 2122 return TLO.CombineTo(Op, 2123 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt)); 2124 } 2125 } 2126 2127 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts. 2128 // Demand the elt/bit if any of the original elts/bits are demanded. 2129 // TODO - bigendian once we have test coverage. 2130 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0 && 2131 TLO.DAG.getDataLayout().isLittleEndian()) { 2132 unsigned Scale = BitWidth / NumSrcEltBits; 2133 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2134 APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits); 2135 APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts); 2136 for (unsigned i = 0; i != Scale; ++i) { 2137 unsigned Offset = i * NumSrcEltBits; 2138 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, Offset); 2139 if (!Sub.isNullValue()) { 2140 DemandedSrcBits |= Sub; 2141 for (unsigned j = 0; j != NumElts; ++j) 2142 if (DemandedElts[j]) 2143 DemandedSrcElts.setBit((j * Scale) + i); 2144 } 2145 } 2146 2147 APInt KnownSrcUndef, KnownSrcZero; 2148 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2149 KnownSrcZero, TLO, Depth + 1)) 2150 return true; 2151 2152 KnownBits KnownSrcBits; 2153 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2154 KnownSrcBits, TLO, Depth + 1)) 2155 return true; 2156 } else if ((NumSrcEltBits % BitWidth) == 0 && 2157 TLO.DAG.getDataLayout().isLittleEndian()) { 2158 unsigned Scale = NumSrcEltBits / BitWidth; 2159 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 2160 APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits); 2161 APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts); 2162 for (unsigned i = 0; i != NumElts; ++i) 2163 if (DemandedElts[i]) { 2164 unsigned Offset = (i % Scale) * BitWidth; 2165 DemandedSrcBits.insertBits(DemandedBits, Offset); 2166 DemandedSrcElts.setBit(i / Scale); 2167 } 2168 2169 if (SrcVT.isVector()) { 2170 APInt KnownSrcUndef, KnownSrcZero; 2171 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef, 2172 KnownSrcZero, TLO, Depth + 1)) 2173 return true; 2174 } 2175 2176 KnownBits KnownSrcBits; 2177 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, 2178 KnownSrcBits, TLO, Depth + 1)) 2179 return true; 2180 } 2181 2182 // If this is a bitcast, let computeKnownBits handle it. Only do this on a 2183 // recursive call where Known may be useful to the caller. 2184 if (Depth > 0) { 2185 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2186 return false; 2187 } 2188 break; 2189 } 2190 case ISD::ADD: 2191 case ISD::MUL: 2192 case ISD::SUB: { 2193 // Add, Sub, and Mul don't demand any bits in positions beyond that 2194 // of the highest bit demanded of them. 2195 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1); 2196 SDNodeFlags Flags = Op.getNode()->getFlags(); 2197 unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros(); 2198 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ); 2199 if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO, 2200 Depth + 1) || 2201 SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO, 2202 Depth + 1) || 2203 // See if the operation should be performed at a smaller bit width. 2204 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) { 2205 if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) { 2206 // Disable the nsw and nuw flags. We can no longer guarantee that we 2207 // won't wrap after simplification. 2208 Flags.setNoSignedWrap(false); 2209 Flags.setNoUnsignedWrap(false); 2210 SDValue NewOp = 2211 TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags); 2212 return TLO.CombineTo(Op, NewOp); 2213 } 2214 return true; 2215 } 2216 2217 // Attempt to avoid multi-use ops if we don't need anything from them. 2218 if (!LoMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 2219 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 2220 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2221 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 2222 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1); 2223 if (DemandedOp0 || DemandedOp1) { 2224 Flags.setNoSignedWrap(false); 2225 Flags.setNoUnsignedWrap(false); 2226 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 2227 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 2228 SDValue NewOp = 2229 TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags); 2230 return TLO.CombineTo(Op, NewOp); 2231 } 2232 } 2233 2234 // If we have a constant operand, we may be able to turn it into -1 if we 2235 // do not demand the high bits. This can make the constant smaller to 2236 // encode, allow more general folding, or match specialized instruction 2237 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that 2238 // is probably not useful (and could be detrimental). 2239 ConstantSDNode *C = isConstOrConstSplat(Op1); 2240 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ); 2241 if (C && !C->isAllOnesValue() && !C->isOne() && 2242 (C->getAPIntValue() | HighMask).isAllOnesValue()) { 2243 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT); 2244 // Disable the nsw and nuw flags. We can no longer guarantee that we 2245 // won't wrap after simplification. 2246 Flags.setNoSignedWrap(false); 2247 Flags.setNoUnsignedWrap(false); 2248 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags); 2249 return TLO.CombineTo(Op, NewOp); 2250 } 2251 2252 LLVM_FALLTHROUGH; 2253 } 2254 default: 2255 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 2256 if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts, 2257 Known, TLO, Depth)) 2258 return true; 2259 break; 2260 } 2261 2262 // Just use computeKnownBits to compute output bits. 2263 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 2264 break; 2265 } 2266 2267 // If we know the value of all of the demanded bits, return this as a 2268 // constant. 2269 if (DemandedBits.isSubsetOf(Known.Zero | Known.One)) { 2270 // Avoid folding to a constant if any OpaqueConstant is involved. 2271 const SDNode *N = Op.getNode(); 2272 for (SDNode *Op : 2273 llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) { 2274 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 2275 if (C->isOpaque()) 2276 return false; 2277 } 2278 if (VT.isInteger()) 2279 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT)); 2280 if (VT.isFloatingPoint()) 2281 return TLO.CombineTo( 2282 Op, 2283 TLO.DAG.getConstantFP( 2284 APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT)); 2285 } 2286 2287 return false; 2288 } 2289 2290 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op, 2291 const APInt &DemandedElts, 2292 APInt &KnownUndef, 2293 APInt &KnownZero, 2294 DAGCombinerInfo &DCI) const { 2295 SelectionDAG &DAG = DCI.DAG; 2296 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 2297 !DCI.isBeforeLegalizeOps()); 2298 2299 bool Simplified = 2300 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO); 2301 if (Simplified) { 2302 DCI.AddToWorklist(Op.getNode()); 2303 DCI.CommitTargetLoweringOpt(TLO); 2304 } 2305 2306 return Simplified; 2307 } 2308 2309 /// Given a vector binary operation and known undefined elements for each input 2310 /// operand, compute whether each element of the output is undefined. 2311 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG, 2312 const APInt &UndefOp0, 2313 const APInt &UndefOp1) { 2314 EVT VT = BO.getValueType(); 2315 assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() && 2316 "Vector binop only"); 2317 2318 EVT EltVT = VT.getVectorElementType(); 2319 unsigned NumElts = VT.getVectorNumElements(); 2320 assert(UndefOp0.getBitWidth() == NumElts && 2321 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis"); 2322 2323 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index, 2324 const APInt &UndefVals) { 2325 if (UndefVals[Index]) 2326 return DAG.getUNDEF(EltVT); 2327 2328 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 2329 // Try hard to make sure that the getNode() call is not creating temporary 2330 // nodes. Ignore opaque integers because they do not constant fold. 2331 SDValue Elt = BV->getOperand(Index); 2332 auto *C = dyn_cast<ConstantSDNode>(Elt); 2333 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque())) 2334 return Elt; 2335 } 2336 2337 return SDValue(); 2338 }; 2339 2340 APInt KnownUndef = APInt::getNullValue(NumElts); 2341 for (unsigned i = 0; i != NumElts; ++i) { 2342 // If both inputs for this element are either constant or undef and match 2343 // the element type, compute the constant/undef result for this element of 2344 // the vector. 2345 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does 2346 // not handle FP constants. The code within getNode() should be refactored 2347 // to avoid the danger of creating a bogus temporary node here. 2348 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0); 2349 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1); 2350 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT) 2351 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef()) 2352 KnownUndef.setBit(i); 2353 } 2354 return KnownUndef; 2355 } 2356 2357 bool TargetLowering::SimplifyDemandedVectorElts( 2358 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef, 2359 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth, 2360 bool AssumeSingleUse) const { 2361 EVT VT = Op.getValueType(); 2362 unsigned Opcode = Op.getOpcode(); 2363 APInt DemandedElts = OriginalDemandedElts; 2364 unsigned NumElts = DemandedElts.getBitWidth(); 2365 assert(VT.isVector() && "Expected vector op"); 2366 2367 KnownUndef = KnownZero = APInt::getNullValue(NumElts); 2368 2369 // TODO: For now we assume we know nothing about scalable vectors. 2370 if (VT.isScalableVector()) 2371 return false; 2372 2373 assert(VT.getVectorNumElements() == NumElts && 2374 "Mask size mismatches value type element count!"); 2375 2376 // Undef operand. 2377 if (Op.isUndef()) { 2378 KnownUndef.setAllBits(); 2379 return false; 2380 } 2381 2382 // If Op has other users, assume that all elements are needed. 2383 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) 2384 DemandedElts.setAllBits(); 2385 2386 // Not demanding any elements from Op. 2387 if (DemandedElts == 0) { 2388 KnownUndef.setAllBits(); 2389 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2390 } 2391 2392 // Limit search depth. 2393 if (Depth >= SelectionDAG::MaxRecursionDepth) 2394 return false; 2395 2396 SDLoc DL(Op); 2397 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 2398 2399 // Helper for demanding the specified elements and all the bits of both binary 2400 // operands. 2401 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) { 2402 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts, 2403 TLO.DAG, Depth + 1); 2404 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts, 2405 TLO.DAG, Depth + 1); 2406 if (NewOp0 || NewOp1) { 2407 SDValue NewOp = TLO.DAG.getNode( 2408 Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, NewOp1 ? NewOp1 : Op1); 2409 return TLO.CombineTo(Op, NewOp); 2410 } 2411 return false; 2412 }; 2413 2414 switch (Opcode) { 2415 case ISD::SCALAR_TO_VECTOR: { 2416 if (!DemandedElts[0]) { 2417 KnownUndef.setAllBits(); 2418 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2419 } 2420 KnownUndef.setHighBits(NumElts - 1); 2421 break; 2422 } 2423 case ISD::BITCAST: { 2424 SDValue Src = Op.getOperand(0); 2425 EVT SrcVT = Src.getValueType(); 2426 2427 // We only handle vectors here. 2428 // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits? 2429 if (!SrcVT.isVector()) 2430 break; 2431 2432 // Fast handling of 'identity' bitcasts. 2433 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2434 if (NumSrcElts == NumElts) 2435 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, 2436 KnownZero, TLO, Depth + 1); 2437 2438 APInt SrcZero, SrcUndef; 2439 APInt SrcDemandedElts = APInt::getNullValue(NumSrcElts); 2440 2441 // Bitcast from 'large element' src vector to 'small element' vector, we 2442 // must demand a source element if any DemandedElt maps to it. 2443 if ((NumElts % NumSrcElts) == 0) { 2444 unsigned Scale = NumElts / NumSrcElts; 2445 for (unsigned i = 0; i != NumElts; ++i) 2446 if (DemandedElts[i]) 2447 SrcDemandedElts.setBit(i / Scale); 2448 2449 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2450 TLO, Depth + 1)) 2451 return true; 2452 2453 // Try calling SimplifyDemandedBits, converting demanded elts to the bits 2454 // of the large element. 2455 // TODO - bigendian once we have test coverage. 2456 if (TLO.DAG.getDataLayout().isLittleEndian()) { 2457 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits(); 2458 APInt SrcDemandedBits = APInt::getNullValue(SrcEltSizeInBits); 2459 for (unsigned i = 0; i != NumElts; ++i) 2460 if (DemandedElts[i]) { 2461 unsigned Ofs = (i % Scale) * EltSizeInBits; 2462 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits); 2463 } 2464 2465 KnownBits Known; 2466 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known, 2467 TLO, Depth + 1)) 2468 return true; 2469 } 2470 2471 // If the src element is zero/undef then all the output elements will be - 2472 // only demanded elements are guaranteed to be correct. 2473 for (unsigned i = 0; i != NumSrcElts; ++i) { 2474 if (SrcDemandedElts[i]) { 2475 if (SrcZero[i]) 2476 KnownZero.setBits(i * Scale, (i + 1) * Scale); 2477 if (SrcUndef[i]) 2478 KnownUndef.setBits(i * Scale, (i + 1) * Scale); 2479 } 2480 } 2481 } 2482 2483 // Bitcast from 'small element' src vector to 'large element' vector, we 2484 // demand all smaller source elements covered by the larger demanded element 2485 // of this vector. 2486 if ((NumSrcElts % NumElts) == 0) { 2487 unsigned Scale = NumSrcElts / NumElts; 2488 for (unsigned i = 0; i != NumElts; ++i) 2489 if (DemandedElts[i]) 2490 SrcDemandedElts.setBits(i * Scale, (i + 1) * Scale); 2491 2492 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 2493 TLO, Depth + 1)) 2494 return true; 2495 2496 // If all the src elements covering an output element are zero/undef, then 2497 // the output element will be as well, assuming it was demanded. 2498 for (unsigned i = 0; i != NumElts; ++i) { 2499 if (DemandedElts[i]) { 2500 if (SrcZero.extractBits(Scale, i * Scale).isAllOnesValue()) 2501 KnownZero.setBit(i); 2502 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnesValue()) 2503 KnownUndef.setBit(i); 2504 } 2505 } 2506 } 2507 break; 2508 } 2509 case ISD::BUILD_VECTOR: { 2510 // Check all elements and simplify any unused elements with UNDEF. 2511 if (!DemandedElts.isAllOnesValue()) { 2512 // Don't simplify BROADCASTS. 2513 if (llvm::any_of(Op->op_values(), 2514 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) { 2515 SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end()); 2516 bool Updated = false; 2517 for (unsigned i = 0; i != NumElts; ++i) { 2518 if (!DemandedElts[i] && !Ops[i].isUndef()) { 2519 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType()); 2520 KnownUndef.setBit(i); 2521 Updated = true; 2522 } 2523 } 2524 if (Updated) 2525 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops)); 2526 } 2527 } 2528 for (unsigned i = 0; i != NumElts; ++i) { 2529 SDValue SrcOp = Op.getOperand(i); 2530 if (SrcOp.isUndef()) { 2531 KnownUndef.setBit(i); 2532 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() && 2533 (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) { 2534 KnownZero.setBit(i); 2535 } 2536 } 2537 break; 2538 } 2539 case ISD::CONCAT_VECTORS: { 2540 EVT SubVT = Op.getOperand(0).getValueType(); 2541 unsigned NumSubVecs = Op.getNumOperands(); 2542 unsigned NumSubElts = SubVT.getVectorNumElements(); 2543 for (unsigned i = 0; i != NumSubVecs; ++i) { 2544 SDValue SubOp = Op.getOperand(i); 2545 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 2546 APInt SubUndef, SubZero; 2547 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO, 2548 Depth + 1)) 2549 return true; 2550 KnownUndef.insertBits(SubUndef, i * NumSubElts); 2551 KnownZero.insertBits(SubZero, i * NumSubElts); 2552 } 2553 break; 2554 } 2555 case ISD::INSERT_SUBVECTOR: { 2556 // Demand any elements from the subvector and the remainder from the src its 2557 // inserted into. 2558 SDValue Src = Op.getOperand(0); 2559 SDValue Sub = Op.getOperand(1); 2560 uint64_t Idx = Op.getConstantOperandVal(2); 2561 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2562 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2563 APInt DemandedSrcElts = DemandedElts; 2564 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 2565 2566 APInt SubUndef, SubZero; 2567 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO, 2568 Depth + 1)) 2569 return true; 2570 2571 // If none of the src operand elements are demanded, replace it with undef. 2572 if (!DemandedSrcElts && !Src.isUndef()) 2573 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 2574 TLO.DAG.getUNDEF(VT), Sub, 2575 Op.getOperand(2))); 2576 2577 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero, 2578 TLO, Depth + 1)) 2579 return true; 2580 KnownUndef.insertBits(SubUndef, Idx); 2581 KnownZero.insertBits(SubZero, Idx); 2582 2583 // Attempt to avoid multi-use ops if we don't need anything from them. 2584 if (!DemandedSrcElts.isAllOnesValue() || 2585 !DemandedSubElts.isAllOnesValue()) { 2586 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 2587 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 2588 SDValue NewSub = SimplifyMultipleUseDemandedVectorElts( 2589 Sub, DemandedSubElts, TLO.DAG, Depth + 1); 2590 if (NewSrc || NewSub) { 2591 NewSrc = NewSrc ? NewSrc : Src; 2592 NewSub = NewSub ? NewSub : Sub; 2593 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 2594 NewSub, Op.getOperand(2)); 2595 return TLO.CombineTo(Op, NewOp); 2596 } 2597 } 2598 break; 2599 } 2600 case ISD::EXTRACT_SUBVECTOR: { 2601 // Offset the demanded elts by the subvector index. 2602 SDValue Src = Op.getOperand(0); 2603 if (Src.getValueType().isScalableVector()) 2604 break; 2605 uint64_t Idx = Op.getConstantOperandVal(1); 2606 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2607 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2608 2609 APInt SrcUndef, SrcZero; 2610 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 2611 Depth + 1)) 2612 return true; 2613 KnownUndef = SrcUndef.extractBits(NumElts, Idx); 2614 KnownZero = SrcZero.extractBits(NumElts, Idx); 2615 2616 // Attempt to avoid multi-use ops if we don't need anything from them. 2617 if (!DemandedElts.isAllOnesValue()) { 2618 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts( 2619 Src, DemandedSrcElts, TLO.DAG, Depth + 1); 2620 if (NewSrc) { 2621 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc, 2622 Op.getOperand(1)); 2623 return TLO.CombineTo(Op, NewOp); 2624 } 2625 } 2626 break; 2627 } 2628 case ISD::INSERT_VECTOR_ELT: { 2629 SDValue Vec = Op.getOperand(0); 2630 SDValue Scl = Op.getOperand(1); 2631 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 2632 2633 // For a legal, constant insertion index, if we don't need this insertion 2634 // then strip it, else remove it from the demanded elts. 2635 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) { 2636 unsigned Idx = CIdx->getZExtValue(); 2637 if (!DemandedElts[Idx]) 2638 return TLO.CombineTo(Op, Vec); 2639 2640 APInt DemandedVecElts(DemandedElts); 2641 DemandedVecElts.clearBit(Idx); 2642 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef, 2643 KnownZero, TLO, Depth + 1)) 2644 return true; 2645 2646 KnownUndef.setBitVal(Idx, Scl.isUndef()); 2647 2648 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl)); 2649 break; 2650 } 2651 2652 APInt VecUndef, VecZero; 2653 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO, 2654 Depth + 1)) 2655 return true; 2656 // Without knowing the insertion index we can't set KnownUndef/KnownZero. 2657 break; 2658 } 2659 case ISD::VSELECT: { 2660 // Try to transform the select condition based on the current demanded 2661 // elements. 2662 // TODO: If a condition element is undef, we can choose from one arm of the 2663 // select (and if one arm is undef, then we can propagate that to the 2664 // result). 2665 // TODO - add support for constant vselect masks (see IR version of this). 2666 APInt UnusedUndef, UnusedZero; 2667 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef, 2668 UnusedZero, TLO, Depth + 1)) 2669 return true; 2670 2671 // See if we can simplify either vselect operand. 2672 APInt DemandedLHS(DemandedElts); 2673 APInt DemandedRHS(DemandedElts); 2674 APInt UndefLHS, ZeroLHS; 2675 APInt UndefRHS, ZeroRHS; 2676 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS, 2677 ZeroLHS, TLO, Depth + 1)) 2678 return true; 2679 if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS, 2680 ZeroRHS, TLO, Depth + 1)) 2681 return true; 2682 2683 KnownUndef = UndefLHS & UndefRHS; 2684 KnownZero = ZeroLHS & ZeroRHS; 2685 break; 2686 } 2687 case ISD::VECTOR_SHUFFLE: { 2688 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 2689 2690 // Collect demanded elements from shuffle operands.. 2691 APInt DemandedLHS(NumElts, 0); 2692 APInt DemandedRHS(NumElts, 0); 2693 for (unsigned i = 0; i != NumElts; ++i) { 2694 int M = ShuffleMask[i]; 2695 if (M < 0 || !DemandedElts[i]) 2696 continue; 2697 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 2698 if (M < (int)NumElts) 2699 DemandedLHS.setBit(M); 2700 else 2701 DemandedRHS.setBit(M - NumElts); 2702 } 2703 2704 // See if we can simplify either shuffle operand. 2705 APInt UndefLHS, ZeroLHS; 2706 APInt UndefRHS, ZeroRHS; 2707 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS, 2708 ZeroLHS, TLO, Depth + 1)) 2709 return true; 2710 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS, 2711 ZeroRHS, TLO, Depth + 1)) 2712 return true; 2713 2714 // Simplify mask using undef elements from LHS/RHS. 2715 bool Updated = false; 2716 bool IdentityLHS = true, IdentityRHS = true; 2717 SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end()); 2718 for (unsigned i = 0; i != NumElts; ++i) { 2719 int &M = NewMask[i]; 2720 if (M < 0) 2721 continue; 2722 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) || 2723 (M >= (int)NumElts && UndefRHS[M - NumElts])) { 2724 Updated = true; 2725 M = -1; 2726 } 2727 IdentityLHS &= (M < 0) || (M == (int)i); 2728 IdentityRHS &= (M < 0) || ((M - NumElts) == i); 2729 } 2730 2731 // Update legal shuffle masks based on demanded elements if it won't reduce 2732 // to Identity which can cause premature removal of the shuffle mask. 2733 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) { 2734 SDValue LegalShuffle = 2735 buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1), 2736 NewMask, TLO.DAG); 2737 if (LegalShuffle) 2738 return TLO.CombineTo(Op, LegalShuffle); 2739 } 2740 2741 // Propagate undef/zero elements from LHS/RHS. 2742 for (unsigned i = 0; i != NumElts; ++i) { 2743 int M = ShuffleMask[i]; 2744 if (M < 0) { 2745 KnownUndef.setBit(i); 2746 } else if (M < (int)NumElts) { 2747 if (UndefLHS[M]) 2748 KnownUndef.setBit(i); 2749 if (ZeroLHS[M]) 2750 KnownZero.setBit(i); 2751 } else { 2752 if (UndefRHS[M - NumElts]) 2753 KnownUndef.setBit(i); 2754 if (ZeroRHS[M - NumElts]) 2755 KnownZero.setBit(i); 2756 } 2757 } 2758 break; 2759 } 2760 case ISD::ANY_EXTEND_VECTOR_INREG: 2761 case ISD::SIGN_EXTEND_VECTOR_INREG: 2762 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2763 APInt SrcUndef, SrcZero; 2764 SDValue Src = Op.getOperand(0); 2765 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2766 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts); 2767 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 2768 Depth + 1)) 2769 return true; 2770 KnownZero = SrcZero.zextOrTrunc(NumElts); 2771 KnownUndef = SrcUndef.zextOrTrunc(NumElts); 2772 2773 if (Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG && 2774 Op.getValueSizeInBits() == Src.getValueSizeInBits() && 2775 DemandedSrcElts == 1 && TLO.DAG.getDataLayout().isLittleEndian()) { 2776 // aext - if we just need the bottom element then we can bitcast. 2777 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2778 } 2779 2780 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { 2781 // zext(undef) upper bits are guaranteed to be zero. 2782 if (DemandedElts.isSubsetOf(KnownUndef)) 2783 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 2784 KnownUndef.clearAllBits(); 2785 } 2786 break; 2787 } 2788 2789 // TODO: There are more binop opcodes that could be handled here - MIN, 2790 // MAX, saturated math, etc. 2791 case ISD::OR: 2792 case ISD::XOR: 2793 case ISD::ADD: 2794 case ISD::SUB: 2795 case ISD::FADD: 2796 case ISD::FSUB: 2797 case ISD::FMUL: 2798 case ISD::FDIV: 2799 case ISD::FREM: { 2800 SDValue Op0 = Op.getOperand(0); 2801 SDValue Op1 = Op.getOperand(1); 2802 2803 APInt UndefRHS, ZeroRHS; 2804 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 2805 Depth + 1)) 2806 return true; 2807 APInt UndefLHS, ZeroLHS; 2808 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 2809 Depth + 1)) 2810 return true; 2811 2812 KnownZero = ZeroLHS & ZeroRHS; 2813 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS); 2814 2815 // Attempt to avoid multi-use ops if we don't need anything from them. 2816 // TODO - use KnownUndef to relax the demandedelts? 2817 if (!DemandedElts.isAllOnesValue()) 2818 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 2819 return true; 2820 break; 2821 } 2822 case ISD::SHL: 2823 case ISD::SRL: 2824 case ISD::SRA: 2825 case ISD::ROTL: 2826 case ISD::ROTR: { 2827 SDValue Op0 = Op.getOperand(0); 2828 SDValue Op1 = Op.getOperand(1); 2829 2830 APInt UndefRHS, ZeroRHS; 2831 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO, 2832 Depth + 1)) 2833 return true; 2834 APInt UndefLHS, ZeroLHS; 2835 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO, 2836 Depth + 1)) 2837 return true; 2838 2839 KnownZero = ZeroLHS; 2840 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop? 2841 2842 // Attempt to avoid multi-use ops if we don't need anything from them. 2843 // TODO - use KnownUndef to relax the demandedelts? 2844 if (!DemandedElts.isAllOnesValue()) 2845 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 2846 return true; 2847 break; 2848 } 2849 case ISD::MUL: 2850 case ISD::AND: { 2851 SDValue Op0 = Op.getOperand(0); 2852 SDValue Op1 = Op.getOperand(1); 2853 2854 APInt SrcUndef, SrcZero; 2855 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO, 2856 Depth + 1)) 2857 return true; 2858 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero, 2859 TLO, Depth + 1)) 2860 return true; 2861 2862 // If either side has a zero element, then the result element is zero, even 2863 // if the other is an UNDEF. 2864 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros 2865 // and then handle 'and' nodes with the rest of the binop opcodes. 2866 KnownZero |= SrcZero; 2867 KnownUndef &= SrcUndef; 2868 KnownUndef &= ~KnownZero; 2869 2870 // Attempt to avoid multi-use ops if we don't need anything from them. 2871 // TODO - use KnownUndef to relax the demandedelts? 2872 if (!DemandedElts.isAllOnesValue()) 2873 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1)) 2874 return true; 2875 break; 2876 } 2877 case ISD::TRUNCATE: 2878 case ISD::SIGN_EXTEND: 2879 case ISD::ZERO_EXTEND: 2880 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 2881 KnownZero, TLO, Depth + 1)) 2882 return true; 2883 2884 if (Op.getOpcode() == ISD::ZERO_EXTEND) { 2885 // zext(undef) upper bits are guaranteed to be zero. 2886 if (DemandedElts.isSubsetOf(KnownUndef)) 2887 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 2888 KnownUndef.clearAllBits(); 2889 } 2890 break; 2891 default: { 2892 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 2893 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef, 2894 KnownZero, TLO, Depth)) 2895 return true; 2896 } else { 2897 KnownBits Known; 2898 APInt DemandedBits = APInt::getAllOnesValue(EltSizeInBits); 2899 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known, 2900 TLO, Depth, AssumeSingleUse)) 2901 return true; 2902 } 2903 break; 2904 } 2905 } 2906 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero"); 2907 2908 // Constant fold all undef cases. 2909 // TODO: Handle zero cases as well. 2910 if (DemandedElts.isSubsetOf(KnownUndef)) 2911 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2912 2913 return false; 2914 } 2915 2916 /// Determine which of the bits specified in Mask are known to be either zero or 2917 /// one and return them in the Known. 2918 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 2919 KnownBits &Known, 2920 const APInt &DemandedElts, 2921 const SelectionDAG &DAG, 2922 unsigned Depth) const { 2923 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2924 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2925 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2926 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2927 "Should use MaskedValueIsZero if you don't know whether Op" 2928 " is a target node!"); 2929 Known.resetAll(); 2930 } 2931 2932 void TargetLowering::computeKnownBitsForTargetInstr( 2933 GISelKnownBits &Analysis, Register R, KnownBits &Known, 2934 const APInt &DemandedElts, const MachineRegisterInfo &MRI, 2935 unsigned Depth) const { 2936 Known.resetAll(); 2937 } 2938 2939 void TargetLowering::computeKnownBitsForFrameIndex( 2940 const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const { 2941 // The low bits are known zero if the pointer is aligned. 2942 Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx))); 2943 } 2944 2945 Align TargetLowering::computeKnownAlignForTargetInstr( 2946 GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI, 2947 unsigned Depth) const { 2948 return Align(1); 2949 } 2950 2951 /// This method can be implemented by targets that want to expose additional 2952 /// information about sign bits to the DAG Combiner. 2953 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 2954 const APInt &, 2955 const SelectionDAG &, 2956 unsigned Depth) const { 2957 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2958 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2959 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2960 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2961 "Should use ComputeNumSignBits if you don't know whether Op" 2962 " is a target node!"); 2963 return 1; 2964 } 2965 2966 unsigned TargetLowering::computeNumSignBitsForTargetInstr( 2967 GISelKnownBits &Analysis, Register R, const APInt &DemandedElts, 2968 const MachineRegisterInfo &MRI, unsigned Depth) const { 2969 return 1; 2970 } 2971 2972 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode( 2973 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero, 2974 TargetLoweringOpt &TLO, unsigned Depth) const { 2975 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2976 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2977 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2978 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2979 "Should use SimplifyDemandedVectorElts if you don't know whether Op" 2980 " is a target node!"); 2981 return false; 2982 } 2983 2984 bool TargetLowering::SimplifyDemandedBitsForTargetNode( 2985 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 2986 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const { 2987 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2988 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2989 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2990 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2991 "Should use SimplifyDemandedBits if you don't know whether Op" 2992 " is a target node!"); 2993 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth); 2994 return false; 2995 } 2996 2997 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode( 2998 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 2999 SelectionDAG &DAG, unsigned Depth) const { 3000 assert( 3001 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 3002 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3003 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3004 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3005 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op" 3006 " is a target node!"); 3007 return SDValue(); 3008 } 3009 3010 SDValue 3011 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, 3012 SDValue N1, MutableArrayRef<int> Mask, 3013 SelectionDAG &DAG) const { 3014 bool LegalMask = isShuffleMaskLegal(Mask, VT); 3015 if (!LegalMask) { 3016 std::swap(N0, N1); 3017 ShuffleVectorSDNode::commuteMask(Mask); 3018 LegalMask = isShuffleMaskLegal(Mask, VT); 3019 } 3020 3021 if (!LegalMask) 3022 return SDValue(); 3023 3024 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask); 3025 } 3026 3027 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const { 3028 return nullptr; 3029 } 3030 3031 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 3032 const SelectionDAG &DAG, 3033 bool SNaN, 3034 unsigned Depth) const { 3035 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 3036 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 3037 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 3038 Op.getOpcode() == ISD::INTRINSIC_VOID) && 3039 "Should use isKnownNeverNaN if you don't know whether Op" 3040 " is a target node!"); 3041 return false; 3042 } 3043 3044 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must 3045 // work with truncating build vectors and vectors with elements of less than 3046 // 8 bits. 3047 bool TargetLowering::isConstTrueVal(const SDNode *N) const { 3048 if (!N) 3049 return false; 3050 3051 APInt CVal; 3052 if (auto *CN = dyn_cast<ConstantSDNode>(N)) { 3053 CVal = CN->getAPIntValue(); 3054 } else if (auto *BV = dyn_cast<BuildVectorSDNode>(N)) { 3055 auto *CN = BV->getConstantSplatNode(); 3056 if (!CN) 3057 return false; 3058 3059 // If this is a truncating build vector, truncate the splat value. 3060 // Otherwise, we may fail to match the expected values below. 3061 unsigned BVEltWidth = BV->getValueType(0).getScalarSizeInBits(); 3062 CVal = CN->getAPIntValue(); 3063 if (BVEltWidth < CVal.getBitWidth()) 3064 CVal = CVal.trunc(BVEltWidth); 3065 } else { 3066 return false; 3067 } 3068 3069 switch (getBooleanContents(N->getValueType(0))) { 3070 case UndefinedBooleanContent: 3071 return CVal[0]; 3072 case ZeroOrOneBooleanContent: 3073 return CVal.isOneValue(); 3074 case ZeroOrNegativeOneBooleanContent: 3075 return CVal.isAllOnesValue(); 3076 } 3077 3078 llvm_unreachable("Invalid boolean contents"); 3079 } 3080 3081 bool TargetLowering::isConstFalseVal(const SDNode *N) const { 3082 if (!N) 3083 return false; 3084 3085 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 3086 if (!CN) { 3087 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 3088 if (!BV) 3089 return false; 3090 3091 // Only interested in constant splats, we don't care about undef 3092 // elements in identifying boolean constants and getConstantSplatNode 3093 // returns NULL if all ops are undef; 3094 CN = BV->getConstantSplatNode(); 3095 if (!CN) 3096 return false; 3097 } 3098 3099 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 3100 return !CN->getAPIntValue()[0]; 3101 3102 return CN->isNullValue(); 3103 } 3104 3105 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 3106 bool SExt) const { 3107 if (VT == MVT::i1) 3108 return N->isOne(); 3109 3110 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 3111 switch (Cnt) { 3112 case TargetLowering::ZeroOrOneBooleanContent: 3113 // An extended value of 1 is always true, unless its original type is i1, 3114 // in which case it will be sign extended to -1. 3115 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 3116 case TargetLowering::UndefinedBooleanContent: 3117 case TargetLowering::ZeroOrNegativeOneBooleanContent: 3118 return N->isAllOnesValue() && SExt; 3119 } 3120 llvm_unreachable("Unexpected enumeration."); 3121 } 3122 3123 /// This helper function of SimplifySetCC tries to optimize the comparison when 3124 /// either operand of the SetCC node is a bitwise-and instruction. 3125 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 3126 ISD::CondCode Cond, const SDLoc &DL, 3127 DAGCombinerInfo &DCI) const { 3128 // Match these patterns in any of their permutations: 3129 // (X & Y) == Y 3130 // (X & Y) != Y 3131 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 3132 std::swap(N0, N1); 3133 3134 EVT OpVT = N0.getValueType(); 3135 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 3136 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 3137 return SDValue(); 3138 3139 SDValue X, Y; 3140 if (N0.getOperand(0) == N1) { 3141 X = N0.getOperand(1); 3142 Y = N0.getOperand(0); 3143 } else if (N0.getOperand(1) == N1) { 3144 X = N0.getOperand(0); 3145 Y = N0.getOperand(1); 3146 } else { 3147 return SDValue(); 3148 } 3149 3150 SelectionDAG &DAG = DCI.DAG; 3151 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3152 if (DAG.isKnownToBeAPowerOfTwo(Y)) { 3153 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 3154 // Note that where Y is variable and is known to have at most one bit set 3155 // (for example, if it is Z & 1) we cannot do this; the expressions are not 3156 // equivalent when Y == 0. 3157 assert(OpVT.isInteger()); 3158 Cond = ISD::getSetCCInverse(Cond, OpVT); 3159 if (DCI.isBeforeLegalizeOps() || 3160 isCondCodeLegal(Cond, N0.getSimpleValueType())) 3161 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 3162 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 3163 // If the target supports an 'and-not' or 'and-complement' logic operation, 3164 // try to use that to make a comparison operation more efficient. 3165 // But don't do this transform if the mask is a single bit because there are 3166 // more efficient ways to deal with that case (for example, 'bt' on x86 or 3167 // 'rlwinm' on PPC). 3168 3169 // Bail out if the compare operand that we want to turn into a zero is 3170 // already a zero (otherwise, infinite loop). 3171 auto *YConst = dyn_cast<ConstantSDNode>(Y); 3172 if (YConst && YConst->isNullValue()) 3173 return SDValue(); 3174 3175 // Transform this into: ~X & Y == 0. 3176 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 3177 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 3178 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 3179 } 3180 3181 return SDValue(); 3182 } 3183 3184 /// There are multiple IR patterns that could be checking whether certain 3185 /// truncation of a signed number would be lossy or not. The pattern which is 3186 /// best at IR level, may not lower optimally. Thus, we want to unfold it. 3187 /// We are looking for the following pattern: (KeptBits is a constant) 3188 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits) 3189 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false. 3190 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0 3191 /// We will unfold it into the natural trunc+sext pattern: 3192 /// ((%x << C) a>> C) dstcond %x 3193 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x) 3194 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck( 3195 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI, 3196 const SDLoc &DL) const { 3197 // We must be comparing with a constant. 3198 ConstantSDNode *C1; 3199 if (!(C1 = dyn_cast<ConstantSDNode>(N1))) 3200 return SDValue(); 3201 3202 // N0 should be: add %x, (1 << (KeptBits-1)) 3203 if (N0->getOpcode() != ISD::ADD) 3204 return SDValue(); 3205 3206 // And we must be 'add'ing a constant. 3207 ConstantSDNode *C01; 3208 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1)))) 3209 return SDValue(); 3210 3211 SDValue X = N0->getOperand(0); 3212 EVT XVT = X.getValueType(); 3213 3214 // Validate constants ... 3215 3216 APInt I1 = C1->getAPIntValue(); 3217 3218 ISD::CondCode NewCond; 3219 if (Cond == ISD::CondCode::SETULT) { 3220 NewCond = ISD::CondCode::SETEQ; 3221 } else if (Cond == ISD::CondCode::SETULE) { 3222 NewCond = ISD::CondCode::SETEQ; 3223 // But need to 'canonicalize' the constant. 3224 I1 += 1; 3225 } else if (Cond == ISD::CondCode::SETUGT) { 3226 NewCond = ISD::CondCode::SETNE; 3227 // But need to 'canonicalize' the constant. 3228 I1 += 1; 3229 } else if (Cond == ISD::CondCode::SETUGE) { 3230 NewCond = ISD::CondCode::SETNE; 3231 } else 3232 return SDValue(); 3233 3234 APInt I01 = C01->getAPIntValue(); 3235 3236 auto checkConstants = [&I1, &I01]() -> bool { 3237 // Both of them must be power-of-two, and the constant from setcc is bigger. 3238 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2(); 3239 }; 3240 3241 if (checkConstants()) { 3242 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256 3243 } else { 3244 // What if we invert constants? (and the target predicate) 3245 I1.negate(); 3246 I01.negate(); 3247 assert(XVT.isInteger()); 3248 NewCond = getSetCCInverse(NewCond, XVT); 3249 if (!checkConstants()) 3250 return SDValue(); 3251 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256 3252 } 3253 3254 // They are power-of-two, so which bit is set? 3255 const unsigned KeptBits = I1.logBase2(); 3256 const unsigned KeptBitsMinusOne = I01.logBase2(); 3257 3258 // Magic! 3259 if (KeptBits != (KeptBitsMinusOne + 1)) 3260 return SDValue(); 3261 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable"); 3262 3263 // We don't want to do this in every single case. 3264 SelectionDAG &DAG = DCI.DAG; 3265 if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck( 3266 XVT, KeptBits)) 3267 return SDValue(); 3268 3269 const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits; 3270 assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable"); 3271 3272 // Unfold into: ((%x << C) a>> C) cond %x 3273 // Where 'cond' will be either 'eq' or 'ne'. 3274 SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT); 3275 SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt); 3276 SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt); 3277 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond); 3278 3279 return T2; 3280 } 3281 3282 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 3283 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift( 3284 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond, 3285 DAGCombinerInfo &DCI, const SDLoc &DL) const { 3286 assert(isConstOrConstSplat(N1C) && 3287 isConstOrConstSplat(N1C)->getAPIntValue().isNullValue() && 3288 "Should be a comparison with 0."); 3289 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3290 "Valid only for [in]equality comparisons."); 3291 3292 unsigned NewShiftOpcode; 3293 SDValue X, C, Y; 3294 3295 SelectionDAG &DAG = DCI.DAG; 3296 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3297 3298 // Look for '(C l>>/<< Y)'. 3299 auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) { 3300 // The shift should be one-use. 3301 if (!V.hasOneUse()) 3302 return false; 3303 unsigned OldShiftOpcode = V.getOpcode(); 3304 switch (OldShiftOpcode) { 3305 case ISD::SHL: 3306 NewShiftOpcode = ISD::SRL; 3307 break; 3308 case ISD::SRL: 3309 NewShiftOpcode = ISD::SHL; 3310 break; 3311 default: 3312 return false; // must be a logical shift. 3313 } 3314 // We should be shifting a constant. 3315 // FIXME: best to use isConstantOrConstantVector(). 3316 C = V.getOperand(0); 3317 ConstantSDNode *CC = 3318 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3319 if (!CC) 3320 return false; 3321 Y = V.getOperand(1); 3322 3323 ConstantSDNode *XC = 3324 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 3325 return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 3326 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG); 3327 }; 3328 3329 // LHS of comparison should be an one-use 'and'. 3330 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 3331 return SDValue(); 3332 3333 X = N0.getOperand(0); 3334 SDValue Mask = N0.getOperand(1); 3335 3336 // 'and' is commutative! 3337 if (!Match(Mask)) { 3338 std::swap(X, Mask); 3339 if (!Match(Mask)) 3340 return SDValue(); 3341 } 3342 3343 EVT VT = X.getValueType(); 3344 3345 // Produce: 3346 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0 3347 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y); 3348 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C); 3349 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond); 3350 return T2; 3351 } 3352 3353 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as 3354 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to 3355 /// handle the commuted versions of these patterns. 3356 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, 3357 ISD::CondCode Cond, const SDLoc &DL, 3358 DAGCombinerInfo &DCI) const { 3359 unsigned BOpcode = N0.getOpcode(); 3360 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) && 3361 "Unexpected binop"); 3362 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode"); 3363 3364 // (X + Y) == X --> Y == 0 3365 // (X - Y) == X --> Y == 0 3366 // (X ^ Y) == X --> Y == 0 3367 SelectionDAG &DAG = DCI.DAG; 3368 EVT OpVT = N0.getValueType(); 3369 SDValue X = N0.getOperand(0); 3370 SDValue Y = N0.getOperand(1); 3371 if (X == N1) 3372 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond); 3373 3374 if (Y != N1) 3375 return SDValue(); 3376 3377 // (X + Y) == Y --> X == 0 3378 // (X ^ Y) == Y --> X == 0 3379 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR) 3380 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond); 3381 3382 // The shift would not be valid if the operands are boolean (i1). 3383 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1) 3384 return SDValue(); 3385 3386 // (X - Y) == Y --> X == Y << 1 3387 EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(), 3388 !DCI.isBeforeLegalize()); 3389 SDValue One = DAG.getConstant(1, DL, ShiftVT); 3390 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One); 3391 if (!DCI.isCalledByLegalizer()) 3392 DCI.AddToWorklist(YShl1.getNode()); 3393 return DAG.getSetCC(DL, VT, X, YShl1, Cond); 3394 } 3395 3396 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT, 3397 SDValue N0, const APInt &C1, 3398 ISD::CondCode Cond, const SDLoc &dl, 3399 SelectionDAG &DAG) { 3400 // Look through truncs that don't change the value of a ctpop. 3401 // FIXME: Add vector support? Need to be careful with setcc result type below. 3402 SDValue CTPOP = N0; 3403 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() && 3404 N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits())) 3405 CTPOP = N0.getOperand(0); 3406 3407 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse()) 3408 return SDValue(); 3409 3410 EVT CTVT = CTPOP.getValueType(); 3411 SDValue CTOp = CTPOP.getOperand(0); 3412 3413 // If this is a vector CTPOP, keep the CTPOP if it is legal. 3414 // TODO: Should we check if CTPOP is legal(or custom) for scalars? 3415 if (VT.isVector() && TLI.isOperationLegal(ISD::CTPOP, CTVT)) 3416 return SDValue(); 3417 3418 // (ctpop x) u< 2 -> (x & x-1) == 0 3419 // (ctpop x) u> 1 -> (x & x-1) != 0 3420 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) { 3421 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond); 3422 if (C1.ugt(CostLimit + (Cond == ISD::SETULT))) 3423 return SDValue(); 3424 if (C1 == 0 && (Cond == ISD::SETULT)) 3425 return SDValue(); // This is handled elsewhere. 3426 3427 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT); 3428 3429 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3430 SDValue Result = CTOp; 3431 for (unsigned i = 0; i < Passes; i++) { 3432 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne); 3433 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add); 3434 } 3435 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 3436 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC); 3437 } 3438 3439 // If ctpop is not supported, expand a power-of-2 comparison based on it. 3440 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) { 3441 // For scalars, keep CTPOP if it is legal or custom. 3442 if (!VT.isVector() && TLI.isOperationLegalOrCustom(ISD::CTPOP, CTVT)) 3443 return SDValue(); 3444 // This is based on X86's custom lowering for CTPOP which produces more 3445 // instructions than the expansion here. 3446 3447 // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0) 3448 // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0) 3449 SDValue Zero = DAG.getConstant(0, dl, CTVT); 3450 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3451 assert(CTVT.isInteger()); 3452 ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT); 3453 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne); 3454 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add); 3455 SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond); 3456 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond); 3457 unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR; 3458 return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS); 3459 } 3460 3461 return SDValue(); 3462 } 3463 3464 /// Try to simplify a setcc built with the specified operands and cc. If it is 3465 /// unable to simplify it, return a null SDValue. 3466 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 3467 ISD::CondCode Cond, bool foldBooleans, 3468 DAGCombinerInfo &DCI, 3469 const SDLoc &dl) const { 3470 SelectionDAG &DAG = DCI.DAG; 3471 const DataLayout &Layout = DAG.getDataLayout(); 3472 EVT OpVT = N0.getValueType(); 3473 3474 // Constant fold or commute setcc. 3475 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl)) 3476 return Fold; 3477 3478 // Ensure that the constant occurs on the RHS and fold constant comparisons. 3479 // TODO: Handle non-splat vector constants. All undef causes trouble. 3480 // FIXME: We can't yet fold constant scalable vector splats, so avoid an 3481 // infinite loop here when we encounter one. 3482 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 3483 if (isConstOrConstSplat(N0) && 3484 (!OpVT.isScalableVector() || !isConstOrConstSplat(N1)) && 3485 (DCI.isBeforeLegalizeOps() || 3486 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 3487 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 3488 3489 // If we have a subtract with the same 2 non-constant operands as this setcc 3490 // -- but in reverse order -- then try to commute the operands of this setcc 3491 // to match. A matching pair of setcc (cmp) and sub may be combined into 1 3492 // instruction on some targets. 3493 if (!isConstOrConstSplat(N0) && !isConstOrConstSplat(N1) && 3494 (DCI.isBeforeLegalizeOps() || 3495 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) && 3496 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) && 3497 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1})) 3498 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 3499 3500 if (auto *N1C = isConstOrConstSplat(N1)) { 3501 const APInt &C1 = N1C->getAPIntValue(); 3502 3503 // Optimize some CTPOP cases. 3504 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG)) 3505 return V; 3506 3507 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 3508 // equality comparison, then we're just comparing whether X itself is 3509 // zero. 3510 if (N0.getOpcode() == ISD::SRL && (C1.isNullValue() || C1.isOneValue()) && 3511 N0.getOperand(0).getOpcode() == ISD::CTLZ && 3512 isPowerOf2_32(N0.getScalarValueSizeInBits())) { 3513 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) { 3514 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3515 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) { 3516 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 3517 // (srl (ctlz x), 5) == 0 -> X != 0 3518 // (srl (ctlz x), 5) != 1 -> X != 0 3519 Cond = ISD::SETNE; 3520 } else { 3521 // (srl (ctlz x), 5) != 0 -> X == 0 3522 // (srl (ctlz x), 5) == 1 -> X == 0 3523 Cond = ISD::SETEQ; 3524 } 3525 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 3526 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero, 3527 Cond); 3528 } 3529 } 3530 } 3531 } 3532 3533 // FIXME: Support vectors. 3534 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 3535 const APInt &C1 = N1C->getAPIntValue(); 3536 3537 // (zext x) == C --> x == (trunc C) 3538 // (sext x) == C --> x == (trunc C) 3539 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3540 DCI.isBeforeLegalize() && N0->hasOneUse()) { 3541 unsigned MinBits = N0.getValueSizeInBits(); 3542 SDValue PreExt; 3543 bool Signed = false; 3544 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 3545 // ZExt 3546 MinBits = N0->getOperand(0).getValueSizeInBits(); 3547 PreExt = N0->getOperand(0); 3548 } else if (N0->getOpcode() == ISD::AND) { 3549 // DAGCombine turns costly ZExts into ANDs 3550 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 3551 if ((C->getAPIntValue()+1).isPowerOf2()) { 3552 MinBits = C->getAPIntValue().countTrailingOnes(); 3553 PreExt = N0->getOperand(0); 3554 } 3555 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 3556 // SExt 3557 MinBits = N0->getOperand(0).getValueSizeInBits(); 3558 PreExt = N0->getOperand(0); 3559 Signed = true; 3560 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 3561 // ZEXTLOAD / SEXTLOAD 3562 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 3563 MinBits = LN0->getMemoryVT().getSizeInBits(); 3564 PreExt = N0; 3565 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 3566 Signed = true; 3567 MinBits = LN0->getMemoryVT().getSizeInBits(); 3568 PreExt = N0; 3569 } 3570 } 3571 3572 // Figure out how many bits we need to preserve this constant. 3573 unsigned ReqdBits = Signed ? 3574 C1.getBitWidth() - C1.getNumSignBits() + 1 : 3575 C1.getActiveBits(); 3576 3577 // Make sure we're not losing bits from the constant. 3578 if (MinBits > 0 && 3579 MinBits < C1.getBitWidth() && 3580 MinBits >= ReqdBits) { 3581 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 3582 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 3583 // Will get folded away. 3584 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 3585 if (MinBits == 1 && C1 == 1) 3586 // Invert the condition. 3587 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 3588 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3589 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 3590 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 3591 } 3592 3593 // If truncating the setcc operands is not desirable, we can still 3594 // simplify the expression in some cases: 3595 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 3596 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 3597 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 3598 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 3599 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 3600 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 3601 SDValue TopSetCC = N0->getOperand(0); 3602 unsigned N0Opc = N0->getOpcode(); 3603 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 3604 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 3605 TopSetCC.getOpcode() == ISD::SETCC && 3606 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 3607 (isConstFalseVal(N1C) || 3608 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 3609 3610 bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) || 3611 (!N1C->isNullValue() && Cond == ISD::SETNE); 3612 3613 if (!Inverse) 3614 return TopSetCC; 3615 3616 ISD::CondCode InvCond = ISD::getSetCCInverse( 3617 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 3618 TopSetCC.getOperand(0).getValueType()); 3619 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 3620 TopSetCC.getOperand(1), 3621 InvCond); 3622 } 3623 } 3624 } 3625 3626 // If the LHS is '(and load, const)', the RHS is 0, the test is for 3627 // equality or unsigned, and all 1 bits of the const are in the same 3628 // partial word, see if we can shorten the load. 3629 if (DCI.isBeforeLegalize() && 3630 !ISD::isSignedIntSetCC(Cond) && 3631 N0.getOpcode() == ISD::AND && C1 == 0 && 3632 N0.getNode()->hasOneUse() && 3633 isa<LoadSDNode>(N0.getOperand(0)) && 3634 N0.getOperand(0).getNode()->hasOneUse() && 3635 isa<ConstantSDNode>(N0.getOperand(1))) { 3636 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 3637 APInt bestMask; 3638 unsigned bestWidth = 0, bestOffset = 0; 3639 if (Lod->isSimple() && Lod->isUnindexed()) { 3640 unsigned origWidth = N0.getValueSizeInBits(); 3641 unsigned maskWidth = origWidth; 3642 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 3643 // 8 bits, but have to be careful... 3644 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 3645 origWidth = Lod->getMemoryVT().getSizeInBits(); 3646 const APInt &Mask = N0.getConstantOperandAPInt(1); 3647 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 3648 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 3649 for (unsigned offset=0; offset<origWidth/width; offset++) { 3650 if (Mask.isSubsetOf(newMask)) { 3651 if (Layout.isLittleEndian()) 3652 bestOffset = (uint64_t)offset * (width/8); 3653 else 3654 bestOffset = (origWidth/width - offset - 1) * (width/8); 3655 bestMask = Mask.lshr(offset * (width/8) * 8); 3656 bestWidth = width; 3657 break; 3658 } 3659 newMask <<= width; 3660 } 3661 } 3662 } 3663 if (bestWidth) { 3664 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 3665 if (newVT.isRound() && 3666 shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) { 3667 SDValue Ptr = Lod->getBasePtr(); 3668 if (bestOffset != 0) 3669 Ptr = 3670 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(bestOffset), dl); 3671 SDValue NewLoad = 3672 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr, 3673 Lod->getPointerInfo().getWithOffset(bestOffset), 3674 Lod->getOriginalAlign()); 3675 return DAG.getSetCC(dl, VT, 3676 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 3677 DAG.getConstant(bestMask.trunc(bestWidth), 3678 dl, newVT)), 3679 DAG.getConstant(0LL, dl, newVT), Cond); 3680 } 3681 } 3682 } 3683 3684 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 3685 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 3686 unsigned InSize = N0.getOperand(0).getValueSizeInBits(); 3687 3688 // If the comparison constant has bits in the upper part, the 3689 // zero-extended value could never match. 3690 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 3691 C1.getBitWidth() - InSize))) { 3692 switch (Cond) { 3693 case ISD::SETUGT: 3694 case ISD::SETUGE: 3695 case ISD::SETEQ: 3696 return DAG.getConstant(0, dl, VT); 3697 case ISD::SETULT: 3698 case ISD::SETULE: 3699 case ISD::SETNE: 3700 return DAG.getConstant(1, dl, VT); 3701 case ISD::SETGT: 3702 case ISD::SETGE: 3703 // True if the sign bit of C1 is set. 3704 return DAG.getConstant(C1.isNegative(), dl, VT); 3705 case ISD::SETLT: 3706 case ISD::SETLE: 3707 // True if the sign bit of C1 isn't set. 3708 return DAG.getConstant(C1.isNonNegative(), dl, VT); 3709 default: 3710 break; 3711 } 3712 } 3713 3714 // Otherwise, we can perform the comparison with the low bits. 3715 switch (Cond) { 3716 case ISD::SETEQ: 3717 case ISD::SETNE: 3718 case ISD::SETUGT: 3719 case ISD::SETUGE: 3720 case ISD::SETULT: 3721 case ISD::SETULE: { 3722 EVT newVT = N0.getOperand(0).getValueType(); 3723 if (DCI.isBeforeLegalizeOps() || 3724 (isOperationLegal(ISD::SETCC, newVT) && 3725 isCondCodeLegal(Cond, newVT.getSimpleVT()))) { 3726 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT); 3727 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 3728 3729 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 3730 NewConst, Cond); 3731 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 3732 } 3733 break; 3734 } 3735 default: 3736 break; // todo, be more careful with signed comparisons 3737 } 3738 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 3739 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3740 !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(), 3741 OpVT)) { 3742 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 3743 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 3744 EVT ExtDstTy = N0.getValueType(); 3745 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 3746 3747 // If the constant doesn't fit into the number of bits for the source of 3748 // the sign extension, it is impossible for both sides to be equal. 3749 if (C1.getMinSignedBits() > ExtSrcTyBits) 3750 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT); 3751 3752 assert(ExtDstTy == N0.getOperand(0).getValueType() && 3753 ExtDstTy != ExtSrcTy && "Unexpected types!"); 3754 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 3755 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0), 3756 DAG.getConstant(Imm, dl, ExtDstTy)); 3757 if (!DCI.isCalledByLegalizer()) 3758 DCI.AddToWorklist(ZextOp.getNode()); 3759 // Otherwise, make this a use of a zext. 3760 return DAG.getSetCC(dl, VT, ZextOp, 3761 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond); 3762 } else if ((N1C->isNullValue() || N1C->isOne()) && 3763 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 3764 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 3765 if (N0.getOpcode() == ISD::SETCC && 3766 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) && 3767 (N0.getValueType() == MVT::i1 || 3768 getBooleanContents(N0.getOperand(0).getValueType()) == 3769 ZeroOrOneBooleanContent)) { 3770 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne()); 3771 if (TrueWhenTrue) 3772 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 3773 // Invert the condition. 3774 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 3775 CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType()); 3776 if (DCI.isBeforeLegalizeOps() || 3777 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 3778 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 3779 } 3780 3781 if ((N0.getOpcode() == ISD::XOR || 3782 (N0.getOpcode() == ISD::AND && 3783 N0.getOperand(0).getOpcode() == ISD::XOR && 3784 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 3785 isOneConstant(N0.getOperand(1))) { 3786 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 3787 // can only do this if the top bits are known zero. 3788 unsigned BitWidth = N0.getValueSizeInBits(); 3789 if (DAG.MaskedValueIsZero(N0, 3790 APInt::getHighBitsSet(BitWidth, 3791 BitWidth-1))) { 3792 // Okay, get the un-inverted input value. 3793 SDValue Val; 3794 if (N0.getOpcode() == ISD::XOR) { 3795 Val = N0.getOperand(0); 3796 } else { 3797 assert(N0.getOpcode() == ISD::AND && 3798 N0.getOperand(0).getOpcode() == ISD::XOR); 3799 // ((X^1)&1)^1 -> X & 1 3800 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 3801 N0.getOperand(0).getOperand(0), 3802 N0.getOperand(1)); 3803 } 3804 3805 return DAG.getSetCC(dl, VT, Val, N1, 3806 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3807 } 3808 } else if (N1C->isOne()) { 3809 SDValue Op0 = N0; 3810 if (Op0.getOpcode() == ISD::TRUNCATE) 3811 Op0 = Op0.getOperand(0); 3812 3813 if ((Op0.getOpcode() == ISD::XOR) && 3814 Op0.getOperand(0).getOpcode() == ISD::SETCC && 3815 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 3816 SDValue XorLHS = Op0.getOperand(0); 3817 SDValue XorRHS = Op0.getOperand(1); 3818 // Ensure that the input setccs return an i1 type or 0/1 value. 3819 if (Op0.getValueType() == MVT::i1 || 3820 (getBooleanContents(XorLHS.getOperand(0).getValueType()) == 3821 ZeroOrOneBooleanContent && 3822 getBooleanContents(XorRHS.getOperand(0).getValueType()) == 3823 ZeroOrOneBooleanContent)) { 3824 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 3825 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 3826 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond); 3827 } 3828 } 3829 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) { 3830 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 3831 if (Op0.getValueType().bitsGT(VT)) 3832 Op0 = DAG.getNode(ISD::AND, dl, VT, 3833 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 3834 DAG.getConstant(1, dl, VT)); 3835 else if (Op0.getValueType().bitsLT(VT)) 3836 Op0 = DAG.getNode(ISD::AND, dl, VT, 3837 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 3838 DAG.getConstant(1, dl, VT)); 3839 3840 return DAG.getSetCC(dl, VT, Op0, 3841 DAG.getConstant(0, dl, Op0.getValueType()), 3842 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3843 } 3844 if (Op0.getOpcode() == ISD::AssertZext && 3845 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 3846 return DAG.getSetCC(dl, VT, Op0, 3847 DAG.getConstant(0, dl, Op0.getValueType()), 3848 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3849 } 3850 } 3851 3852 // Given: 3853 // icmp eq/ne (urem %x, %y), 0 3854 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem': 3855 // icmp eq/ne %x, 0 3856 if (N0.getOpcode() == ISD::UREM && N1C->isNullValue() && 3857 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 3858 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0)); 3859 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1)); 3860 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2) 3861 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 3862 } 3863 3864 if (SDValue V = 3865 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl)) 3866 return V; 3867 } 3868 3869 // These simplifications apply to splat vectors as well. 3870 // TODO: Handle more splat vector cases. 3871 if (auto *N1C = isConstOrConstSplat(N1)) { 3872 const APInt &C1 = N1C->getAPIntValue(); 3873 3874 APInt MinVal, MaxVal; 3875 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits(); 3876 if (ISD::isSignedIntSetCC(Cond)) { 3877 MinVal = APInt::getSignedMinValue(OperandBitSize); 3878 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 3879 } else { 3880 MinVal = APInt::getMinValue(OperandBitSize); 3881 MaxVal = APInt::getMaxValue(OperandBitSize); 3882 } 3883 3884 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 3885 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 3886 // X >= MIN --> true 3887 if (C1 == MinVal) 3888 return DAG.getBoolConstant(true, dl, VT, OpVT); 3889 3890 if (!VT.isVector()) { // TODO: Support this for vectors. 3891 // X >= C0 --> X > (C0 - 1) 3892 APInt C = C1 - 1; 3893 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 3894 if ((DCI.isBeforeLegalizeOps() || 3895 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 3896 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 3897 isLegalICmpImmediate(C.getSExtValue())))) { 3898 return DAG.getSetCC(dl, VT, N0, 3899 DAG.getConstant(C, dl, N1.getValueType()), 3900 NewCC); 3901 } 3902 } 3903 } 3904 3905 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 3906 // X <= MAX --> true 3907 if (C1 == MaxVal) 3908 return DAG.getBoolConstant(true, dl, VT, OpVT); 3909 3910 // X <= C0 --> X < (C0 + 1) 3911 if (!VT.isVector()) { // TODO: Support this for vectors. 3912 APInt C = C1 + 1; 3913 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 3914 if ((DCI.isBeforeLegalizeOps() || 3915 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 3916 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 3917 isLegalICmpImmediate(C.getSExtValue())))) { 3918 return DAG.getSetCC(dl, VT, N0, 3919 DAG.getConstant(C, dl, N1.getValueType()), 3920 NewCC); 3921 } 3922 } 3923 } 3924 3925 if (Cond == ISD::SETLT || Cond == ISD::SETULT) { 3926 if (C1 == MinVal) 3927 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false 3928 3929 // TODO: Support this for vectors after legalize ops. 3930 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 3931 // Canonicalize setlt X, Max --> setne X, Max 3932 if (C1 == MaxVal) 3933 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 3934 3935 // If we have setult X, 1, turn it into seteq X, 0 3936 if (C1 == MinVal+1) 3937 return DAG.getSetCC(dl, VT, N0, 3938 DAG.getConstant(MinVal, dl, N0.getValueType()), 3939 ISD::SETEQ); 3940 } 3941 } 3942 3943 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) { 3944 if (C1 == MaxVal) 3945 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false 3946 3947 // TODO: Support this for vectors after legalize ops. 3948 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 3949 // Canonicalize setgt X, Min --> setne X, Min 3950 if (C1 == MinVal) 3951 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 3952 3953 // If we have setugt X, Max-1, turn it into seteq X, Max 3954 if (C1 == MaxVal-1) 3955 return DAG.getSetCC(dl, VT, N0, 3956 DAG.getConstant(MaxVal, dl, N0.getValueType()), 3957 ISD::SETEQ); 3958 } 3959 } 3960 3961 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) { 3962 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 3963 if (C1.isNullValue()) 3964 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift( 3965 VT, N0, N1, Cond, DCI, dl)) 3966 return CC; 3967 3968 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y). 3969 // For example, when high 32-bits of i64 X are known clear: 3970 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0 3971 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1 3972 bool CmpZero = N1C->getAPIntValue().isNullValue(); 3973 bool CmpNegOne = N1C->getAPIntValue().isAllOnesValue(); 3974 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) { 3975 // Match or(lo,shl(hi,bw/2)) pattern. 3976 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) { 3977 unsigned EltBits = V.getScalarValueSizeInBits(); 3978 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0) 3979 return false; 3980 SDValue LHS = V.getOperand(0); 3981 SDValue RHS = V.getOperand(1); 3982 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2); 3983 // Unshifted element must have zero upperbits. 3984 if (RHS.getOpcode() == ISD::SHL && 3985 isa<ConstantSDNode>(RHS.getOperand(1)) && 3986 RHS.getConstantOperandAPInt(1) == (EltBits / 2) && 3987 DAG.MaskedValueIsZero(LHS, HiBits)) { 3988 Lo = LHS; 3989 Hi = RHS.getOperand(0); 3990 return true; 3991 } 3992 if (LHS.getOpcode() == ISD::SHL && 3993 isa<ConstantSDNode>(LHS.getOperand(1)) && 3994 LHS.getConstantOperandAPInt(1) == (EltBits / 2) && 3995 DAG.MaskedValueIsZero(RHS, HiBits)) { 3996 Lo = RHS; 3997 Hi = LHS.getOperand(0); 3998 return true; 3999 } 4000 return false; 4001 }; 4002 4003 auto MergeConcat = [&](SDValue Lo, SDValue Hi) { 4004 unsigned EltBits = N0.getScalarValueSizeInBits(); 4005 unsigned HalfBits = EltBits / 2; 4006 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits); 4007 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT); 4008 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits); 4009 SDValue NewN0 = 4010 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask); 4011 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits; 4012 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond); 4013 }; 4014 4015 SDValue Lo, Hi; 4016 if (IsConcat(N0, Lo, Hi)) 4017 return MergeConcat(Lo, Hi); 4018 4019 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) { 4020 SDValue Lo0, Lo1, Hi0, Hi1; 4021 if (IsConcat(N0.getOperand(0), Lo0, Hi0) && 4022 IsConcat(N0.getOperand(1), Lo1, Hi1)) { 4023 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1), 4024 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1)); 4025 } 4026 } 4027 } 4028 } 4029 4030 // If we have "setcc X, C0", check to see if we can shrink the immediate 4031 // by changing cc. 4032 // TODO: Support this for vectors after legalize ops. 4033 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4034 // SETUGT X, SINTMAX -> SETLT X, 0 4035 // SETUGE X, SINTMIN -> SETLT X, 0 4036 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) || 4037 (Cond == ISD::SETUGE && C1.isMinSignedValue())) 4038 return DAG.getSetCC(dl, VT, N0, 4039 DAG.getConstant(0, dl, N1.getValueType()), 4040 ISD::SETLT); 4041 4042 // SETULT X, SINTMIN -> SETGT X, -1 4043 // SETULE X, SINTMAX -> SETGT X, -1 4044 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) || 4045 (Cond == ISD::SETULE && C1.isMaxSignedValue())) 4046 return DAG.getSetCC(dl, VT, N0, 4047 DAG.getAllOnesConstant(dl, N1.getValueType()), 4048 ISD::SETGT); 4049 } 4050 } 4051 4052 // Back to non-vector simplifications. 4053 // TODO: Can we do these for vector splats? 4054 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4055 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4056 const APInt &C1 = N1C->getAPIntValue(); 4057 EVT ShValTy = N0.getValueType(); 4058 4059 // Fold bit comparisons when we can. This will result in an 4060 // incorrect value when boolean false is negative one, unless 4061 // the bitsize is 1 in which case the false value is the same 4062 // in practice regardless of the representation. 4063 if ((VT.getSizeInBits() == 1 || 4064 getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) && 4065 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4066 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) && 4067 N0.getOpcode() == ISD::AND) { 4068 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4069 EVT ShiftTy = 4070 getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4071 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 4072 // Perform the xform if the AND RHS is a single bit. 4073 unsigned ShCt = AndRHS->getAPIntValue().logBase2(); 4074 if (AndRHS->getAPIntValue().isPowerOf2() && 4075 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4076 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4077 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4078 DAG.getConstant(ShCt, dl, ShiftTy))); 4079 } 4080 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 4081 // (X & 8) == 8 --> (X & 8) >> 3 4082 // Perform the xform if C1 is a single bit. 4083 unsigned ShCt = C1.logBase2(); 4084 if (C1.isPowerOf2() && 4085 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4086 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4087 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4088 DAG.getConstant(ShCt, dl, ShiftTy))); 4089 } 4090 } 4091 } 4092 } 4093 4094 if (C1.getMinSignedBits() <= 64 && 4095 !isLegalICmpImmediate(C1.getSExtValue())) { 4096 EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4097 // (X & -256) == 256 -> (X >> 8) == 1 4098 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4099 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 4100 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4101 const APInt &AndRHSC = AndRHS->getAPIntValue(); 4102 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) { 4103 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 4104 if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4105 SDValue Shift = 4106 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0), 4107 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4108 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy); 4109 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 4110 } 4111 } 4112 } 4113 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 4114 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 4115 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 4116 // X < 0x100000000 -> (X >> 32) < 1 4117 // X >= 0x100000000 -> (X >> 32) >= 1 4118 // X <= 0x0ffffffff -> (X >> 32) < 1 4119 // X > 0x0ffffffff -> (X >> 32) >= 1 4120 unsigned ShiftBits; 4121 APInt NewC = C1; 4122 ISD::CondCode NewCond = Cond; 4123 if (AdjOne) { 4124 ShiftBits = C1.countTrailingOnes(); 4125 NewC = NewC + 1; 4126 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4127 } else { 4128 ShiftBits = C1.countTrailingZeros(); 4129 } 4130 NewC.lshrInPlace(ShiftBits); 4131 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 4132 isLegalICmpImmediate(NewC.getSExtValue()) && 4133 !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4134 SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4135 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4136 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy); 4137 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 4138 } 4139 } 4140 } 4141 } 4142 4143 if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) { 4144 auto *CFP = cast<ConstantFPSDNode>(N1); 4145 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value"); 4146 4147 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 4148 // constant if knowing that the operand is non-nan is enough. We prefer to 4149 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 4150 // materialize 0.0. 4151 if (Cond == ISD::SETO || Cond == ISD::SETUO) 4152 return DAG.getSetCC(dl, VT, N0, N0, Cond); 4153 4154 // setcc (fneg x), C -> setcc swap(pred) x, -C 4155 if (N0.getOpcode() == ISD::FNEG) { 4156 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 4157 if (DCI.isBeforeLegalizeOps() || 4158 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 4159 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 4160 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 4161 } 4162 } 4163 4164 // If the condition is not legal, see if we can find an equivalent one 4165 // which is legal. 4166 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 4167 // If the comparison was an awkward floating-point == or != and one of 4168 // the comparison operands is infinity or negative infinity, convert the 4169 // condition to a less-awkward <= or >=. 4170 if (CFP->getValueAPF().isInfinity()) { 4171 bool IsNegInf = CFP->getValueAPF().isNegative(); 4172 ISD::CondCode NewCond = ISD::SETCC_INVALID; 4173 switch (Cond) { 4174 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break; 4175 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break; 4176 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break; 4177 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break; 4178 default: break; 4179 } 4180 if (NewCond != ISD::SETCC_INVALID && 4181 isCondCodeLegal(NewCond, N0.getSimpleValueType())) 4182 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4183 } 4184 } 4185 } 4186 4187 if (N0 == N1) { 4188 // The sext(setcc()) => setcc() optimization relies on the appropriate 4189 // constant being emitted. 4190 assert(!N0.getValueType().isInteger() && 4191 "Integer types should be handled by FoldSetCC"); 4192 4193 bool EqTrue = ISD::isTrueWhenEqual(Cond); 4194 unsigned UOF = ISD::getUnorderedFlavor(Cond); 4195 if (UOF == 2) // FP operators that are undefined on NaNs. 4196 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4197 if (UOF == unsigned(EqTrue)) 4198 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4199 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 4200 // if it is not already. 4201 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 4202 if (NewCond != Cond && 4203 (DCI.isBeforeLegalizeOps() || 4204 isCondCodeLegal(NewCond, N0.getSimpleValueType()))) 4205 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4206 } 4207 4208 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4209 N0.getValueType().isInteger()) { 4210 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 4211 N0.getOpcode() == ISD::XOR) { 4212 // Simplify (X+Y) == (X+Z) --> Y == Z 4213 if (N0.getOpcode() == N1.getOpcode()) { 4214 if (N0.getOperand(0) == N1.getOperand(0)) 4215 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 4216 if (N0.getOperand(1) == N1.getOperand(1)) 4217 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 4218 if (isCommutativeBinOp(N0.getOpcode())) { 4219 // If X op Y == Y op X, try other combinations. 4220 if (N0.getOperand(0) == N1.getOperand(1)) 4221 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 4222 Cond); 4223 if (N0.getOperand(1) == N1.getOperand(0)) 4224 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 4225 Cond); 4226 } 4227 } 4228 4229 // If RHS is a legal immediate value for a compare instruction, we need 4230 // to be careful about increasing register pressure needlessly. 4231 bool LegalRHSImm = false; 4232 4233 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 4234 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4235 // Turn (X+C1) == C2 --> X == C2-C1 4236 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) { 4237 return DAG.getSetCC(dl, VT, N0.getOperand(0), 4238 DAG.getConstant(RHSC->getAPIntValue()- 4239 LHSR->getAPIntValue(), 4240 dl, N0.getValueType()), Cond); 4241 } 4242 4243 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0. 4244 if (N0.getOpcode() == ISD::XOR) 4245 // If we know that all of the inverted bits are zero, don't bother 4246 // performing the inversion. 4247 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue())) 4248 return 4249 DAG.getSetCC(dl, VT, N0.getOperand(0), 4250 DAG.getConstant(LHSR->getAPIntValue() ^ 4251 RHSC->getAPIntValue(), 4252 dl, N0.getValueType()), 4253 Cond); 4254 } 4255 4256 // Turn (C1-X) == C2 --> X == C1-C2 4257 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) { 4258 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) { 4259 return 4260 DAG.getSetCC(dl, VT, N0.getOperand(1), 4261 DAG.getConstant(SUBC->getAPIntValue() - 4262 RHSC->getAPIntValue(), 4263 dl, N0.getValueType()), 4264 Cond); 4265 } 4266 } 4267 4268 // Could RHSC fold directly into a compare? 4269 if (RHSC->getValueType(0).getSizeInBits() <= 64) 4270 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 4271 } 4272 4273 // (X+Y) == X --> Y == 0 and similar folds. 4274 // Don't do this if X is an immediate that can fold into a cmp 4275 // instruction and X+Y has other uses. It could be an induction variable 4276 // chain, and the transform would increase register pressure. 4277 if (!LegalRHSImm || N0.hasOneUse()) 4278 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI)) 4279 return V; 4280 } 4281 4282 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 4283 N1.getOpcode() == ISD::XOR) 4284 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI)) 4285 return V; 4286 4287 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI)) 4288 return V; 4289 } 4290 4291 // Fold remainder of division by a constant. 4292 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) && 4293 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4294 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4295 4296 // When division is cheap or optimizing for minimum size, 4297 // fall through to DIVREM creation by skipping this fold. 4298 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttribute(Attribute::MinSize)) { 4299 if (N0.getOpcode() == ISD::UREM) { 4300 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4301 return Folded; 4302 } else if (N0.getOpcode() == ISD::SREM) { 4303 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4304 return Folded; 4305 } 4306 } 4307 } 4308 4309 // Fold away ALL boolean setcc's. 4310 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) { 4311 SDValue Temp; 4312 switch (Cond) { 4313 default: llvm_unreachable("Unknown integer setcc!"); 4314 case ISD::SETEQ: // X == Y -> ~(X^Y) 4315 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4316 N0 = DAG.getNOT(dl, Temp, OpVT); 4317 if (!DCI.isCalledByLegalizer()) 4318 DCI.AddToWorklist(Temp.getNode()); 4319 break; 4320 case ISD::SETNE: // X != Y --> (X^Y) 4321 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4322 break; 4323 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 4324 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 4325 Temp = DAG.getNOT(dl, N0, OpVT); 4326 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp); 4327 if (!DCI.isCalledByLegalizer()) 4328 DCI.AddToWorklist(Temp.getNode()); 4329 break; 4330 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 4331 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 4332 Temp = DAG.getNOT(dl, N1, OpVT); 4333 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp); 4334 if (!DCI.isCalledByLegalizer()) 4335 DCI.AddToWorklist(Temp.getNode()); 4336 break; 4337 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 4338 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 4339 Temp = DAG.getNOT(dl, N0, OpVT); 4340 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp); 4341 if (!DCI.isCalledByLegalizer()) 4342 DCI.AddToWorklist(Temp.getNode()); 4343 break; 4344 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 4345 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 4346 Temp = DAG.getNOT(dl, N1, OpVT); 4347 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp); 4348 break; 4349 } 4350 if (VT.getScalarType() != MVT::i1) { 4351 if (!DCI.isCalledByLegalizer()) 4352 DCI.AddToWorklist(N0.getNode()); 4353 // FIXME: If running after legalize, we probably can't do this. 4354 ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT)); 4355 N0 = DAG.getNode(ExtendCode, dl, VT, N0); 4356 } 4357 return N0; 4358 } 4359 4360 // Could not fold it. 4361 return SDValue(); 4362 } 4363 4364 /// Returns true (and the GlobalValue and the offset) if the node is a 4365 /// GlobalAddress + offset. 4366 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA, 4367 int64_t &Offset) const { 4368 4369 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode(); 4370 4371 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 4372 GA = GASD->getGlobal(); 4373 Offset += GASD->getOffset(); 4374 return true; 4375 } 4376 4377 if (N->getOpcode() == ISD::ADD) { 4378 SDValue N1 = N->getOperand(0); 4379 SDValue N2 = N->getOperand(1); 4380 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 4381 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 4382 Offset += V->getSExtValue(); 4383 return true; 4384 } 4385 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 4386 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 4387 Offset += V->getSExtValue(); 4388 return true; 4389 } 4390 } 4391 } 4392 4393 return false; 4394 } 4395 4396 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 4397 DAGCombinerInfo &DCI) const { 4398 // Default implementation: no optimization. 4399 return SDValue(); 4400 } 4401 4402 //===----------------------------------------------------------------------===// 4403 // Inline Assembler Implementation Methods 4404 //===----------------------------------------------------------------------===// 4405 4406 TargetLowering::ConstraintType 4407 TargetLowering::getConstraintType(StringRef Constraint) const { 4408 unsigned S = Constraint.size(); 4409 4410 if (S == 1) { 4411 switch (Constraint[0]) { 4412 default: break; 4413 case 'r': 4414 return C_RegisterClass; 4415 case 'm': // memory 4416 case 'o': // offsetable 4417 case 'V': // not offsetable 4418 return C_Memory; 4419 case 'n': // Simple Integer 4420 case 'E': // Floating Point Constant 4421 case 'F': // Floating Point Constant 4422 return C_Immediate; 4423 case 'i': // Simple Integer or Relocatable Constant 4424 case 's': // Relocatable Constant 4425 case 'p': // Address. 4426 case 'X': // Allow ANY value. 4427 case 'I': // Target registers. 4428 case 'J': 4429 case 'K': 4430 case 'L': 4431 case 'M': 4432 case 'N': 4433 case 'O': 4434 case 'P': 4435 case '<': 4436 case '>': 4437 return C_Other; 4438 } 4439 } 4440 4441 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') { 4442 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 4443 return C_Memory; 4444 return C_Register; 4445 } 4446 return C_Unknown; 4447 } 4448 4449 /// Try to replace an X constraint, which matches anything, with another that 4450 /// has more specific requirements based on the type of the corresponding 4451 /// operand. 4452 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 4453 if (ConstraintVT.isInteger()) 4454 return "r"; 4455 if (ConstraintVT.isFloatingPoint()) 4456 return "f"; // works for many targets 4457 return nullptr; 4458 } 4459 4460 SDValue TargetLowering::LowerAsmOutputForConstraint( 4461 SDValue &Chain, SDValue &Flag, const SDLoc &DL, 4462 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const { 4463 return SDValue(); 4464 } 4465 4466 /// Lower the specified operand into the Ops vector. 4467 /// If it is invalid, don't add anything to Ops. 4468 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 4469 std::string &Constraint, 4470 std::vector<SDValue> &Ops, 4471 SelectionDAG &DAG) const { 4472 4473 if (Constraint.length() > 1) return; 4474 4475 char ConstraintLetter = Constraint[0]; 4476 switch (ConstraintLetter) { 4477 default: break; 4478 case 'X': // Allows any operand; labels (basic block) use this. 4479 if (Op.getOpcode() == ISD::BasicBlock || 4480 Op.getOpcode() == ISD::TargetBlockAddress) { 4481 Ops.push_back(Op); 4482 return; 4483 } 4484 LLVM_FALLTHROUGH; 4485 case 'i': // Simple Integer or Relocatable Constant 4486 case 'n': // Simple Integer 4487 case 's': { // Relocatable Constant 4488 4489 GlobalAddressSDNode *GA; 4490 ConstantSDNode *C; 4491 BlockAddressSDNode *BA; 4492 uint64_t Offset = 0; 4493 4494 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C), 4495 // etc., since getelementpointer is variadic. We can't use 4496 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible 4497 // while in this case the GA may be furthest from the root node which is 4498 // likely an ISD::ADD. 4499 while (1) { 4500 if ((GA = dyn_cast<GlobalAddressSDNode>(Op)) && ConstraintLetter != 'n') { 4501 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 4502 GA->getValueType(0), 4503 Offset + GA->getOffset())); 4504 return; 4505 } else if ((C = dyn_cast<ConstantSDNode>(Op)) && 4506 ConstraintLetter != 's') { 4507 // gcc prints these as sign extended. Sign extend value to 64 bits 4508 // now; without this it would get ZExt'd later in 4509 // ScheduleDAGSDNodes::EmitNode, which is very generic. 4510 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1; 4511 BooleanContent BCont = getBooleanContents(MVT::i64); 4512 ISD::NodeType ExtOpc = IsBool ? getExtendForContent(BCont) 4513 : ISD::SIGN_EXTEND; 4514 int64_t ExtVal = ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() 4515 : C->getSExtValue(); 4516 Ops.push_back(DAG.getTargetConstant(Offset + ExtVal, 4517 SDLoc(C), MVT::i64)); 4518 return; 4519 } else if ((BA = dyn_cast<BlockAddressSDNode>(Op)) && 4520 ConstraintLetter != 'n') { 4521 Ops.push_back(DAG.getTargetBlockAddress( 4522 BA->getBlockAddress(), BA->getValueType(0), 4523 Offset + BA->getOffset(), BA->getTargetFlags())); 4524 return; 4525 } else { 4526 const unsigned OpCode = Op.getOpcode(); 4527 if (OpCode == ISD::ADD || OpCode == ISD::SUB) { 4528 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0)))) 4529 Op = Op.getOperand(1); 4530 // Subtraction is not commutative. 4531 else if (OpCode == ISD::ADD && 4532 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))) 4533 Op = Op.getOperand(0); 4534 else 4535 return; 4536 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue(); 4537 continue; 4538 } 4539 } 4540 return; 4541 } 4542 break; 4543 } 4544 } 4545 } 4546 4547 std::pair<unsigned, const TargetRegisterClass *> 4548 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 4549 StringRef Constraint, 4550 MVT VT) const { 4551 if (Constraint.empty() || Constraint[0] != '{') 4552 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr)); 4553 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?"); 4554 4555 // Remove the braces from around the name. 4556 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 4557 4558 std::pair<unsigned, const TargetRegisterClass *> R = 4559 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr)); 4560 4561 // Figure out which register class contains this reg. 4562 for (const TargetRegisterClass *RC : RI->regclasses()) { 4563 // If none of the value types for this register class are valid, we 4564 // can't use it. For example, 64-bit reg classes on 32-bit targets. 4565 if (!isLegalRC(*RI, *RC)) 4566 continue; 4567 4568 for (const MCPhysReg &PR : *RC) { 4569 if (RegName.equals_lower(RI->getRegAsmName(PR))) { 4570 std::pair<unsigned, const TargetRegisterClass *> S = 4571 std::make_pair(PR, RC); 4572 4573 // If this register class has the requested value type, return it, 4574 // otherwise keep searching and return the first class found 4575 // if no other is found which explicitly has the requested type. 4576 if (RI->isTypeLegalForClass(*RC, VT)) 4577 return S; 4578 if (!R.second) 4579 R = S; 4580 } 4581 } 4582 } 4583 4584 return R; 4585 } 4586 4587 //===----------------------------------------------------------------------===// 4588 // Constraint Selection. 4589 4590 /// Return true of this is an input operand that is a matching constraint like 4591 /// "4". 4592 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 4593 assert(!ConstraintCode.empty() && "No known constraint!"); 4594 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 4595 } 4596 4597 /// If this is an input matching constraint, this method returns the output 4598 /// operand it matches. 4599 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 4600 assert(!ConstraintCode.empty() && "No known constraint!"); 4601 return atoi(ConstraintCode.c_str()); 4602 } 4603 4604 /// Split up the constraint string from the inline assembly value into the 4605 /// specific constraints and their prefixes, and also tie in the associated 4606 /// operand values. 4607 /// If this returns an empty vector, and if the constraint string itself 4608 /// isn't empty, there was an error parsing. 4609 TargetLowering::AsmOperandInfoVector 4610 TargetLowering::ParseConstraints(const DataLayout &DL, 4611 const TargetRegisterInfo *TRI, 4612 const CallBase &Call) const { 4613 /// Information about all of the constraints. 4614 AsmOperandInfoVector ConstraintOperands; 4615 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 4616 unsigned maCount = 0; // Largest number of multiple alternative constraints. 4617 4618 // Do a prepass over the constraints, canonicalizing them, and building up the 4619 // ConstraintOperands list. 4620 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 4621 unsigned ResNo = 0; // ResNo - The result number of the next output. 4622 4623 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 4624 ConstraintOperands.emplace_back(std::move(CI)); 4625 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 4626 4627 // Update multiple alternative constraint count. 4628 if (OpInfo.multipleAlternatives.size() > maCount) 4629 maCount = OpInfo.multipleAlternatives.size(); 4630 4631 OpInfo.ConstraintVT = MVT::Other; 4632 4633 // Compute the value type for each operand. 4634 switch (OpInfo.Type) { 4635 case InlineAsm::isOutput: 4636 // Indirect outputs just consume an argument. 4637 if (OpInfo.isIndirect) { 4638 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 4639 break; 4640 } 4641 4642 // The return value of the call is this value. As such, there is no 4643 // corresponding argument. 4644 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 4645 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 4646 OpInfo.ConstraintVT = 4647 getSimpleValueType(DL, STy->getElementType(ResNo)); 4648 } else { 4649 assert(ResNo == 0 && "Asm only has one result!"); 4650 OpInfo.ConstraintVT = getSimpleValueType(DL, Call.getType()); 4651 } 4652 ++ResNo; 4653 break; 4654 case InlineAsm::isInput: 4655 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 4656 break; 4657 case InlineAsm::isClobber: 4658 // Nothing to do. 4659 break; 4660 } 4661 4662 if (OpInfo.CallOperandVal) { 4663 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 4664 if (OpInfo.isIndirect) { 4665 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 4666 if (!PtrTy) 4667 report_fatal_error("Indirect operand for inline asm not a pointer!"); 4668 OpTy = PtrTy->getElementType(); 4669 } 4670 4671 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 4672 if (StructType *STy = dyn_cast<StructType>(OpTy)) 4673 if (STy->getNumElements() == 1) 4674 OpTy = STy->getElementType(0); 4675 4676 // If OpTy is not a single value, it may be a struct/union that we 4677 // can tile with integers. 4678 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 4679 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 4680 switch (BitSize) { 4681 default: break; 4682 case 1: 4683 case 8: 4684 case 16: 4685 case 32: 4686 case 64: 4687 case 128: 4688 OpInfo.ConstraintVT = 4689 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true); 4690 break; 4691 } 4692 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) { 4693 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace()); 4694 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize); 4695 } else { 4696 OpInfo.ConstraintVT = MVT::getVT(OpTy, true); 4697 } 4698 } 4699 } 4700 4701 // If we have multiple alternative constraints, select the best alternative. 4702 if (!ConstraintOperands.empty()) { 4703 if (maCount) { 4704 unsigned bestMAIndex = 0; 4705 int bestWeight = -1; 4706 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 4707 int weight = -1; 4708 unsigned maIndex; 4709 // Compute the sums of the weights for each alternative, keeping track 4710 // of the best (highest weight) one so far. 4711 for (maIndex = 0; maIndex < maCount; ++maIndex) { 4712 int weightSum = 0; 4713 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 4714 cIndex != eIndex; ++cIndex) { 4715 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 4716 if (OpInfo.Type == InlineAsm::isClobber) 4717 continue; 4718 4719 // If this is an output operand with a matching input operand, 4720 // look up the matching input. If their types mismatch, e.g. one 4721 // is an integer, the other is floating point, or their sizes are 4722 // different, flag it as an maCantMatch. 4723 if (OpInfo.hasMatchingInput()) { 4724 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 4725 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 4726 if ((OpInfo.ConstraintVT.isInteger() != 4727 Input.ConstraintVT.isInteger()) || 4728 (OpInfo.ConstraintVT.getSizeInBits() != 4729 Input.ConstraintVT.getSizeInBits())) { 4730 weightSum = -1; // Can't match. 4731 break; 4732 } 4733 } 4734 } 4735 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 4736 if (weight == -1) { 4737 weightSum = -1; 4738 break; 4739 } 4740 weightSum += weight; 4741 } 4742 // Update best. 4743 if (weightSum > bestWeight) { 4744 bestWeight = weightSum; 4745 bestMAIndex = maIndex; 4746 } 4747 } 4748 4749 // Now select chosen alternative in each constraint. 4750 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 4751 cIndex != eIndex; ++cIndex) { 4752 AsmOperandInfo &cInfo = ConstraintOperands[cIndex]; 4753 if (cInfo.Type == InlineAsm::isClobber) 4754 continue; 4755 cInfo.selectAlternative(bestMAIndex); 4756 } 4757 } 4758 } 4759 4760 // Check and hook up tied operands, choose constraint code to use. 4761 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 4762 cIndex != eIndex; ++cIndex) { 4763 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 4764 4765 // If this is an output operand with a matching input operand, look up the 4766 // matching input. If their types mismatch, e.g. one is an integer, the 4767 // other is floating point, or their sizes are different, flag it as an 4768 // error. 4769 if (OpInfo.hasMatchingInput()) { 4770 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 4771 4772 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 4773 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 4774 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 4775 OpInfo.ConstraintVT); 4776 std::pair<unsigned, const TargetRegisterClass *> InputRC = 4777 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 4778 Input.ConstraintVT); 4779 if ((OpInfo.ConstraintVT.isInteger() != 4780 Input.ConstraintVT.isInteger()) || 4781 (MatchRC.second != InputRC.second)) { 4782 report_fatal_error("Unsupported asm: input constraint" 4783 " with a matching output constraint of" 4784 " incompatible type!"); 4785 } 4786 } 4787 } 4788 } 4789 4790 return ConstraintOperands; 4791 } 4792 4793 /// Return an integer indicating how general CT is. 4794 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 4795 switch (CT) { 4796 case TargetLowering::C_Immediate: 4797 case TargetLowering::C_Other: 4798 case TargetLowering::C_Unknown: 4799 return 0; 4800 case TargetLowering::C_Register: 4801 return 1; 4802 case TargetLowering::C_RegisterClass: 4803 return 2; 4804 case TargetLowering::C_Memory: 4805 return 3; 4806 } 4807 llvm_unreachable("Invalid constraint type"); 4808 } 4809 4810 /// Examine constraint type and operand type and determine a weight value. 4811 /// This object must already have been set up with the operand type 4812 /// and the current alternative constraint selected. 4813 TargetLowering::ConstraintWeight 4814 TargetLowering::getMultipleConstraintMatchWeight( 4815 AsmOperandInfo &info, int maIndex) const { 4816 InlineAsm::ConstraintCodeVector *rCodes; 4817 if (maIndex >= (int)info.multipleAlternatives.size()) 4818 rCodes = &info.Codes; 4819 else 4820 rCodes = &info.multipleAlternatives[maIndex].Codes; 4821 ConstraintWeight BestWeight = CW_Invalid; 4822 4823 // Loop over the options, keeping track of the most general one. 4824 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) { 4825 ConstraintWeight weight = 4826 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str()); 4827 if (weight > BestWeight) 4828 BestWeight = weight; 4829 } 4830 4831 return BestWeight; 4832 } 4833 4834 /// Examine constraint type and operand type and determine a weight value. 4835 /// This object must already have been set up with the operand type 4836 /// and the current alternative constraint selected. 4837 TargetLowering::ConstraintWeight 4838 TargetLowering::getSingleConstraintMatchWeight( 4839 AsmOperandInfo &info, const char *constraint) const { 4840 ConstraintWeight weight = CW_Invalid; 4841 Value *CallOperandVal = info.CallOperandVal; 4842 // If we don't have a value, we can't do a match, 4843 // but allow it at the lowest weight. 4844 if (!CallOperandVal) 4845 return CW_Default; 4846 // Look at the constraint type. 4847 switch (*constraint) { 4848 case 'i': // immediate integer. 4849 case 'n': // immediate integer with a known value. 4850 if (isa<ConstantInt>(CallOperandVal)) 4851 weight = CW_Constant; 4852 break; 4853 case 's': // non-explicit intregal immediate. 4854 if (isa<GlobalValue>(CallOperandVal)) 4855 weight = CW_Constant; 4856 break; 4857 case 'E': // immediate float if host format. 4858 case 'F': // immediate float. 4859 if (isa<ConstantFP>(CallOperandVal)) 4860 weight = CW_Constant; 4861 break; 4862 case '<': // memory operand with autodecrement. 4863 case '>': // memory operand with autoincrement. 4864 case 'm': // memory operand. 4865 case 'o': // offsettable memory operand 4866 case 'V': // non-offsettable memory operand 4867 weight = CW_Memory; 4868 break; 4869 case 'r': // general register. 4870 case 'g': // general register, memory operand or immediate integer. 4871 // note: Clang converts "g" to "imr". 4872 if (CallOperandVal->getType()->isIntegerTy()) 4873 weight = CW_Register; 4874 break; 4875 case 'X': // any operand. 4876 default: 4877 weight = CW_Default; 4878 break; 4879 } 4880 return weight; 4881 } 4882 4883 /// If there are multiple different constraints that we could pick for this 4884 /// operand (e.g. "imr") try to pick the 'best' one. 4885 /// This is somewhat tricky: constraints fall into four classes: 4886 /// Other -> immediates and magic values 4887 /// Register -> one specific register 4888 /// RegisterClass -> a group of regs 4889 /// Memory -> memory 4890 /// Ideally, we would pick the most specific constraint possible: if we have 4891 /// something that fits into a register, we would pick it. The problem here 4892 /// is that if we have something that could either be in a register or in 4893 /// memory that use of the register could cause selection of *other* 4894 /// operands to fail: they might only succeed if we pick memory. Because of 4895 /// this the heuristic we use is: 4896 /// 4897 /// 1) If there is an 'other' constraint, and if the operand is valid for 4898 /// that constraint, use it. This makes us take advantage of 'i' 4899 /// constraints when available. 4900 /// 2) Otherwise, pick the most general constraint present. This prefers 4901 /// 'm' over 'r', for example. 4902 /// 4903 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 4904 const TargetLowering &TLI, 4905 SDValue Op, SelectionDAG *DAG) { 4906 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 4907 unsigned BestIdx = 0; 4908 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 4909 int BestGenerality = -1; 4910 4911 // Loop over the options, keeping track of the most general one. 4912 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 4913 TargetLowering::ConstraintType CType = 4914 TLI.getConstraintType(OpInfo.Codes[i]); 4915 4916 // Indirect 'other' or 'immediate' constraints are not allowed. 4917 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory || 4918 CType == TargetLowering::C_Register || 4919 CType == TargetLowering::C_RegisterClass)) 4920 continue; 4921 4922 // If this is an 'other' or 'immediate' constraint, see if the operand is 4923 // valid for it. For example, on X86 we might have an 'rI' constraint. If 4924 // the operand is an integer in the range [0..31] we want to use I (saving a 4925 // load of a register), otherwise we must use 'r'. 4926 if ((CType == TargetLowering::C_Other || 4927 CType == TargetLowering::C_Immediate) && Op.getNode()) { 4928 assert(OpInfo.Codes[i].size() == 1 && 4929 "Unhandled multi-letter 'other' constraint"); 4930 std::vector<SDValue> ResultOps; 4931 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 4932 ResultOps, *DAG); 4933 if (!ResultOps.empty()) { 4934 BestType = CType; 4935 BestIdx = i; 4936 break; 4937 } 4938 } 4939 4940 // Things with matching constraints can only be registers, per gcc 4941 // documentation. This mainly affects "g" constraints. 4942 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 4943 continue; 4944 4945 // This constraint letter is more general than the previous one, use it. 4946 int Generality = getConstraintGenerality(CType); 4947 if (Generality > BestGenerality) { 4948 BestType = CType; 4949 BestIdx = i; 4950 BestGenerality = Generality; 4951 } 4952 } 4953 4954 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 4955 OpInfo.ConstraintType = BestType; 4956 } 4957 4958 /// Determines the constraint code and constraint type to use for the specific 4959 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 4960 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 4961 SDValue Op, 4962 SelectionDAG *DAG) const { 4963 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 4964 4965 // Single-letter constraints ('r') are very common. 4966 if (OpInfo.Codes.size() == 1) { 4967 OpInfo.ConstraintCode = OpInfo.Codes[0]; 4968 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 4969 } else { 4970 ChooseConstraint(OpInfo, *this, Op, DAG); 4971 } 4972 4973 // 'X' matches anything. 4974 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 4975 // Labels and constants are handled elsewhere ('X' is the only thing 4976 // that matches labels). For Functions, the type here is the type of 4977 // the result, which is not what we want to look at; leave them alone. 4978 Value *v = OpInfo.CallOperandVal; 4979 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) { 4980 OpInfo.CallOperandVal = v; 4981 return; 4982 } 4983 4984 if (Op.getNode() && Op.getOpcode() == ISD::TargetBlockAddress) 4985 return; 4986 4987 // Otherwise, try to resolve it to something we know about by looking at 4988 // the actual operand type. 4989 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 4990 OpInfo.ConstraintCode = Repl; 4991 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 4992 } 4993 } 4994 } 4995 4996 /// Given an exact SDIV by a constant, create a multiplication 4997 /// with the multiplicative inverse of the constant. 4998 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, 4999 const SDLoc &dl, SelectionDAG &DAG, 5000 SmallVectorImpl<SDNode *> &Created) { 5001 SDValue Op0 = N->getOperand(0); 5002 SDValue Op1 = N->getOperand(1); 5003 EVT VT = N->getValueType(0); 5004 EVT SVT = VT.getScalarType(); 5005 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 5006 EVT ShSVT = ShVT.getScalarType(); 5007 5008 bool UseSRA = false; 5009 SmallVector<SDValue, 16> Shifts, Factors; 5010 5011 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5012 if (C->isNullValue()) 5013 return false; 5014 APInt Divisor = C->getAPIntValue(); 5015 unsigned Shift = Divisor.countTrailingZeros(); 5016 if (Shift) { 5017 Divisor.ashrInPlace(Shift); 5018 UseSRA = true; 5019 } 5020 // Calculate the multiplicative inverse, using Newton's method. 5021 APInt t; 5022 APInt Factor = Divisor; 5023 while ((t = Divisor * Factor) != 1) 5024 Factor *= APInt(Divisor.getBitWidth(), 2) - t; 5025 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 5026 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 5027 return true; 5028 }; 5029 5030 // Collect all magic values from the build vector. 5031 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern)) 5032 return SDValue(); 5033 5034 SDValue Shift, Factor; 5035 if (Op1.getOpcode() == ISD::BUILD_VECTOR) { 5036 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5037 Factor = DAG.getBuildVector(VT, dl, Factors); 5038 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) { 5039 assert(Shifts.size() == 1 && Factors.size() == 1 && 5040 "Expected matchUnaryPredicate to return one element for scalable " 5041 "vectors"); 5042 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5043 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5044 } else { 5045 assert(isa<ConstantSDNode>(Op1) && "Expected a constant"); 5046 Shift = Shifts[0]; 5047 Factor = Factors[0]; 5048 } 5049 5050 SDValue Res = Op0; 5051 5052 // Shift the value upfront if it is even, so the LSB is one. 5053 if (UseSRA) { 5054 // TODO: For UDIV use SRL instead of SRA. 5055 SDNodeFlags Flags; 5056 Flags.setExact(true); 5057 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags); 5058 Created.push_back(Res.getNode()); 5059 } 5060 5061 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 5062 } 5063 5064 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 5065 SelectionDAG &DAG, 5066 SmallVectorImpl<SDNode *> &Created) const { 5067 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 5068 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5069 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 5070 return SDValue(N, 0); // Lower SDIV as SDIV 5071 return SDValue(); 5072 } 5073 5074 /// Given an ISD::SDIV node expressing a divide by constant, 5075 /// return a DAG expression to select that will generate the same value by 5076 /// multiplying by a magic number. 5077 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5078 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 5079 bool IsAfterLegalization, 5080 SmallVectorImpl<SDNode *> &Created) const { 5081 SDLoc dl(N); 5082 EVT VT = N->getValueType(0); 5083 EVT SVT = VT.getScalarType(); 5084 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5085 EVT ShSVT = ShVT.getScalarType(); 5086 unsigned EltBits = VT.getScalarSizeInBits(); 5087 EVT MulVT; 5088 5089 // Check to see if we can do this. 5090 // FIXME: We should be more aggressive here. 5091 if (!isTypeLegal(VT)) { 5092 // Limit this to simple scalars for now. 5093 if (VT.isVector() || !VT.isSimple()) 5094 return SDValue(); 5095 5096 // If this type will be promoted to a large enough type with a legal 5097 // multiply operation, we can go ahead and do this transform. 5098 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5099 return SDValue(); 5100 5101 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5102 if (MulVT.getSizeInBits() < (2 * EltBits) || 5103 !isOperationLegal(ISD::MUL, MulVT)) 5104 return SDValue(); 5105 } 5106 5107 // If the sdiv has an 'exact' bit we can use a simpler lowering. 5108 if (N->getFlags().hasExact()) 5109 return BuildExactSDIV(*this, N, dl, DAG, Created); 5110 5111 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks; 5112 5113 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5114 if (C->isNullValue()) 5115 return false; 5116 5117 const APInt &Divisor = C->getAPIntValue(); 5118 APInt::ms magics = Divisor.magic(); 5119 int NumeratorFactor = 0; 5120 int ShiftMask = -1; 5121 5122 if (Divisor.isOneValue() || Divisor.isAllOnesValue()) { 5123 // If d is +1/-1, we just multiply the numerator by +1/-1. 5124 NumeratorFactor = Divisor.getSExtValue(); 5125 magics.m = 0; 5126 magics.s = 0; 5127 ShiftMask = 0; 5128 } else if (Divisor.isStrictlyPositive() && magics.m.isNegative()) { 5129 // If d > 0 and m < 0, add the numerator. 5130 NumeratorFactor = 1; 5131 } else if (Divisor.isNegative() && magics.m.isStrictlyPositive()) { 5132 // If d < 0 and m > 0, subtract the numerator. 5133 NumeratorFactor = -1; 5134 } 5135 5136 MagicFactors.push_back(DAG.getConstant(magics.m, dl, SVT)); 5137 Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT)); 5138 Shifts.push_back(DAG.getConstant(magics.s, dl, ShSVT)); 5139 ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT)); 5140 return true; 5141 }; 5142 5143 SDValue N0 = N->getOperand(0); 5144 SDValue N1 = N->getOperand(1); 5145 5146 // Collect the shifts / magic values from each element. 5147 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern)) 5148 return SDValue(); 5149 5150 SDValue MagicFactor, Factor, Shift, ShiftMask; 5151 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5152 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5153 Factor = DAG.getBuildVector(VT, dl, Factors); 5154 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5155 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks); 5156 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5157 assert(MagicFactors.size() == 1 && Factors.size() == 1 && 5158 Shifts.size() == 1 && ShiftMasks.size() == 1 && 5159 "Expected matchUnaryPredicate to return one element for scalable " 5160 "vectors"); 5161 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5162 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5163 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5164 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]); 5165 } else { 5166 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 5167 MagicFactor = MagicFactors[0]; 5168 Factor = Factors[0]; 5169 Shift = Shifts[0]; 5170 ShiftMask = ShiftMasks[0]; 5171 } 5172 5173 // Multiply the numerator (operand 0) by the magic value. 5174 // FIXME: We should support doing a MUL in a wider type. 5175 auto GetMULHS = [&](SDValue X, SDValue Y) { 5176 // If the type isn't legal, use a wider mul of the the type calculated 5177 // earlier. 5178 if (!isTypeLegal(VT)) { 5179 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X); 5180 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y); 5181 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 5182 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 5183 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 5184 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 5185 } 5186 5187 if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization)) 5188 return DAG.getNode(ISD::MULHS, dl, VT, X, Y); 5189 if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) { 5190 SDValue LoHi = 5191 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5192 return SDValue(LoHi.getNode(), 1); 5193 } 5194 return SDValue(); 5195 }; 5196 5197 SDValue Q = GetMULHS(N0, MagicFactor); 5198 if (!Q) 5199 return SDValue(); 5200 5201 Created.push_back(Q.getNode()); 5202 5203 // (Optionally) Add/subtract the numerator using Factor. 5204 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor); 5205 Created.push_back(Factor.getNode()); 5206 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor); 5207 Created.push_back(Q.getNode()); 5208 5209 // Shift right algebraic by shift value. 5210 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift); 5211 Created.push_back(Q.getNode()); 5212 5213 // Extract the sign bit, mask it and add it to the quotient. 5214 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT); 5215 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift); 5216 Created.push_back(T.getNode()); 5217 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask); 5218 Created.push_back(T.getNode()); 5219 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 5220 } 5221 5222 /// Given an ISD::UDIV node expressing a divide by constant, 5223 /// return a DAG expression to select that will generate the same value by 5224 /// multiplying by a magic number. 5225 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5226 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG, 5227 bool IsAfterLegalization, 5228 SmallVectorImpl<SDNode *> &Created) const { 5229 SDLoc dl(N); 5230 EVT VT = N->getValueType(0); 5231 EVT SVT = VT.getScalarType(); 5232 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5233 EVT ShSVT = ShVT.getScalarType(); 5234 unsigned EltBits = VT.getScalarSizeInBits(); 5235 EVT MulVT; 5236 5237 // Check to see if we can do this. 5238 // FIXME: We should be more aggressive here. 5239 if (!isTypeLegal(VT)) { 5240 // Limit this to simple scalars for now. 5241 if (VT.isVector() || !VT.isSimple()) 5242 return SDValue(); 5243 5244 // If this type will be promoted to a large enough type with a legal 5245 // multiply operation, we can go ahead and do this transform. 5246 if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger) 5247 return SDValue(); 5248 5249 MulVT = getTypeToTransformTo(*DAG.getContext(), VT); 5250 if (MulVT.getSizeInBits() < (2 * EltBits) || 5251 !isOperationLegal(ISD::MUL, MulVT)) 5252 return SDValue(); 5253 } 5254 5255 bool UseNPQ = false; 5256 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors; 5257 5258 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 5259 if (C->isNullValue()) 5260 return false; 5261 // FIXME: We should use a narrower constant when the upper 5262 // bits are known to be zero. 5263 const APInt& Divisor = C->getAPIntValue(); 5264 APInt::mu magics = Divisor.magicu(); 5265 unsigned PreShift = 0, PostShift = 0; 5266 5267 // If the divisor is even, we can avoid using the expensive fixup by 5268 // shifting the divided value upfront. 5269 if (magics.a != 0 && !Divisor[0]) { 5270 PreShift = Divisor.countTrailingZeros(); 5271 // Get magic number for the shifted divisor. 5272 magics = Divisor.lshr(PreShift).magicu(PreShift); 5273 assert(magics.a == 0 && "Should use cheap fixup now"); 5274 } 5275 5276 APInt Magic = magics.m; 5277 5278 unsigned SelNPQ; 5279 if (magics.a == 0 || Divisor.isOneValue()) { 5280 assert(magics.s < Divisor.getBitWidth() && 5281 "We shouldn't generate an undefined shift!"); 5282 PostShift = magics.s; 5283 SelNPQ = false; 5284 } else { 5285 PostShift = magics.s - 1; 5286 SelNPQ = true; 5287 } 5288 5289 PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT)); 5290 MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT)); 5291 NPQFactors.push_back( 5292 DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1) 5293 : APInt::getNullValue(EltBits), 5294 dl, SVT)); 5295 PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT)); 5296 UseNPQ |= SelNPQ; 5297 return true; 5298 }; 5299 5300 SDValue N0 = N->getOperand(0); 5301 SDValue N1 = N->getOperand(1); 5302 5303 // Collect the shifts/magic values from each element. 5304 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern)) 5305 return SDValue(); 5306 5307 SDValue PreShift, PostShift, MagicFactor, NPQFactor; 5308 if (N1.getOpcode() == ISD::BUILD_VECTOR) { 5309 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts); 5310 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5311 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors); 5312 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts); 5313 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 5314 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 && 5315 NPQFactors.size() == 1 && PostShifts.size() == 1 && 5316 "Expected matchUnaryPredicate to return one for scalable vectors"); 5317 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]); 5318 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5319 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]); 5320 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]); 5321 } else { 5322 assert(isa<ConstantSDNode>(N1) && "Expected a constant"); 5323 PreShift = PreShifts[0]; 5324 MagicFactor = MagicFactors[0]; 5325 PostShift = PostShifts[0]; 5326 } 5327 5328 SDValue Q = N0; 5329 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift); 5330 Created.push_back(Q.getNode()); 5331 5332 // FIXME: We should support doing a MUL in a wider type. 5333 auto GetMULHU = [&](SDValue X, SDValue Y) { 5334 // If the type isn't legal, use a wider mul of the the type calculated 5335 // earlier. 5336 if (!isTypeLegal(VT)) { 5337 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X); 5338 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y); 5339 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y); 5340 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y, 5341 DAG.getShiftAmountConstant(EltBits, MulVT, dl)); 5342 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y); 5343 } 5344 5345 if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization)) 5346 return DAG.getNode(ISD::MULHU, dl, VT, X, Y); 5347 if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) { 5348 SDValue LoHi = 5349 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5350 return SDValue(LoHi.getNode(), 1); 5351 } 5352 return SDValue(); // No mulhu or equivalent 5353 }; 5354 5355 // Multiply the numerator (operand 0) by the magic value. 5356 Q = GetMULHU(Q, MagicFactor); 5357 if (!Q) 5358 return SDValue(); 5359 5360 Created.push_back(Q.getNode()); 5361 5362 if (UseNPQ) { 5363 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q); 5364 Created.push_back(NPQ.getNode()); 5365 5366 // For vectors we might have a mix of non-NPQ/NPQ paths, so use 5367 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero. 5368 if (VT.isVector()) 5369 NPQ = GetMULHU(NPQ, NPQFactor); 5370 else 5371 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT)); 5372 5373 Created.push_back(NPQ.getNode()); 5374 5375 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 5376 Created.push_back(Q.getNode()); 5377 } 5378 5379 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift); 5380 Created.push_back(Q.getNode()); 5381 5382 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 5383 5384 SDValue One = DAG.getConstant(1, dl, VT); 5385 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ); 5386 return DAG.getSelect(dl, VT, IsOne, N0, Q); 5387 } 5388 5389 /// If all values in Values that *don't* match the predicate are same 'splat' 5390 /// value, then replace all values with that splat value. 5391 /// Else, if AlternativeReplacement was provided, then replace all values that 5392 /// do match predicate with AlternativeReplacement value. 5393 static void 5394 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values, 5395 std::function<bool(SDValue)> Predicate, 5396 SDValue AlternativeReplacement = SDValue()) { 5397 SDValue Replacement; 5398 // Is there a value for which the Predicate does *NOT* match? What is it? 5399 auto SplatValue = llvm::find_if_not(Values, Predicate); 5400 if (SplatValue != Values.end()) { 5401 // Does Values consist only of SplatValue's and values matching Predicate? 5402 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) { 5403 return Value == *SplatValue || Predicate(Value); 5404 })) // Then we shall replace values matching predicate with SplatValue. 5405 Replacement = *SplatValue; 5406 } 5407 if (!Replacement) { 5408 // Oops, we did not find the "baseline" splat value. 5409 if (!AlternativeReplacement) 5410 return; // Nothing to do. 5411 // Let's replace with provided value then. 5412 Replacement = AlternativeReplacement; 5413 } 5414 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement); 5415 } 5416 5417 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE 5418 /// where the divisor is constant and the comparison target is zero, 5419 /// return a DAG expression that will generate the same comparison result 5420 /// using only multiplications, additions and shifts/rotations. 5421 /// Ref: "Hacker's Delight" 10-17. 5422 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode, 5423 SDValue CompTargetNode, 5424 ISD::CondCode Cond, 5425 DAGCombinerInfo &DCI, 5426 const SDLoc &DL) const { 5427 SmallVector<SDNode *, 5> Built; 5428 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 5429 DCI, DL, Built)) { 5430 for (SDNode *N : Built) 5431 DCI.AddToWorklist(N); 5432 return Folded; 5433 } 5434 5435 return SDValue(); 5436 } 5437 5438 SDValue 5439 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode, 5440 SDValue CompTargetNode, ISD::CondCode Cond, 5441 DAGCombinerInfo &DCI, const SDLoc &DL, 5442 SmallVectorImpl<SDNode *> &Created) const { 5443 // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q) 5444 // - D must be constant, with D = D0 * 2^K where D0 is odd 5445 // - P is the multiplicative inverse of D0 modulo 2^W 5446 // - Q = floor(((2^W) - 1) / D) 5447 // where W is the width of the common type of N and D. 5448 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5449 "Only applicable for (in)equality comparisons."); 5450 5451 SelectionDAG &DAG = DCI.DAG; 5452 5453 EVT VT = REMNode.getValueType(); 5454 EVT SVT = VT.getScalarType(); 5455 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5456 EVT ShSVT = ShVT.getScalarType(); 5457 5458 // If MUL is unavailable, we cannot proceed in any case. 5459 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 5460 return SDValue(); 5461 5462 bool ComparingWithAllZeros = true; 5463 bool AllComparisonsWithNonZerosAreTautological = true; 5464 bool HadTautologicalLanes = false; 5465 bool AllLanesAreTautological = true; 5466 bool HadEvenDivisor = false; 5467 bool AllDivisorsArePowerOfTwo = true; 5468 bool HadTautologicalInvertedLanes = false; 5469 SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts; 5470 5471 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) { 5472 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 5473 if (CDiv->isNullValue()) 5474 return false; 5475 5476 const APInt &D = CDiv->getAPIntValue(); 5477 const APInt &Cmp = CCmp->getAPIntValue(); 5478 5479 ComparingWithAllZeros &= Cmp.isNullValue(); 5480 5481 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 5482 // if C2 is not less than C1, the comparison is always false. 5483 // But we will only be able to produce the comparison that will give the 5484 // opposive tautological answer. So this lane would need to be fixed up. 5485 bool TautologicalInvertedLane = D.ule(Cmp); 5486 HadTautologicalInvertedLanes |= TautologicalInvertedLane; 5487 5488 // If all lanes are tautological (either all divisors are ones, or divisor 5489 // is not greater than the constant we are comparing with), 5490 // we will prefer to avoid the fold. 5491 bool TautologicalLane = D.isOneValue() || TautologicalInvertedLane; 5492 HadTautologicalLanes |= TautologicalLane; 5493 AllLanesAreTautological &= TautologicalLane; 5494 5495 // If we are comparing with non-zero, we need'll need to subtract said 5496 // comparison value from the LHS. But there is no point in doing that if 5497 // every lane where we are comparing with non-zero is tautological.. 5498 if (!Cmp.isNullValue()) 5499 AllComparisonsWithNonZerosAreTautological &= TautologicalLane; 5500 5501 // Decompose D into D0 * 2^K 5502 unsigned K = D.countTrailingZeros(); 5503 assert((!D.isOneValue() || (K == 0)) && "For divisor '1' we won't rotate."); 5504 APInt D0 = D.lshr(K); 5505 5506 // D is even if it has trailing zeros. 5507 HadEvenDivisor |= (K != 0); 5508 // D is a power-of-two if D0 is one. 5509 // If all divisors are power-of-two, we will prefer to avoid the fold. 5510 AllDivisorsArePowerOfTwo &= D0.isOneValue(); 5511 5512 // P = inv(D0, 2^W) 5513 // 2^W requires W + 1 bits, so we have to extend and then truncate. 5514 unsigned W = D.getBitWidth(); 5515 APInt P = D0.zext(W + 1) 5516 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 5517 .trunc(W); 5518 assert(!P.isNullValue() && "No multiplicative inverse!"); // unreachable 5519 assert((D0 * P).isOneValue() && "Multiplicative inverse sanity check."); 5520 5521 // Q = floor((2^W - 1) u/ D) 5522 // R = ((2^W - 1) u% D) 5523 APInt Q, R; 5524 APInt::udivrem(APInt::getAllOnesValue(W), D, Q, R); 5525 5526 // If we are comparing with zero, then that comparison constant is okay, 5527 // else it may need to be one less than that. 5528 if (Cmp.ugt(R)) 5529 Q -= 1; 5530 5531 assert(APInt::getAllOnesValue(ShSVT.getSizeInBits()).ugt(K) && 5532 "We are expecting that K is always less than all-ones for ShSVT"); 5533 5534 // If the lane is tautological the result can be constant-folded. 5535 if (TautologicalLane) { 5536 // Set P and K amount to a bogus values so we can try to splat them. 5537 P = 0; 5538 K = -1; 5539 // And ensure that comparison constant is tautological, 5540 // it will always compare true/false. 5541 Q = -1; 5542 } 5543 5544 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 5545 KAmts.push_back( 5546 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 5547 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 5548 return true; 5549 }; 5550 5551 SDValue N = REMNode.getOperand(0); 5552 SDValue D = REMNode.getOperand(1); 5553 5554 // Collect the values from each element. 5555 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern)) 5556 return SDValue(); 5557 5558 // If all lanes are tautological, the result can be constant-folded. 5559 if (AllLanesAreTautological) 5560 return SDValue(); 5561 5562 // If this is a urem by a powers-of-two, avoid the fold since it can be 5563 // best implemented as a bit test. 5564 if (AllDivisorsArePowerOfTwo) 5565 return SDValue(); 5566 5567 SDValue PVal, KVal, QVal; 5568 if (VT.isVector()) { 5569 if (HadTautologicalLanes) { 5570 // Try to turn PAmts into a splat, since we don't care about the values 5571 // that are currently '0'. If we can't, just keep '0'`s. 5572 turnVectorIntoSplatVector(PAmts, isNullConstant); 5573 // Try to turn KAmts into a splat, since we don't care about the values 5574 // that are currently '-1'. If we can't, change them to '0'`s. 5575 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 5576 DAG.getConstant(0, DL, ShSVT)); 5577 } 5578 5579 PVal = DAG.getBuildVector(VT, DL, PAmts); 5580 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 5581 QVal = DAG.getBuildVector(VT, DL, QAmts); 5582 } else { 5583 PVal = PAmts[0]; 5584 KVal = KAmts[0]; 5585 QVal = QAmts[0]; 5586 } 5587 5588 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) { 5589 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT)) 5590 return SDValue(); // FIXME: Could/should use `ISD::ADD`? 5591 assert(CompTargetNode.getValueType() == N.getValueType() && 5592 "Expecting that the types on LHS and RHS of comparisons match."); 5593 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode); 5594 } 5595 5596 // (mul N, P) 5597 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 5598 Created.push_back(Op0.getNode()); 5599 5600 // Rotate right only if any divisor was even. We avoid rotates for all-odd 5601 // divisors as a performance improvement, since rotating by 0 is a no-op. 5602 if (HadEvenDivisor) { 5603 // We need ROTR to do this. 5604 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 5605 return SDValue(); 5606 SDNodeFlags Flags; 5607 Flags.setExact(true); 5608 // UREM: (rotr (mul N, P), K) 5609 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal, Flags); 5610 Created.push_back(Op0.getNode()); 5611 } 5612 5613 // UREM: (setule/setugt (rotr (mul N, P), K), Q) 5614 SDValue NewCC = 5615 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 5616 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 5617 if (!HadTautologicalInvertedLanes) 5618 return NewCC; 5619 5620 // If any lanes previously compared always-false, the NewCC will give 5621 // always-true result for them, so we need to fixup those lanes. 5622 // Or the other way around for inequality predicate. 5623 assert(VT.isVector() && "Can/should only get here for vectors."); 5624 Created.push_back(NewCC.getNode()); 5625 5626 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 5627 // if C2 is not less than C1, the comparison is always false. 5628 // But we have produced the comparison that will give the 5629 // opposive tautological answer. So these lanes would need to be fixed up. 5630 SDValue TautologicalInvertedChannels = 5631 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE); 5632 Created.push_back(TautologicalInvertedChannels.getNode()); 5633 5634 // NOTE: we avoid letting illegal types through even if we're before legalize 5635 // ops – legalization has a hard time producing good code for this. 5636 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) { 5637 // If we have a vector select, let's replace the comparison results in the 5638 // affected lanes with the correct tautological result. 5639 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true, 5640 DL, SETCCVT, SETCCVT); 5641 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels, 5642 Replacement, NewCC); 5643 } 5644 5645 // Else, we can just invert the comparison result in the appropriate lanes. 5646 // 5647 // NOTE: see the note above VSELECT above. 5648 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT)) 5649 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC, 5650 TautologicalInvertedChannels); 5651 5652 return SDValue(); // Don't know how to lower. 5653 } 5654 5655 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE 5656 /// where the divisor is constant and the comparison target is zero, 5657 /// return a DAG expression that will generate the same comparison result 5658 /// using only multiplications, additions and shifts/rotations. 5659 /// Ref: "Hacker's Delight" 10-17. 5660 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode, 5661 SDValue CompTargetNode, 5662 ISD::CondCode Cond, 5663 DAGCombinerInfo &DCI, 5664 const SDLoc &DL) const { 5665 SmallVector<SDNode *, 7> Built; 5666 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 5667 DCI, DL, Built)) { 5668 assert(Built.size() <= 7 && "Max size prediction failed."); 5669 for (SDNode *N : Built) 5670 DCI.AddToWorklist(N); 5671 return Folded; 5672 } 5673 5674 return SDValue(); 5675 } 5676 5677 SDValue 5678 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode, 5679 SDValue CompTargetNode, ISD::CondCode Cond, 5680 DAGCombinerInfo &DCI, const SDLoc &DL, 5681 SmallVectorImpl<SDNode *> &Created) const { 5682 // Fold: 5683 // (seteq/ne (srem N, D), 0) 5684 // To: 5685 // (setule/ugt (rotr (add (mul N, P), A), K), Q) 5686 // 5687 // - D must be constant, with D = D0 * 2^K where D0 is odd 5688 // - P is the multiplicative inverse of D0 modulo 2^W 5689 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k))) 5690 // - Q = floor((2 * A) / (2^K)) 5691 // where W is the width of the common type of N and D. 5692 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5693 "Only applicable for (in)equality comparisons."); 5694 5695 SelectionDAG &DAG = DCI.DAG; 5696 5697 EVT VT = REMNode.getValueType(); 5698 EVT SVT = VT.getScalarType(); 5699 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5700 EVT ShSVT = ShVT.getScalarType(); 5701 5702 // If we are after ops legalization, and MUL is unavailable, we can not 5703 // proceed. 5704 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT)) 5705 return SDValue(); 5706 5707 // TODO: Could support comparing with non-zero too. 5708 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode); 5709 if (!CompTarget || !CompTarget->isNullValue()) 5710 return SDValue(); 5711 5712 bool HadIntMinDivisor = false; 5713 bool HadOneDivisor = false; 5714 bool AllDivisorsAreOnes = true; 5715 bool HadEvenDivisor = false; 5716 bool NeedToApplyOffset = false; 5717 bool AllDivisorsArePowerOfTwo = true; 5718 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts; 5719 5720 auto BuildSREMPattern = [&](ConstantSDNode *C) { 5721 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 5722 if (C->isNullValue()) 5723 return false; 5724 5725 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine. 5726 5727 // WARNING: this fold is only valid for positive divisors! 5728 APInt D = C->getAPIntValue(); 5729 if (D.isNegative()) 5730 D.negate(); // `rem %X, -C` is equivalent to `rem %X, C` 5731 5732 HadIntMinDivisor |= D.isMinSignedValue(); 5733 5734 // If all divisors are ones, we will prefer to avoid the fold. 5735 HadOneDivisor |= D.isOneValue(); 5736 AllDivisorsAreOnes &= D.isOneValue(); 5737 5738 // Decompose D into D0 * 2^K 5739 unsigned K = D.countTrailingZeros(); 5740 assert((!D.isOneValue() || (K == 0)) && "For divisor '1' we won't rotate."); 5741 APInt D0 = D.lshr(K); 5742 5743 if (!D.isMinSignedValue()) { 5744 // D is even if it has trailing zeros; unless it's INT_MIN, in which case 5745 // we don't care about this lane in this fold, we'll special-handle it. 5746 HadEvenDivisor |= (K != 0); 5747 } 5748 5749 // D is a power-of-two if D0 is one. This includes INT_MIN. 5750 // If all divisors are power-of-two, we will prefer to avoid the fold. 5751 AllDivisorsArePowerOfTwo &= D0.isOneValue(); 5752 5753 // P = inv(D0, 2^W) 5754 // 2^W requires W + 1 bits, so we have to extend and then truncate. 5755 unsigned W = D.getBitWidth(); 5756 APInt P = D0.zext(W + 1) 5757 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 5758 .trunc(W); 5759 assert(!P.isNullValue() && "No multiplicative inverse!"); // unreachable 5760 assert((D0 * P).isOneValue() && "Multiplicative inverse sanity check."); 5761 5762 // A = floor((2^(W - 1) - 1) / D0) & -2^K 5763 APInt A = APInt::getSignedMaxValue(W).udiv(D0); 5764 A.clearLowBits(K); 5765 5766 if (!D.isMinSignedValue()) { 5767 // If divisor INT_MIN, then we don't care about this lane in this fold, 5768 // we'll special-handle it. 5769 NeedToApplyOffset |= A != 0; 5770 } 5771 5772 // Q = floor((2 * A) / (2^K)) 5773 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K)); 5774 5775 assert(APInt::getAllOnesValue(SVT.getSizeInBits()).ugt(A) && 5776 "We are expecting that A is always less than all-ones for SVT"); 5777 assert(APInt::getAllOnesValue(ShSVT.getSizeInBits()).ugt(K) && 5778 "We are expecting that K is always less than all-ones for ShSVT"); 5779 5780 // If the divisor is 1 the result can be constant-folded. Likewise, we 5781 // don't care about INT_MIN lanes, those can be set to undef if appropriate. 5782 if (D.isOneValue()) { 5783 // Set P, A and K to a bogus values so we can try to splat them. 5784 P = 0; 5785 A = -1; 5786 K = -1; 5787 5788 // x ?% 1 == 0 <--> true <--> x u<= -1 5789 Q = -1; 5790 } 5791 5792 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 5793 AAmts.push_back(DAG.getConstant(A, DL, SVT)); 5794 KAmts.push_back( 5795 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 5796 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 5797 return true; 5798 }; 5799 5800 SDValue N = REMNode.getOperand(0); 5801 SDValue D = REMNode.getOperand(1); 5802 5803 // Collect the values from each element. 5804 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern)) 5805 return SDValue(); 5806 5807 // If this is a srem by a one, avoid the fold since it can be constant-folded. 5808 if (AllDivisorsAreOnes) 5809 return SDValue(); 5810 5811 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold 5812 // since it can be best implemented as a bit test. 5813 if (AllDivisorsArePowerOfTwo) 5814 return SDValue(); 5815 5816 SDValue PVal, AVal, KVal, QVal; 5817 if (D.getOpcode() == ISD::BUILD_VECTOR) { 5818 if (HadOneDivisor) { 5819 // Try to turn PAmts into a splat, since we don't care about the values 5820 // that are currently '0'. If we can't, just keep '0'`s. 5821 turnVectorIntoSplatVector(PAmts, isNullConstant); 5822 // Try to turn AAmts into a splat, since we don't care about the 5823 // values that are currently '-1'. If we can't, change them to '0'`s. 5824 turnVectorIntoSplatVector(AAmts, isAllOnesConstant, 5825 DAG.getConstant(0, DL, SVT)); 5826 // Try to turn KAmts into a splat, since we don't care about the values 5827 // that are currently '-1'. If we can't, change them to '0'`s. 5828 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 5829 DAG.getConstant(0, DL, ShSVT)); 5830 } 5831 5832 PVal = DAG.getBuildVector(VT, DL, PAmts); 5833 AVal = DAG.getBuildVector(VT, DL, AAmts); 5834 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 5835 QVal = DAG.getBuildVector(VT, DL, QAmts); 5836 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) { 5837 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 && 5838 QAmts.size() == 1 && 5839 "Expected matchUnaryPredicate to return one element for scalable " 5840 "vectors"); 5841 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 5842 AVal = DAG.getSplatVector(VT, DL, AAmts[0]); 5843 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 5844 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 5845 } else { 5846 assert(isa<ConstantSDNode>(D) && "Expected a constant"); 5847 PVal = PAmts[0]; 5848 AVal = AAmts[0]; 5849 KVal = KAmts[0]; 5850 QVal = QAmts[0]; 5851 } 5852 5853 // (mul N, P) 5854 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 5855 Created.push_back(Op0.getNode()); 5856 5857 if (NeedToApplyOffset) { 5858 // We need ADD to do this. 5859 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT)) 5860 return SDValue(); 5861 5862 // (add (mul N, P), A) 5863 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal); 5864 Created.push_back(Op0.getNode()); 5865 } 5866 5867 // Rotate right only if any divisor was even. We avoid rotates for all-odd 5868 // divisors as a performance improvement, since rotating by 0 is a no-op. 5869 if (HadEvenDivisor) { 5870 // We need ROTR to do this. 5871 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT)) 5872 return SDValue(); 5873 SDNodeFlags Flags; 5874 Flags.setExact(true); 5875 // SREM: (rotr (add (mul N, P), A), K) 5876 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal, Flags); 5877 Created.push_back(Op0.getNode()); 5878 } 5879 5880 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q) 5881 SDValue Fold = 5882 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 5883 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 5884 5885 // If we didn't have lanes with INT_MIN divisor, then we're done. 5886 if (!HadIntMinDivisor) 5887 return Fold; 5888 5889 // That fold is only valid for positive divisors. Which effectively means, 5890 // it is invalid for INT_MIN divisors. So if we have such a lane, 5891 // we must fix-up results for said lanes. 5892 assert(VT.isVector() && "Can/should only get here for vectors."); 5893 5894 // NOTE: we avoid letting illegal types through even if we're before legalize 5895 // ops – legalization has a hard time producing good code for the code that 5896 // follows. 5897 if (!isOperationLegalOrCustom(ISD::SETEQ, VT) || 5898 !isOperationLegalOrCustom(ISD::AND, VT) || 5899 !isOperationLegalOrCustom(Cond, VT) || 5900 !isOperationLegalOrCustom(ISD::VSELECT, VT)) 5901 return SDValue(); 5902 5903 Created.push_back(Fold.getNode()); 5904 5905 SDValue IntMin = DAG.getConstant( 5906 APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT); 5907 SDValue IntMax = DAG.getConstant( 5908 APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT); 5909 SDValue Zero = 5910 DAG.getConstant(APInt::getNullValue(SVT.getScalarSizeInBits()), DL, VT); 5911 5912 // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded. 5913 SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ); 5914 Created.push_back(DivisorIsIntMin.getNode()); 5915 5916 // (N s% INT_MIN) ==/!= 0 <--> (N & INT_MAX) ==/!= 0 5917 SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax); 5918 Created.push_back(Masked.getNode()); 5919 SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond); 5920 Created.push_back(MaskedIsZero.getNode()); 5921 5922 // To produce final result we need to blend 2 vectors: 'SetCC' and 5923 // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick 5924 // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is 5925 // constant-folded, select can get lowered to a shuffle with constant mask. 5926 SDValue Blended = 5927 DAG.getNode(ISD::VSELECT, DL, VT, DivisorIsIntMin, MaskedIsZero, Fold); 5928 5929 return Blended; 5930 } 5931 5932 bool TargetLowering:: 5933 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 5934 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 5935 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 5936 "be a constant integer"); 5937 return true; 5938 } 5939 5940 return false; 5941 } 5942 5943 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 5944 const DenormalMode &Mode) const { 5945 SDLoc DL(Op); 5946 EVT VT = Op.getValueType(); 5947 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 5948 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 5949 // Testing it with denormal inputs to avoid wrong estimate. 5950 if (Mode.Input == DenormalMode::IEEE) { 5951 // This is specifically a check for the handling of denormal inputs, 5952 // not the result. 5953 5954 // Test = fabs(X) < SmallestNormal 5955 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 5956 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 5957 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 5958 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 5959 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 5960 } 5961 // Test = X == 0.0 5962 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 5963 } 5964 5965 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 5966 bool LegalOps, bool OptForSize, 5967 NegatibleCost &Cost, 5968 unsigned Depth) const { 5969 // fneg is removable even if it has multiple uses. 5970 if (Op.getOpcode() == ISD::FNEG) { 5971 Cost = NegatibleCost::Cheaper; 5972 return Op.getOperand(0); 5973 } 5974 5975 // Don't recurse exponentially. 5976 if (Depth > SelectionDAG::MaxRecursionDepth) 5977 return SDValue(); 5978 5979 // Pre-increment recursion depth for use in recursive calls. 5980 ++Depth; 5981 const SDNodeFlags Flags = Op->getFlags(); 5982 const TargetOptions &Options = DAG.getTarget().Options; 5983 EVT VT = Op.getValueType(); 5984 unsigned Opcode = Op.getOpcode(); 5985 5986 // Don't allow anything with multiple uses unless we know it is free. 5987 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) { 5988 bool IsFreeExtend = Opcode == ISD::FP_EXTEND && 5989 isFPExtFree(VT, Op.getOperand(0).getValueType()); 5990 if (!IsFreeExtend) 5991 return SDValue(); 5992 } 5993 5994 auto RemoveDeadNode = [&](SDValue N) { 5995 if (N && N.getNode()->use_empty()) 5996 DAG.RemoveDeadNode(N.getNode()); 5997 }; 5998 5999 SDLoc DL(Op); 6000 6001 // Because getNegatedExpression can delete nodes we need a handle to keep 6002 // temporary nodes alive in case the recursion manages to create an identical 6003 // node. 6004 std::list<HandleSDNode> Handles; 6005 6006 switch (Opcode) { 6007 case ISD::ConstantFP: { 6008 // Don't invert constant FP values after legalization unless the target says 6009 // the negated constant is legal. 6010 bool IsOpLegal = 6011 isOperationLegal(ISD::ConstantFP, VT) || 6012 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT, 6013 OptForSize); 6014 6015 if (LegalOps && !IsOpLegal) 6016 break; 6017 6018 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 6019 V.changeSign(); 6020 SDValue CFP = DAG.getConstantFP(V, DL, VT); 6021 6022 // If we already have the use of the negated floating constant, it is free 6023 // to negate it even it has multiple uses. 6024 if (!Op.hasOneUse() && CFP.use_empty()) 6025 break; 6026 Cost = NegatibleCost::Neutral; 6027 return CFP; 6028 } 6029 case ISD::BUILD_VECTOR: { 6030 // Only permit BUILD_VECTOR of constants. 6031 if (llvm::any_of(Op->op_values(), [&](SDValue N) { 6032 return !N.isUndef() && !isa<ConstantFPSDNode>(N); 6033 })) 6034 break; 6035 6036 bool IsOpLegal = 6037 (isOperationLegal(ISD::ConstantFP, VT) && 6038 isOperationLegal(ISD::BUILD_VECTOR, VT)) || 6039 llvm::all_of(Op->op_values(), [&](SDValue N) { 6040 return N.isUndef() || 6041 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT, 6042 OptForSize); 6043 }); 6044 6045 if (LegalOps && !IsOpLegal) 6046 break; 6047 6048 SmallVector<SDValue, 4> Ops; 6049 for (SDValue C : Op->op_values()) { 6050 if (C.isUndef()) { 6051 Ops.push_back(C); 6052 continue; 6053 } 6054 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF(); 6055 V.changeSign(); 6056 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType())); 6057 } 6058 Cost = NegatibleCost::Neutral; 6059 return DAG.getBuildVector(VT, DL, Ops); 6060 } 6061 case ISD::FADD: { 6062 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6063 break; 6064 6065 // After operation legalization, it might not be legal to create new FSUBs. 6066 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT)) 6067 break; 6068 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6069 6070 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y) 6071 NegatibleCost CostX = NegatibleCost::Expensive; 6072 SDValue NegX = 6073 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6074 // Prevent this node from being deleted by the next call. 6075 if (NegX) 6076 Handles.emplace_back(NegX); 6077 6078 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X) 6079 NegatibleCost CostY = NegatibleCost::Expensive; 6080 SDValue NegY = 6081 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6082 6083 // We're done with the handles. 6084 Handles.clear(); 6085 6086 // Negate the X if its cost is less or equal than Y. 6087 if (NegX && (CostX <= CostY)) { 6088 Cost = CostX; 6089 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags); 6090 if (NegY != N) 6091 RemoveDeadNode(NegY); 6092 return N; 6093 } 6094 6095 // Negate the Y if it is not expensive. 6096 if (NegY) { 6097 Cost = CostY; 6098 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags); 6099 if (NegX != N) 6100 RemoveDeadNode(NegX); 6101 return N; 6102 } 6103 break; 6104 } 6105 case ISD::FSUB: { 6106 // We can't turn -(A-B) into B-A when we honor signed zeros. 6107 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6108 break; 6109 6110 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6111 // fold (fneg (fsub 0, Y)) -> Y 6112 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true)) 6113 if (C->isZero()) { 6114 Cost = NegatibleCost::Cheaper; 6115 return Y; 6116 } 6117 6118 // fold (fneg (fsub X, Y)) -> (fsub Y, X) 6119 Cost = NegatibleCost::Neutral; 6120 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags); 6121 } 6122 case ISD::FMUL: 6123 case ISD::FDIV: { 6124 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6125 6126 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 6127 NegatibleCost CostX = NegatibleCost::Expensive; 6128 SDValue NegX = 6129 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6130 // Prevent this node from being deleted by the next call. 6131 if (NegX) 6132 Handles.emplace_back(NegX); 6133 6134 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 6135 NegatibleCost CostY = NegatibleCost::Expensive; 6136 SDValue NegY = 6137 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6138 6139 // We're done with the handles. 6140 Handles.clear(); 6141 6142 // Negate the X if its cost is less or equal than Y. 6143 if (NegX && (CostX <= CostY)) { 6144 Cost = CostX; 6145 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags); 6146 if (NegY != N) 6147 RemoveDeadNode(NegY); 6148 return N; 6149 } 6150 6151 // Ignore X * 2.0 because that is expected to be canonicalized to X + X. 6152 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1))) 6153 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL) 6154 break; 6155 6156 // Negate the Y if it is not expensive. 6157 if (NegY) { 6158 Cost = CostY; 6159 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags); 6160 if (NegX != N) 6161 RemoveDeadNode(NegX); 6162 return N; 6163 } 6164 break; 6165 } 6166 case ISD::FMA: 6167 case ISD::FMAD: { 6168 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6169 break; 6170 6171 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2); 6172 NegatibleCost CostZ = NegatibleCost::Expensive; 6173 SDValue NegZ = 6174 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth); 6175 // Give up if fail to negate the Z. 6176 if (!NegZ) 6177 break; 6178 6179 // Prevent this node from being deleted by the next two calls. 6180 Handles.emplace_back(NegZ); 6181 6182 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z)) 6183 NegatibleCost CostX = NegatibleCost::Expensive; 6184 SDValue NegX = 6185 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6186 // Prevent this node from being deleted by the next call. 6187 if (NegX) 6188 Handles.emplace_back(NegX); 6189 6190 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z)) 6191 NegatibleCost CostY = NegatibleCost::Expensive; 6192 SDValue NegY = 6193 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6194 6195 // We're done with the handles. 6196 Handles.clear(); 6197 6198 // Negate the X if its cost is less or equal than Y. 6199 if (NegX && (CostX <= CostY)) { 6200 Cost = std::min(CostX, CostZ); 6201 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags); 6202 if (NegY != N) 6203 RemoveDeadNode(NegY); 6204 return N; 6205 } 6206 6207 // Negate the Y if it is not expensive. 6208 if (NegY) { 6209 Cost = std::min(CostY, CostZ); 6210 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags); 6211 if (NegX != N) 6212 RemoveDeadNode(NegX); 6213 return N; 6214 } 6215 break; 6216 } 6217 6218 case ISD::FP_EXTEND: 6219 case ISD::FSIN: 6220 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6221 OptForSize, Cost, Depth)) 6222 return DAG.getNode(Opcode, DL, VT, NegV); 6223 break; 6224 case ISD::FP_ROUND: 6225 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6226 OptForSize, Cost, Depth)) 6227 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1)); 6228 break; 6229 } 6230 6231 return SDValue(); 6232 } 6233 6234 //===----------------------------------------------------------------------===// 6235 // Legalization Utilities 6236 //===----------------------------------------------------------------------===// 6237 6238 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, 6239 SDValue LHS, SDValue RHS, 6240 SmallVectorImpl<SDValue> &Result, 6241 EVT HiLoVT, SelectionDAG &DAG, 6242 MulExpansionKind Kind, SDValue LL, 6243 SDValue LH, SDValue RL, SDValue RH) const { 6244 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 6245 Opcode == ISD::SMUL_LOHI); 6246 6247 bool HasMULHS = (Kind == MulExpansionKind::Always) || 6248 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 6249 bool HasMULHU = (Kind == MulExpansionKind::Always) || 6250 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 6251 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 6252 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 6253 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 6254 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 6255 6256 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 6257 return false; 6258 6259 unsigned OuterBitSize = VT.getScalarSizeInBits(); 6260 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 6261 6262 // LL, LH, RL, and RH must be either all NULL or all set to a value. 6263 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 6264 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 6265 6266 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 6267 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 6268 bool Signed) -> bool { 6269 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 6270 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 6271 Hi = SDValue(Lo.getNode(), 1); 6272 return true; 6273 } 6274 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 6275 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 6276 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 6277 return true; 6278 } 6279 return false; 6280 }; 6281 6282 SDValue Lo, Hi; 6283 6284 if (!LL.getNode() && !RL.getNode() && 6285 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6286 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 6287 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 6288 } 6289 6290 if (!LL.getNode()) 6291 return false; 6292 6293 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 6294 if (DAG.MaskedValueIsZero(LHS, HighMask) && 6295 DAG.MaskedValueIsZero(RHS, HighMask)) { 6296 // The inputs are both zero-extended. 6297 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 6298 Result.push_back(Lo); 6299 Result.push_back(Hi); 6300 if (Opcode != ISD::MUL) { 6301 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6302 Result.push_back(Zero); 6303 Result.push_back(Zero); 6304 } 6305 return true; 6306 } 6307 } 6308 6309 if (!VT.isVector() && Opcode == ISD::MUL && 6310 DAG.ComputeNumSignBits(LHS) > InnerBitSize && 6311 DAG.ComputeNumSignBits(RHS) > InnerBitSize) { 6312 // The input values are both sign-extended. 6313 // TODO non-MUL case? 6314 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 6315 Result.push_back(Lo); 6316 Result.push_back(Hi); 6317 return true; 6318 } 6319 } 6320 6321 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 6322 EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout()); 6323 if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) { 6324 // FIXME getShiftAmountTy does not always return a sensible result when VT 6325 // is an illegal type, and so the type may be too small to fit the shift 6326 // amount. Override it with i32. The shift will have to be legalized. 6327 ShiftAmountTy = MVT::i32; 6328 } 6329 SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy); 6330 6331 if (!LH.getNode() && !RH.getNode() && 6332 isOperationLegalOrCustom(ISD::SRL, VT) && 6333 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6334 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 6335 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 6336 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 6337 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 6338 } 6339 6340 if (!LH.getNode()) 6341 return false; 6342 6343 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 6344 return false; 6345 6346 Result.push_back(Lo); 6347 6348 if (Opcode == ISD::MUL) { 6349 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 6350 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 6351 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 6352 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 6353 Result.push_back(Hi); 6354 return true; 6355 } 6356 6357 // Compute the full width result. 6358 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 6359 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 6360 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6361 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 6362 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 6363 }; 6364 6365 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6366 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 6367 return false; 6368 6369 // This is effectively the add part of a multiply-add of half-sized operands, 6370 // so it cannot overflow. 6371 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 6372 6373 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 6374 return false; 6375 6376 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6377 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6378 6379 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) && 6380 isOperationLegalOrCustom(ISD::ADDE, VT)); 6381 if (UseGlue) 6382 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 6383 Merge(Lo, Hi)); 6384 else 6385 Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next, 6386 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType)); 6387 6388 SDValue Carry = Next.getValue(1); 6389 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6390 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 6391 6392 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 6393 return false; 6394 6395 if (UseGlue) 6396 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 6397 Carry); 6398 else 6399 Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi, 6400 Zero, Carry); 6401 6402 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 6403 6404 if (Opcode == ISD::SMUL_LOHI) { 6405 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 6406 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 6407 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 6408 6409 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 6410 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 6411 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 6412 } 6413 6414 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6415 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 6416 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6417 return true; 6418 } 6419 6420 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 6421 SelectionDAG &DAG, MulExpansionKind Kind, 6422 SDValue LL, SDValue LH, SDValue RL, 6423 SDValue RH) const { 6424 SmallVector<SDValue, 2> Result; 6425 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N), 6426 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 6427 DAG, Kind, LL, LH, RL, RH); 6428 if (Ok) { 6429 assert(Result.size() == 2); 6430 Lo = Result[0]; 6431 Hi = Result[1]; 6432 } 6433 return Ok; 6434 } 6435 6436 // Check that (every element of) Z is undef or not an exact multiple of BW. 6437 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) { 6438 return ISD::matchUnaryPredicate( 6439 Z, 6440 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; }, 6441 true); 6442 } 6443 6444 bool TargetLowering::expandFunnelShift(SDNode *Node, SDValue &Result, 6445 SelectionDAG &DAG) const { 6446 EVT VT = Node->getValueType(0); 6447 6448 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 6449 !isOperationLegalOrCustom(ISD::SRL, VT) || 6450 !isOperationLegalOrCustom(ISD::SUB, VT) || 6451 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 6452 return false; 6453 6454 SDValue X = Node->getOperand(0); 6455 SDValue Y = Node->getOperand(1); 6456 SDValue Z = Node->getOperand(2); 6457 6458 unsigned BW = VT.getScalarSizeInBits(); 6459 bool IsFSHL = Node->getOpcode() == ISD::FSHL; 6460 SDLoc DL(SDValue(Node, 0)); 6461 6462 EVT ShVT = Z.getValueType(); 6463 6464 // If a funnel shift in the other direction is more supported, use it. 6465 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL; 6466 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 6467 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) { 6468 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 6469 // fshl X, Y, Z -> fshr X, Y, -Z 6470 // fshr X, Y, Z -> fshl X, Y, -Z 6471 SDValue Zero = DAG.getConstant(0, DL, ShVT); 6472 Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z); 6473 } else { 6474 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z 6475 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z 6476 SDValue One = DAG.getConstant(1, DL, ShVT); 6477 if (IsFSHL) { 6478 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 6479 X = DAG.getNode(ISD::SRL, DL, VT, X, One); 6480 } else { 6481 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 6482 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One); 6483 } 6484 Z = DAG.getNOT(DL, Z, ShVT); 6485 } 6486 Result = DAG.getNode(RevOpcode, DL, VT, X, Y, Z); 6487 return true; 6488 } 6489 6490 SDValue ShX, ShY; 6491 SDValue ShAmt, InvShAmt; 6492 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 6493 // fshl: X << C | Y >> (BW - C) 6494 // fshr: X << (BW - C) | Y >> C 6495 // where C = Z % BW is not zero 6496 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 6497 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 6498 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt); 6499 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt); 6500 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6501 } else { 6502 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW)) 6503 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW) 6504 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT); 6505 if (isPowerOf2_32(BW)) { 6506 // Z % BW -> Z & (BW - 1) 6507 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask); 6508 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1) 6509 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask); 6510 } else { 6511 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 6512 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 6513 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt); 6514 } 6515 6516 SDValue One = DAG.getConstant(1, DL, ShVT); 6517 if (IsFSHL) { 6518 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt); 6519 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One); 6520 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt); 6521 } else { 6522 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One); 6523 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt); 6524 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt); 6525 } 6526 } 6527 Result = DAG.getNode(ISD::OR, DL, VT, ShX, ShY); 6528 return true; 6529 } 6530 6531 // TODO: Merge with expandFunnelShift. 6532 bool TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps, 6533 SDValue &Result, SelectionDAG &DAG) const { 6534 EVT VT = Node->getValueType(0); 6535 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 6536 bool IsLeft = Node->getOpcode() == ISD::ROTL; 6537 SDValue Op0 = Node->getOperand(0); 6538 SDValue Op1 = Node->getOperand(1); 6539 SDLoc DL(SDValue(Node, 0)); 6540 6541 EVT ShVT = Op1.getValueType(); 6542 SDValue Zero = DAG.getConstant(0, DL, ShVT); 6543 6544 // If a rotate in the other direction is supported, use it. 6545 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL; 6546 if (isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) { 6547 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 6548 Result = DAG.getNode(RevRot, DL, VT, Op0, Sub); 6549 return true; 6550 } 6551 6552 if (!AllowVectorOps && VT.isVector() && 6553 (!isOperationLegalOrCustom(ISD::SHL, VT) || 6554 !isOperationLegalOrCustom(ISD::SRL, VT) || 6555 !isOperationLegalOrCustom(ISD::SUB, VT) || 6556 !isOperationLegalOrCustomOrPromote(ISD::OR, VT) || 6557 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 6558 return false; 6559 6560 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL; 6561 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL; 6562 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 6563 SDValue ShVal; 6564 SDValue HsVal; 6565 if (isPowerOf2_32(EltSizeInBits)) { 6566 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1)) 6567 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1)) 6568 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 6569 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC); 6570 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 6571 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC); 6572 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt); 6573 } else { 6574 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w)) 6575 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w)) 6576 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 6577 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC); 6578 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 6579 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt); 6580 SDValue One = DAG.getConstant(1, DL, ShVT); 6581 HsVal = 6582 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt); 6583 } 6584 Result = DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal); 6585 return true; 6586 } 6587 6588 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 6589 SelectionDAG &DAG) const { 6590 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 6591 SDValue Src = Node->getOperand(OpNo); 6592 EVT SrcVT = Src.getValueType(); 6593 EVT DstVT = Node->getValueType(0); 6594 SDLoc dl(SDValue(Node, 0)); 6595 6596 // FIXME: Only f32 to i64 conversions are supported. 6597 if (SrcVT != MVT::f32 || DstVT != MVT::i64) 6598 return false; 6599 6600 if (Node->isStrictFPOpcode()) 6601 // When a NaN is converted to an integer a trap is allowed. We can't 6602 // use this expansion here because it would eliminate that trap. Other 6603 // traps are also allowed and cannot be eliminated. See 6604 // IEEE 754-2008 sec 5.8. 6605 return false; 6606 6607 // Expand f32 -> i64 conversion 6608 // This algorithm comes from compiler-rt's implementation of fixsfdi: 6609 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c 6610 unsigned SrcEltBits = SrcVT.getScalarSizeInBits(); 6611 EVT IntVT = SrcVT.changeTypeToInteger(); 6612 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout()); 6613 6614 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 6615 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 6616 SDValue Bias = DAG.getConstant(127, dl, IntVT); 6617 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT); 6618 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT); 6619 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 6620 6621 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src); 6622 6623 SDValue ExponentBits = DAG.getNode( 6624 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 6625 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT)); 6626 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 6627 6628 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT, 6629 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 6630 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT)); 6631 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT); 6632 6633 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 6634 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 6635 DAG.getConstant(0x00800000, dl, IntVT)); 6636 6637 R = DAG.getZExtOrTrunc(R, dl, DstVT); 6638 6639 R = DAG.getSelectCC( 6640 dl, Exponent, ExponentLoBit, 6641 DAG.getNode(ISD::SHL, dl, DstVT, R, 6642 DAG.getZExtOrTrunc( 6643 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 6644 dl, IntShVT)), 6645 DAG.getNode(ISD::SRL, dl, DstVT, R, 6646 DAG.getZExtOrTrunc( 6647 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 6648 dl, IntShVT)), 6649 ISD::SETGT); 6650 6651 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT, 6652 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign); 6653 6654 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 6655 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT); 6656 return true; 6657 } 6658 6659 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result, 6660 SDValue &Chain, 6661 SelectionDAG &DAG) const { 6662 SDLoc dl(SDValue(Node, 0)); 6663 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 6664 SDValue Src = Node->getOperand(OpNo); 6665 6666 EVT SrcVT = Src.getValueType(); 6667 EVT DstVT = Node->getValueType(0); 6668 EVT SetCCVT = 6669 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 6670 EVT DstSetCCVT = 6671 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 6672 6673 // Only expand vector types if we have the appropriate vector bit operations. 6674 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT : 6675 ISD::FP_TO_SINT; 6676 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) || 6677 !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT))) 6678 return false; 6679 6680 // If the maximum float value is smaller then the signed integer range, 6681 // the destination signmask can't be represented by the float, so we can 6682 // just use FP_TO_SINT directly. 6683 const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT); 6684 APFloat APF(APFSem, APInt::getNullValue(SrcVT.getScalarSizeInBits())); 6685 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits()); 6686 if (APFloat::opOverflow & 6687 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) { 6688 if (Node->isStrictFPOpcode()) { 6689 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 6690 { Node->getOperand(0), Src }); 6691 Chain = Result.getValue(1); 6692 } else 6693 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 6694 return true; 6695 } 6696 6697 // Don't expand it if there isn't cheap fsub instruction. 6698 if (!isOperationLegalOrCustom( 6699 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT)) 6700 return false; 6701 6702 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 6703 SDValue Sel; 6704 6705 if (Node->isStrictFPOpcode()) { 6706 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 6707 Node->getOperand(0), /*IsSignaling*/ true); 6708 Chain = Sel.getValue(1); 6709 } else { 6710 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT); 6711 } 6712 6713 bool Strict = Node->isStrictFPOpcode() || 6714 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false); 6715 6716 if (Strict) { 6717 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the 6718 // signmask then offset (the result of which should be fully representable). 6719 // Sel = Src < 0x8000000000000000 6720 // FltOfs = select Sel, 0, 0x8000000000000000 6721 // IntOfs = select Sel, 0, 0x8000000000000000 6722 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 6723 6724 // TODO: Should any fast-math-flags be set for the FSUB? 6725 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel, 6726 DAG.getConstantFP(0.0, dl, SrcVT), Cst); 6727 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 6728 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel, 6729 DAG.getConstant(0, dl, DstVT), 6730 DAG.getConstant(SignMask, dl, DstVT)); 6731 SDValue SInt; 6732 if (Node->isStrictFPOpcode()) { 6733 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other }, 6734 { Chain, Src, FltOfs }); 6735 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 6736 { Val.getValue(1), Val }); 6737 Chain = SInt.getValue(1); 6738 } else { 6739 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs); 6740 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val); 6741 } 6742 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 6743 } else { 6744 // Expand based on maximum range of FP_TO_SINT: 6745 // True = fp_to_sint(Src) 6746 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000) 6747 // Result = select (Src < 0x8000000000000000), True, False 6748 6749 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 6750 // TODO: Should any fast-math-flags be set for the FSUB? 6751 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, 6752 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 6753 False = DAG.getNode(ISD::XOR, dl, DstVT, False, 6754 DAG.getConstant(SignMask, dl, DstVT)); 6755 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 6756 Result = DAG.getSelect(dl, DstVT, Sel, True, False); 6757 } 6758 return true; 6759 } 6760 6761 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result, 6762 SDValue &Chain, 6763 SelectionDAG &DAG) const { 6764 // This transform is not correct for converting 0 when rounding mode is set 6765 // to round toward negative infinity which will produce -0.0. So disable under 6766 // strictfp. 6767 if (Node->isStrictFPOpcode()) 6768 return false; 6769 6770 SDValue Src = Node->getOperand(0); 6771 EVT SrcVT = Src.getValueType(); 6772 EVT DstVT = Node->getValueType(0); 6773 6774 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64) 6775 return false; 6776 6777 // Only expand vector types if we have the appropriate vector bit operations. 6778 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 6779 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 6780 !isOperationLegalOrCustom(ISD::FSUB, DstVT) || 6781 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 6782 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 6783 return false; 6784 6785 SDLoc dl(SDValue(Node, 0)); 6786 EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout()); 6787 6788 // Implementation of unsigned i64 to f64 following the algorithm in 6789 // __floatundidf in compiler_rt. This implementation performs rounding 6790 // correctly in all rounding modes with the exception of converting 0 6791 // when rounding toward negative infinity. In that case the fsub will produce 6792 // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect. 6793 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT); 6794 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP( 6795 BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT); 6796 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT); 6797 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT); 6798 SDValue HiShift = DAG.getConstant(32, dl, ShiftVT); 6799 6800 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask); 6801 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift); 6802 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52); 6803 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84); 6804 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr); 6805 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr); 6806 SDValue HiSub = 6807 DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52); 6808 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub); 6809 return true; 6810 } 6811 6812 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node, 6813 SelectionDAG &DAG) const { 6814 SDLoc dl(Node); 6815 unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ? 6816 ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 6817 EVT VT = Node->getValueType(0); 6818 6819 if (VT.isScalableVector()) 6820 report_fatal_error( 6821 "Expanding fminnum/fmaxnum for scalable vectors is undefined."); 6822 6823 if (isOperationLegalOrCustom(NewOp, VT)) { 6824 SDValue Quiet0 = Node->getOperand(0); 6825 SDValue Quiet1 = Node->getOperand(1); 6826 6827 if (!Node->getFlags().hasNoNaNs()) { 6828 // Insert canonicalizes if it's possible we need to quiet to get correct 6829 // sNaN behavior. 6830 if (!DAG.isKnownNeverSNaN(Quiet0)) { 6831 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0, 6832 Node->getFlags()); 6833 } 6834 if (!DAG.isKnownNeverSNaN(Quiet1)) { 6835 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1, 6836 Node->getFlags()); 6837 } 6838 } 6839 6840 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags()); 6841 } 6842 6843 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that 6844 // instead if there are no NaNs. 6845 if (Node->getFlags().hasNoNaNs()) { 6846 unsigned IEEE2018Op = 6847 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM; 6848 if (isOperationLegalOrCustom(IEEE2018Op, VT)) { 6849 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0), 6850 Node->getOperand(1), Node->getFlags()); 6851 } 6852 } 6853 6854 // If none of the above worked, but there are no NaNs, then expand to 6855 // a compare/select sequence. This is required for correctness since 6856 // InstCombine might have canonicalized a fcmp+select sequence to a 6857 // FMINNUM/FMAXNUM node. If we were to fall through to the default 6858 // expansion to libcall, we might introduce a link-time dependency 6859 // on libm into a file that originally did not have one. 6860 if (Node->getFlags().hasNoNaNs()) { 6861 ISD::CondCode Pred = 6862 Node->getOpcode() == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT; 6863 SDValue Op1 = Node->getOperand(0); 6864 SDValue Op2 = Node->getOperand(1); 6865 SDValue SelCC = DAG.getSelectCC(dl, Op1, Op2, Op1, Op2, Pred); 6866 // Copy FMF flags, but always set the no-signed-zeros flag 6867 // as this is implied by the FMINNUM/FMAXNUM semantics. 6868 SDNodeFlags Flags = Node->getFlags(); 6869 Flags.setNoSignedZeros(true); 6870 SelCC->setFlags(Flags); 6871 return SelCC; 6872 } 6873 6874 return SDValue(); 6875 } 6876 6877 bool TargetLowering::expandCTPOP(SDNode *Node, SDValue &Result, 6878 SelectionDAG &DAG) const { 6879 SDLoc dl(Node); 6880 EVT VT = Node->getValueType(0); 6881 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6882 SDValue Op = Node->getOperand(0); 6883 unsigned Len = VT.getScalarSizeInBits(); 6884 assert(VT.isInteger() && "CTPOP not implemented for this type."); 6885 6886 // TODO: Add support for irregular type lengths. 6887 if (!(Len <= 128 && Len % 8 == 0)) 6888 return false; 6889 6890 // Only expand vector types if we have the appropriate vector bit operations. 6891 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::ADD, VT) || 6892 !isOperationLegalOrCustom(ISD::SUB, VT) || 6893 !isOperationLegalOrCustom(ISD::SRL, VT) || 6894 (Len != 8 && !isOperationLegalOrCustom(ISD::MUL, VT)) || 6895 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 6896 return false; 6897 6898 // This is the "best" algorithm from 6899 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 6900 SDValue Mask55 = 6901 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 6902 SDValue Mask33 = 6903 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 6904 SDValue Mask0F = 6905 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 6906 SDValue Mask01 = 6907 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 6908 6909 // v = v - ((v >> 1) & 0x55555555...) 6910 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 6911 DAG.getNode(ISD::AND, dl, VT, 6912 DAG.getNode(ISD::SRL, dl, VT, Op, 6913 DAG.getConstant(1, dl, ShVT)), 6914 Mask55)); 6915 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 6916 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 6917 DAG.getNode(ISD::AND, dl, VT, 6918 DAG.getNode(ISD::SRL, dl, VT, Op, 6919 DAG.getConstant(2, dl, ShVT)), 6920 Mask33)); 6921 // v = (v + (v >> 4)) & 0x0F0F0F0F... 6922 Op = DAG.getNode(ISD::AND, dl, VT, 6923 DAG.getNode(ISD::ADD, dl, VT, Op, 6924 DAG.getNode(ISD::SRL, dl, VT, Op, 6925 DAG.getConstant(4, dl, ShVT))), 6926 Mask0F); 6927 // v = (v * 0x01010101...) >> (Len - 8) 6928 if (Len > 8) 6929 Op = 6930 DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::MUL, dl, VT, Op, Mask01), 6931 DAG.getConstant(Len - 8, dl, ShVT)); 6932 6933 Result = Op; 6934 return true; 6935 } 6936 6937 bool TargetLowering::expandCTLZ(SDNode *Node, SDValue &Result, 6938 SelectionDAG &DAG) const { 6939 SDLoc dl(Node); 6940 EVT VT = Node->getValueType(0); 6941 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6942 SDValue Op = Node->getOperand(0); 6943 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 6944 6945 // If the non-ZERO_UNDEF version is supported we can use that instead. 6946 if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF && 6947 isOperationLegalOrCustom(ISD::CTLZ, VT)) { 6948 Result = DAG.getNode(ISD::CTLZ, dl, VT, Op); 6949 return true; 6950 } 6951 6952 // If the ZERO_UNDEF version is supported use that and handle the zero case. 6953 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 6954 EVT SetCCVT = 6955 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6956 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 6957 SDValue Zero = DAG.getConstant(0, dl, VT); 6958 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 6959 Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero, 6960 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ); 6961 return true; 6962 } 6963 6964 // Only expand vector types if we have the appropriate vector bit operations. 6965 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 6966 !isOperationLegalOrCustom(ISD::CTPOP, VT) || 6967 !isOperationLegalOrCustom(ISD::SRL, VT) || 6968 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 6969 return false; 6970 6971 // for now, we do this: 6972 // x = x | (x >> 1); 6973 // x = x | (x >> 2); 6974 // ... 6975 // x = x | (x >>16); 6976 // x = x | (x >>32); // for 64-bit input 6977 // return popcount(~x); 6978 // 6979 // Ref: "Hacker's Delight" by Henry Warren 6980 for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) { 6981 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 6982 Op = DAG.getNode(ISD::OR, dl, VT, Op, 6983 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp)); 6984 } 6985 Op = DAG.getNOT(dl, Op, VT); 6986 Result = DAG.getNode(ISD::CTPOP, dl, VT, Op); 6987 return true; 6988 } 6989 6990 bool TargetLowering::expandCTTZ(SDNode *Node, SDValue &Result, 6991 SelectionDAG &DAG) const { 6992 SDLoc dl(Node); 6993 EVT VT = Node->getValueType(0); 6994 SDValue Op = Node->getOperand(0); 6995 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 6996 6997 // If the non-ZERO_UNDEF version is supported we can use that instead. 6998 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF && 6999 isOperationLegalOrCustom(ISD::CTTZ, VT)) { 7000 Result = DAG.getNode(ISD::CTTZ, dl, VT, Op); 7001 return true; 7002 } 7003 7004 // If the ZERO_UNDEF version is supported use that and handle the zero case. 7005 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) { 7006 EVT SetCCVT = 7007 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7008 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op); 7009 SDValue Zero = DAG.getConstant(0, dl, VT); 7010 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 7011 Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero, 7012 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ); 7013 return true; 7014 } 7015 7016 // Only expand vector types if we have the appropriate vector bit operations. 7017 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 7018 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 7019 !isOperationLegalOrCustom(ISD::CTLZ, VT)) || 7020 !isOperationLegalOrCustom(ISD::SUB, VT) || 7021 !isOperationLegalOrCustomOrPromote(ISD::AND, VT) || 7022 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 7023 return false; 7024 7025 // for now, we use: { return popcount(~x & (x - 1)); } 7026 // unless the target has ctlz but not ctpop, in which case we use: 7027 // { return 32 - nlz(~x & (x-1)); } 7028 // Ref: "Hacker's Delight" by Henry Warren 7029 SDValue Tmp = DAG.getNode( 7030 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT), 7031 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT))); 7032 7033 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 7034 if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) { 7035 Result = 7036 DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT), 7037 DAG.getNode(ISD::CTLZ, dl, VT, Tmp)); 7038 return true; 7039 } 7040 7041 Result = DAG.getNode(ISD::CTPOP, dl, VT, Tmp); 7042 return true; 7043 } 7044 7045 bool TargetLowering::expandABS(SDNode *N, SDValue &Result, 7046 SelectionDAG &DAG, bool IsNegative) const { 7047 SDLoc dl(N); 7048 EVT VT = N->getValueType(0); 7049 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7050 SDValue Op = N->getOperand(0); 7051 7052 // abs(x) -> smax(x,sub(0,x)) 7053 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 7054 isOperationLegal(ISD::SMAX, VT)) { 7055 SDValue Zero = DAG.getConstant(0, dl, VT); 7056 Result = DAG.getNode(ISD::SMAX, dl, VT, Op, 7057 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7058 return true; 7059 } 7060 7061 // abs(x) -> umin(x,sub(0,x)) 7062 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 7063 isOperationLegal(ISD::UMIN, VT)) { 7064 SDValue Zero = DAG.getConstant(0, dl, VT); 7065 Result = DAG.getNode(ISD::UMIN, dl, VT, Op, 7066 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7067 return true; 7068 } 7069 7070 // 0 - abs(x) -> smin(x, sub(0,x)) 7071 if (IsNegative && isOperationLegal(ISD::SUB, VT) && 7072 isOperationLegal(ISD::SMIN, VT)) { 7073 SDValue Zero = DAG.getConstant(0, dl, VT); 7074 Result = DAG.getNode(ISD::SMIN, dl, VT, Op, 7075 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 7076 return true; 7077 } 7078 7079 // Only expand vector types if we have the appropriate vector operations. 7080 if (VT.isVector() && 7081 (!isOperationLegalOrCustom(ISD::SRA, VT) || 7082 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) || 7083 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) || 7084 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 7085 return false; 7086 7087 SDValue Shift = 7088 DAG.getNode(ISD::SRA, dl, VT, Op, 7089 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT)); 7090 if (!IsNegative) { 7091 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, Op, Shift); 7092 Result = DAG.getNode(ISD::XOR, dl, VT, Add, Shift); 7093 } else { 7094 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y)) 7095 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift); 7096 Result = DAG.getNode(ISD::SUB, dl, VT, Shift, Xor); 7097 } 7098 return true; 7099 } 7100 7101 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const { 7102 SDLoc dl(N); 7103 EVT VT = N->getValueType(0); 7104 SDValue Op = N->getOperand(0); 7105 7106 if (!VT.isSimple()) 7107 return SDValue(); 7108 7109 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7110 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 7111 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 7112 default: 7113 return SDValue(); 7114 case MVT::i16: 7115 // Use a rotate by 8. This can be further expanded if necessary. 7116 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7117 case MVT::i32: 7118 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7119 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7120 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7121 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7122 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 7123 DAG.getConstant(0xFF0000, dl, VT)); 7124 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT)); 7125 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 7126 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 7127 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 7128 case MVT::i64: 7129 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 7130 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 7131 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7132 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7133 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7134 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7135 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 7136 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 7137 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, 7138 DAG.getConstant(255ULL<<48, dl, VT)); 7139 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, 7140 DAG.getConstant(255ULL<<40, dl, VT)); 7141 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, 7142 DAG.getConstant(255ULL<<32, dl, VT)); 7143 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, 7144 DAG.getConstant(255ULL<<24, dl, VT)); 7145 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 7146 DAG.getConstant(255ULL<<16, dl, VT)); 7147 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, 7148 DAG.getConstant(255ULL<<8 , dl, VT)); 7149 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7); 7150 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5); 7151 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 7152 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 7153 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6); 7154 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 7155 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4); 7156 } 7157 } 7158 7159 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const { 7160 SDLoc dl(N); 7161 EVT VT = N->getValueType(0); 7162 SDValue Op = N->getOperand(0); 7163 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7164 unsigned Sz = VT.getScalarSizeInBits(); 7165 7166 SDValue Tmp, Tmp2, Tmp3; 7167 7168 // If we can, perform BSWAP first and then the mask+swap the i4, then i2 7169 // and finally the i1 pairs. 7170 // TODO: We can easily support i4/i2 legal types if any target ever does. 7171 if (Sz >= 8 && isPowerOf2_32(Sz)) { 7172 // Create the masks - repeating the pattern every byte. 7173 APInt MaskHi4 = APInt::getSplat(Sz, APInt(8, 0xF0)); 7174 APInt MaskHi2 = APInt::getSplat(Sz, APInt(8, 0xCC)); 7175 APInt MaskHi1 = APInt::getSplat(Sz, APInt(8, 0xAA)); 7176 APInt MaskLo4 = APInt::getSplat(Sz, APInt(8, 0x0F)); 7177 APInt MaskLo2 = APInt::getSplat(Sz, APInt(8, 0x33)); 7178 APInt MaskLo1 = APInt::getSplat(Sz, APInt(8, 0x55)); 7179 7180 // BSWAP if the type is wider than a single byte. 7181 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op); 7182 7183 // swap i4: ((V & 0xF0) >> 4) | ((V & 0x0F) << 4) 7184 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi4, dl, VT)); 7185 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo4, dl, VT)); 7186 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(4, dl, SHVT)); 7187 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT)); 7188 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7189 7190 // swap i2: ((V & 0xCC) >> 2) | ((V & 0x33) << 2) 7191 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi2, dl, VT)); 7192 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo2, dl, VT)); 7193 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(2, dl, SHVT)); 7194 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT)); 7195 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7196 7197 // swap i1: ((V & 0xAA) >> 1) | ((V & 0x55) << 1) 7198 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi1, dl, VT)); 7199 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo1, dl, VT)); 7200 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(1, dl, SHVT)); 7201 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT)); 7202 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7203 return Tmp; 7204 } 7205 7206 Tmp = DAG.getConstant(0, dl, VT); 7207 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) { 7208 if (I < J) 7209 Tmp2 = 7210 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT)); 7211 else 7212 Tmp2 = 7213 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT)); 7214 7215 APInt Shift(Sz, 1); 7216 Shift <<= J; 7217 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT)); 7218 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2); 7219 } 7220 7221 return Tmp; 7222 } 7223 7224 std::pair<SDValue, SDValue> 7225 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 7226 SelectionDAG &DAG) const { 7227 SDLoc SL(LD); 7228 SDValue Chain = LD->getChain(); 7229 SDValue BasePTR = LD->getBasePtr(); 7230 EVT SrcVT = LD->getMemoryVT(); 7231 EVT DstVT = LD->getValueType(0); 7232 ISD::LoadExtType ExtType = LD->getExtensionType(); 7233 7234 if (SrcVT.isScalableVector()) 7235 report_fatal_error("Cannot scalarize scalable vector loads"); 7236 7237 unsigned NumElem = SrcVT.getVectorNumElements(); 7238 7239 EVT SrcEltVT = SrcVT.getScalarType(); 7240 EVT DstEltVT = DstVT.getScalarType(); 7241 7242 // A vector must always be stored in memory as-is, i.e. without any padding 7243 // between the elements, since various code depend on it, e.g. in the 7244 // handling of a bitcast of a vector type to int, which may be done with a 7245 // vector store followed by an integer load. A vector that does not have 7246 // elements that are byte-sized must therefore be stored as an integer 7247 // built out of the extracted vector elements. 7248 if (!SrcEltVT.isByteSized()) { 7249 unsigned NumLoadBits = SrcVT.getStoreSizeInBits(); 7250 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits); 7251 7252 unsigned NumSrcBits = SrcVT.getSizeInBits(); 7253 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits); 7254 7255 unsigned SrcEltBits = SrcEltVT.getSizeInBits(); 7256 SDValue SrcEltBitMask = DAG.getConstant( 7257 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT); 7258 7259 // Load the whole vector and avoid masking off the top bits as it makes 7260 // the codegen worse. 7261 SDValue Load = 7262 DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, 7263 LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(), 7264 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 7265 7266 SmallVector<SDValue, 8> Vals; 7267 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7268 unsigned ShiftIntoIdx = 7269 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 7270 SDValue ShiftAmount = 7271 DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(), 7272 LoadVT, SL, /*LegalTypes=*/false); 7273 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount); 7274 SDValue Elt = 7275 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask); 7276 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt); 7277 7278 if (ExtType != ISD::NON_EXTLOAD) { 7279 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType); 7280 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar); 7281 } 7282 7283 Vals.push_back(Scalar); 7284 } 7285 7286 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 7287 return std::make_pair(Value, Load.getValue(1)); 7288 } 7289 7290 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 7291 assert(SrcEltVT.isByteSized()); 7292 7293 SmallVector<SDValue, 8> Vals; 7294 SmallVector<SDValue, 8> LoadChains; 7295 7296 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7297 SDValue ScalarLoad = 7298 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 7299 LD->getPointerInfo().getWithOffset(Idx * Stride), 7300 SrcEltVT, LD->getOriginalAlign(), 7301 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 7302 7303 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride)); 7304 7305 Vals.push_back(ScalarLoad.getValue(0)); 7306 LoadChains.push_back(ScalarLoad.getValue(1)); 7307 } 7308 7309 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 7310 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 7311 7312 return std::make_pair(Value, NewChain); 7313 } 7314 7315 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 7316 SelectionDAG &DAG) const { 7317 SDLoc SL(ST); 7318 7319 SDValue Chain = ST->getChain(); 7320 SDValue BasePtr = ST->getBasePtr(); 7321 SDValue Value = ST->getValue(); 7322 EVT StVT = ST->getMemoryVT(); 7323 7324 if (StVT.isScalableVector()) 7325 report_fatal_error("Cannot scalarize scalable vector stores"); 7326 7327 // The type of the data we want to save 7328 EVT RegVT = Value.getValueType(); 7329 EVT RegSclVT = RegVT.getScalarType(); 7330 7331 // The type of data as saved in memory. 7332 EVT MemSclVT = StVT.getScalarType(); 7333 7334 unsigned NumElem = StVT.getVectorNumElements(); 7335 7336 // A vector must always be stored in memory as-is, i.e. without any padding 7337 // between the elements, since various code depend on it, e.g. in the 7338 // handling of a bitcast of a vector type to int, which may be done with a 7339 // vector store followed by an integer load. A vector that does not have 7340 // elements that are byte-sized must therefore be stored as an integer 7341 // built out of the extracted vector elements. 7342 if (!MemSclVT.isByteSized()) { 7343 unsigned NumBits = StVT.getSizeInBits(); 7344 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 7345 7346 SDValue CurrVal = DAG.getConstant(0, SL, IntVT); 7347 7348 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7349 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 7350 DAG.getVectorIdxConstant(Idx, SL)); 7351 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt); 7352 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc); 7353 unsigned ShiftIntoIdx = 7354 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 7355 SDValue ShiftAmount = 7356 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT); 7357 SDValue ShiftedElt = 7358 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount); 7359 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt); 7360 } 7361 7362 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(), 7363 ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 7364 ST->getAAInfo()); 7365 } 7366 7367 // Store Stride in bytes 7368 unsigned Stride = MemSclVT.getSizeInBits() / 8; 7369 assert(Stride && "Zero stride!"); 7370 // Extract each of the elements from the original vector and save them into 7371 // memory individually. 7372 SmallVector<SDValue, 8> Stores; 7373 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7374 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 7375 DAG.getVectorIdxConstant(Idx, SL)); 7376 7377 SDValue Ptr = 7378 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride)); 7379 7380 // This scalar TruncStore may be illegal, but we legalize it later. 7381 SDValue Store = DAG.getTruncStore( 7382 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 7383 MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 7384 ST->getAAInfo()); 7385 7386 Stores.push_back(Store); 7387 } 7388 7389 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 7390 } 7391 7392 std::pair<SDValue, SDValue> 7393 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 7394 assert(LD->getAddressingMode() == ISD::UNINDEXED && 7395 "unaligned indexed loads not implemented!"); 7396 SDValue Chain = LD->getChain(); 7397 SDValue Ptr = LD->getBasePtr(); 7398 EVT VT = LD->getValueType(0); 7399 EVT LoadedVT = LD->getMemoryVT(); 7400 SDLoc dl(LD); 7401 auto &MF = DAG.getMachineFunction(); 7402 7403 if (VT.isFloatingPoint() || VT.isVector()) { 7404 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 7405 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 7406 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) && 7407 LoadedVT.isVector()) { 7408 // Scalarize the load and let the individual components be handled. 7409 return scalarizeVectorLoad(LD, DAG); 7410 } 7411 7412 // Expand to a (misaligned) integer load of the same size, 7413 // then bitconvert to floating point or vector. 7414 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 7415 LD->getMemOperand()); 7416 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 7417 if (LoadedVT != VT) 7418 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 7419 ISD::ANY_EXTEND, dl, VT, Result); 7420 7421 return std::make_pair(Result, newLoad.getValue(1)); 7422 } 7423 7424 // Copy the value to a (aligned) stack slot using (unaligned) integer 7425 // loads and stores, then do a (aligned) load from the stack slot. 7426 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 7427 unsigned LoadedBytes = LoadedVT.getStoreSize(); 7428 unsigned RegBytes = RegVT.getSizeInBits() / 8; 7429 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 7430 7431 // Make sure the stack slot is also aligned for the register type. 7432 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 7433 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex(); 7434 SmallVector<SDValue, 8> Stores; 7435 SDValue StackPtr = StackBase; 7436 unsigned Offset = 0; 7437 7438 EVT PtrVT = Ptr.getValueType(); 7439 EVT StackPtrVT = StackPtr.getValueType(); 7440 7441 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 7442 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 7443 7444 // Do all but one copies using the full register width. 7445 for (unsigned i = 1; i < NumRegs; i++) { 7446 // Load one integer register's worth from the original location. 7447 SDValue Load = DAG.getLoad( 7448 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 7449 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 7450 LD->getAAInfo()); 7451 // Follow the load with a store to the stack slot. Remember the store. 7452 Stores.push_back(DAG.getStore( 7453 Load.getValue(1), dl, Load, StackPtr, 7454 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset))); 7455 // Increment the pointers. 7456 Offset += RegBytes; 7457 7458 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 7459 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 7460 } 7461 7462 // The last copy may be partial. Do an extending load. 7463 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 7464 8 * (LoadedBytes - Offset)); 7465 SDValue Load = 7466 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 7467 LD->getPointerInfo().getWithOffset(Offset), MemVT, 7468 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 7469 LD->getAAInfo()); 7470 // Follow the load with a store to the stack slot. Remember the store. 7471 // On big-endian machines this requires a truncating store to ensure 7472 // that the bits end up in the right place. 7473 Stores.push_back(DAG.getTruncStore( 7474 Load.getValue(1), dl, Load, StackPtr, 7475 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT)); 7476 7477 // The order of the stores doesn't matter - say it with a TokenFactor. 7478 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7479 7480 // Finally, perform the original load only redirected to the stack slot. 7481 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 7482 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), 7483 LoadedVT); 7484 7485 // Callers expect a MERGE_VALUES node. 7486 return std::make_pair(Load, TF); 7487 } 7488 7489 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 7490 "Unaligned load of unsupported type."); 7491 7492 // Compute the new VT that is half the size of the old one. This is an 7493 // integer MVT. 7494 unsigned NumBits = LoadedVT.getSizeInBits(); 7495 EVT NewLoadedVT; 7496 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 7497 NumBits >>= 1; 7498 7499 Align Alignment = LD->getOriginalAlign(); 7500 unsigned IncrementSize = NumBits / 8; 7501 ISD::LoadExtType HiExtType = LD->getExtensionType(); 7502 7503 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 7504 if (HiExtType == ISD::NON_EXTLOAD) 7505 HiExtType = ISD::ZEXTLOAD; 7506 7507 // Load the value in two parts 7508 SDValue Lo, Hi; 7509 if (DAG.getDataLayout().isLittleEndian()) { 7510 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 7511 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7512 LD->getAAInfo()); 7513 7514 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 7515 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 7516 LD->getPointerInfo().getWithOffset(IncrementSize), 7517 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7518 LD->getAAInfo()); 7519 } else { 7520 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 7521 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7522 LD->getAAInfo()); 7523 7524 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 7525 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 7526 LD->getPointerInfo().getWithOffset(IncrementSize), 7527 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7528 LD->getAAInfo()); 7529 } 7530 7531 // aggregate the two parts 7532 SDValue ShiftAmount = 7533 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(), 7534 DAG.getDataLayout())); 7535 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 7536 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 7537 7538 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 7539 Hi.getValue(1)); 7540 7541 return std::make_pair(Result, TF); 7542 } 7543 7544 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 7545 SelectionDAG &DAG) const { 7546 assert(ST->getAddressingMode() == ISD::UNINDEXED && 7547 "unaligned indexed stores not implemented!"); 7548 SDValue Chain = ST->getChain(); 7549 SDValue Ptr = ST->getBasePtr(); 7550 SDValue Val = ST->getValue(); 7551 EVT VT = Val.getValueType(); 7552 Align Alignment = ST->getOriginalAlign(); 7553 auto &MF = DAG.getMachineFunction(); 7554 EVT StoreMemVT = ST->getMemoryVT(); 7555 7556 SDLoc dl(ST); 7557 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) { 7558 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7559 if (isTypeLegal(intVT)) { 7560 if (!isOperationLegalOrCustom(ISD::STORE, intVT) && 7561 StoreMemVT.isVector()) { 7562 // Scalarize the store and let the individual components be handled. 7563 SDValue Result = scalarizeVectorStore(ST, DAG); 7564 return Result; 7565 } 7566 // Expand to a bitconvert of the value to the integer type of the 7567 // same size, then a (misaligned) int store. 7568 // FIXME: Does not handle truncating floating point stores! 7569 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 7570 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 7571 Alignment, ST->getMemOperand()->getFlags()); 7572 return Result; 7573 } 7574 // Do a (aligned) store to a stack slot, then copy from the stack slot 7575 // to the final destination using (unaligned) integer loads and stores. 7576 MVT RegVT = getRegisterType( 7577 *DAG.getContext(), 7578 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits())); 7579 EVT PtrVT = Ptr.getValueType(); 7580 unsigned StoredBytes = StoreMemVT.getStoreSize(); 7581 unsigned RegBytes = RegVT.getSizeInBits() / 8; 7582 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 7583 7584 // Make sure the stack slot is also aligned for the register type. 7585 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT); 7586 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 7587 7588 // Perform the original store, only redirected to the stack slot. 7589 SDValue Store = DAG.getTruncStore( 7590 Chain, dl, Val, StackPtr, 7591 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT); 7592 7593 EVT StackPtrVT = StackPtr.getValueType(); 7594 7595 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 7596 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 7597 SmallVector<SDValue, 8> Stores; 7598 unsigned Offset = 0; 7599 7600 // Do all but one copies using the full register width. 7601 for (unsigned i = 1; i < NumRegs; i++) { 7602 // Load one integer register's worth from the stack slot. 7603 SDValue Load = DAG.getLoad( 7604 RegVT, dl, Store, StackPtr, 7605 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)); 7606 // Store it to the final location. Remember the store. 7607 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 7608 ST->getPointerInfo().getWithOffset(Offset), 7609 ST->getOriginalAlign(), 7610 ST->getMemOperand()->getFlags())); 7611 // Increment the pointers. 7612 Offset += RegBytes; 7613 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 7614 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 7615 } 7616 7617 // The last store may be partial. Do a truncating store. On big-endian 7618 // machines this requires an extending load from the stack slot to ensure 7619 // that the bits are in the right place. 7620 EVT LoadMemVT = 7621 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset)); 7622 7623 // Load from the stack slot. 7624 SDValue Load = DAG.getExtLoad( 7625 ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 7626 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT); 7627 7628 Stores.push_back( 7629 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 7630 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT, 7631 ST->getOriginalAlign(), 7632 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 7633 // The order of the stores doesn't matter - say it with a TokenFactor. 7634 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7635 return Result; 7636 } 7637 7638 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() && 7639 "Unaligned store of unknown type."); 7640 // Get the half-size VT 7641 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext()); 7642 unsigned NumBits = NewStoredVT.getFixedSizeInBits(); 7643 unsigned IncrementSize = NumBits / 8; 7644 7645 // Divide the stored value in two parts. 7646 SDValue ShiftAmount = DAG.getConstant( 7647 NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout())); 7648 SDValue Lo = Val; 7649 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 7650 7651 // Store the two parts 7652 SDValue Store1, Store2; 7653 Store1 = DAG.getTruncStore(Chain, dl, 7654 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 7655 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 7656 ST->getMemOperand()->getFlags()); 7657 7658 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 7659 Store2 = DAG.getTruncStore( 7660 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 7661 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 7662 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 7663 7664 SDValue Result = 7665 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 7666 return Result; 7667 } 7668 7669 SDValue 7670 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 7671 const SDLoc &DL, EVT DataVT, 7672 SelectionDAG &DAG, 7673 bool IsCompressedMemory) const { 7674 SDValue Increment; 7675 EVT AddrVT = Addr.getValueType(); 7676 EVT MaskVT = Mask.getValueType(); 7677 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() && 7678 "Incompatible types of Data and Mask"); 7679 if (IsCompressedMemory) { 7680 if (DataVT.isScalableVector()) 7681 report_fatal_error( 7682 "Cannot currently handle compressed memory with scalable vectors"); 7683 // Incrementing the pointer according to number of '1's in the mask. 7684 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 7685 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 7686 if (MaskIntVT.getSizeInBits() < 32) { 7687 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 7688 MaskIntVT = MVT::i32; 7689 } 7690 7691 // Count '1's with POPCNT. 7692 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 7693 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 7694 // Scale is an element size in bytes. 7695 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 7696 AddrVT); 7697 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 7698 } else if (DataVT.isScalableVector()) { 7699 Increment = DAG.getVScale(DL, AddrVT, 7700 APInt(AddrVT.getFixedSizeInBits(), 7701 DataVT.getStoreSize().getKnownMinSize())); 7702 } else 7703 Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT); 7704 7705 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 7706 } 7707 7708 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, 7709 SDValue Idx, 7710 EVT VecVT, 7711 const SDLoc &dl) { 7712 if (!VecVT.isScalableVector() && isa<ConstantSDNode>(Idx)) 7713 return Idx; 7714 7715 EVT IdxVT = Idx.getValueType(); 7716 unsigned NElts = VecVT.getVectorMinNumElements(); 7717 if (VecVT.isScalableVector()) { 7718 // If this is a constant index and we know the value is less than the 7719 // minimum number of elements then it's safe to return Idx. 7720 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx)) 7721 if (IdxCst->getZExtValue() < NElts) 7722 return Idx; 7723 7724 SDValue VS = DAG.getVScale(dl, IdxVT, 7725 APInt(IdxVT.getFixedSizeInBits(), 7726 NElts)); 7727 SDValue Sub = DAG.getNode(ISD::SUB, dl, IdxVT, VS, 7728 DAG.getConstant(1, dl, IdxVT)); 7729 7730 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub); 7731 } else { 7732 if (isPowerOf2_32(NElts)) { 7733 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), 7734 Log2_32(NElts)); 7735 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 7736 DAG.getConstant(Imm, dl, IdxVT)); 7737 } 7738 } 7739 7740 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 7741 DAG.getConstant(NElts - 1, dl, IdxVT)); 7742 } 7743 7744 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 7745 SDValue VecPtr, EVT VecVT, 7746 SDValue Index) const { 7747 SDLoc dl(Index); 7748 // Make sure the index type is big enough to compute in. 7749 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType()); 7750 7751 EVT EltVT = VecVT.getVectorElementType(); 7752 7753 // Calculate the element offset and add it to the pointer. 7754 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size. 7755 assert(EltSize * 8 == EltVT.getFixedSizeInBits() && 7756 "Converting bits to bytes lost precision"); 7757 7758 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl); 7759 7760 EVT IdxVT = Index.getValueType(); 7761 7762 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 7763 DAG.getConstant(EltSize, dl, IdxVT)); 7764 return DAG.getMemBasePlusOffset(VecPtr, Index, dl); 7765 } 7766 7767 //===----------------------------------------------------------------------===// 7768 // Implementation of Emulated TLS Model 7769 //===----------------------------------------------------------------------===// 7770 7771 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 7772 SelectionDAG &DAG) const { 7773 // Access to address of TLS varialbe xyz is lowered to a function call: 7774 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 7775 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7776 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 7777 SDLoc dl(GA); 7778 7779 ArgListTy Args; 7780 ArgListEntry Entry; 7781 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 7782 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 7783 StringRef EmuTlsVarName(NameString); 7784 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 7785 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 7786 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 7787 Entry.Ty = VoidPtrType; 7788 Args.push_back(Entry); 7789 7790 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 7791 7792 TargetLowering::CallLoweringInfo CLI(DAG); 7793 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 7794 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 7795 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7796 7797 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 7798 // At last for X86 targets, maybe good for other targets too? 7799 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7800 MFI.setAdjustsStack(true); // Is this only for X86 target? 7801 MFI.setHasCalls(true); 7802 7803 assert((GA->getOffset() == 0) && 7804 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 7805 return CallResult.first; 7806 } 7807 7808 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 7809 SelectionDAG &DAG) const { 7810 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 7811 if (!isCtlzFast()) 7812 return SDValue(); 7813 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 7814 SDLoc dl(Op); 7815 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 7816 if (C->isNullValue() && CC == ISD::SETEQ) { 7817 EVT VT = Op.getOperand(0).getValueType(); 7818 SDValue Zext = Op.getOperand(0); 7819 if (VT.bitsLT(MVT::i32)) { 7820 VT = MVT::i32; 7821 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 7822 } 7823 unsigned Log2b = Log2_32(VT.getSizeInBits()); 7824 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 7825 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 7826 DAG.getConstant(Log2b, dl, MVT::i32)); 7827 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 7828 } 7829 } 7830 return SDValue(); 7831 } 7832 7833 // Convert redundant addressing modes (e.g. scaling is redundant 7834 // when accessing bytes). 7835 ISD::MemIndexType 7836 TargetLowering::getCanonicalIndexType(ISD::MemIndexType IndexType, EVT MemVT, 7837 SDValue Offsets) const { 7838 bool IsScaledIndex = 7839 (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::UNSIGNED_SCALED); 7840 bool IsSignedIndex = 7841 (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::SIGNED_UNSCALED); 7842 7843 // Scaling is unimportant for bytes, canonicalize to unscaled. 7844 if (IsScaledIndex && MemVT.getScalarType() == MVT::i8) { 7845 IsScaledIndex = false; 7846 IndexType = IsSignedIndex ? ISD::SIGNED_UNSCALED : ISD::UNSIGNED_UNSCALED; 7847 } 7848 7849 return IndexType; 7850 } 7851 7852 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const { 7853 SDValue Op0 = Node->getOperand(0); 7854 SDValue Op1 = Node->getOperand(1); 7855 EVT VT = Op0.getValueType(); 7856 unsigned Opcode = Node->getOpcode(); 7857 SDLoc DL(Node); 7858 7859 // umin(x,y) -> sub(x,usubsat(x,y)) 7860 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) && 7861 isOperationLegal(ISD::USUBSAT, VT)) { 7862 return DAG.getNode(ISD::SUB, DL, VT, Op0, 7863 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1)); 7864 } 7865 7866 // umax(x,y) -> add(x,usubsat(y,x)) 7867 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) && 7868 isOperationLegal(ISD::USUBSAT, VT)) { 7869 return DAG.getNode(ISD::ADD, DL, VT, Op0, 7870 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0)); 7871 } 7872 7873 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 7874 ISD::CondCode CC; 7875 switch (Opcode) { 7876 default: llvm_unreachable("How did we get here?"); 7877 case ISD::SMAX: CC = ISD::SETGT; break; 7878 case ISD::SMIN: CC = ISD::SETLT; break; 7879 case ISD::UMAX: CC = ISD::SETUGT; break; 7880 case ISD::UMIN: CC = ISD::SETULT; break; 7881 } 7882 7883 // FIXME: Should really try to split the vector in case it's legal on a 7884 // subvector. 7885 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 7886 return DAG.UnrollVectorOp(Node); 7887 7888 SDValue Cond = DAG.getSetCC(DL, VT, Op0, Op1, CC); 7889 return DAG.getSelect(DL, VT, Cond, Op0, Op1); 7890 } 7891 7892 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const { 7893 unsigned Opcode = Node->getOpcode(); 7894 SDValue LHS = Node->getOperand(0); 7895 SDValue RHS = Node->getOperand(1); 7896 EVT VT = LHS.getValueType(); 7897 SDLoc dl(Node); 7898 7899 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 7900 assert(VT.isInteger() && "Expected operands to be integers"); 7901 7902 // usub.sat(a, b) -> umax(a, b) - b 7903 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) { 7904 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS); 7905 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS); 7906 } 7907 7908 // uadd.sat(a, b) -> umin(a, ~b) + b 7909 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) { 7910 SDValue InvRHS = DAG.getNOT(dl, RHS, VT); 7911 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS); 7912 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS); 7913 } 7914 7915 unsigned OverflowOp; 7916 switch (Opcode) { 7917 case ISD::SADDSAT: 7918 OverflowOp = ISD::SADDO; 7919 break; 7920 case ISD::UADDSAT: 7921 OverflowOp = ISD::UADDO; 7922 break; 7923 case ISD::SSUBSAT: 7924 OverflowOp = ISD::SSUBO; 7925 break; 7926 case ISD::USUBSAT: 7927 OverflowOp = ISD::USUBO; 7928 break; 7929 default: 7930 llvm_unreachable("Expected method to receive signed or unsigned saturation " 7931 "addition or subtraction node."); 7932 } 7933 7934 // FIXME: Should really try to split the vector in case it's legal on a 7935 // subvector. 7936 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 7937 return DAG.UnrollVectorOp(Node); 7938 7939 unsigned BitWidth = LHS.getScalarValueSizeInBits(); 7940 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7941 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 7942 SDValue SumDiff = Result.getValue(0); 7943 SDValue Overflow = Result.getValue(1); 7944 SDValue Zero = DAG.getConstant(0, dl, VT); 7945 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT); 7946 7947 if (Opcode == ISD::UADDSAT) { 7948 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 7949 // (LHS + RHS) | OverflowMask 7950 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 7951 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask); 7952 } 7953 // Overflow ? 0xffff.... : (LHS + RHS) 7954 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff); 7955 } 7956 7957 if (Opcode == ISD::USUBSAT) { 7958 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 7959 // (LHS - RHS) & ~OverflowMask 7960 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 7961 SDValue Not = DAG.getNOT(dl, OverflowMask, VT); 7962 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not); 7963 } 7964 // Overflow ? 0 : (LHS - RHS) 7965 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff); 7966 } 7967 7968 // SatMax -> Overflow && SumDiff < 0 7969 // SatMin -> Overflow && SumDiff >= 0 7970 APInt MinVal = APInt::getSignedMinValue(BitWidth); 7971 APInt MaxVal = APInt::getSignedMaxValue(BitWidth); 7972 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 7973 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 7974 SDValue SumNeg = DAG.getSetCC(dl, BoolVT, SumDiff, Zero, ISD::SETLT); 7975 Result = DAG.getSelect(dl, VT, SumNeg, SatMax, SatMin); 7976 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff); 7977 } 7978 7979 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const { 7980 unsigned Opcode = Node->getOpcode(); 7981 bool IsSigned = Opcode == ISD::SSHLSAT; 7982 SDValue LHS = Node->getOperand(0); 7983 SDValue RHS = Node->getOperand(1); 7984 EVT VT = LHS.getValueType(); 7985 SDLoc dl(Node); 7986 7987 assert((Node->getOpcode() == ISD::SSHLSAT || 7988 Node->getOpcode() == ISD::USHLSAT) && 7989 "Expected a SHLSAT opcode"); 7990 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 7991 assert(VT.isInteger() && "Expected operands to be integers"); 7992 7993 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate. 7994 7995 unsigned BW = VT.getScalarSizeInBits(); 7996 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS); 7997 SDValue Orig = 7998 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS); 7999 8000 SDValue SatVal; 8001 if (IsSigned) { 8002 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT); 8003 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT); 8004 SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT), 8005 SatMin, SatMax, ISD::SETLT); 8006 } else { 8007 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT); 8008 } 8009 Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE); 8010 8011 return Result; 8012 } 8013 8014 SDValue 8015 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const { 8016 assert((Node->getOpcode() == ISD::SMULFIX || 8017 Node->getOpcode() == ISD::UMULFIX || 8018 Node->getOpcode() == ISD::SMULFIXSAT || 8019 Node->getOpcode() == ISD::UMULFIXSAT) && 8020 "Expected a fixed point multiplication opcode"); 8021 8022 SDLoc dl(Node); 8023 SDValue LHS = Node->getOperand(0); 8024 SDValue RHS = Node->getOperand(1); 8025 EVT VT = LHS.getValueType(); 8026 unsigned Scale = Node->getConstantOperandVal(2); 8027 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT || 8028 Node->getOpcode() == ISD::UMULFIXSAT); 8029 bool Signed = (Node->getOpcode() == ISD::SMULFIX || 8030 Node->getOpcode() == ISD::SMULFIXSAT); 8031 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8032 unsigned VTSize = VT.getScalarSizeInBits(); 8033 8034 if (!Scale) { 8035 // [us]mul.fix(a, b, 0) -> mul(a, b) 8036 if (!Saturating) { 8037 if (isOperationLegalOrCustom(ISD::MUL, VT)) 8038 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8039 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) { 8040 SDValue Result = 8041 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8042 SDValue Product = Result.getValue(0); 8043 SDValue Overflow = Result.getValue(1); 8044 SDValue Zero = DAG.getConstant(0, dl, VT); 8045 8046 APInt MinVal = APInt::getSignedMinValue(VTSize); 8047 APInt MaxVal = APInt::getSignedMaxValue(VTSize); 8048 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 8049 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 8050 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Product, Zero, ISD::SETLT); 8051 Result = DAG.getSelect(dl, VT, ProdNeg, SatMax, SatMin); 8052 return DAG.getSelect(dl, VT, Overflow, Result, Product); 8053 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) { 8054 SDValue Result = 8055 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 8056 SDValue Product = Result.getValue(0); 8057 SDValue Overflow = Result.getValue(1); 8058 8059 APInt MaxVal = APInt::getMaxValue(VTSize); 8060 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 8061 return DAG.getSelect(dl, VT, Overflow, SatMax, Product); 8062 } 8063 } 8064 8065 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) && 8066 "Expected scale to be less than the number of bits if signed or at " 8067 "most the number of bits if unsigned."); 8068 assert(LHS.getValueType() == RHS.getValueType() && 8069 "Expected both operands to be the same type"); 8070 8071 // Get the upper and lower bits of the result. 8072 SDValue Lo, Hi; 8073 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI; 8074 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU; 8075 if (isOperationLegalOrCustom(LoHiOp, VT)) { 8076 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS); 8077 Lo = Result.getValue(0); 8078 Hi = Result.getValue(1); 8079 } else if (isOperationLegalOrCustom(HiOp, VT)) { 8080 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8081 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS); 8082 } else if (VT.isVector()) { 8083 return SDValue(); 8084 } else { 8085 report_fatal_error("Unable to expand fixed point multiplication."); 8086 } 8087 8088 if (Scale == VTSize) 8089 // Result is just the top half since we'd be shifting by the width of the 8090 // operand. Overflow impossible so this works for both UMULFIX and 8091 // UMULFIXSAT. 8092 return Hi; 8093 8094 // The result will need to be shifted right by the scale since both operands 8095 // are scaled. The result is given to us in 2 halves, so we only want part of 8096 // both in the result. 8097 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 8098 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo, 8099 DAG.getConstant(Scale, dl, ShiftTy)); 8100 if (!Saturating) 8101 return Result; 8102 8103 if (!Signed) { 8104 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the 8105 // widened multiplication) aren't all zeroes. 8106 8107 // Saturate to max if ((Hi >> Scale) != 0), 8108 // which is the same as if (Hi > ((1 << Scale) - 1)) 8109 APInt MaxVal = APInt::getMaxValue(VTSize); 8110 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), 8111 dl, VT); 8112 Result = DAG.getSelectCC(dl, Hi, LowMask, 8113 DAG.getConstant(MaxVal, dl, VT), Result, 8114 ISD::SETUGT); 8115 8116 return Result; 8117 } 8118 8119 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the 8120 // widened multiplication) aren't all ones or all zeroes. 8121 8122 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT); 8123 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT); 8124 8125 if (Scale == 0) { 8126 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo, 8127 DAG.getConstant(VTSize - 1, dl, ShiftTy)); 8128 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE); 8129 // Saturated to SatMin if wide product is negative, and SatMax if wide 8130 // product is positive ... 8131 SDValue Zero = DAG.getConstant(0, dl, VT); 8132 SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax, 8133 ISD::SETLT); 8134 // ... but only if we overflowed. 8135 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result); 8136 } 8137 8138 // We handled Scale==0 above so all the bits to examine is in Hi. 8139 8140 // Saturate to max if ((Hi >> (Scale - 1)) > 0), 8141 // which is the same as if (Hi > (1 << (Scale - 1)) - 1) 8142 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), 8143 dl, VT); 8144 Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT); 8145 // Saturate to min if (Hi >> (Scale - 1)) < -1), 8146 // which is the same as if (HI < (-1 << (Scale - 1)) 8147 SDValue HighMask = 8148 DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), 8149 dl, VT); 8150 Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT); 8151 return Result; 8152 } 8153 8154 SDValue 8155 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, 8156 SDValue LHS, SDValue RHS, 8157 unsigned Scale, SelectionDAG &DAG) const { 8158 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT || 8159 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) && 8160 "Expected a fixed point division opcode"); 8161 8162 EVT VT = LHS.getValueType(); 8163 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 8164 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 8165 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8166 8167 // If there is enough room in the type to upscale the LHS or downscale the 8168 // RHS before the division, we can perform it in this type without having to 8169 // resize. For signed operations, the LHS headroom is the number of 8170 // redundant sign bits, and for unsigned ones it is the number of zeroes. 8171 // The headroom for the RHS is the number of trailing zeroes. 8172 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1 8173 : DAG.computeKnownBits(LHS).countMinLeadingZeros(); 8174 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros(); 8175 8176 // For signed saturating operations, we need to be able to detect true integer 8177 // division overflow; that is, when you have MIN / -EPS. However, this 8178 // is undefined behavior and if we emit divisions that could take such 8179 // values it may cause undesired behavior (arithmetic exceptions on x86, for 8180 // example). 8181 // Avoid this by requiring an extra bit so that we never get this case. 8182 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale 8183 // signed saturating division, we need to emit a whopping 32-bit division. 8184 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed)) 8185 return SDValue(); 8186 8187 unsigned LHSShift = std::min(LHSLead, Scale); 8188 unsigned RHSShift = Scale - LHSShift; 8189 8190 // At this point, we know that if we shift the LHS up by LHSShift and the 8191 // RHS down by RHSShift, we can emit a regular division with a final scaling 8192 // factor of Scale. 8193 8194 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 8195 if (LHSShift) 8196 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS, 8197 DAG.getConstant(LHSShift, dl, ShiftTy)); 8198 if (RHSShift) 8199 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS, 8200 DAG.getConstant(RHSShift, dl, ShiftTy)); 8201 8202 SDValue Quot; 8203 if (Signed) { 8204 // For signed operations, if the resulting quotient is negative and the 8205 // remainder is nonzero, subtract 1 from the quotient to round towards 8206 // negative infinity. 8207 SDValue Rem; 8208 // FIXME: Ideally we would always produce an SDIVREM here, but if the 8209 // type isn't legal, SDIVREM cannot be expanded. There is no reason why 8210 // we couldn't just form a libcall, but the type legalizer doesn't do it. 8211 if (isTypeLegal(VT) && 8212 isOperationLegalOrCustom(ISD::SDIVREM, VT)) { 8213 Quot = DAG.getNode(ISD::SDIVREM, dl, 8214 DAG.getVTList(VT, VT), 8215 LHS, RHS); 8216 Rem = Quot.getValue(1); 8217 Quot = Quot.getValue(0); 8218 } else { 8219 Quot = DAG.getNode(ISD::SDIV, dl, VT, 8220 LHS, RHS); 8221 Rem = DAG.getNode(ISD::SREM, dl, VT, 8222 LHS, RHS); 8223 } 8224 SDValue Zero = DAG.getConstant(0, dl, VT); 8225 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE); 8226 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT); 8227 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT); 8228 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg); 8229 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot, 8230 DAG.getConstant(1, dl, VT)); 8231 Quot = DAG.getSelect(dl, VT, 8232 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg), 8233 Sub1, Quot); 8234 } else 8235 Quot = DAG.getNode(ISD::UDIV, dl, VT, 8236 LHS, RHS); 8237 8238 return Quot; 8239 } 8240 8241 void TargetLowering::expandUADDSUBO( 8242 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 8243 SDLoc dl(Node); 8244 SDValue LHS = Node->getOperand(0); 8245 SDValue RHS = Node->getOperand(1); 8246 bool IsAdd = Node->getOpcode() == ISD::UADDO; 8247 8248 // If ADD/SUBCARRY is legal, use that instead. 8249 unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY; 8250 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) { 8251 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1)); 8252 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(), 8253 { LHS, RHS, CarryIn }); 8254 Result = SDValue(NodeCarry.getNode(), 0); 8255 Overflow = SDValue(NodeCarry.getNode(), 1); 8256 return; 8257 } 8258 8259 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 8260 LHS.getValueType(), LHS, RHS); 8261 8262 EVT ResultType = Node->getValueType(1); 8263 EVT SetCCType = getSetCCResultType( 8264 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 8265 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 8266 SDValue SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC); 8267 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 8268 } 8269 8270 void TargetLowering::expandSADDSUBO( 8271 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 8272 SDLoc dl(Node); 8273 SDValue LHS = Node->getOperand(0); 8274 SDValue RHS = Node->getOperand(1); 8275 bool IsAdd = Node->getOpcode() == ISD::SADDO; 8276 8277 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 8278 LHS.getValueType(), LHS, RHS); 8279 8280 EVT ResultType = Node->getValueType(1); 8281 EVT OType = getSetCCResultType( 8282 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 8283 8284 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow. 8285 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT; 8286 if (isOperationLegalOrCustom(OpcSat, LHS.getValueType())) { 8287 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS); 8288 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE); 8289 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 8290 return; 8291 } 8292 8293 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 8294 8295 // For an addition, the result should be less than one of the operands (LHS) 8296 // if and only if the other operand (RHS) is negative, otherwise there will 8297 // be overflow. 8298 // For a subtraction, the result should be less than one of the operands 8299 // (LHS) if and only if the other operand (RHS) is (non-zero) positive, 8300 // otherwise there will be overflow. 8301 SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT); 8302 SDValue ConditionRHS = 8303 DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT); 8304 8305 Overflow = DAG.getBoolExtOrTrunc( 8306 DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl, 8307 ResultType, ResultType); 8308 } 8309 8310 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result, 8311 SDValue &Overflow, SelectionDAG &DAG) const { 8312 SDLoc dl(Node); 8313 EVT VT = Node->getValueType(0); 8314 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8315 SDValue LHS = Node->getOperand(0); 8316 SDValue RHS = Node->getOperand(1); 8317 bool isSigned = Node->getOpcode() == ISD::SMULO; 8318 8319 // For power-of-two multiplications we can use a simpler shift expansion. 8320 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 8321 const APInt &C = RHSC->getAPIntValue(); 8322 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 8323 if (C.isPowerOf2()) { 8324 // smulo(x, signed_min) is same as umulo(x, signed_min). 8325 bool UseArithShift = isSigned && !C.isMinSignedValue(); 8326 EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout()); 8327 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy); 8328 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt); 8329 Overflow = DAG.getSetCC(dl, SetCCVT, 8330 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 8331 dl, VT, Result, ShiftAmt), 8332 LHS, ISD::SETNE); 8333 return true; 8334 } 8335 } 8336 8337 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2); 8338 if (VT.isVector()) 8339 WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT, 8340 VT.getVectorNumElements()); 8341 8342 SDValue BottomHalf; 8343 SDValue TopHalf; 8344 static const unsigned Ops[2][3] = 8345 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 8346 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 8347 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 8348 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8349 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 8350 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 8351 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 8352 RHS); 8353 TopHalf = BottomHalf.getValue(1); 8354 } else if (isTypeLegal(WideVT)) { 8355 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 8356 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 8357 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 8358 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul); 8359 SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl, 8360 getShiftAmountTy(WideVT, DAG.getDataLayout())); 8361 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, 8362 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt)); 8363 } else { 8364 if (VT.isVector()) 8365 return false; 8366 8367 // We can fall back to a libcall with an illegal type for the MUL if we 8368 // have a libcall big enough. 8369 // Also, we can fall back to a division in some cases, but that's a big 8370 // performance hit in the general case. 8371 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 8372 if (WideVT == MVT::i16) 8373 LC = RTLIB::MUL_I16; 8374 else if (WideVT == MVT::i32) 8375 LC = RTLIB::MUL_I32; 8376 else if (WideVT == MVT::i64) 8377 LC = RTLIB::MUL_I64; 8378 else if (WideVT == MVT::i128) 8379 LC = RTLIB::MUL_I128; 8380 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!"); 8381 8382 SDValue HiLHS; 8383 SDValue HiRHS; 8384 if (isSigned) { 8385 // The high part is obtained by SRA'ing all but one of the bits of low 8386 // part. 8387 unsigned LoSize = VT.getFixedSizeInBits(); 8388 HiLHS = 8389 DAG.getNode(ISD::SRA, dl, VT, LHS, 8390 DAG.getConstant(LoSize - 1, dl, 8391 getPointerTy(DAG.getDataLayout()))); 8392 HiRHS = 8393 DAG.getNode(ISD::SRA, dl, VT, RHS, 8394 DAG.getConstant(LoSize - 1, dl, 8395 getPointerTy(DAG.getDataLayout()))); 8396 } else { 8397 HiLHS = DAG.getConstant(0, dl, VT); 8398 HiRHS = DAG.getConstant(0, dl, VT); 8399 } 8400 8401 // Here we're passing the 2 arguments explicitly as 4 arguments that are 8402 // pre-lowered to the correct types. This all depends upon WideVT not 8403 // being a legal type for the architecture and thus has to be split to 8404 // two arguments. 8405 SDValue Ret; 8406 TargetLowering::MakeLibCallOptions CallOptions; 8407 CallOptions.setSExt(isSigned); 8408 CallOptions.setIsPostTypeLegalization(true); 8409 if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) { 8410 // Halves of WideVT are packed into registers in different order 8411 // depending on platform endianness. This is usually handled by 8412 // the C calling convention, but we can't defer to it in 8413 // the legalizer. 8414 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS }; 8415 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 8416 } else { 8417 SDValue Args[] = { HiLHS, LHS, HiRHS, RHS }; 8418 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 8419 } 8420 assert(Ret.getOpcode() == ISD::MERGE_VALUES && 8421 "Ret value is a collection of constituent nodes holding result."); 8422 if (DAG.getDataLayout().isLittleEndian()) { 8423 // Same as above. 8424 BottomHalf = Ret.getOperand(0); 8425 TopHalf = Ret.getOperand(1); 8426 } else { 8427 BottomHalf = Ret.getOperand(1); 8428 TopHalf = Ret.getOperand(0); 8429 } 8430 } 8431 8432 Result = BottomHalf; 8433 if (isSigned) { 8434 SDValue ShiftAmt = DAG.getConstant( 8435 VT.getScalarSizeInBits() - 1, dl, 8436 getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout())); 8437 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt); 8438 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE); 8439 } else { 8440 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, 8441 DAG.getConstant(0, dl, VT), ISD::SETNE); 8442 } 8443 8444 // Truncate the result if SetCC returns a larger type than needed. 8445 EVT RType = Node->getValueType(1); 8446 if (RType.bitsLT(Overflow.getValueType())) 8447 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow); 8448 8449 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() && 8450 "Unexpected result type for S/UMULO legalization"); 8451 return true; 8452 } 8453 8454 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const { 8455 SDLoc dl(Node); 8456 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 8457 SDValue Op = Node->getOperand(0); 8458 EVT VT = Op.getValueType(); 8459 8460 if (VT.isScalableVector()) 8461 report_fatal_error( 8462 "Expanding reductions for scalable vectors is undefined."); 8463 8464 // Try to use a shuffle reduction for power of two vectors. 8465 if (VT.isPow2VectorType()) { 8466 while (VT.getVectorNumElements() > 1) { 8467 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 8468 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) 8469 break; 8470 8471 SDValue Lo, Hi; 8472 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl); 8473 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi); 8474 VT = HalfVT; 8475 } 8476 } 8477 8478 EVT EltVT = VT.getVectorElementType(); 8479 unsigned NumElts = VT.getVectorNumElements(); 8480 8481 SmallVector<SDValue, 8> Ops; 8482 DAG.ExtractVectorElements(Op, Ops, 0, NumElts); 8483 8484 SDValue Res = Ops[0]; 8485 for (unsigned i = 1; i < NumElts; i++) 8486 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags()); 8487 8488 // Result type may be wider than element type. 8489 if (EltVT != Node->getValueType(0)) 8490 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res); 8491 return Res; 8492 } 8493 8494 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const { 8495 SDLoc dl(Node); 8496 SDValue AccOp = Node->getOperand(0); 8497 SDValue VecOp = Node->getOperand(1); 8498 SDNodeFlags Flags = Node->getFlags(); 8499 8500 EVT VT = VecOp.getValueType(); 8501 EVT EltVT = VT.getVectorElementType(); 8502 8503 if (VT.isScalableVector()) 8504 report_fatal_error( 8505 "Expanding reductions for scalable vectors is undefined."); 8506 8507 unsigned NumElts = VT.getVectorNumElements(); 8508 8509 SmallVector<SDValue, 8> Ops; 8510 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts); 8511 8512 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 8513 8514 SDValue Res = AccOp; 8515 for (unsigned i = 0; i < NumElts; i++) 8516 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags); 8517 8518 return Res; 8519 } 8520 8521 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result, 8522 SelectionDAG &DAG) const { 8523 EVT VT = Node->getValueType(0); 8524 SDLoc dl(Node); 8525 bool isSigned = Node->getOpcode() == ISD::SREM; 8526 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV; 8527 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 8528 SDValue Dividend = Node->getOperand(0); 8529 SDValue Divisor = Node->getOperand(1); 8530 if (isOperationLegalOrCustom(DivRemOpc, VT)) { 8531 SDVTList VTs = DAG.getVTList(VT, VT); 8532 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1); 8533 return true; 8534 } else if (isOperationLegalOrCustom(DivOpc, VT)) { 8535 // X % Y -> X-X/Y*Y 8536 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor); 8537 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor); 8538 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 8539 return true; 8540 } 8541 return false; 8542 } 8543 8544 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node, 8545 SelectionDAG &DAG) const { 8546 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT; 8547 SDLoc dl(SDValue(Node, 0)); 8548 SDValue Src = Node->getOperand(0); 8549 8550 // DstVT is the result type, while SatVT is the size to which we saturate 8551 EVT SrcVT = Src.getValueType(); 8552 EVT DstVT = Node->getValueType(0); 8553 8554 unsigned SatWidth = Node->getConstantOperandVal(1); 8555 unsigned DstWidth = DstVT.getScalarSizeInBits(); 8556 assert(SatWidth <= DstWidth && 8557 "Expected saturation width smaller than result width"); 8558 8559 // Determine minimum and maximum integer values and their corresponding 8560 // floating-point values. 8561 APInt MinInt, MaxInt; 8562 if (IsSigned) { 8563 MinInt = APInt::getSignedMinValue(SatWidth).sextOrSelf(DstWidth); 8564 MaxInt = APInt::getSignedMaxValue(SatWidth).sextOrSelf(DstWidth); 8565 } else { 8566 MinInt = APInt::getMinValue(SatWidth).zextOrSelf(DstWidth); 8567 MaxInt = APInt::getMaxValue(SatWidth).zextOrSelf(DstWidth); 8568 } 8569 8570 // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as 8571 // libcall emission cannot handle this. Large result types will fail. 8572 if (SrcVT == MVT::f16) { 8573 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src); 8574 SrcVT = Src.getValueType(); 8575 } 8576 8577 APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 8578 APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 8579 8580 APFloat::opStatus MinStatus = 8581 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero); 8582 APFloat::opStatus MaxStatus = 8583 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero); 8584 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) && 8585 !(MaxStatus & APFloat::opStatus::opInexact); 8586 8587 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT); 8588 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT); 8589 8590 // If the integer bounds are exactly representable as floats and min/max are 8591 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence 8592 // of comparisons and selects. 8593 bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) && 8594 isOperationLegal(ISD::FMAXNUM, SrcVT); 8595 if (AreExactFloatBounds && MinMaxLegal) { 8596 SDValue Clamped = Src; 8597 8598 // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat. 8599 Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode); 8600 // Clamp by MaxFloat from above. NaN cannot occur. 8601 Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode); 8602 // Convert clamped value to integer. 8603 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, 8604 dl, DstVT, Clamped); 8605 8606 // In the unsigned case we're done, because we mapped NaN to MinFloat, 8607 // which will cast to zero. 8608 if (!IsSigned) 8609 return FpToInt; 8610 8611 // Otherwise, select 0 if Src is NaN. 8612 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 8613 return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt, 8614 ISD::CondCode::SETUO); 8615 } 8616 8617 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT); 8618 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT); 8619 8620 // Result of direct conversion. The assumption here is that the operation is 8621 // non-trapping and it's fine to apply it to an out-of-range value if we 8622 // select it away later. 8623 SDValue FpToInt = 8624 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src); 8625 8626 SDValue Select = FpToInt; 8627 8628 // If Src ULT MinFloat, select MinInt. In particular, this also selects 8629 // MinInt if Src is NaN. 8630 Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select, 8631 ISD::CondCode::SETULT); 8632 // If Src OGT MaxFloat, select MaxInt. 8633 Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select, 8634 ISD::CondCode::SETOGT); 8635 8636 // In the unsigned case we are done, because we mapped NaN to MinInt, which 8637 // is already zero. 8638 if (!IsSigned) 8639 return Select; 8640 8641 // Otherwise, select 0 if Src is NaN. 8642 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 8643 return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO); 8644 } 8645 8646 SDValue TargetLowering::expandVectorSplice(SDNode *Node, 8647 SelectionDAG &DAG) const { 8648 assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!"); 8649 assert(Node->getValueType(0).isScalableVector() && 8650 "Fixed length vector types expected to use SHUFFLE_VECTOR!"); 8651 8652 EVT VT = Node->getValueType(0); 8653 SDValue V1 = Node->getOperand(0); 8654 SDValue V2 = Node->getOperand(1); 8655 int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue(); 8656 SDLoc DL(Node); 8657 8658 // Expand through memory thusly: 8659 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr 8660 // Store V1, Ptr 8661 // Store V2, Ptr + sizeof(V1) 8662 // If (Imm < 0) 8663 // TrailingElts = -Imm 8664 // Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt)) 8665 // else 8666 // Ptr = Ptr + (Imm * sizeof(VT.Elt)) 8667 // Res = Load Ptr 8668 8669 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false); 8670 8671 EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 8672 VT.getVectorElementCount() * 2); 8673 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment); 8674 EVT PtrVT = StackPtr.getValueType(); 8675 auto &MF = DAG.getMachineFunction(); 8676 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 8677 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex); 8678 8679 // Store the lo part of CONCAT_VECTORS(V1, V2) 8680 SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo); 8681 // Store the hi part of CONCAT_VECTORS(V1, V2) 8682 SDValue OffsetToV2 = DAG.getVScale( 8683 DL, PtrVT, 8684 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 8685 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2); 8686 SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo); 8687 8688 if (Imm >= 0) { 8689 // Load back the required element. getVectorElementPointer takes care of 8690 // clamping the index if it's out-of-bounds. 8691 StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2)); 8692 // Load the spliced result 8693 return DAG.getLoad(VT, DL, StoreV2, StackPtr, 8694 MachinePointerInfo::getUnknownStack(MF)); 8695 } 8696 8697 uint64_t TrailingElts = -Imm; 8698 8699 // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2. 8700 TypeSize EltByteSize = VT.getVectorElementType().getStoreSize(); 8701 SDValue TrailingBytes = 8702 DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT); 8703 8704 if (TrailingElts > VT.getVectorMinNumElements()) { 8705 SDValue VLBytes = DAG.getVScale( 8706 DL, PtrVT, 8707 APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize())); 8708 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes); 8709 } 8710 8711 // Calculate the start address of the spliced result. 8712 StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes); 8713 8714 // Load the spliced result 8715 return DAG.getLoad(VT, DL, StoreV2, StackPtr2, 8716 MachinePointerInfo::getUnknownStack(MF)); 8717 } 8718 8719 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, 8720 SDValue &LHS, SDValue &RHS, 8721 SDValue &CC, bool &NeedInvert, 8722 const SDLoc &dl, SDValue &Chain, 8723 bool IsSignaling) const { 8724 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8725 MVT OpVT = LHS.getSimpleValueType(); 8726 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get(); 8727 NeedInvert = false; 8728 switch (TLI.getCondCodeAction(CCCode, OpVT)) { 8729 default: 8730 llvm_unreachable("Unknown condition code action!"); 8731 case TargetLowering::Legal: 8732 // Nothing to do. 8733 break; 8734 case TargetLowering::Expand: { 8735 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode); 8736 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 8737 std::swap(LHS, RHS); 8738 CC = DAG.getCondCode(InvCC); 8739 return true; 8740 } 8741 // Swapping operands didn't work. Try inverting the condition. 8742 bool NeedSwap = false; 8743 InvCC = getSetCCInverse(CCCode, OpVT); 8744 if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 8745 // If inverting the condition is not enough, try swapping operands 8746 // on top of it. 8747 InvCC = ISD::getSetCCSwappedOperands(InvCC); 8748 NeedSwap = true; 8749 } 8750 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 8751 CC = DAG.getCondCode(InvCC); 8752 NeedInvert = true; 8753 if (NeedSwap) 8754 std::swap(LHS, RHS); 8755 return true; 8756 } 8757 8758 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID; 8759 unsigned Opc = 0; 8760 switch (CCCode) { 8761 default: 8762 llvm_unreachable("Don't know how to expand this condition!"); 8763 case ISD::SETUO: 8764 if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) { 8765 CC1 = ISD::SETUNE; 8766 CC2 = ISD::SETUNE; 8767 Opc = ISD::OR; 8768 break; 8769 } 8770 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 8771 "If SETUE is expanded, SETOEQ or SETUNE must be legal!"); 8772 NeedInvert = true; 8773 LLVM_FALLTHROUGH; 8774 case ISD::SETO: 8775 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) && 8776 "If SETO is expanded, SETOEQ must be legal!"); 8777 CC1 = ISD::SETOEQ; 8778 CC2 = ISD::SETOEQ; 8779 Opc = ISD::AND; 8780 break; 8781 case ISD::SETONE: 8782 case ISD::SETUEQ: 8783 // If the SETUO or SETO CC isn't legal, we might be able to use 8784 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one 8785 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping 8786 // the operands. 8787 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 8788 if (!TLI.isCondCodeLegal(CC2, OpVT) && 8789 (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) || 8790 TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) { 8791 CC1 = ISD::SETOGT; 8792 CC2 = ISD::SETOLT; 8793 Opc = ISD::OR; 8794 NeedInvert = ((unsigned)CCCode & 0x8U); 8795 break; 8796 } 8797 LLVM_FALLTHROUGH; 8798 case ISD::SETOEQ: 8799 case ISD::SETOGT: 8800 case ISD::SETOGE: 8801 case ISD::SETOLT: 8802 case ISD::SETOLE: 8803 case ISD::SETUNE: 8804 case ISD::SETUGT: 8805 case ISD::SETUGE: 8806 case ISD::SETULT: 8807 case ISD::SETULE: 8808 // If we are floating point, assign and break, otherwise fall through. 8809 if (!OpVT.isInteger()) { 8810 // We can use the 4th bit to tell if we are the unordered 8811 // or ordered version of the opcode. 8812 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 8813 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND; 8814 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10); 8815 break; 8816 } 8817 // Fallthrough if we are unsigned integer. 8818 LLVM_FALLTHROUGH; 8819 case ISD::SETLE: 8820 case ISD::SETGT: 8821 case ISD::SETGE: 8822 case ISD::SETLT: 8823 case ISD::SETNE: 8824 case ISD::SETEQ: 8825 // If all combinations of inverting the condition and swapping operands 8826 // didn't work then we have no means to expand the condition. 8827 llvm_unreachable("Don't know how to expand this condition!"); 8828 } 8829 8830 SDValue SetCC1, SetCC2; 8831 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) { 8832 // If we aren't the ordered or unorder operation, 8833 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS). 8834 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling); 8835 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling); 8836 } else { 8837 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS) 8838 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling); 8839 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling); 8840 } 8841 if (Chain) 8842 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1), 8843 SetCC2.getValue(1)); 8844 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2); 8845 RHS = SDValue(); 8846 CC = SDValue(); 8847 return true; 8848 } 8849 } 8850 return false; 8851 } 8852