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