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