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 (Op.getDstAlign() < (VT.getSizeInBits() / 8) && 198 !allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign())) 199 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1); 200 assert(VT.isInteger()); 201 202 // Find the largest legal integer type. 203 MVT LVT = MVT::i64; 204 while (!isTypeLegal(LVT)) 205 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1); 206 assert(LVT.isInteger()); 207 208 // If the type we've chosen is larger than the largest legal integer type 209 // then use that instead. 210 if (VT.bitsGT(LVT)) 211 VT = LVT; 212 } 213 214 unsigned NumMemOps = 0; 215 uint64_t Size = Op.size(); 216 while (Size) { 217 unsigned VTSize = VT.getSizeInBits() / 8; 218 while (VTSize > Size) { 219 // For now, only use non-vector load / store's for the left-over pieces. 220 EVT NewVT = VT; 221 unsigned NewVTSize; 222 223 bool Found = false; 224 if (VT.isVector() || VT.isFloatingPoint()) { 225 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32; 226 if (isOperationLegalOrCustom(ISD::STORE, NewVT) && 227 isSafeMemOpType(NewVT.getSimpleVT())) 228 Found = true; 229 else if (NewVT == MVT::i64 && 230 isOperationLegalOrCustom(ISD::STORE, MVT::f64) && 231 isSafeMemOpType(MVT::f64)) { 232 // i64 is usually not legal on 32-bit targets, but f64 may be. 233 NewVT = MVT::f64; 234 Found = true; 235 } 236 } 237 238 if (!Found) { 239 do { 240 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1); 241 if (NewVT == MVT::i8) 242 break; 243 } while (!isSafeMemOpType(NewVT.getSimpleVT())); 244 } 245 NewVTSize = NewVT.getSizeInBits() / 8; 246 247 // If the new VT cannot cover all of the remaining bits, then consider 248 // issuing a (or a pair of) unaligned and overlapping load / store. 249 bool Fast; 250 if (NumMemOps && Op.allowOverlap() && NewVTSize < Size && 251 allowsMisalignedMemoryAccesses( 252 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1), 253 MachineMemOperand::MONone, &Fast) && 254 Fast) 255 VTSize = Size; 256 else { 257 VT = NewVT; 258 VTSize = NewVTSize; 259 } 260 } 261 262 if (++NumMemOps > Limit) 263 return false; 264 265 MemOps.push_back(VT); 266 Size -= VTSize; 267 } 268 269 return true; 270 } 271 272 /// Soften the operands of a comparison. This code is shared among BR_CC, 273 /// SELECT_CC, and SETCC handlers. 274 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 275 SDValue &NewLHS, SDValue &NewRHS, 276 ISD::CondCode &CCCode, 277 const SDLoc &dl, const SDValue OldLHS, 278 const SDValue OldRHS) const { 279 SDValue Chain; 280 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS, 281 OldRHS, Chain); 282 } 283 284 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 285 SDValue &NewLHS, SDValue &NewRHS, 286 ISD::CondCode &CCCode, 287 const SDLoc &dl, const SDValue OldLHS, 288 const SDValue OldRHS, 289 SDValue &Chain, 290 bool IsSignaling) const { 291 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc 292 // not supporting it. We can update this code when libgcc provides such 293 // functions. 294 295 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128) 296 && "Unsupported setcc type!"); 297 298 // Expand into one or more soft-fp libcall(s). 299 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL; 300 bool ShouldInvertCC = false; 301 switch (CCCode) { 302 case ISD::SETEQ: 303 case ISD::SETOEQ: 304 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 305 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 306 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 307 break; 308 case ISD::SETNE: 309 case ISD::SETUNE: 310 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : 311 (VT == MVT::f64) ? RTLIB::UNE_F64 : 312 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128; 313 break; 314 case ISD::SETGE: 315 case ISD::SETOGE: 316 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 317 (VT == MVT::f64) ? RTLIB::OGE_F64 : 318 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 319 break; 320 case ISD::SETLT: 321 case ISD::SETOLT: 322 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 323 (VT == MVT::f64) ? RTLIB::OLT_F64 : 324 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 325 break; 326 case ISD::SETLE: 327 case ISD::SETOLE: 328 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 329 (VT == MVT::f64) ? RTLIB::OLE_F64 : 330 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 331 break; 332 case ISD::SETGT: 333 case ISD::SETOGT: 334 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 335 (VT == MVT::f64) ? RTLIB::OGT_F64 : 336 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 337 break; 338 case ISD::SETO: 339 ShouldInvertCC = true; 340 LLVM_FALLTHROUGH; 341 case ISD::SETUO: 342 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 343 (VT == MVT::f64) ? RTLIB::UO_F64 : 344 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 345 break; 346 case ISD::SETONE: 347 // SETONE = O && UNE 348 ShouldInvertCC = true; 349 LLVM_FALLTHROUGH; 350 case ISD::SETUEQ: 351 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 352 (VT == MVT::f64) ? RTLIB::UO_F64 : 353 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 354 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 355 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 356 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 357 break; 358 default: 359 // Invert CC for unordered comparisons 360 ShouldInvertCC = true; 361 switch (CCCode) { 362 case ISD::SETULT: 363 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 364 (VT == MVT::f64) ? RTLIB::OGE_F64 : 365 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 366 break; 367 case ISD::SETULE: 368 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 369 (VT == MVT::f64) ? RTLIB::OGT_F64 : 370 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 371 break; 372 case ISD::SETUGT: 373 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 374 (VT == MVT::f64) ? RTLIB::OLE_F64 : 375 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 376 break; 377 case ISD::SETUGE: 378 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 379 (VT == MVT::f64) ? RTLIB::OLT_F64 : 380 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 381 break; 382 default: llvm_unreachable("Do not know how to soften this setcc!"); 383 } 384 } 385 386 // Use the target specific return value for comparions lib calls. 387 EVT RetVT = getCmpLibcallReturnType(); 388 SDValue Ops[2] = {NewLHS, NewRHS}; 389 TargetLowering::MakeLibCallOptions CallOptions; 390 EVT OpsVT[2] = { OldLHS.getValueType(), 391 OldRHS.getValueType() }; 392 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT, true); 393 auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain); 394 NewLHS = Call.first; 395 NewRHS = DAG.getConstant(0, dl, RetVT); 396 397 CCCode = getCmpLibcallCC(LC1); 398 if (ShouldInvertCC) { 399 assert(RetVT.isInteger()); 400 CCCode = getSetCCInverse(CCCode, RetVT); 401 } 402 403 if (LC2 == RTLIB::UNKNOWN_LIBCALL) { 404 // Update Chain. 405 Chain = Call.second; 406 } else { 407 EVT SetCCVT = 408 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT); 409 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode); 410 auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain); 411 CCCode = getCmpLibcallCC(LC2); 412 if (ShouldInvertCC) 413 CCCode = getSetCCInverse(CCCode, RetVT); 414 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode); 415 if (Chain) 416 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second, 417 Call2.second); 418 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl, 419 Tmp.getValueType(), Tmp, NewLHS); 420 NewRHS = SDValue(); 421 } 422 } 423 424 /// Return the entry encoding for a jump table in the current function. The 425 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum. 426 unsigned TargetLowering::getJumpTableEncoding() const { 427 // In non-pic modes, just use the address of a block. 428 if (!isPositionIndependent()) 429 return MachineJumpTableInfo::EK_BlockAddress; 430 431 // In PIC mode, if the target supports a GPRel32 directive, use it. 432 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr) 433 return MachineJumpTableInfo::EK_GPRel32BlockAddress; 434 435 // Otherwise, use a label difference. 436 return MachineJumpTableInfo::EK_LabelDifference32; 437 } 438 439 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table, 440 SelectionDAG &DAG) const { 441 // If our PIC model is GP relative, use the global offset table as the base. 442 unsigned JTEncoding = getJumpTableEncoding(); 443 444 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) || 445 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress)) 446 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout())); 447 448 return Table; 449 } 450 451 /// This returns the relocation base for the given PIC jumptable, the same as 452 /// getPICJumpTableRelocBase, but as an MCExpr. 453 const MCExpr * 454 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 455 unsigned JTI,MCContext &Ctx) const{ 456 // The normal PIC reloc base is the label at the start of the jump table. 457 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx); 458 } 459 460 bool 461 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 462 const TargetMachine &TM = getTargetMachine(); 463 const GlobalValue *GV = GA->getGlobal(); 464 465 // If the address is not even local to this DSO we will have to load it from 466 // a got and then add the offset. 467 if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 468 return false; 469 470 // If the code is position independent we will have to add a base register. 471 if (isPositionIndependent()) 472 return false; 473 474 // Otherwise we can do it. 475 return true; 476 } 477 478 //===----------------------------------------------------------------------===// 479 // Optimization Methods 480 //===----------------------------------------------------------------------===// 481 482 /// If the specified instruction has a constant integer operand and there are 483 /// bits set in that constant that are not demanded, then clear those bits and 484 /// return true. 485 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 486 const APInt &DemandedBits, 487 const APInt &DemandedElts, 488 TargetLoweringOpt &TLO) const { 489 SDLoc DL(Op); 490 unsigned Opcode = Op.getOpcode(); 491 492 // Do target-specific constant optimization. 493 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 494 return TLO.New.getNode(); 495 496 // FIXME: ISD::SELECT, ISD::SELECT_CC 497 switch (Opcode) { 498 default: 499 break; 500 case ISD::XOR: 501 case ISD::AND: 502 case ISD::OR: { 503 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 504 if (!Op1C) 505 return false; 506 507 // If this is a 'not' op, don't touch it because that's a canonical form. 508 const APInt &C = Op1C->getAPIntValue(); 509 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C)) 510 return false; 511 512 if (!C.isSubsetOf(DemandedBits)) { 513 EVT VT = Op.getValueType(); 514 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT); 515 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC); 516 return TLO.CombineTo(Op, NewOp); 517 } 518 519 break; 520 } 521 } 522 523 return false; 524 } 525 526 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, 527 const APInt &DemandedBits, 528 TargetLoweringOpt &TLO) const { 529 EVT VT = Op.getValueType(); 530 APInt DemandedElts = VT.isVector() 531 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 532 : APInt(1, 1); 533 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO); 534 } 535 536 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. 537 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be 538 /// generalized for targets with other types of implicit widening casts. 539 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth, 540 const APInt &Demanded, 541 TargetLoweringOpt &TLO) const { 542 assert(Op.getNumOperands() == 2 && 543 "ShrinkDemandedOp only supports binary operators!"); 544 assert(Op.getNode()->getNumValues() == 1 && 545 "ShrinkDemandedOp only supports nodes with one result!"); 546 547 SelectionDAG &DAG = TLO.DAG; 548 SDLoc dl(Op); 549 550 // Early return, as this function cannot handle vector types. 551 if (Op.getValueType().isVector()) 552 return false; 553 554 // Don't do this if the node has another user, which may require the 555 // full value. 556 if (!Op.getNode()->hasOneUse()) 557 return false; 558 559 // Search for the smallest integer type with free casts to and from 560 // Op's type. For expedience, just check power-of-2 integer types. 561 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 562 unsigned DemandedSize = Demanded.getActiveBits(); 563 unsigned SmallVTBits = DemandedSize; 564 if (!isPowerOf2_32(SmallVTBits)) 565 SmallVTBits = NextPowerOf2(SmallVTBits); 566 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) { 567 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits); 568 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) && 569 TLI.isZExtFree(SmallVT, Op.getValueType())) { 570 // We found a type with free casts. 571 SDValue X = DAG.getNode( 572 Op.getOpcode(), dl, SmallVT, 573 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)), 574 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1))); 575 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?"); 576 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X); 577 return TLO.CombineTo(Op, Z); 578 } 579 } 580 return false; 581 } 582 583 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 584 DAGCombinerInfo &DCI) const { 585 SelectionDAG &DAG = DCI.DAG; 586 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 587 !DCI.isBeforeLegalizeOps()); 588 KnownBits Known; 589 590 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO); 591 if (Simplified) { 592 DCI.AddToWorklist(Op.getNode()); 593 DCI.CommitTargetLoweringOpt(TLO); 594 } 595 return Simplified; 596 } 597 598 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 599 KnownBits &Known, 600 TargetLoweringOpt &TLO, 601 unsigned Depth, 602 bool AssumeSingleUse) const { 603 EVT VT = Op.getValueType(); 604 605 // TODO: We can probably do more work on calculating the known bits and 606 // simplifying the operations for scalable vectors, but for now we just 607 // bail out. 608 if (VT.isScalableVector()) { 609 // Pretend we don't know anything for now. 610 Known = KnownBits(DemandedBits.getBitWidth()); 611 return false; 612 } 613 614 APInt DemandedElts = VT.isVector() 615 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 616 : APInt(1, 1); 617 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth, 618 AssumeSingleUse); 619 } 620 621 // TODO: Can we merge SelectionDAG::GetDemandedBits into this? 622 // TODO: Under what circumstances can we create nodes? Constant folding? 623 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 624 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 625 SelectionDAG &DAG, unsigned Depth) const { 626 // Limit search depth. 627 if (Depth >= SelectionDAG::MaxRecursionDepth) 628 return SDValue(); 629 630 // Ignore UNDEFs. 631 if (Op.isUndef()) 632 return SDValue(); 633 634 // Not demanding any bits/elts from Op. 635 if (DemandedBits == 0 || DemandedElts == 0) 636 return DAG.getUNDEF(Op.getValueType()); 637 638 unsigned NumElts = DemandedElts.getBitWidth(); 639 unsigned BitWidth = DemandedBits.getBitWidth(); 640 KnownBits LHSKnown, RHSKnown; 641 switch (Op.getOpcode()) { 642 case ISD::BITCAST: { 643 SDValue Src = peekThroughBitcasts(Op.getOperand(0)); 644 EVT SrcVT = Src.getValueType(); 645 EVT DstVT = Op.getValueType(); 646 if (SrcVT == DstVT) 647 return Src; 648 649 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 650 unsigned NumDstEltBits = DstVT.getScalarSizeInBits(); 651 if (NumSrcEltBits == NumDstEltBits) 652 if (SDValue V = SimplifyMultipleUseDemandedBits( 653 Src, DemandedBits, DemandedElts, DAG, Depth + 1)) 654 return DAG.getBitcast(DstVT, V); 655 656 // TODO - bigendian once we have test coverage. 657 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0 && 658 DAG.getDataLayout().isLittleEndian()) { 659 unsigned Scale = NumDstEltBits / NumSrcEltBits; 660 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 661 APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits); 662 APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts); 663 for (unsigned i = 0; i != Scale; ++i) { 664 unsigned Offset = i * NumSrcEltBits; 665 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, Offset); 666 if (!Sub.isNullValue()) { 667 DemandedSrcBits |= Sub; 668 for (unsigned j = 0; j != NumElts; ++j) 669 if (DemandedElts[j]) 670 DemandedSrcElts.setBit((j * Scale) + i); 671 } 672 } 673 674 if (SDValue V = SimplifyMultipleUseDemandedBits( 675 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 676 return DAG.getBitcast(DstVT, V); 677 } 678 679 // TODO - bigendian once we have test coverage. 680 if ((NumSrcEltBits % NumDstEltBits) == 0 && 681 DAG.getDataLayout().isLittleEndian()) { 682 unsigned Scale = NumSrcEltBits / NumDstEltBits; 683 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 684 APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits); 685 APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts); 686 for (unsigned i = 0; i != NumElts; ++i) 687 if (DemandedElts[i]) { 688 unsigned Offset = (i % Scale) * NumDstEltBits; 689 DemandedSrcBits.insertBits(DemandedBits, Offset); 690 DemandedSrcElts.setBit(i / Scale); 691 } 692 693 if (SDValue V = SimplifyMultipleUseDemandedBits( 694 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1)) 695 return DAG.getBitcast(DstVT, V); 696 } 697 698 break; 699 } 700 case ISD::AND: { 701 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 702 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 703 704 // If all of the demanded bits are known 1 on one side, return the other. 705 // These bits cannot contribute to the result of the 'and' in this 706 // context. 707 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) 708 return Op.getOperand(0); 709 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One)) 710 return Op.getOperand(1); 711 break; 712 } 713 case ISD::OR: { 714 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 715 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 716 717 // If all of the demanded bits are known zero on one side, return the 718 // other. These bits cannot contribute to the result of the 'or' in this 719 // context. 720 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero)) 721 return Op.getOperand(0); 722 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero)) 723 return Op.getOperand(1); 724 break; 725 } 726 case ISD::XOR: { 727 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 728 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 729 730 // If all of the demanded bits are known zero on one side, return the 731 // other. 732 if (DemandedBits.isSubsetOf(RHSKnown.Zero)) 733 return Op.getOperand(0); 734 if (DemandedBits.isSubsetOf(LHSKnown.Zero)) 735 return Op.getOperand(1); 736 break; 737 } 738 case ISD::SHL: { 739 // If we are only demanding sign bits then we can use the shift source 740 // directly. 741 if (const APInt *MaxSA = 742 DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 743 SDValue Op0 = Op.getOperand(0); 744 unsigned ShAmt = MaxSA->getZExtValue(); 745 unsigned NumSignBits = 746 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 747 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 748 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 749 return Op0; 750 } 751 break; 752 } 753 case ISD::SETCC: { 754 SDValue Op0 = Op.getOperand(0); 755 SDValue Op1 = Op.getOperand(1); 756 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 757 // If (1) we only need the sign-bit, (2) the setcc operands are the same 758 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 759 // -1, we may be able to bypass the setcc. 760 if (DemandedBits.isSignMask() && 761 Op0.getScalarValueSizeInBits() == BitWidth && 762 getBooleanContents(Op0.getValueType()) == 763 BooleanContent::ZeroOrNegativeOneBooleanContent) { 764 // If we're testing X < 0, then this compare isn't needed - just use X! 765 // FIXME: We're limiting to integer types here, but this should also work 766 // if we don't care about FP signed-zero. The use of SETLT with FP means 767 // that we don't care about NaNs. 768 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 769 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 770 return Op0; 771 } 772 break; 773 } 774 case ISD::SIGN_EXTEND_INREG: { 775 // If none of the extended bits are demanded, eliminate the sextinreg. 776 SDValue Op0 = Op.getOperand(0); 777 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 778 unsigned ExBits = ExVT.getScalarSizeInBits(); 779 if (DemandedBits.getActiveBits() <= ExBits) 780 return Op0; 781 // If the input is already sign extended, just drop the extension. 782 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 783 if (NumSignBits >= (BitWidth - ExBits + 1)) 784 return Op0; 785 break; 786 } 787 case ISD::ANY_EXTEND_VECTOR_INREG: 788 case ISD::SIGN_EXTEND_VECTOR_INREG: 789 case ISD::ZERO_EXTEND_VECTOR_INREG: { 790 // If we only want the lowest element and none of extended bits, then we can 791 // return the bitcasted source vector. 792 SDValue Src = Op.getOperand(0); 793 EVT SrcVT = Src.getValueType(); 794 EVT DstVT = Op.getValueType(); 795 if (DemandedElts == 1 && DstVT.getSizeInBits() == SrcVT.getSizeInBits() && 796 DAG.getDataLayout().isLittleEndian() && 797 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) { 798 return DAG.getBitcast(DstVT, Src); 799 } 800 break; 801 } 802 case ISD::INSERT_VECTOR_ELT: { 803 // If we don't demand the inserted element, return the base vector. 804 SDValue Vec = Op.getOperand(0); 805 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 806 EVT VecVT = Vec.getValueType(); 807 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) && 808 !DemandedElts[CIdx->getZExtValue()]) 809 return Vec; 810 break; 811 } 812 case ISD::INSERT_SUBVECTOR: { 813 // If we don't demand the inserted subvector, return the base vector. 814 SDValue Vec = Op.getOperand(0); 815 SDValue Sub = Op.getOperand(1); 816 uint64_t Idx = Op.getConstantOperandVal(2); 817 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 818 if (DemandedElts.extractBits(NumSubElts, Idx) == 0) 819 return Vec; 820 break; 821 } 822 case ISD::VECTOR_SHUFFLE: { 823 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 824 825 // If all the demanded elts are from one operand and are inline, 826 // then we can use the operand directly. 827 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true; 828 for (unsigned i = 0; i != NumElts; ++i) { 829 int M = ShuffleMask[i]; 830 if (M < 0 || !DemandedElts[i]) 831 continue; 832 AllUndef = false; 833 IdentityLHS &= (M == (int)i); 834 IdentityRHS &= ((M - NumElts) == i); 835 } 836 837 if (AllUndef) 838 return DAG.getUNDEF(Op.getValueType()); 839 if (IdentityLHS) 840 return Op.getOperand(0); 841 if (IdentityRHS) 842 return Op.getOperand(1); 843 break; 844 } 845 default: 846 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) 847 if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode( 848 Op, DemandedBits, DemandedElts, DAG, Depth)) 849 return V; 850 break; 851 } 852 return SDValue(); 853 } 854 855 SDValue TargetLowering::SimplifyMultipleUseDemandedBits( 856 SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG, 857 unsigned Depth) const { 858 EVT VT = Op.getValueType(); 859 APInt DemandedElts = VT.isVector() 860 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 861 : APInt(1, 1); 862 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 863 Depth); 864 } 865 866 SDValue TargetLowering::SimplifyMultipleUseDemandedVectorElts( 867 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG, 868 unsigned Depth) const { 869 APInt DemandedBits = APInt::getAllOnesValue(Op.getScalarValueSizeInBits()); 870 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG, 871 Depth); 872 } 873 874 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the 875 /// result of Op are ever used downstream. If we can use this information to 876 /// simplify Op, create a new simplified DAG node and return true, returning the 877 /// original and new nodes in Old and New. Otherwise, analyze the expression and 878 /// return a mask of Known bits for the expression (used to simplify the 879 /// caller). The Known bits may only be accurate for those bits in the 880 /// OriginalDemandedBits and OriginalDemandedElts. 881 bool TargetLowering::SimplifyDemandedBits( 882 SDValue Op, const APInt &OriginalDemandedBits, 883 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 884 unsigned Depth, bool AssumeSingleUse) const { 885 unsigned BitWidth = OriginalDemandedBits.getBitWidth(); 886 assert(Op.getScalarValueSizeInBits() == BitWidth && 887 "Mask size mismatches value type size!"); 888 889 // Don't know anything. 890 Known = KnownBits(BitWidth); 891 892 // TODO: We can probably do more work on calculating the known bits and 893 // simplifying the operations for scalable vectors, but for now we just 894 // bail out. 895 if (Op.getValueType().isScalableVector()) 896 return false; 897 898 unsigned NumElts = OriginalDemandedElts.getBitWidth(); 899 assert((!Op.getValueType().isVector() || 900 NumElts == Op.getValueType().getVectorNumElements()) && 901 "Unexpected vector size"); 902 903 APInt DemandedBits = OriginalDemandedBits; 904 APInt DemandedElts = OriginalDemandedElts; 905 SDLoc dl(Op); 906 auto &DL = TLO.DAG.getDataLayout(); 907 908 // Undef operand. 909 if (Op.isUndef()) 910 return false; 911 912 if (Op.getOpcode() == ISD::Constant) { 913 // We know all of the bits for a constant! 914 Known = KnownBits::makeConstant(cast<ConstantSDNode>(Op)->getAPIntValue()); 915 return false; 916 } 917 918 if (Op.getOpcode() == ISD::ConstantFP) { 919 // We know all of the bits for a floating point constant! 920 Known = KnownBits::makeConstant( 921 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()); 922 return false; 923 } 924 925 // Other users may use these bits. 926 EVT VT = Op.getValueType(); 927 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) { 928 if (Depth != 0) { 929 // If not at the root, Just compute the Known bits to 930 // simplify things downstream. 931 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 932 return false; 933 } 934 // If this is the root being simplified, allow it to have multiple uses, 935 // just set the DemandedBits/Elts to all bits. 936 DemandedBits = APInt::getAllOnesValue(BitWidth); 937 DemandedElts = APInt::getAllOnesValue(NumElts); 938 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) { 939 // Not demanding any bits/elts from Op. 940 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 941 } else if (Depth >= SelectionDAG::MaxRecursionDepth) { 942 // Limit search depth. 943 return false; 944 } 945 946 KnownBits Known2; 947 switch (Op.getOpcode()) { 948 case ISD::TargetConstant: 949 llvm_unreachable("Can't simplify this node"); 950 case ISD::SCALAR_TO_VECTOR: { 951 if (!DemandedElts[0]) 952 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 953 954 KnownBits SrcKnown; 955 SDValue Src = Op.getOperand(0); 956 unsigned SrcBitWidth = Src.getScalarValueSizeInBits(); 957 APInt SrcDemandedBits = DemandedBits.zextOrSelf(SrcBitWidth); 958 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1)) 959 return true; 960 961 // Upper elements are undef, so only get the knownbits if we just demand 962 // the bottom element. 963 if (DemandedElts == 1) 964 Known = SrcKnown.anyextOrTrunc(BitWidth); 965 break; 966 } 967 case ISD::BUILD_VECTOR: 968 // Collect the known bits that are shared by every demanded element. 969 // TODO: Call SimplifyDemandedBits for non-constant demanded elements. 970 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 971 return false; // Don't fall through, will infinitely loop. 972 case ISD::LOAD: { 973 LoadSDNode *LD = cast<LoadSDNode>(Op); 974 if (getTargetConstantFromLoad(LD)) { 975 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 976 return false; // Don't fall through, will infinitely loop. 977 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 978 // If this is a ZEXTLoad and we are looking at the loaded value. 979 EVT MemVT = LD->getMemoryVT(); 980 unsigned MemBits = MemVT.getScalarSizeInBits(); 981 Known.Zero.setBitsFrom(MemBits); 982 return false; // Don't fall through, will infinitely loop. 983 } 984 break; 985 } 986 case ISD::INSERT_VECTOR_ELT: { 987 SDValue Vec = Op.getOperand(0); 988 SDValue Scl = Op.getOperand(1); 989 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 990 EVT VecVT = Vec.getValueType(); 991 992 // If index isn't constant, assume we need all vector elements AND the 993 // inserted element. 994 APInt DemandedVecElts(DemandedElts); 995 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) { 996 unsigned Idx = CIdx->getZExtValue(); 997 DemandedVecElts.clearBit(Idx); 998 999 // Inserted element is not required. 1000 if (!DemandedElts[Idx]) 1001 return TLO.CombineTo(Op, Vec); 1002 } 1003 1004 KnownBits KnownScl; 1005 unsigned NumSclBits = Scl.getScalarValueSizeInBits(); 1006 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits); 1007 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1)) 1008 return true; 1009 1010 Known = KnownScl.anyextOrTrunc(BitWidth); 1011 1012 KnownBits KnownVec; 1013 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO, 1014 Depth + 1)) 1015 return true; 1016 1017 if (!!DemandedVecElts) 1018 Known = KnownBits::commonBits(Known, KnownVec); 1019 1020 return false; 1021 } 1022 case ISD::INSERT_SUBVECTOR: { 1023 // Demand any elements from the subvector and the remainder from the src its 1024 // inserted into. 1025 SDValue Src = Op.getOperand(0); 1026 SDValue Sub = Op.getOperand(1); 1027 uint64_t Idx = Op.getConstantOperandVal(2); 1028 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 1029 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 1030 APInt DemandedSrcElts = DemandedElts; 1031 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 1032 1033 KnownBits KnownSub, KnownSrc; 1034 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO, 1035 Depth + 1)) 1036 return true; 1037 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO, 1038 Depth + 1)) 1039 return true; 1040 1041 Known.Zero.setAllBits(); 1042 Known.One.setAllBits(); 1043 if (!!DemandedSubElts) 1044 Known = KnownBits::commonBits(Known, KnownSub); 1045 if (!!DemandedSrcElts) 1046 Known = KnownBits::commonBits(Known, KnownSrc); 1047 1048 // Attempt to avoid multi-use src if we don't need anything from it. 1049 if (!DemandedBits.isAllOnesValue() || !DemandedSubElts.isAllOnesValue() || 1050 !DemandedSrcElts.isAllOnesValue()) { 1051 SDValue NewSub = SimplifyMultipleUseDemandedBits( 1052 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1); 1053 SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1054 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1055 if (NewSub || NewSrc) { 1056 NewSub = NewSub ? NewSub : Sub; 1057 NewSrc = NewSrc ? NewSrc : Src; 1058 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub, 1059 Op.getOperand(2)); 1060 return TLO.CombineTo(Op, NewOp); 1061 } 1062 } 1063 break; 1064 } 1065 case ISD::EXTRACT_SUBVECTOR: { 1066 // Offset the demanded elts by the subvector index. 1067 SDValue Src = Op.getOperand(0); 1068 if (Src.getValueType().isScalableVector()) 1069 break; 1070 uint64_t Idx = Op.getConstantOperandVal(1); 1071 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 1072 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 1073 1074 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO, 1075 Depth + 1)) 1076 return true; 1077 1078 // Attempt to avoid multi-use src if we don't need anything from it. 1079 if (!DemandedBits.isAllOnesValue() || !DemandedSrcElts.isAllOnesValue()) { 1080 SDValue DemandedSrc = SimplifyMultipleUseDemandedBits( 1081 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1); 1082 if (DemandedSrc) { 1083 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, 1084 Op.getOperand(1)); 1085 return TLO.CombineTo(Op, NewOp); 1086 } 1087 } 1088 break; 1089 } 1090 case ISD::CONCAT_VECTORS: { 1091 Known.Zero.setAllBits(); 1092 Known.One.setAllBits(); 1093 EVT SubVT = Op.getOperand(0).getValueType(); 1094 unsigned NumSubVecs = Op.getNumOperands(); 1095 unsigned NumSubElts = SubVT.getVectorNumElements(); 1096 for (unsigned i = 0; i != NumSubVecs; ++i) { 1097 APInt DemandedSubElts = 1098 DemandedElts.extractBits(NumSubElts, i * NumSubElts); 1099 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts, 1100 Known2, TLO, Depth + 1)) 1101 return true; 1102 // Known bits are shared by every demanded subvector element. 1103 if (!!DemandedSubElts) 1104 Known = KnownBits::commonBits(Known, Known2); 1105 } 1106 break; 1107 } 1108 case ISD::VECTOR_SHUFFLE: { 1109 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 1110 1111 // Collect demanded elements from shuffle operands.. 1112 APInt DemandedLHS(NumElts, 0); 1113 APInt DemandedRHS(NumElts, 0); 1114 for (unsigned i = 0; i != NumElts; ++i) { 1115 if (!DemandedElts[i]) 1116 continue; 1117 int M = ShuffleMask[i]; 1118 if (M < 0) { 1119 // For UNDEF elements, we don't know anything about the common state of 1120 // the shuffle result. 1121 DemandedLHS.clearAllBits(); 1122 DemandedRHS.clearAllBits(); 1123 break; 1124 } 1125 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 1126 if (M < (int)NumElts) 1127 DemandedLHS.setBit(M); 1128 else 1129 DemandedRHS.setBit(M - NumElts); 1130 } 1131 1132 if (!!DemandedLHS || !!DemandedRHS) { 1133 SDValue Op0 = Op.getOperand(0); 1134 SDValue Op1 = Op.getOperand(1); 1135 1136 Known.Zero.setAllBits(); 1137 Known.One.setAllBits(); 1138 if (!!DemandedLHS) { 1139 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO, 1140 Depth + 1)) 1141 return true; 1142 Known = KnownBits::commonBits(Known, Known2); 1143 } 1144 if (!!DemandedRHS) { 1145 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO, 1146 Depth + 1)) 1147 return true; 1148 Known = KnownBits::commonBits(Known, Known2); 1149 } 1150 1151 // Attempt to avoid multi-use ops if we don't need anything from them. 1152 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1153 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1); 1154 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1155 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1); 1156 if (DemandedOp0 || DemandedOp1) { 1157 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1158 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1159 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask); 1160 return TLO.CombineTo(Op, NewOp); 1161 } 1162 } 1163 break; 1164 } 1165 case ISD::AND: { 1166 SDValue Op0 = Op.getOperand(0); 1167 SDValue Op1 = Op.getOperand(1); 1168 1169 // If the RHS is a constant, check to see if the LHS would be zero without 1170 // using the bits from the RHS. Below, we use knowledge about the RHS to 1171 // simplify the LHS, here we're using information from the LHS to simplify 1172 // the RHS. 1173 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) { 1174 // Do not increment Depth here; that can cause an infinite loop. 1175 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth); 1176 // If the LHS already has zeros where RHSC does, this 'and' is dead. 1177 if ((LHSKnown.Zero & DemandedBits) == 1178 (~RHSC->getAPIntValue() & DemandedBits)) 1179 return TLO.CombineTo(Op, Op0); 1180 1181 // If any of the set bits in the RHS are known zero on the LHS, shrink 1182 // the constant. 1183 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits, 1184 DemandedElts, TLO)) 1185 return true; 1186 1187 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its 1188 // constant, but if this 'and' is only clearing bits that were just set by 1189 // the xor, then this 'and' can be eliminated by shrinking the mask of 1190 // the xor. For example, for a 32-bit X: 1191 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1 1192 if (isBitwiseNot(Op0) && Op0.hasOneUse() && 1193 LHSKnown.One == ~RHSC->getAPIntValue()) { 1194 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1); 1195 return TLO.CombineTo(Op, Xor); 1196 } 1197 } 1198 1199 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1200 Depth + 1)) 1201 return true; 1202 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1203 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts, 1204 Known2, TLO, Depth + 1)) 1205 return true; 1206 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1207 1208 // Attempt to avoid multi-use ops if we don't need anything from them. 1209 if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1210 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1211 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1212 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1213 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1214 if (DemandedOp0 || DemandedOp1) { 1215 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1216 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1217 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1218 return TLO.CombineTo(Op, NewOp); 1219 } 1220 } 1221 1222 // If all of the demanded bits are known one on one side, return the other. 1223 // These bits cannot contribute to the result of the 'and'. 1224 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) 1225 return TLO.CombineTo(Op, Op0); 1226 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One)) 1227 return TLO.CombineTo(Op, Op1); 1228 // If all of the demanded bits in the inputs are known zeros, return zero. 1229 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1230 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT)); 1231 // If the RHS is a constant, see if we can simplify it. 1232 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts, 1233 TLO)) 1234 return true; 1235 // If the operation can be done in a smaller type, do so. 1236 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1237 return true; 1238 1239 Known &= Known2; 1240 break; 1241 } 1242 case ISD::OR: { 1243 SDValue Op0 = Op.getOperand(0); 1244 SDValue Op1 = Op.getOperand(1); 1245 1246 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1247 Depth + 1)) 1248 return true; 1249 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1250 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts, 1251 Known2, TLO, Depth + 1)) 1252 return true; 1253 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1254 1255 // Attempt to avoid multi-use ops if we don't need anything from them. 1256 if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1257 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1258 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1259 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1260 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1261 if (DemandedOp0 || DemandedOp1) { 1262 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1263 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1264 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1265 return TLO.CombineTo(Op, NewOp); 1266 } 1267 } 1268 1269 // If all of the demanded bits are known zero on one side, return the other. 1270 // These bits cannot contribute to the result of the 'or'. 1271 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) 1272 return TLO.CombineTo(Op, Op0); 1273 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero)) 1274 return TLO.CombineTo(Op, Op1); 1275 // If the RHS is a constant, see if we can simplify it. 1276 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1277 return true; 1278 // If the operation can be done in a smaller type, do so. 1279 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1280 return true; 1281 1282 Known |= Known2; 1283 break; 1284 } 1285 case ISD::XOR: { 1286 SDValue Op0 = Op.getOperand(0); 1287 SDValue Op1 = Op.getOperand(1); 1288 1289 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, 1290 Depth + 1)) 1291 return true; 1292 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1293 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO, 1294 Depth + 1)) 1295 return true; 1296 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1297 1298 // Attempt to avoid multi-use ops if we don't need anything from them. 1299 if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1300 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1301 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1302 SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits( 1303 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1); 1304 if (DemandedOp0 || DemandedOp1) { 1305 Op0 = DemandedOp0 ? DemandedOp0 : Op0; 1306 Op1 = DemandedOp1 ? DemandedOp1 : Op1; 1307 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1); 1308 return TLO.CombineTo(Op, NewOp); 1309 } 1310 } 1311 1312 // If all of the demanded bits are known zero on one side, return the other. 1313 // These bits cannot contribute to the result of the 'xor'. 1314 if (DemandedBits.isSubsetOf(Known.Zero)) 1315 return TLO.CombineTo(Op, Op0); 1316 if (DemandedBits.isSubsetOf(Known2.Zero)) 1317 return TLO.CombineTo(Op, Op1); 1318 // If the operation can be done in a smaller type, do so. 1319 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1320 return true; 1321 1322 // If all of the unknown bits are known to be zero on one side or the other 1323 // turn this into an *inclusive* or. 1324 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 1325 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 1326 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1)); 1327 1328 ConstantSDNode* C = isConstOrConstSplat(Op1, DemandedElts); 1329 if (C) { 1330 // If one side is a constant, and all of the set bits in the constant are 1331 // also known set on the other side, turn this into an AND, as we know 1332 // the bits will be cleared. 1333 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 1334 // NB: it is okay if more bits are known than are requested 1335 if (C->getAPIntValue() == Known2.One) { 1336 SDValue ANDC = 1337 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT); 1338 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC)); 1339 } 1340 1341 // If the RHS is a constant, see if we can change it. Don't alter a -1 1342 // constant because that's a 'not' op, and that is better for combining 1343 // and codegen. 1344 if (!C->isAllOnesValue() && 1345 DemandedBits.isSubsetOf(C->getAPIntValue())) { 1346 // We're flipping all demanded bits. Flip the undemanded bits too. 1347 SDValue New = TLO.DAG.getNOT(dl, Op0, VT); 1348 return TLO.CombineTo(Op, New); 1349 } 1350 } 1351 1352 // If we can't turn this into a 'not', try to shrink the constant. 1353 if (!C || !C->isAllOnesValue()) 1354 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1355 return true; 1356 1357 Known ^= Known2; 1358 break; 1359 } 1360 case ISD::SELECT: 1361 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO, 1362 Depth + 1)) 1363 return true; 1364 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO, 1365 Depth + 1)) 1366 return true; 1367 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1368 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1369 1370 // If the operands are constants, see if we can simplify them. 1371 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1372 return true; 1373 1374 // Only known if known in both the LHS and RHS. 1375 Known = KnownBits::commonBits(Known, Known2); 1376 break; 1377 case ISD::SELECT_CC: 1378 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO, 1379 Depth + 1)) 1380 return true; 1381 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO, 1382 Depth + 1)) 1383 return true; 1384 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1385 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 1386 1387 // If the operands are constants, see if we can simplify them. 1388 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO)) 1389 return true; 1390 1391 // Only known if known in both the LHS and RHS. 1392 Known = KnownBits::commonBits(Known, Known2); 1393 break; 1394 case ISD::SETCC: { 1395 SDValue Op0 = Op.getOperand(0); 1396 SDValue Op1 = Op.getOperand(1); 1397 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 1398 // If (1) we only need the sign-bit, (2) the setcc operands are the same 1399 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 1400 // -1, we may be able to bypass the setcc. 1401 if (DemandedBits.isSignMask() && 1402 Op0.getScalarValueSizeInBits() == BitWidth && 1403 getBooleanContents(Op0.getValueType()) == 1404 BooleanContent::ZeroOrNegativeOneBooleanContent) { 1405 // If we're testing X < 0, then this compare isn't needed - just use X! 1406 // FIXME: We're limiting to integer types here, but this should also work 1407 // if we don't care about FP signed-zero. The use of SETLT with FP means 1408 // that we don't care about NaNs. 1409 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 1410 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 1411 return TLO.CombineTo(Op, Op0); 1412 1413 // TODO: Should we check for other forms of sign-bit comparisons? 1414 // Examples: X <= -1, X >= 0 1415 } 1416 if (getBooleanContents(Op0.getValueType()) == 1417 TargetLowering::ZeroOrOneBooleanContent && 1418 BitWidth > 1) 1419 Known.Zero.setBitsFrom(1); 1420 break; 1421 } 1422 case ISD::SHL: { 1423 SDValue Op0 = Op.getOperand(0); 1424 SDValue Op1 = Op.getOperand(1); 1425 EVT ShiftVT = Op1.getValueType(); 1426 1427 if (const APInt *SA = 1428 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1429 unsigned ShAmt = SA->getZExtValue(); 1430 if (ShAmt == 0) 1431 return TLO.CombineTo(Op, Op0); 1432 1433 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 1434 // single shift. We can do this if the bottom bits (which are shifted 1435 // out) are never demanded. 1436 // TODO - support non-uniform vector amounts. 1437 if (Op0.getOpcode() == ISD::SRL) { 1438 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) { 1439 if (const APInt *SA2 = 1440 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1441 unsigned C1 = SA2->getZExtValue(); 1442 unsigned Opc = ISD::SHL; 1443 int Diff = ShAmt - C1; 1444 if (Diff < 0) { 1445 Diff = -Diff; 1446 Opc = ISD::SRL; 1447 } 1448 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1449 return TLO.CombineTo( 1450 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1451 } 1452 } 1453 } 1454 1455 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 1456 // are not demanded. This will likely allow the anyext to be folded away. 1457 // TODO - support non-uniform vector amounts. 1458 if (Op0.getOpcode() == ISD::ANY_EXTEND) { 1459 SDValue InnerOp = Op0.getOperand(0); 1460 EVT InnerVT = InnerOp.getValueType(); 1461 unsigned InnerBits = InnerVT.getScalarSizeInBits(); 1462 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits && 1463 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 1464 EVT ShTy = getShiftAmountTy(InnerVT, DL); 1465 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits())) 1466 ShTy = InnerVT; 1467 SDValue NarrowShl = 1468 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp, 1469 TLO.DAG.getConstant(ShAmt, dl, ShTy)); 1470 return TLO.CombineTo( 1471 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl)); 1472 } 1473 1474 // Repeat the SHL optimization above in cases where an extension 1475 // intervenes: (shl (anyext (shr x, c1)), c2) to 1476 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 1477 // aren't demanded (as above) and that the shifted upper c1 bits of 1478 // x aren't demanded. 1479 // TODO - support non-uniform vector amounts. 1480 if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL && 1481 InnerOp.hasOneUse()) { 1482 if (const APInt *SA2 = 1483 TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) { 1484 unsigned InnerShAmt = SA2->getZExtValue(); 1485 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits && 1486 DemandedBits.getActiveBits() <= 1487 (InnerBits - InnerShAmt + ShAmt) && 1488 DemandedBits.countTrailingZeros() >= ShAmt) { 1489 SDValue NewSA = 1490 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT); 1491 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 1492 InnerOp.getOperand(0)); 1493 return TLO.CombineTo( 1494 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA)); 1495 } 1496 } 1497 } 1498 } 1499 1500 APInt InDemandedMask = DemandedBits.lshr(ShAmt); 1501 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1502 Depth + 1)) 1503 return true; 1504 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1505 Known.Zero <<= ShAmt; 1506 Known.One <<= ShAmt; 1507 // low bits known zero. 1508 Known.Zero.setLowBits(ShAmt); 1509 1510 // Try shrinking the operation as long as the shift amount will still be 1511 // in range. 1512 if ((ShAmt < DemandedBits.getActiveBits()) && 1513 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 1514 return true; 1515 } 1516 1517 // If we are only demanding sign bits then we can use the shift source 1518 // directly. 1519 if (const APInt *MaxSA = 1520 TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 1521 unsigned ShAmt = MaxSA->getZExtValue(); 1522 unsigned NumSignBits = 1523 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1524 unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1525 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits)) 1526 return TLO.CombineTo(Op, Op0); 1527 } 1528 break; 1529 } 1530 case ISD::SRL: { 1531 SDValue Op0 = Op.getOperand(0); 1532 SDValue Op1 = Op.getOperand(1); 1533 EVT ShiftVT = Op1.getValueType(); 1534 1535 if (const APInt *SA = 1536 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1537 unsigned ShAmt = SA->getZExtValue(); 1538 if (ShAmt == 0) 1539 return TLO.CombineTo(Op, Op0); 1540 1541 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 1542 // single shift. We can do this if the top bits (which are shifted out) 1543 // are never demanded. 1544 // TODO - support non-uniform vector amounts. 1545 if (Op0.getOpcode() == ISD::SHL) { 1546 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) { 1547 if (const APInt *SA2 = 1548 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) { 1549 unsigned C1 = SA2->getZExtValue(); 1550 unsigned Opc = ISD::SRL; 1551 int Diff = ShAmt - C1; 1552 if (Diff < 0) { 1553 Diff = -Diff; 1554 Opc = ISD::SHL; 1555 } 1556 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT); 1557 return TLO.CombineTo( 1558 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1559 } 1560 } 1561 } 1562 1563 APInt InDemandedMask = (DemandedBits << ShAmt); 1564 1565 // If the shift is exact, then it does demand the low bits (and knows that 1566 // they are zero). 1567 if (Op->getFlags().hasExact()) 1568 InDemandedMask.setLowBits(ShAmt); 1569 1570 // Compute the new bits that are at the top now. 1571 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1572 Depth + 1)) 1573 return true; 1574 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1575 Known.Zero.lshrInPlace(ShAmt); 1576 Known.One.lshrInPlace(ShAmt); 1577 // High bits known zero. 1578 Known.Zero.setHighBits(ShAmt); 1579 } 1580 break; 1581 } 1582 case ISD::SRA: { 1583 SDValue Op0 = Op.getOperand(0); 1584 SDValue Op1 = Op.getOperand(1); 1585 EVT ShiftVT = Op1.getValueType(); 1586 1587 // If we only want bits that already match the signbit then we don't need 1588 // to shift. 1589 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countTrailingZeros(); 1590 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >= 1591 NumHiDemandedBits) 1592 return TLO.CombineTo(Op, Op0); 1593 1594 // If this is an arithmetic shift right and only the low-bit is set, we can 1595 // always convert this into a logical shr, even if the shift amount is 1596 // variable. The low bit of the shift cannot be an input sign bit unless 1597 // the shift amount is >= the size of the datatype, which is undefined. 1598 if (DemandedBits.isOneValue()) 1599 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 1600 1601 if (const APInt *SA = 1602 TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) { 1603 unsigned ShAmt = SA->getZExtValue(); 1604 if (ShAmt == 0) 1605 return TLO.CombineTo(Op, Op0); 1606 1607 APInt InDemandedMask = (DemandedBits << ShAmt); 1608 1609 // If the shift is exact, then it does demand the low bits (and knows that 1610 // they are zero). 1611 if (Op->getFlags().hasExact()) 1612 InDemandedMask.setLowBits(ShAmt); 1613 1614 // If any of the demanded bits are produced by the sign extension, we also 1615 // demand the input sign bit. 1616 if (DemandedBits.countLeadingZeros() < ShAmt) 1617 InDemandedMask.setSignBit(); 1618 1619 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, 1620 Depth + 1)) 1621 return true; 1622 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1623 Known.Zero.lshrInPlace(ShAmt); 1624 Known.One.lshrInPlace(ShAmt); 1625 1626 // If the input sign bit is known to be zero, or if none of the top bits 1627 // are demanded, turn this into an unsigned shift right. 1628 if (Known.Zero[BitWidth - ShAmt - 1] || 1629 DemandedBits.countLeadingZeros() >= ShAmt) { 1630 SDNodeFlags Flags; 1631 Flags.setExact(Op->getFlags().hasExact()); 1632 return TLO.CombineTo( 1633 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags)); 1634 } 1635 1636 int Log2 = DemandedBits.exactLogBase2(); 1637 if (Log2 >= 0) { 1638 // The bit must come from the sign. 1639 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT); 1640 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA)); 1641 } 1642 1643 if (Known.One[BitWidth - ShAmt - 1]) 1644 // New bits are known one. 1645 Known.One.setHighBits(ShAmt); 1646 1647 // Attempt to avoid multi-use ops if we don't need anything from them. 1648 if (!InDemandedMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) { 1649 SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits( 1650 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1); 1651 if (DemandedOp0) { 1652 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1); 1653 return TLO.CombineTo(Op, NewOp); 1654 } 1655 } 1656 } 1657 break; 1658 } 1659 case ISD::FSHL: 1660 case ISD::FSHR: { 1661 SDValue Op0 = Op.getOperand(0); 1662 SDValue Op1 = Op.getOperand(1); 1663 SDValue Op2 = Op.getOperand(2); 1664 bool IsFSHL = (Op.getOpcode() == ISD::FSHL); 1665 1666 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) { 1667 unsigned Amt = SA->getAPIntValue().urem(BitWidth); 1668 1669 // For fshl, 0-shift returns the 1st arg. 1670 // For fshr, 0-shift returns the 2nd arg. 1671 if (Amt == 0) { 1672 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts, 1673 Known, TLO, Depth + 1)) 1674 return true; 1675 break; 1676 } 1677 1678 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt)) 1679 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt) 1680 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt)); 1681 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt); 1682 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO, 1683 Depth + 1)) 1684 return true; 1685 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO, 1686 Depth + 1)) 1687 return true; 1688 1689 Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1690 Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt)); 1691 Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1692 Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt); 1693 Known.One |= Known2.One; 1694 Known.Zero |= Known2.Zero; 1695 } 1696 1697 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1698 if (isPowerOf2_32(BitWidth)) { 1699 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1); 1700 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, 1701 Known2, TLO, Depth + 1)) 1702 return true; 1703 } 1704 break; 1705 } 1706 case ISD::ROTL: 1707 case ISD::ROTR: { 1708 SDValue Op0 = Op.getOperand(0); 1709 SDValue Op1 = Op.getOperand(1); 1710 1711 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 1712 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1)) 1713 return TLO.CombineTo(Op, Op0); 1714 1715 // For pow-2 bitwidths we only demand the bottom modulo amt bits. 1716 if (isPowerOf2_32(BitWidth)) { 1717 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1); 1718 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO, 1719 Depth + 1)) 1720 return true; 1721 } 1722 break; 1723 } 1724 case ISD::UMIN: { 1725 // Check if one arg is always less than (or equal) to the other arg. 1726 SDValue Op0 = Op.getOperand(0); 1727 SDValue Op1 = Op.getOperand(1); 1728 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 1729 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 1730 Known = KnownBits::umin(Known0, Known1); 1731 if (Optional<bool> IsULE = KnownBits::ule(Known0, Known1)) 1732 return TLO.CombineTo(Op, IsULE.getValue() ? Op0 : Op1); 1733 if (Optional<bool> IsULT = KnownBits::ult(Known0, Known1)) 1734 return TLO.CombineTo(Op, IsULT.getValue() ? Op0 : Op1); 1735 break; 1736 } 1737 case ISD::UMAX: { 1738 // Check if one arg is always greater than (or equal) to the other arg. 1739 SDValue Op0 = Op.getOperand(0); 1740 SDValue Op1 = Op.getOperand(1); 1741 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1); 1742 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1); 1743 Known = KnownBits::umax(Known0, Known1); 1744 if (Optional<bool> IsUGE = KnownBits::uge(Known0, Known1)) 1745 return TLO.CombineTo(Op, IsUGE.getValue() ? Op0 : Op1); 1746 if (Optional<bool> IsUGT = KnownBits::ugt(Known0, Known1)) 1747 return TLO.CombineTo(Op, IsUGT.getValue() ? Op0 : Op1); 1748 break; 1749 } 1750 case ISD::BITREVERSE: { 1751 SDValue Src = Op.getOperand(0); 1752 APInt DemandedSrcBits = DemandedBits.reverseBits(); 1753 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 1754 Depth + 1)) 1755 return true; 1756 Known.One = Known2.One.reverseBits(); 1757 Known.Zero = Known2.Zero.reverseBits(); 1758 break; 1759 } 1760 case ISD::BSWAP: { 1761 SDValue Src = Op.getOperand(0); 1762 APInt DemandedSrcBits = DemandedBits.byteSwap(); 1763 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO, 1764 Depth + 1)) 1765 return true; 1766 Known.One = Known2.One.byteSwap(); 1767 Known.Zero = Known2.Zero.byteSwap(); 1768 break; 1769 } 1770 case ISD::CTPOP: { 1771 // If only 1 bit is demanded, replace with PARITY as long as we're before 1772 // op legalization. 1773 // FIXME: Limit to scalars for now. 1774 if (DemandedBits.isOneValue() && !TLO.LegalOps && !VT.isVector()) 1775 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT, 1776 Op.getOperand(0))); 1777 1778 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1779 break; 1780 } 1781 case ISD::SIGN_EXTEND_INREG: { 1782 SDValue Op0 = Op.getOperand(0); 1783 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1784 unsigned ExVTBits = ExVT.getScalarSizeInBits(); 1785 1786 // If we only care about the highest bit, don't bother shifting right. 1787 if (DemandedBits.isSignMask()) { 1788 unsigned NumSignBits = 1789 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1); 1790 bool AlreadySignExtended = NumSignBits >= BitWidth - ExVTBits + 1; 1791 // However if the input is already sign extended we expect the sign 1792 // extension to be dropped altogether later and do not simplify. 1793 if (!AlreadySignExtended) { 1794 // Compute the correct shift amount type, which must be getShiftAmountTy 1795 // for scalar types after legalization. 1796 EVT ShiftAmtTy = VT; 1797 if (TLO.LegalTypes() && !ShiftAmtTy.isVector()) 1798 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL); 1799 1800 SDValue ShiftAmt = 1801 TLO.DAG.getConstant(BitWidth - ExVTBits, dl, ShiftAmtTy); 1802 return TLO.CombineTo(Op, 1803 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt)); 1804 } 1805 } 1806 1807 // If none of the extended bits are demanded, eliminate the sextinreg. 1808 if (DemandedBits.getActiveBits() <= ExVTBits) 1809 return TLO.CombineTo(Op, Op0); 1810 1811 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits); 1812 1813 // Since the sign extended bits are demanded, we know that the sign 1814 // bit is demanded. 1815 InputDemandedBits.setBit(ExVTBits - 1); 1816 1817 if (SimplifyDemandedBits(Op0, InputDemandedBits, Known, TLO, Depth + 1)) 1818 return true; 1819 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1820 1821 // If the sign bit of the input is known set or clear, then we know the 1822 // top bits of the result. 1823 1824 // If the input sign bit is known zero, convert this into a zero extension. 1825 if (Known.Zero[ExVTBits - 1]) 1826 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT)); 1827 1828 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits); 1829 if (Known.One[ExVTBits - 1]) { // Input sign bit known set 1830 Known.One.setBitsFrom(ExVTBits); 1831 Known.Zero &= Mask; 1832 } else { // Input sign bit unknown 1833 Known.Zero &= Mask; 1834 Known.One &= Mask; 1835 } 1836 break; 1837 } 1838 case ISD::BUILD_PAIR: { 1839 EVT HalfVT = Op.getOperand(0).getValueType(); 1840 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 1841 1842 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 1843 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 1844 1845 KnownBits KnownLo, KnownHi; 1846 1847 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1)) 1848 return true; 1849 1850 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1)) 1851 return true; 1852 1853 Known.Zero = KnownLo.Zero.zext(BitWidth) | 1854 KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth); 1855 1856 Known.One = KnownLo.One.zext(BitWidth) | 1857 KnownHi.One.zext(BitWidth).shl(HalfBitWidth); 1858 break; 1859 } 1860 case ISD::ZERO_EXTEND: 1861 case ISD::ZERO_EXTEND_VECTOR_INREG: { 1862 SDValue Src = Op.getOperand(0); 1863 EVT SrcVT = Src.getValueType(); 1864 unsigned InBits = SrcVT.getScalarSizeInBits(); 1865 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 1866 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG; 1867 1868 // If none of the top bits are demanded, convert this into an any_extend. 1869 if (DemandedBits.getActiveBits() <= InBits) { 1870 // If we only need the non-extended bits of the bottom element 1871 // then we can just bitcast to the result. 1872 if (IsVecInReg && DemandedElts == 1 && 1873 VT.getSizeInBits() == SrcVT.getSizeInBits() && 1874 TLO.DAG.getDataLayout().isLittleEndian()) 1875 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 1876 1877 unsigned Opc = 1878 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 1879 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 1880 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 1881 } 1882 1883 APInt InDemandedBits = DemandedBits.trunc(InBits); 1884 APInt InDemandedElts = DemandedElts.zextOrSelf(InElts); 1885 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 1886 Depth + 1)) 1887 return true; 1888 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1889 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 1890 Known = Known.zext(BitWidth); 1891 1892 // Attempt to avoid multi-use ops if we don't need anything from them. 1893 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1894 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 1895 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 1896 break; 1897 } 1898 case ISD::SIGN_EXTEND: 1899 case ISD::SIGN_EXTEND_VECTOR_INREG: { 1900 SDValue Src = Op.getOperand(0); 1901 EVT SrcVT = Src.getValueType(); 1902 unsigned InBits = SrcVT.getScalarSizeInBits(); 1903 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 1904 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG; 1905 1906 // If none of the top bits are demanded, convert this into an any_extend. 1907 if (DemandedBits.getActiveBits() <= InBits) { 1908 // If we only need the non-extended bits of the bottom element 1909 // then we can just bitcast to the result. 1910 if (IsVecInReg && DemandedElts == 1 && 1911 VT.getSizeInBits() == SrcVT.getSizeInBits() && 1912 TLO.DAG.getDataLayout().isLittleEndian()) 1913 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 1914 1915 unsigned Opc = 1916 IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND; 1917 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 1918 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 1919 } 1920 1921 APInt InDemandedBits = DemandedBits.trunc(InBits); 1922 APInt InDemandedElts = DemandedElts.zextOrSelf(InElts); 1923 1924 // Since some of the sign extended bits are demanded, we know that the sign 1925 // bit is demanded. 1926 InDemandedBits.setBit(InBits - 1); 1927 1928 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 1929 Depth + 1)) 1930 return true; 1931 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1932 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 1933 1934 // If the sign bit is known one, the top bits match. 1935 Known = Known.sext(BitWidth); 1936 1937 // If the sign bit is known zero, convert this to a zero extend. 1938 if (Known.isNonNegative()) { 1939 unsigned Opc = 1940 IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND; 1941 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) 1942 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src)); 1943 } 1944 1945 // Attempt to avoid multi-use ops if we don't need anything from them. 1946 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1947 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 1948 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 1949 break; 1950 } 1951 case ISD::ANY_EXTEND: 1952 case ISD::ANY_EXTEND_VECTOR_INREG: { 1953 SDValue Src = Op.getOperand(0); 1954 EVT SrcVT = Src.getValueType(); 1955 unsigned InBits = SrcVT.getScalarSizeInBits(); 1956 unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1; 1957 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG; 1958 1959 // If we only need the bottom element then we can just bitcast. 1960 // TODO: Handle ANY_EXTEND? 1961 if (IsVecInReg && DemandedElts == 1 && 1962 VT.getSizeInBits() == SrcVT.getSizeInBits() && 1963 TLO.DAG.getDataLayout().isLittleEndian()) 1964 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 1965 1966 APInt InDemandedBits = DemandedBits.trunc(InBits); 1967 APInt InDemandedElts = DemandedElts.zextOrSelf(InElts); 1968 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO, 1969 Depth + 1)) 1970 return true; 1971 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1972 assert(Known.getBitWidth() == InBits && "Src width has changed?"); 1973 Known = Known.anyext(BitWidth); 1974 1975 // Attempt to avoid multi-use ops if we don't need anything from them. 1976 if (SDValue NewSrc = SimplifyMultipleUseDemandedBits( 1977 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1)) 1978 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc)); 1979 break; 1980 } 1981 case ISD::TRUNCATE: { 1982 SDValue Src = Op.getOperand(0); 1983 1984 // Simplify the input, using demanded bit information, and compute the known 1985 // zero/one bits live out. 1986 unsigned OperandBitWidth = Src.getScalarValueSizeInBits(); 1987 APInt TruncMask = DemandedBits.zext(OperandBitWidth); 1988 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO, 1989 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 const APInt *ShAmtC = 2013 TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts); 2014 if (!ShAmtC) 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 SDValue NewShAmt = TLO.DAG.getConstant( 2027 ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes())); 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, NewShAmt)); 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 !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(), 3740 OpVT)) { 3741 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 3742 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 3743 EVT ExtDstTy = N0.getValueType(); 3744 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 3745 3746 // If the constant doesn't fit into the number of bits for the source of 3747 // the sign extension, it is impossible for both sides to be equal. 3748 if (C1.getMinSignedBits() > ExtSrcTyBits) 3749 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT); 3750 3751 assert(ExtDstTy == N0.getOperand(0).getValueType() && 3752 ExtDstTy != ExtSrcTy && "Unexpected types!"); 3753 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 3754 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0), 3755 DAG.getConstant(Imm, dl, ExtDstTy)); 3756 if (!DCI.isCalledByLegalizer()) 3757 DCI.AddToWorklist(ZextOp.getNode()); 3758 // Otherwise, make this a use of a zext. 3759 return DAG.getSetCC(dl, VT, ZextOp, 3760 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond); 3761 } else if ((N1C->isNullValue() || N1C->isOne()) && 3762 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 3763 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 3764 if (N0.getOpcode() == ISD::SETCC && 3765 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) && 3766 (N0.getValueType() == MVT::i1 || 3767 getBooleanContents(N0.getOperand(0).getValueType()) == 3768 ZeroOrOneBooleanContent)) { 3769 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne()); 3770 if (TrueWhenTrue) 3771 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 3772 // Invert the condition. 3773 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 3774 CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType()); 3775 if (DCI.isBeforeLegalizeOps() || 3776 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 3777 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 3778 } 3779 3780 if ((N0.getOpcode() == ISD::XOR || 3781 (N0.getOpcode() == ISD::AND && 3782 N0.getOperand(0).getOpcode() == ISD::XOR && 3783 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 3784 isOneConstant(N0.getOperand(1))) { 3785 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 3786 // can only do this if the top bits are known zero. 3787 unsigned BitWidth = N0.getValueSizeInBits(); 3788 if (DAG.MaskedValueIsZero(N0, 3789 APInt::getHighBitsSet(BitWidth, 3790 BitWidth-1))) { 3791 // Okay, get the un-inverted input value. 3792 SDValue Val; 3793 if (N0.getOpcode() == ISD::XOR) { 3794 Val = N0.getOperand(0); 3795 } else { 3796 assert(N0.getOpcode() == ISD::AND && 3797 N0.getOperand(0).getOpcode() == ISD::XOR); 3798 // ((X^1)&1)^1 -> X & 1 3799 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 3800 N0.getOperand(0).getOperand(0), 3801 N0.getOperand(1)); 3802 } 3803 3804 return DAG.getSetCC(dl, VT, Val, N1, 3805 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3806 } 3807 } else if (N1C->isOne()) { 3808 SDValue Op0 = N0; 3809 if (Op0.getOpcode() == ISD::TRUNCATE) 3810 Op0 = Op0.getOperand(0); 3811 3812 if ((Op0.getOpcode() == ISD::XOR) && 3813 Op0.getOperand(0).getOpcode() == ISD::SETCC && 3814 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 3815 SDValue XorLHS = Op0.getOperand(0); 3816 SDValue XorRHS = Op0.getOperand(1); 3817 // Ensure that the input setccs return an i1 type or 0/1 value. 3818 if (Op0.getValueType() == MVT::i1 || 3819 (getBooleanContents(XorLHS.getOperand(0).getValueType()) == 3820 ZeroOrOneBooleanContent && 3821 getBooleanContents(XorRHS.getOperand(0).getValueType()) == 3822 ZeroOrOneBooleanContent)) { 3823 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 3824 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 3825 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond); 3826 } 3827 } 3828 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) { 3829 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 3830 if (Op0.getValueType().bitsGT(VT)) 3831 Op0 = DAG.getNode(ISD::AND, dl, VT, 3832 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 3833 DAG.getConstant(1, dl, VT)); 3834 else if (Op0.getValueType().bitsLT(VT)) 3835 Op0 = DAG.getNode(ISD::AND, dl, VT, 3836 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 3837 DAG.getConstant(1, dl, VT)); 3838 3839 return DAG.getSetCC(dl, VT, Op0, 3840 DAG.getConstant(0, dl, Op0.getValueType()), 3841 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3842 } 3843 if (Op0.getOpcode() == ISD::AssertZext && 3844 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 3845 return DAG.getSetCC(dl, VT, Op0, 3846 DAG.getConstant(0, dl, Op0.getValueType()), 3847 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3848 } 3849 } 3850 3851 // Given: 3852 // icmp eq/ne (urem %x, %y), 0 3853 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem': 3854 // icmp eq/ne %x, 0 3855 if (N0.getOpcode() == ISD::UREM && N1C->isNullValue() && 3856 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 3857 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0)); 3858 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1)); 3859 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2) 3860 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 3861 } 3862 3863 if (SDValue V = 3864 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl)) 3865 return V; 3866 } 3867 3868 // These simplifications apply to splat vectors as well. 3869 // TODO: Handle more splat vector cases. 3870 if (auto *N1C = isConstOrConstSplat(N1)) { 3871 const APInt &C1 = N1C->getAPIntValue(); 3872 3873 APInt MinVal, MaxVal; 3874 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits(); 3875 if (ISD::isSignedIntSetCC(Cond)) { 3876 MinVal = APInt::getSignedMinValue(OperandBitSize); 3877 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 3878 } else { 3879 MinVal = APInt::getMinValue(OperandBitSize); 3880 MaxVal = APInt::getMaxValue(OperandBitSize); 3881 } 3882 3883 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 3884 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 3885 // X >= MIN --> true 3886 if (C1 == MinVal) 3887 return DAG.getBoolConstant(true, dl, VT, OpVT); 3888 3889 if (!VT.isVector()) { // TODO: Support this for vectors. 3890 // X >= C0 --> X > (C0 - 1) 3891 APInt C = C1 - 1; 3892 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 3893 if ((DCI.isBeforeLegalizeOps() || 3894 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 3895 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 3896 isLegalICmpImmediate(C.getSExtValue())))) { 3897 return DAG.getSetCC(dl, VT, N0, 3898 DAG.getConstant(C, dl, N1.getValueType()), 3899 NewCC); 3900 } 3901 } 3902 } 3903 3904 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 3905 // X <= MAX --> true 3906 if (C1 == MaxVal) 3907 return DAG.getBoolConstant(true, dl, VT, OpVT); 3908 3909 // X <= C0 --> X < (C0 + 1) 3910 if (!VT.isVector()) { // TODO: Support this for vectors. 3911 APInt C = C1 + 1; 3912 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 3913 if ((DCI.isBeforeLegalizeOps() || 3914 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 3915 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 3916 isLegalICmpImmediate(C.getSExtValue())))) { 3917 return DAG.getSetCC(dl, VT, N0, 3918 DAG.getConstant(C, dl, N1.getValueType()), 3919 NewCC); 3920 } 3921 } 3922 } 3923 3924 if (Cond == ISD::SETLT || Cond == ISD::SETULT) { 3925 if (C1 == MinVal) 3926 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false 3927 3928 // TODO: Support this for vectors after legalize ops. 3929 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 3930 // Canonicalize setlt X, Max --> setne X, Max 3931 if (C1 == MaxVal) 3932 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 3933 3934 // If we have setult X, 1, turn it into seteq X, 0 3935 if (C1 == MinVal+1) 3936 return DAG.getSetCC(dl, VT, N0, 3937 DAG.getConstant(MinVal, dl, N0.getValueType()), 3938 ISD::SETEQ); 3939 } 3940 } 3941 3942 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) { 3943 if (C1 == MaxVal) 3944 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false 3945 3946 // TODO: Support this for vectors after legalize ops. 3947 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 3948 // Canonicalize setgt X, Min --> setne X, Min 3949 if (C1 == MinVal) 3950 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 3951 3952 // If we have setugt X, Max-1, turn it into seteq X, Max 3953 if (C1 == MaxVal-1) 3954 return DAG.getSetCC(dl, VT, N0, 3955 DAG.getConstant(MaxVal, dl, N0.getValueType()), 3956 ISD::SETEQ); 3957 } 3958 } 3959 3960 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) { 3961 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 3962 if (C1.isNullValue()) 3963 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift( 3964 VT, N0, N1, Cond, DCI, dl)) 3965 return CC; 3966 3967 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y). 3968 // For example, when high 32-bits of i64 X are known clear: 3969 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0 3970 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1 3971 bool CmpZero = N1C->getAPIntValue().isNullValue(); 3972 bool CmpNegOne = N1C->getAPIntValue().isAllOnesValue(); 3973 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) { 3974 // Match or(lo,shl(hi,bw/2)) pattern. 3975 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) { 3976 unsigned EltBits = V.getScalarValueSizeInBits(); 3977 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0) 3978 return false; 3979 SDValue LHS = V.getOperand(0); 3980 SDValue RHS = V.getOperand(1); 3981 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2); 3982 // Unshifted element must have zero upperbits. 3983 if (RHS.getOpcode() == ISD::SHL && 3984 isa<ConstantSDNode>(RHS.getOperand(1)) && 3985 RHS.getConstantOperandAPInt(1) == (EltBits / 2) && 3986 DAG.MaskedValueIsZero(LHS, HiBits)) { 3987 Lo = LHS; 3988 Hi = RHS.getOperand(0); 3989 return true; 3990 } 3991 if (LHS.getOpcode() == ISD::SHL && 3992 isa<ConstantSDNode>(LHS.getOperand(1)) && 3993 LHS.getConstantOperandAPInt(1) == (EltBits / 2) && 3994 DAG.MaskedValueIsZero(RHS, HiBits)) { 3995 Lo = RHS; 3996 Hi = LHS.getOperand(0); 3997 return true; 3998 } 3999 return false; 4000 }; 4001 4002 auto MergeConcat = [&](SDValue Lo, SDValue Hi) { 4003 unsigned EltBits = N0.getScalarValueSizeInBits(); 4004 unsigned HalfBits = EltBits / 2; 4005 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits); 4006 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT); 4007 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits); 4008 SDValue NewN0 = 4009 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask); 4010 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits; 4011 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond); 4012 }; 4013 4014 SDValue Lo, Hi; 4015 if (IsConcat(N0, Lo, Hi)) 4016 return MergeConcat(Lo, Hi); 4017 4018 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) { 4019 SDValue Lo0, Lo1, Hi0, Hi1; 4020 if (IsConcat(N0.getOperand(0), Lo0, Hi0) && 4021 IsConcat(N0.getOperand(1), Lo1, Hi1)) { 4022 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1), 4023 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1)); 4024 } 4025 } 4026 } 4027 } 4028 4029 // If we have "setcc X, C0", check to see if we can shrink the immediate 4030 // by changing cc. 4031 // TODO: Support this for vectors after legalize ops. 4032 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 4033 // SETUGT X, SINTMAX -> SETLT X, 0 4034 // SETUGE X, SINTMIN -> SETLT X, 0 4035 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) || 4036 (Cond == ISD::SETUGE && C1.isMinSignedValue())) 4037 return DAG.getSetCC(dl, VT, N0, 4038 DAG.getConstant(0, dl, N1.getValueType()), 4039 ISD::SETLT); 4040 4041 // SETULT X, SINTMIN -> SETGT X, -1 4042 // SETULE X, SINTMAX -> SETGT X, -1 4043 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) || 4044 (Cond == ISD::SETULE && C1.isMaxSignedValue())) 4045 return DAG.getSetCC(dl, VT, N0, 4046 DAG.getAllOnesConstant(dl, N1.getValueType()), 4047 ISD::SETGT); 4048 } 4049 } 4050 4051 // Back to non-vector simplifications. 4052 // TODO: Can we do these for vector splats? 4053 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 4054 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4055 const APInt &C1 = N1C->getAPIntValue(); 4056 EVT ShValTy = N0.getValueType(); 4057 4058 // Fold bit comparisons when we can. This will result in an 4059 // incorrect value when boolean false is negative one, unless 4060 // the bitsize is 1 in which case the false value is the same 4061 // in practice regardless of the representation. 4062 if ((VT.getSizeInBits() == 1 || 4063 getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) && 4064 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4065 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) && 4066 N0.getOpcode() == ISD::AND) { 4067 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4068 EVT ShiftTy = 4069 getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4070 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 4071 // Perform the xform if the AND RHS is a single bit. 4072 unsigned ShCt = AndRHS->getAPIntValue().logBase2(); 4073 if (AndRHS->getAPIntValue().isPowerOf2() && 4074 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4075 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4076 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4077 DAG.getConstant(ShCt, dl, ShiftTy))); 4078 } 4079 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 4080 // (X & 8) == 8 --> (X & 8) >> 3 4081 // Perform the xform if C1 is a single bit. 4082 unsigned ShCt = C1.logBase2(); 4083 if (C1.isPowerOf2() && 4084 !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) { 4085 return DAG.getNode(ISD::TRUNCATE, dl, VT, 4086 DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4087 DAG.getConstant(ShCt, dl, ShiftTy))); 4088 } 4089 } 4090 } 4091 } 4092 4093 if (C1.getMinSignedBits() <= 64 && 4094 !isLegalICmpImmediate(C1.getSExtValue())) { 4095 EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize()); 4096 // (X & -256) == 256 -> (X >> 8) == 1 4097 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4098 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 4099 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4100 const APInt &AndRHSC = AndRHS->getAPIntValue(); 4101 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) { 4102 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 4103 if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4104 SDValue Shift = 4105 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0), 4106 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4107 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy); 4108 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 4109 } 4110 } 4111 } 4112 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 4113 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 4114 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 4115 // X < 0x100000000 -> (X >> 32) < 1 4116 // X >= 0x100000000 -> (X >> 32) >= 1 4117 // X <= 0x0ffffffff -> (X >> 32) < 1 4118 // X > 0x0ffffffff -> (X >> 32) >= 1 4119 unsigned ShiftBits; 4120 APInt NewC = C1; 4121 ISD::CondCode NewCond = Cond; 4122 if (AdjOne) { 4123 ShiftBits = C1.countTrailingOnes(); 4124 NewC = NewC + 1; 4125 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 4126 } else { 4127 ShiftBits = C1.countTrailingZeros(); 4128 } 4129 NewC.lshrInPlace(ShiftBits); 4130 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 4131 isLegalICmpImmediate(NewC.getSExtValue()) && 4132 !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) { 4133 SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0, 4134 DAG.getConstant(ShiftBits, dl, ShiftTy)); 4135 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy); 4136 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 4137 } 4138 } 4139 } 4140 } 4141 4142 if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) { 4143 auto *CFP = cast<ConstantFPSDNode>(N1); 4144 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value"); 4145 4146 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 4147 // constant if knowing that the operand is non-nan is enough. We prefer to 4148 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 4149 // materialize 0.0. 4150 if (Cond == ISD::SETO || Cond == ISD::SETUO) 4151 return DAG.getSetCC(dl, VT, N0, N0, Cond); 4152 4153 // setcc (fneg x), C -> setcc swap(pred) x, -C 4154 if (N0.getOpcode() == ISD::FNEG) { 4155 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 4156 if (DCI.isBeforeLegalizeOps() || 4157 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 4158 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 4159 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 4160 } 4161 } 4162 4163 // If the condition is not legal, see if we can find an equivalent one 4164 // which is legal. 4165 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 4166 // If the comparison was an awkward floating-point == or != and one of 4167 // the comparison operands is infinity or negative infinity, convert the 4168 // condition to a less-awkward <= or >=. 4169 if (CFP->getValueAPF().isInfinity()) { 4170 bool IsNegInf = CFP->getValueAPF().isNegative(); 4171 ISD::CondCode NewCond = ISD::SETCC_INVALID; 4172 switch (Cond) { 4173 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break; 4174 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break; 4175 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break; 4176 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break; 4177 default: break; 4178 } 4179 if (NewCond != ISD::SETCC_INVALID && 4180 isCondCodeLegal(NewCond, N0.getSimpleValueType())) 4181 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4182 } 4183 } 4184 } 4185 4186 if (N0 == N1) { 4187 // The sext(setcc()) => setcc() optimization relies on the appropriate 4188 // constant being emitted. 4189 assert(!N0.getValueType().isInteger() && 4190 "Integer types should be handled by FoldSetCC"); 4191 4192 bool EqTrue = ISD::isTrueWhenEqual(Cond); 4193 unsigned UOF = ISD::getUnorderedFlavor(Cond); 4194 if (UOF == 2) // FP operators that are undefined on NaNs. 4195 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4196 if (UOF == unsigned(EqTrue)) 4197 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 4198 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 4199 // if it is not already. 4200 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 4201 if (NewCond != Cond && 4202 (DCI.isBeforeLegalizeOps() || 4203 isCondCodeLegal(NewCond, N0.getSimpleValueType()))) 4204 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 4205 } 4206 4207 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4208 N0.getValueType().isInteger()) { 4209 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 4210 N0.getOpcode() == ISD::XOR) { 4211 // Simplify (X+Y) == (X+Z) --> Y == Z 4212 if (N0.getOpcode() == N1.getOpcode()) { 4213 if (N0.getOperand(0) == N1.getOperand(0)) 4214 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 4215 if (N0.getOperand(1) == N1.getOperand(1)) 4216 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 4217 if (isCommutativeBinOp(N0.getOpcode())) { 4218 // If X op Y == Y op X, try other combinations. 4219 if (N0.getOperand(0) == N1.getOperand(1)) 4220 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 4221 Cond); 4222 if (N0.getOperand(1) == N1.getOperand(0)) 4223 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 4224 Cond); 4225 } 4226 } 4227 4228 // If RHS is a legal immediate value for a compare instruction, we need 4229 // to be careful about increasing register pressure needlessly. 4230 bool LegalRHSImm = false; 4231 4232 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 4233 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4234 // Turn (X+C1) == C2 --> X == C2-C1 4235 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) { 4236 return DAG.getSetCC(dl, VT, N0.getOperand(0), 4237 DAG.getConstant(RHSC->getAPIntValue()- 4238 LHSR->getAPIntValue(), 4239 dl, N0.getValueType()), Cond); 4240 } 4241 4242 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0. 4243 if (N0.getOpcode() == ISD::XOR) 4244 // If we know that all of the inverted bits are zero, don't bother 4245 // performing the inversion. 4246 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue())) 4247 return 4248 DAG.getSetCC(dl, VT, N0.getOperand(0), 4249 DAG.getConstant(LHSR->getAPIntValue() ^ 4250 RHSC->getAPIntValue(), 4251 dl, N0.getValueType()), 4252 Cond); 4253 } 4254 4255 // Turn (C1-X) == C2 --> X == C1-C2 4256 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) { 4257 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) { 4258 return 4259 DAG.getSetCC(dl, VT, N0.getOperand(1), 4260 DAG.getConstant(SUBC->getAPIntValue() - 4261 RHSC->getAPIntValue(), 4262 dl, N0.getValueType()), 4263 Cond); 4264 } 4265 } 4266 4267 // Could RHSC fold directly into a compare? 4268 if (RHSC->getValueType(0).getSizeInBits() <= 64) 4269 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 4270 } 4271 4272 // (X+Y) == X --> Y == 0 and similar folds. 4273 // Don't do this if X is an immediate that can fold into a cmp 4274 // instruction and X+Y has other uses. It could be an induction variable 4275 // chain, and the transform would increase register pressure. 4276 if (!LegalRHSImm || N0.hasOneUse()) 4277 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI)) 4278 return V; 4279 } 4280 4281 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 4282 N1.getOpcode() == ISD::XOR) 4283 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI)) 4284 return V; 4285 4286 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI)) 4287 return V; 4288 } 4289 4290 // Fold remainder of division by a constant. 4291 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) && 4292 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 4293 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4294 4295 // When division is cheap or optimizing for minimum size, 4296 // fall through to DIVREM creation by skipping this fold. 4297 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttribute(Attribute::MinSize)) { 4298 if (N0.getOpcode() == ISD::UREM) { 4299 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4300 return Folded; 4301 } else if (N0.getOpcode() == ISD::SREM) { 4302 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl)) 4303 return Folded; 4304 } 4305 } 4306 } 4307 4308 // Fold away ALL boolean setcc's. 4309 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) { 4310 SDValue Temp; 4311 switch (Cond) { 4312 default: llvm_unreachable("Unknown integer setcc!"); 4313 case ISD::SETEQ: // X == Y -> ~(X^Y) 4314 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4315 N0 = DAG.getNOT(dl, Temp, OpVT); 4316 if (!DCI.isCalledByLegalizer()) 4317 DCI.AddToWorklist(Temp.getNode()); 4318 break; 4319 case ISD::SETNE: // X != Y --> (X^Y) 4320 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 4321 break; 4322 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 4323 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 4324 Temp = DAG.getNOT(dl, N0, OpVT); 4325 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp); 4326 if (!DCI.isCalledByLegalizer()) 4327 DCI.AddToWorklist(Temp.getNode()); 4328 break; 4329 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 4330 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 4331 Temp = DAG.getNOT(dl, N1, OpVT); 4332 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp); 4333 if (!DCI.isCalledByLegalizer()) 4334 DCI.AddToWorklist(Temp.getNode()); 4335 break; 4336 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 4337 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 4338 Temp = DAG.getNOT(dl, N0, OpVT); 4339 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp); 4340 if (!DCI.isCalledByLegalizer()) 4341 DCI.AddToWorklist(Temp.getNode()); 4342 break; 4343 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 4344 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 4345 Temp = DAG.getNOT(dl, N1, OpVT); 4346 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp); 4347 break; 4348 } 4349 if (VT.getScalarType() != MVT::i1) { 4350 if (!DCI.isCalledByLegalizer()) 4351 DCI.AddToWorklist(N0.getNode()); 4352 // FIXME: If running after legalize, we probably can't do this. 4353 ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT)); 4354 N0 = DAG.getNode(ExtendCode, dl, VT, N0); 4355 } 4356 return N0; 4357 } 4358 4359 // Could not fold it. 4360 return SDValue(); 4361 } 4362 4363 /// Returns true (and the GlobalValue and the offset) if the node is a 4364 /// GlobalAddress + offset. 4365 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA, 4366 int64_t &Offset) const { 4367 4368 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode(); 4369 4370 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 4371 GA = GASD->getGlobal(); 4372 Offset += GASD->getOffset(); 4373 return true; 4374 } 4375 4376 if (N->getOpcode() == ISD::ADD) { 4377 SDValue N1 = N->getOperand(0); 4378 SDValue N2 = N->getOperand(1); 4379 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 4380 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 4381 Offset += V->getSExtValue(); 4382 return true; 4383 } 4384 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 4385 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 4386 Offset += V->getSExtValue(); 4387 return true; 4388 } 4389 } 4390 } 4391 4392 return false; 4393 } 4394 4395 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 4396 DAGCombinerInfo &DCI) const { 4397 // Default implementation: no optimization. 4398 return SDValue(); 4399 } 4400 4401 //===----------------------------------------------------------------------===// 4402 // Inline Assembler Implementation Methods 4403 //===----------------------------------------------------------------------===// 4404 4405 TargetLowering::ConstraintType 4406 TargetLowering::getConstraintType(StringRef Constraint) const { 4407 unsigned S = Constraint.size(); 4408 4409 if (S == 1) { 4410 switch (Constraint[0]) { 4411 default: break; 4412 case 'r': 4413 return C_RegisterClass; 4414 case 'm': // memory 4415 case 'o': // offsetable 4416 case 'V': // not offsetable 4417 return C_Memory; 4418 case 'n': // Simple Integer 4419 case 'E': // Floating Point Constant 4420 case 'F': // Floating Point Constant 4421 return C_Immediate; 4422 case 'i': // Simple Integer or Relocatable Constant 4423 case 's': // Relocatable Constant 4424 case 'p': // Address. 4425 case 'X': // Allow ANY value. 4426 case 'I': // Target registers. 4427 case 'J': 4428 case 'K': 4429 case 'L': 4430 case 'M': 4431 case 'N': 4432 case 'O': 4433 case 'P': 4434 case '<': 4435 case '>': 4436 return C_Other; 4437 } 4438 } 4439 4440 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') { 4441 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 4442 return C_Memory; 4443 return C_Register; 4444 } 4445 return C_Unknown; 4446 } 4447 4448 /// Try to replace an X constraint, which matches anything, with another that 4449 /// has more specific requirements based on the type of the corresponding 4450 /// operand. 4451 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 4452 if (ConstraintVT.isInteger()) 4453 return "r"; 4454 if (ConstraintVT.isFloatingPoint()) 4455 return "f"; // works for many targets 4456 return nullptr; 4457 } 4458 4459 SDValue TargetLowering::LowerAsmOutputForConstraint( 4460 SDValue &Chain, SDValue &Flag, const SDLoc &DL, 4461 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const { 4462 return SDValue(); 4463 } 4464 4465 /// Lower the specified operand into the Ops vector. 4466 /// If it is invalid, don't add anything to Ops. 4467 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 4468 std::string &Constraint, 4469 std::vector<SDValue> &Ops, 4470 SelectionDAG &DAG) const { 4471 4472 if (Constraint.length() > 1) return; 4473 4474 char ConstraintLetter = Constraint[0]; 4475 switch (ConstraintLetter) { 4476 default: break; 4477 case 'X': // Allows any operand; labels (basic block) use this. 4478 if (Op.getOpcode() == ISD::BasicBlock || 4479 Op.getOpcode() == ISD::TargetBlockAddress) { 4480 Ops.push_back(Op); 4481 return; 4482 } 4483 LLVM_FALLTHROUGH; 4484 case 'i': // Simple Integer or Relocatable Constant 4485 case 'n': // Simple Integer 4486 case 's': { // Relocatable Constant 4487 4488 GlobalAddressSDNode *GA; 4489 ConstantSDNode *C; 4490 BlockAddressSDNode *BA; 4491 uint64_t Offset = 0; 4492 4493 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C), 4494 // etc., since getelementpointer is variadic. We can't use 4495 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible 4496 // while in this case the GA may be furthest from the root node which is 4497 // likely an ISD::ADD. 4498 while (1) { 4499 if ((GA = dyn_cast<GlobalAddressSDNode>(Op)) && ConstraintLetter != 'n') { 4500 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 4501 GA->getValueType(0), 4502 Offset + GA->getOffset())); 4503 return; 4504 } else if ((C = dyn_cast<ConstantSDNode>(Op)) && 4505 ConstraintLetter != 's') { 4506 // gcc prints these as sign extended. Sign extend value to 64 bits 4507 // now; without this it would get ZExt'd later in 4508 // ScheduleDAGSDNodes::EmitNode, which is very generic. 4509 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1; 4510 BooleanContent BCont = getBooleanContents(MVT::i64); 4511 ISD::NodeType ExtOpc = IsBool ? getExtendForContent(BCont) 4512 : ISD::SIGN_EXTEND; 4513 int64_t ExtVal = ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() 4514 : C->getSExtValue(); 4515 Ops.push_back(DAG.getTargetConstant(Offset + ExtVal, 4516 SDLoc(C), MVT::i64)); 4517 return; 4518 } else if ((BA = dyn_cast<BlockAddressSDNode>(Op)) && 4519 ConstraintLetter != 'n') { 4520 Ops.push_back(DAG.getTargetBlockAddress( 4521 BA->getBlockAddress(), BA->getValueType(0), 4522 Offset + BA->getOffset(), BA->getTargetFlags())); 4523 return; 4524 } else { 4525 const unsigned OpCode = Op.getOpcode(); 4526 if (OpCode == ISD::ADD || OpCode == ISD::SUB) { 4527 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0)))) 4528 Op = Op.getOperand(1); 4529 // Subtraction is not commutative. 4530 else if (OpCode == ISD::ADD && 4531 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))) 4532 Op = Op.getOperand(0); 4533 else 4534 return; 4535 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue(); 4536 continue; 4537 } 4538 } 4539 return; 4540 } 4541 break; 4542 } 4543 } 4544 } 4545 4546 std::pair<unsigned, const TargetRegisterClass *> 4547 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 4548 StringRef Constraint, 4549 MVT VT) const { 4550 if (Constraint.empty() || Constraint[0] != '{') 4551 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr)); 4552 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?"); 4553 4554 // Remove the braces from around the name. 4555 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 4556 4557 std::pair<unsigned, const TargetRegisterClass *> R = 4558 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr)); 4559 4560 // Figure out which register class contains this reg. 4561 for (const TargetRegisterClass *RC : RI->regclasses()) { 4562 // If none of the value types for this register class are valid, we 4563 // can't use it. For example, 64-bit reg classes on 32-bit targets. 4564 if (!isLegalRC(*RI, *RC)) 4565 continue; 4566 4567 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); 4568 I != E; ++I) { 4569 if (RegName.equals_lower(RI->getRegAsmName(*I))) { 4570 std::pair<unsigned, const TargetRegisterClass *> S = 4571 std::make_pair(*I, RC); 4572 4573 // If this register class has the requested value type, return it, 4574 // otherwise keep searching and return the first class found 4575 // if no other is found which explicitly has the requested type. 4576 if (RI->isTypeLegalForClass(*RC, VT)) 4577 return S; 4578 if (!R.second) 4579 R = S; 4580 } 4581 } 4582 } 4583 4584 return R; 4585 } 4586 4587 //===----------------------------------------------------------------------===// 4588 // Constraint Selection. 4589 4590 /// Return true of this is an input operand that is a matching constraint like 4591 /// "4". 4592 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 4593 assert(!ConstraintCode.empty() && "No known constraint!"); 4594 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 4595 } 4596 4597 /// If this is an input matching constraint, this method returns the output 4598 /// operand it matches. 4599 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 4600 assert(!ConstraintCode.empty() && "No known constraint!"); 4601 return atoi(ConstraintCode.c_str()); 4602 } 4603 4604 /// Split up the constraint string from the inline assembly value into the 4605 /// specific constraints and their prefixes, and also tie in the associated 4606 /// operand values. 4607 /// If this returns an empty vector, and if the constraint string itself 4608 /// isn't empty, there was an error parsing. 4609 TargetLowering::AsmOperandInfoVector 4610 TargetLowering::ParseConstraints(const DataLayout &DL, 4611 const TargetRegisterInfo *TRI, 4612 const CallBase &Call) const { 4613 /// Information about all of the constraints. 4614 AsmOperandInfoVector ConstraintOperands; 4615 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 4616 unsigned maCount = 0; // Largest number of multiple alternative constraints. 4617 4618 // Do a prepass over the constraints, canonicalizing them, and building up the 4619 // ConstraintOperands list. 4620 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 4621 unsigned ResNo = 0; // ResNo - The result number of the next output. 4622 4623 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 4624 ConstraintOperands.emplace_back(std::move(CI)); 4625 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 4626 4627 // Update multiple alternative constraint count. 4628 if (OpInfo.multipleAlternatives.size() > maCount) 4629 maCount = OpInfo.multipleAlternatives.size(); 4630 4631 OpInfo.ConstraintVT = MVT::Other; 4632 4633 // Compute the value type for each operand. 4634 switch (OpInfo.Type) { 4635 case InlineAsm::isOutput: 4636 // Indirect outputs just consume an argument. 4637 if (OpInfo.isIndirect) { 4638 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 4639 break; 4640 } 4641 4642 // The return value of the call is this value. As such, there is no 4643 // corresponding argument. 4644 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 4645 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 4646 OpInfo.ConstraintVT = 4647 getSimpleValueType(DL, STy->getElementType(ResNo)); 4648 } else { 4649 assert(ResNo == 0 && "Asm only has one result!"); 4650 OpInfo.ConstraintVT = getSimpleValueType(DL, Call.getType()); 4651 } 4652 ++ResNo; 4653 break; 4654 case InlineAsm::isInput: 4655 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 4656 break; 4657 case InlineAsm::isClobber: 4658 // Nothing to do. 4659 break; 4660 } 4661 4662 if (OpInfo.CallOperandVal) { 4663 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 4664 if (OpInfo.isIndirect) { 4665 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 4666 if (!PtrTy) 4667 report_fatal_error("Indirect operand for inline asm not a pointer!"); 4668 OpTy = PtrTy->getElementType(); 4669 } 4670 4671 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 4672 if (StructType *STy = dyn_cast<StructType>(OpTy)) 4673 if (STy->getNumElements() == 1) 4674 OpTy = STy->getElementType(0); 4675 4676 // If OpTy is not a single value, it may be a struct/union that we 4677 // can tile with integers. 4678 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 4679 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 4680 switch (BitSize) { 4681 default: break; 4682 case 1: 4683 case 8: 4684 case 16: 4685 case 32: 4686 case 64: 4687 case 128: 4688 OpInfo.ConstraintVT = 4689 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true); 4690 break; 4691 } 4692 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) { 4693 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace()); 4694 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize); 4695 } else { 4696 OpInfo.ConstraintVT = MVT::getVT(OpTy, true); 4697 } 4698 } 4699 } 4700 4701 // If we have multiple alternative constraints, select the best alternative. 4702 if (!ConstraintOperands.empty()) { 4703 if (maCount) { 4704 unsigned bestMAIndex = 0; 4705 int bestWeight = -1; 4706 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 4707 int weight = -1; 4708 unsigned maIndex; 4709 // Compute the sums of the weights for each alternative, keeping track 4710 // of the best (highest weight) one so far. 4711 for (maIndex = 0; maIndex < maCount; ++maIndex) { 4712 int weightSum = 0; 4713 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 4714 cIndex != eIndex; ++cIndex) { 4715 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 4716 if (OpInfo.Type == InlineAsm::isClobber) 4717 continue; 4718 4719 // If this is an output operand with a matching input operand, 4720 // look up the matching input. If their types mismatch, e.g. one 4721 // is an integer, the other is floating point, or their sizes are 4722 // different, flag it as an maCantMatch. 4723 if (OpInfo.hasMatchingInput()) { 4724 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 4725 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 4726 if ((OpInfo.ConstraintVT.isInteger() != 4727 Input.ConstraintVT.isInteger()) || 4728 (OpInfo.ConstraintVT.getSizeInBits() != 4729 Input.ConstraintVT.getSizeInBits())) { 4730 weightSum = -1; // Can't match. 4731 break; 4732 } 4733 } 4734 } 4735 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 4736 if (weight == -1) { 4737 weightSum = -1; 4738 break; 4739 } 4740 weightSum += weight; 4741 } 4742 // Update best. 4743 if (weightSum > bestWeight) { 4744 bestWeight = weightSum; 4745 bestMAIndex = maIndex; 4746 } 4747 } 4748 4749 // Now select chosen alternative in each constraint. 4750 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 4751 cIndex != eIndex; ++cIndex) { 4752 AsmOperandInfo &cInfo = ConstraintOperands[cIndex]; 4753 if (cInfo.Type == InlineAsm::isClobber) 4754 continue; 4755 cInfo.selectAlternative(bestMAIndex); 4756 } 4757 } 4758 } 4759 4760 // Check and hook up tied operands, choose constraint code to use. 4761 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 4762 cIndex != eIndex; ++cIndex) { 4763 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 4764 4765 // If this is an output operand with a matching input operand, look up the 4766 // matching input. If their types mismatch, e.g. one is an integer, the 4767 // other is floating point, or their sizes are different, flag it as an 4768 // error. 4769 if (OpInfo.hasMatchingInput()) { 4770 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 4771 4772 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 4773 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 4774 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 4775 OpInfo.ConstraintVT); 4776 std::pair<unsigned, const TargetRegisterClass *> InputRC = 4777 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 4778 Input.ConstraintVT); 4779 if ((OpInfo.ConstraintVT.isInteger() != 4780 Input.ConstraintVT.isInteger()) || 4781 (MatchRC.second != InputRC.second)) { 4782 report_fatal_error("Unsupported asm: input constraint" 4783 " with a matching output constraint of" 4784 " incompatible type!"); 4785 } 4786 } 4787 } 4788 } 4789 4790 return ConstraintOperands; 4791 } 4792 4793 /// Return an integer indicating how general CT is. 4794 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 4795 switch (CT) { 4796 case TargetLowering::C_Immediate: 4797 case TargetLowering::C_Other: 4798 case TargetLowering::C_Unknown: 4799 return 0; 4800 case TargetLowering::C_Register: 4801 return 1; 4802 case TargetLowering::C_RegisterClass: 4803 return 2; 4804 case TargetLowering::C_Memory: 4805 return 3; 4806 } 4807 llvm_unreachable("Invalid constraint type"); 4808 } 4809 4810 /// Examine constraint type and operand type and determine a weight value. 4811 /// This object must already have been set up with the operand type 4812 /// and the current alternative constraint selected. 4813 TargetLowering::ConstraintWeight 4814 TargetLowering::getMultipleConstraintMatchWeight( 4815 AsmOperandInfo &info, int maIndex) const { 4816 InlineAsm::ConstraintCodeVector *rCodes; 4817 if (maIndex >= (int)info.multipleAlternatives.size()) 4818 rCodes = &info.Codes; 4819 else 4820 rCodes = &info.multipleAlternatives[maIndex].Codes; 4821 ConstraintWeight BestWeight = CW_Invalid; 4822 4823 // Loop over the options, keeping track of the most general one. 4824 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) { 4825 ConstraintWeight weight = 4826 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str()); 4827 if (weight > BestWeight) 4828 BestWeight = weight; 4829 } 4830 4831 return BestWeight; 4832 } 4833 4834 /// Examine constraint type and operand type and determine a weight value. 4835 /// This object must already have been set up with the operand type 4836 /// and the current alternative constraint selected. 4837 TargetLowering::ConstraintWeight 4838 TargetLowering::getSingleConstraintMatchWeight( 4839 AsmOperandInfo &info, const char *constraint) const { 4840 ConstraintWeight weight = CW_Invalid; 4841 Value *CallOperandVal = info.CallOperandVal; 4842 // If we don't have a value, we can't do a match, 4843 // but allow it at the lowest weight. 4844 if (!CallOperandVal) 4845 return CW_Default; 4846 // Look at the constraint type. 4847 switch (*constraint) { 4848 case 'i': // immediate integer. 4849 case 'n': // immediate integer with a known value. 4850 if (isa<ConstantInt>(CallOperandVal)) 4851 weight = CW_Constant; 4852 break; 4853 case 's': // non-explicit intregal immediate. 4854 if (isa<GlobalValue>(CallOperandVal)) 4855 weight = CW_Constant; 4856 break; 4857 case 'E': // immediate float if host format. 4858 case 'F': // immediate float. 4859 if (isa<ConstantFP>(CallOperandVal)) 4860 weight = CW_Constant; 4861 break; 4862 case '<': // memory operand with autodecrement. 4863 case '>': // memory operand with autoincrement. 4864 case 'm': // memory operand. 4865 case 'o': // offsettable memory operand 4866 case 'V': // non-offsettable memory operand 4867 weight = CW_Memory; 4868 break; 4869 case 'r': // general register. 4870 case 'g': // general register, memory operand or immediate integer. 4871 // note: Clang converts "g" to "imr". 4872 if (CallOperandVal->getType()->isIntegerTy()) 4873 weight = CW_Register; 4874 break; 4875 case 'X': // any operand. 4876 default: 4877 weight = CW_Default; 4878 break; 4879 } 4880 return weight; 4881 } 4882 4883 /// If there are multiple different constraints that we could pick for this 4884 /// operand (e.g. "imr") try to pick the 'best' one. 4885 /// This is somewhat tricky: constraints fall into four classes: 4886 /// Other -> immediates and magic values 4887 /// Register -> one specific register 4888 /// RegisterClass -> a group of regs 4889 /// Memory -> memory 4890 /// Ideally, we would pick the most specific constraint possible: if we have 4891 /// something that fits into a register, we would pick it. The problem here 4892 /// is that if we have something that could either be in a register or in 4893 /// memory that use of the register could cause selection of *other* 4894 /// operands to fail: they might only succeed if we pick memory. Because of 4895 /// this the heuristic we use is: 4896 /// 4897 /// 1) If there is an 'other' constraint, and if the operand is valid for 4898 /// that constraint, use it. This makes us take advantage of 'i' 4899 /// constraints when available. 4900 /// 2) Otherwise, pick the most general constraint present. This prefers 4901 /// 'm' over 'r', for example. 4902 /// 4903 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 4904 const TargetLowering &TLI, 4905 SDValue Op, SelectionDAG *DAG) { 4906 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 4907 unsigned BestIdx = 0; 4908 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 4909 int BestGenerality = -1; 4910 4911 // Loop over the options, keeping track of the most general one. 4912 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 4913 TargetLowering::ConstraintType CType = 4914 TLI.getConstraintType(OpInfo.Codes[i]); 4915 4916 // Indirect 'other' or 'immediate' constraints are not allowed. 4917 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory || 4918 CType == TargetLowering::C_Register || 4919 CType == TargetLowering::C_RegisterClass)) 4920 continue; 4921 4922 // If this is an 'other' or 'immediate' constraint, see if the operand is 4923 // valid for it. For example, on X86 we might have an 'rI' constraint. If 4924 // the operand is an integer in the range [0..31] we want to use I (saving a 4925 // load of a register), otherwise we must use 'r'. 4926 if ((CType == TargetLowering::C_Other || 4927 CType == TargetLowering::C_Immediate) && Op.getNode()) { 4928 assert(OpInfo.Codes[i].size() == 1 && 4929 "Unhandled multi-letter 'other' constraint"); 4930 std::vector<SDValue> ResultOps; 4931 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 4932 ResultOps, *DAG); 4933 if (!ResultOps.empty()) { 4934 BestType = CType; 4935 BestIdx = i; 4936 break; 4937 } 4938 } 4939 4940 // Things with matching constraints can only be registers, per gcc 4941 // documentation. This mainly affects "g" constraints. 4942 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 4943 continue; 4944 4945 // This constraint letter is more general than the previous one, use it. 4946 int Generality = getConstraintGenerality(CType); 4947 if (Generality > BestGenerality) { 4948 BestType = CType; 4949 BestIdx = i; 4950 BestGenerality = Generality; 4951 } 4952 } 4953 4954 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 4955 OpInfo.ConstraintType = BestType; 4956 } 4957 4958 /// Determines the constraint code and constraint type to use for the specific 4959 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 4960 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 4961 SDValue Op, 4962 SelectionDAG *DAG) const { 4963 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 4964 4965 // Single-letter constraints ('r') are very common. 4966 if (OpInfo.Codes.size() == 1) { 4967 OpInfo.ConstraintCode = OpInfo.Codes[0]; 4968 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 4969 } else { 4970 ChooseConstraint(OpInfo, *this, Op, DAG); 4971 } 4972 4973 // 'X' matches anything. 4974 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 4975 // Labels and constants are handled elsewhere ('X' is the only thing 4976 // that matches labels). For Functions, the type here is the type of 4977 // the result, which is not what we want to look at; leave them alone. 4978 Value *v = OpInfo.CallOperandVal; 4979 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) { 4980 OpInfo.CallOperandVal = v; 4981 return; 4982 } 4983 4984 if (Op.getNode() && Op.getOpcode() == ISD::TargetBlockAddress) 4985 return; 4986 4987 // Otherwise, try to resolve it to something we know about by looking at 4988 // the actual operand type. 4989 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 4990 OpInfo.ConstraintCode = Repl; 4991 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 4992 } 4993 } 4994 } 4995 4996 /// Given an exact SDIV by a constant, create a multiplication 4997 /// with the multiplicative inverse of the constant. 4998 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, 4999 const SDLoc &dl, SelectionDAG &DAG, 5000 SmallVectorImpl<SDNode *> &Created) { 5001 SDValue Op0 = N->getOperand(0); 5002 SDValue Op1 = N->getOperand(1); 5003 EVT VT = N->getValueType(0); 5004 EVT SVT = VT.getScalarType(); 5005 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 5006 EVT ShSVT = ShVT.getScalarType(); 5007 5008 bool UseSRA = false; 5009 SmallVector<SDValue, 16> Shifts, Factors; 5010 5011 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5012 if (C->isNullValue()) 5013 return false; 5014 APInt Divisor = C->getAPIntValue(); 5015 unsigned Shift = Divisor.countTrailingZeros(); 5016 if (Shift) { 5017 Divisor.ashrInPlace(Shift); 5018 UseSRA = true; 5019 } 5020 // Calculate the multiplicative inverse, using Newton's method. 5021 APInt t; 5022 APInt Factor = Divisor; 5023 while ((t = Divisor * Factor) != 1) 5024 Factor *= APInt(Divisor.getBitWidth(), 2) - t; 5025 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 5026 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 5027 return true; 5028 }; 5029 5030 // Collect all magic values from the build vector. 5031 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern)) 5032 return SDValue(); 5033 5034 SDValue Shift, Factor; 5035 if (VT.isFixedLengthVector()) { 5036 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5037 Factor = DAG.getBuildVector(VT, dl, Factors); 5038 } else if (VT.isScalableVector()) { 5039 assert(Shifts.size() == 1 && Factors.size() == 1 && 5040 "Expected matchUnaryPredicate to return one element for scalable " 5041 "vectors"); 5042 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5043 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5044 } else { 5045 Shift = Shifts[0]; 5046 Factor = Factors[0]; 5047 } 5048 5049 SDValue Res = Op0; 5050 5051 // Shift the value upfront if it is even, so the LSB is one. 5052 if (UseSRA) { 5053 // TODO: For UDIV use SRL instead of SRA. 5054 SDNodeFlags Flags; 5055 Flags.setExact(true); 5056 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags); 5057 Created.push_back(Res.getNode()); 5058 } 5059 5060 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 5061 } 5062 5063 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 5064 SelectionDAG &DAG, 5065 SmallVectorImpl<SDNode *> &Created) const { 5066 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 5067 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5068 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 5069 return SDValue(N, 0); // Lower SDIV as SDIV 5070 return SDValue(); 5071 } 5072 5073 /// Given an ISD::SDIV node expressing a divide by constant, 5074 /// return a DAG expression to select that will generate the same value by 5075 /// multiplying by a magic number. 5076 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5077 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 5078 bool IsAfterLegalization, 5079 SmallVectorImpl<SDNode *> &Created) const { 5080 SDLoc dl(N); 5081 EVT VT = N->getValueType(0); 5082 EVT SVT = VT.getScalarType(); 5083 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5084 EVT ShSVT = ShVT.getScalarType(); 5085 unsigned EltBits = VT.getScalarSizeInBits(); 5086 5087 // Check to see if we can do this. 5088 // FIXME: We should be more aggressive here. 5089 if (!isTypeLegal(VT)) 5090 return SDValue(); 5091 5092 // If the sdiv has an 'exact' bit we can use a simpler lowering. 5093 if (N->getFlags().hasExact()) 5094 return BuildExactSDIV(*this, N, dl, DAG, Created); 5095 5096 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks; 5097 5098 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 5099 if (C->isNullValue()) 5100 return false; 5101 5102 const APInt &Divisor = C->getAPIntValue(); 5103 APInt::ms magics = Divisor.magic(); 5104 int NumeratorFactor = 0; 5105 int ShiftMask = -1; 5106 5107 if (Divisor.isOneValue() || Divisor.isAllOnesValue()) { 5108 // If d is +1/-1, we just multiply the numerator by +1/-1. 5109 NumeratorFactor = Divisor.getSExtValue(); 5110 magics.m = 0; 5111 magics.s = 0; 5112 ShiftMask = 0; 5113 } else if (Divisor.isStrictlyPositive() && magics.m.isNegative()) { 5114 // If d > 0 and m < 0, add the numerator. 5115 NumeratorFactor = 1; 5116 } else if (Divisor.isNegative() && magics.m.isStrictlyPositive()) { 5117 // If d < 0 and m > 0, subtract the numerator. 5118 NumeratorFactor = -1; 5119 } 5120 5121 MagicFactors.push_back(DAG.getConstant(magics.m, dl, SVT)); 5122 Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT)); 5123 Shifts.push_back(DAG.getConstant(magics.s, dl, ShSVT)); 5124 ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT)); 5125 return true; 5126 }; 5127 5128 SDValue N0 = N->getOperand(0); 5129 SDValue N1 = N->getOperand(1); 5130 5131 // Collect the shifts / magic values from each element. 5132 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern)) 5133 return SDValue(); 5134 5135 SDValue MagicFactor, Factor, Shift, ShiftMask; 5136 if (VT.isFixedLengthVector()) { 5137 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5138 Factor = DAG.getBuildVector(VT, dl, Factors); 5139 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 5140 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks); 5141 } else if (VT.isScalableVector()) { 5142 assert(MagicFactors.size() == 1 && Factors.size() == 1 && 5143 Shifts.size() == 1 && ShiftMasks.size() == 1 && 5144 "Expected matchUnaryPredicate to return one element for scalable " 5145 "vectors"); 5146 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5147 Factor = DAG.getSplatVector(VT, dl, Factors[0]); 5148 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]); 5149 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]); 5150 } else { 5151 MagicFactor = MagicFactors[0]; 5152 Factor = Factors[0]; 5153 Shift = Shifts[0]; 5154 ShiftMask = ShiftMasks[0]; 5155 } 5156 5157 // Multiply the numerator (operand 0) by the magic value. 5158 // FIXME: We should support doing a MUL in a wider type. 5159 SDValue Q; 5160 if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization)) 5161 Q = DAG.getNode(ISD::MULHS, dl, VT, N0, MagicFactor); 5162 else if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) { 5163 SDValue LoHi = 5164 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), N0, MagicFactor); 5165 Q = SDValue(LoHi.getNode(), 1); 5166 } else 5167 return SDValue(); // No mulhs or equivalent. 5168 Created.push_back(Q.getNode()); 5169 5170 // (Optionally) Add/subtract the numerator using Factor. 5171 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor); 5172 Created.push_back(Factor.getNode()); 5173 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor); 5174 Created.push_back(Q.getNode()); 5175 5176 // Shift right algebraic by shift value. 5177 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift); 5178 Created.push_back(Q.getNode()); 5179 5180 // Extract the sign bit, mask it and add it to the quotient. 5181 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT); 5182 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift); 5183 Created.push_back(T.getNode()); 5184 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask); 5185 Created.push_back(T.getNode()); 5186 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 5187 } 5188 5189 /// Given an ISD::UDIV node expressing a divide by constant, 5190 /// return a DAG expression to select that will generate the same value by 5191 /// multiplying by a magic number. 5192 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 5193 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG, 5194 bool IsAfterLegalization, 5195 SmallVectorImpl<SDNode *> &Created) const { 5196 SDLoc dl(N); 5197 EVT VT = N->getValueType(0); 5198 EVT SVT = VT.getScalarType(); 5199 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5200 EVT ShSVT = ShVT.getScalarType(); 5201 unsigned EltBits = VT.getScalarSizeInBits(); 5202 5203 // Check to see if we can do this. 5204 // FIXME: We should be more aggressive here. 5205 if (!isTypeLegal(VT)) 5206 return SDValue(); 5207 5208 bool UseNPQ = false; 5209 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors; 5210 5211 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 5212 if (C->isNullValue()) 5213 return false; 5214 // FIXME: We should use a narrower constant when the upper 5215 // bits are known to be zero. 5216 APInt Divisor = C->getAPIntValue(); 5217 APInt::mu magics = Divisor.magicu(); 5218 unsigned PreShift = 0, PostShift = 0; 5219 5220 // If the divisor is even, we can avoid using the expensive fixup by 5221 // shifting the divided value upfront. 5222 if (magics.a != 0 && !Divisor[0]) { 5223 PreShift = Divisor.countTrailingZeros(); 5224 // Get magic number for the shifted divisor. 5225 magics = Divisor.lshr(PreShift).magicu(PreShift); 5226 assert(magics.a == 0 && "Should use cheap fixup now"); 5227 } 5228 5229 APInt Magic = magics.m; 5230 5231 unsigned SelNPQ; 5232 if (magics.a == 0 || Divisor.isOneValue()) { 5233 assert(magics.s < Divisor.getBitWidth() && 5234 "We shouldn't generate an undefined shift!"); 5235 PostShift = magics.s; 5236 SelNPQ = false; 5237 } else { 5238 PostShift = magics.s - 1; 5239 SelNPQ = true; 5240 } 5241 5242 PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT)); 5243 MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT)); 5244 NPQFactors.push_back( 5245 DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1) 5246 : APInt::getNullValue(EltBits), 5247 dl, SVT)); 5248 PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT)); 5249 UseNPQ |= SelNPQ; 5250 return true; 5251 }; 5252 5253 SDValue N0 = N->getOperand(0); 5254 SDValue N1 = N->getOperand(1); 5255 5256 // Collect the shifts/magic values from each element. 5257 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern)) 5258 return SDValue(); 5259 5260 SDValue PreShift, PostShift, MagicFactor, NPQFactor; 5261 if (VT.isFixedLengthVector()) { 5262 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts); 5263 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 5264 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors); 5265 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts); 5266 } else if (VT.isScalableVector()) { 5267 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 && 5268 NPQFactors.size() == 1 && PostShifts.size() == 1 && 5269 "Expected matchUnaryPredicate to return one for scalable vectors"); 5270 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]); 5271 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]); 5272 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]); 5273 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]); 5274 } else { 5275 PreShift = PreShifts[0]; 5276 MagicFactor = MagicFactors[0]; 5277 PostShift = PostShifts[0]; 5278 } 5279 5280 SDValue Q = N0; 5281 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift); 5282 Created.push_back(Q.getNode()); 5283 5284 // FIXME: We should support doing a MUL in a wider type. 5285 auto GetMULHU = [&](SDValue X, SDValue Y) { 5286 if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization)) 5287 return DAG.getNode(ISD::MULHU, dl, VT, X, Y); 5288 if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) { 5289 SDValue LoHi = 5290 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 5291 return SDValue(LoHi.getNode(), 1); 5292 } 5293 return SDValue(); // No mulhu or equivalent 5294 }; 5295 5296 // Multiply the numerator (operand 0) by the magic value. 5297 Q = GetMULHU(Q, MagicFactor); 5298 if (!Q) 5299 return SDValue(); 5300 5301 Created.push_back(Q.getNode()); 5302 5303 if (UseNPQ) { 5304 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q); 5305 Created.push_back(NPQ.getNode()); 5306 5307 // For vectors we might have a mix of non-NPQ/NPQ paths, so use 5308 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero. 5309 if (VT.isVector()) 5310 NPQ = GetMULHU(NPQ, NPQFactor); 5311 else 5312 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT)); 5313 5314 Created.push_back(NPQ.getNode()); 5315 5316 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 5317 Created.push_back(Q.getNode()); 5318 } 5319 5320 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift); 5321 Created.push_back(Q.getNode()); 5322 5323 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 5324 5325 SDValue One = DAG.getConstant(1, dl, VT); 5326 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ); 5327 return DAG.getSelect(dl, VT, IsOne, N0, Q); 5328 } 5329 5330 /// If all values in Values that *don't* match the predicate are same 'splat' 5331 /// value, then replace all values with that splat value. 5332 /// Else, if AlternativeReplacement was provided, then replace all values that 5333 /// do match predicate with AlternativeReplacement value. 5334 static void 5335 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values, 5336 std::function<bool(SDValue)> Predicate, 5337 SDValue AlternativeReplacement = SDValue()) { 5338 SDValue Replacement; 5339 // Is there a value for which the Predicate does *NOT* match? What is it? 5340 auto SplatValue = llvm::find_if_not(Values, Predicate); 5341 if (SplatValue != Values.end()) { 5342 // Does Values consist only of SplatValue's and values matching Predicate? 5343 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) { 5344 return Value == *SplatValue || Predicate(Value); 5345 })) // Then we shall replace values matching predicate with SplatValue. 5346 Replacement = *SplatValue; 5347 } 5348 if (!Replacement) { 5349 // Oops, we did not find the "baseline" splat value. 5350 if (!AlternativeReplacement) 5351 return; // Nothing to do. 5352 // Let's replace with provided value then. 5353 Replacement = AlternativeReplacement; 5354 } 5355 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement); 5356 } 5357 5358 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE 5359 /// where the divisor is constant and the comparison target is zero, 5360 /// return a DAG expression that will generate the same comparison result 5361 /// using only multiplications, additions and shifts/rotations. 5362 /// Ref: "Hacker's Delight" 10-17. 5363 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode, 5364 SDValue CompTargetNode, 5365 ISD::CondCode Cond, 5366 DAGCombinerInfo &DCI, 5367 const SDLoc &DL) const { 5368 SmallVector<SDNode *, 5> Built; 5369 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 5370 DCI, DL, Built)) { 5371 for (SDNode *N : Built) 5372 DCI.AddToWorklist(N); 5373 return Folded; 5374 } 5375 5376 return SDValue(); 5377 } 5378 5379 SDValue 5380 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode, 5381 SDValue CompTargetNode, ISD::CondCode Cond, 5382 DAGCombinerInfo &DCI, const SDLoc &DL, 5383 SmallVectorImpl<SDNode *> &Created) const { 5384 // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q) 5385 // - D must be constant, with D = D0 * 2^K where D0 is odd 5386 // - P is the multiplicative inverse of D0 modulo 2^W 5387 // - Q = floor(((2^W) - 1) / D) 5388 // where W is the width of the common type of N and D. 5389 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5390 "Only applicable for (in)equality comparisons."); 5391 5392 SelectionDAG &DAG = DCI.DAG; 5393 5394 EVT VT = REMNode.getValueType(); 5395 EVT SVT = VT.getScalarType(); 5396 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5397 EVT ShSVT = ShVT.getScalarType(); 5398 5399 // If MUL is unavailable, we cannot proceed in any case. 5400 if (!isOperationLegalOrCustom(ISD::MUL, VT)) 5401 return SDValue(); 5402 5403 bool ComparingWithAllZeros = true; 5404 bool AllComparisonsWithNonZerosAreTautological = true; 5405 bool HadTautologicalLanes = false; 5406 bool AllLanesAreTautological = true; 5407 bool HadEvenDivisor = false; 5408 bool AllDivisorsArePowerOfTwo = true; 5409 bool HadTautologicalInvertedLanes = false; 5410 SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts; 5411 5412 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) { 5413 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 5414 if (CDiv->isNullValue()) 5415 return false; 5416 5417 const APInt &D = CDiv->getAPIntValue(); 5418 const APInt &Cmp = CCmp->getAPIntValue(); 5419 5420 ComparingWithAllZeros &= Cmp.isNullValue(); 5421 5422 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 5423 // if C2 is not less than C1, the comparison is always false. 5424 // But we will only be able to produce the comparison that will give the 5425 // opposive tautological answer. So this lane would need to be fixed up. 5426 bool TautologicalInvertedLane = D.ule(Cmp); 5427 HadTautologicalInvertedLanes |= TautologicalInvertedLane; 5428 5429 // If all lanes are tautological (either all divisors are ones, or divisor 5430 // is not greater than the constant we are comparing with), 5431 // we will prefer to avoid the fold. 5432 bool TautologicalLane = D.isOneValue() || TautologicalInvertedLane; 5433 HadTautologicalLanes |= TautologicalLane; 5434 AllLanesAreTautological &= TautologicalLane; 5435 5436 // If we are comparing with non-zero, we need'll need to subtract said 5437 // comparison value from the LHS. But there is no point in doing that if 5438 // every lane where we are comparing with non-zero is tautological.. 5439 if (!Cmp.isNullValue()) 5440 AllComparisonsWithNonZerosAreTautological &= TautologicalLane; 5441 5442 // Decompose D into D0 * 2^K 5443 unsigned K = D.countTrailingZeros(); 5444 assert((!D.isOneValue() || (K == 0)) && "For divisor '1' we won't rotate."); 5445 APInt D0 = D.lshr(K); 5446 5447 // D is even if it has trailing zeros. 5448 HadEvenDivisor |= (K != 0); 5449 // D is a power-of-two if D0 is one. 5450 // If all divisors are power-of-two, we will prefer to avoid the fold. 5451 AllDivisorsArePowerOfTwo &= D0.isOneValue(); 5452 5453 // P = inv(D0, 2^W) 5454 // 2^W requires W + 1 bits, so we have to extend and then truncate. 5455 unsigned W = D.getBitWidth(); 5456 APInt P = D0.zext(W + 1) 5457 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 5458 .trunc(W); 5459 assert(!P.isNullValue() && "No multiplicative inverse!"); // unreachable 5460 assert((D0 * P).isOneValue() && "Multiplicative inverse sanity check."); 5461 5462 // Q = floor((2^W - 1) u/ D) 5463 // R = ((2^W - 1) u% D) 5464 APInt Q, R; 5465 APInt::udivrem(APInt::getAllOnesValue(W), D, Q, R); 5466 5467 // If we are comparing with zero, then that comparison constant is okay, 5468 // else it may need to be one less than that. 5469 if (Cmp.ugt(R)) 5470 Q -= 1; 5471 5472 assert(APInt::getAllOnesValue(ShSVT.getSizeInBits()).ugt(K) && 5473 "We are expecting that K is always less than all-ones for ShSVT"); 5474 5475 // If the lane is tautological the result can be constant-folded. 5476 if (TautologicalLane) { 5477 // Set P and K amount to a bogus values so we can try to splat them. 5478 P = 0; 5479 K = -1; 5480 // And ensure that comparison constant is tautological, 5481 // it will always compare true/false. 5482 Q = -1; 5483 } 5484 5485 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 5486 KAmts.push_back( 5487 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 5488 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 5489 return true; 5490 }; 5491 5492 SDValue N = REMNode.getOperand(0); 5493 SDValue D = REMNode.getOperand(1); 5494 5495 // Collect the values from each element. 5496 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern)) 5497 return SDValue(); 5498 5499 // If all lanes are tautological, the result can be constant-folded. 5500 if (AllLanesAreTautological) 5501 return SDValue(); 5502 5503 // If this is a urem by a powers-of-two, avoid the fold since it can be 5504 // best implemented as a bit test. 5505 if (AllDivisorsArePowerOfTwo) 5506 return SDValue(); 5507 5508 SDValue PVal, KVal, QVal; 5509 if (VT.isVector()) { 5510 if (HadTautologicalLanes) { 5511 // Try to turn PAmts into a splat, since we don't care about the values 5512 // that are currently '0'. If we can't, just keep '0'`s. 5513 turnVectorIntoSplatVector(PAmts, isNullConstant); 5514 // Try to turn KAmts into a splat, since we don't care about the values 5515 // that are currently '-1'. If we can't, change them to '0'`s. 5516 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 5517 DAG.getConstant(0, DL, ShSVT)); 5518 } 5519 5520 PVal = DAG.getBuildVector(VT, DL, PAmts); 5521 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 5522 QVal = DAG.getBuildVector(VT, DL, QAmts); 5523 } else { 5524 PVal = PAmts[0]; 5525 KVal = KAmts[0]; 5526 QVal = QAmts[0]; 5527 } 5528 5529 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) { 5530 if (!isOperationLegalOrCustom(ISD::SUB, VT)) 5531 return SDValue(); // FIXME: Could/should use `ISD::ADD`? 5532 assert(CompTargetNode.getValueType() == N.getValueType() && 5533 "Expecting that the types on LHS and RHS of comparisons match."); 5534 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode); 5535 } 5536 5537 // (mul N, P) 5538 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 5539 Created.push_back(Op0.getNode()); 5540 5541 // Rotate right only if any divisor was even. We avoid rotates for all-odd 5542 // divisors as a performance improvement, since rotating by 0 is a no-op. 5543 if (HadEvenDivisor) { 5544 // We need ROTR to do this. 5545 if (!isOperationLegalOrCustom(ISD::ROTR, VT)) 5546 return SDValue(); 5547 SDNodeFlags Flags; 5548 Flags.setExact(true); 5549 // UREM: (rotr (mul N, P), K) 5550 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal, Flags); 5551 Created.push_back(Op0.getNode()); 5552 } 5553 5554 // UREM: (setule/setugt (rotr (mul N, P), K), Q) 5555 SDValue NewCC = 5556 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 5557 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 5558 if (!HadTautologicalInvertedLanes) 5559 return NewCC; 5560 5561 // If any lanes previously compared always-false, the NewCC will give 5562 // always-true result for them, so we need to fixup those lanes. 5563 // Or the other way around for inequality predicate. 5564 assert(VT.isVector() && "Can/should only get here for vectors."); 5565 Created.push_back(NewCC.getNode()); 5566 5567 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`, 5568 // if C2 is not less than C1, the comparison is always false. 5569 // But we have produced the comparison that will give the 5570 // opposive tautological answer. So these lanes would need to be fixed up. 5571 SDValue TautologicalInvertedChannels = 5572 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE); 5573 Created.push_back(TautologicalInvertedChannels.getNode()); 5574 5575 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) { 5576 // If we have a vector select, let's replace the comparison results in the 5577 // affected lanes with the correct tautological result. 5578 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true, 5579 DL, SETCCVT, SETCCVT); 5580 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels, 5581 Replacement, NewCC); 5582 } 5583 5584 // Else, we can just invert the comparison result in the appropriate lanes. 5585 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT)) 5586 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC, 5587 TautologicalInvertedChannels); 5588 5589 return SDValue(); // Don't know how to lower. 5590 } 5591 5592 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE 5593 /// where the divisor is constant and the comparison target is zero, 5594 /// return a DAG expression that will generate the same comparison result 5595 /// using only multiplications, additions and shifts/rotations. 5596 /// Ref: "Hacker's Delight" 10-17. 5597 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode, 5598 SDValue CompTargetNode, 5599 ISD::CondCode Cond, 5600 DAGCombinerInfo &DCI, 5601 const SDLoc &DL) const { 5602 SmallVector<SDNode *, 7> Built; 5603 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 5604 DCI, DL, Built)) { 5605 assert(Built.size() <= 7 && "Max size prediction failed."); 5606 for (SDNode *N : Built) 5607 DCI.AddToWorklist(N); 5608 return Folded; 5609 } 5610 5611 return SDValue(); 5612 } 5613 5614 SDValue 5615 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode, 5616 SDValue CompTargetNode, ISD::CondCode Cond, 5617 DAGCombinerInfo &DCI, const SDLoc &DL, 5618 SmallVectorImpl<SDNode *> &Created) const { 5619 // Fold: 5620 // (seteq/ne (srem N, D), 0) 5621 // To: 5622 // (setule/ugt (rotr (add (mul N, P), A), K), Q) 5623 // 5624 // - D must be constant, with D = D0 * 2^K where D0 is odd 5625 // - P is the multiplicative inverse of D0 modulo 2^W 5626 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k))) 5627 // - Q = floor((2 * A) / (2^K)) 5628 // where W is the width of the common type of N and D. 5629 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 5630 "Only applicable for (in)equality comparisons."); 5631 5632 SelectionDAG &DAG = DCI.DAG; 5633 5634 EVT VT = REMNode.getValueType(); 5635 EVT SVT = VT.getScalarType(); 5636 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5637 EVT ShSVT = ShVT.getScalarType(); 5638 5639 // If MUL is unavailable, we cannot proceed in any case. 5640 if (!isOperationLegalOrCustom(ISD::MUL, VT)) 5641 return SDValue(); 5642 5643 // TODO: Could support comparing with non-zero too. 5644 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode); 5645 if (!CompTarget || !CompTarget->isNullValue()) 5646 return SDValue(); 5647 5648 bool HadIntMinDivisor = false; 5649 bool HadOneDivisor = false; 5650 bool AllDivisorsAreOnes = true; 5651 bool HadEvenDivisor = false; 5652 bool NeedToApplyOffset = false; 5653 bool AllDivisorsArePowerOfTwo = true; 5654 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts; 5655 5656 auto BuildSREMPattern = [&](ConstantSDNode *C) { 5657 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 5658 if (C->isNullValue()) 5659 return false; 5660 5661 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine. 5662 5663 // WARNING: this fold is only valid for positive divisors! 5664 APInt D = C->getAPIntValue(); 5665 if (D.isNegative()) 5666 D.negate(); // `rem %X, -C` is equivalent to `rem %X, C` 5667 5668 HadIntMinDivisor |= D.isMinSignedValue(); 5669 5670 // If all divisors are ones, we will prefer to avoid the fold. 5671 HadOneDivisor |= D.isOneValue(); 5672 AllDivisorsAreOnes &= D.isOneValue(); 5673 5674 // Decompose D into D0 * 2^K 5675 unsigned K = D.countTrailingZeros(); 5676 assert((!D.isOneValue() || (K == 0)) && "For divisor '1' we won't rotate."); 5677 APInt D0 = D.lshr(K); 5678 5679 if (!D.isMinSignedValue()) { 5680 // D is even if it has trailing zeros; unless it's INT_MIN, in which case 5681 // we don't care about this lane in this fold, we'll special-handle it. 5682 HadEvenDivisor |= (K != 0); 5683 } 5684 5685 // D is a power-of-two if D0 is one. This includes INT_MIN. 5686 // If all divisors are power-of-two, we will prefer to avoid the fold. 5687 AllDivisorsArePowerOfTwo &= D0.isOneValue(); 5688 5689 // P = inv(D0, 2^W) 5690 // 2^W requires W + 1 bits, so we have to extend and then truncate. 5691 unsigned W = D.getBitWidth(); 5692 APInt P = D0.zext(W + 1) 5693 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 5694 .trunc(W); 5695 assert(!P.isNullValue() && "No multiplicative inverse!"); // unreachable 5696 assert((D0 * P).isOneValue() && "Multiplicative inverse sanity check."); 5697 5698 // A = floor((2^(W - 1) - 1) / D0) & -2^K 5699 APInt A = APInt::getSignedMaxValue(W).udiv(D0); 5700 A.clearLowBits(K); 5701 5702 if (!D.isMinSignedValue()) { 5703 // If divisor INT_MIN, then we don't care about this lane in this fold, 5704 // we'll special-handle it. 5705 NeedToApplyOffset |= A != 0; 5706 } 5707 5708 // Q = floor((2 * A) / (2^K)) 5709 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K)); 5710 5711 assert(APInt::getAllOnesValue(SVT.getSizeInBits()).ugt(A) && 5712 "We are expecting that A is always less than all-ones for SVT"); 5713 assert(APInt::getAllOnesValue(ShSVT.getSizeInBits()).ugt(K) && 5714 "We are expecting that K is always less than all-ones for ShSVT"); 5715 5716 // If the divisor is 1 the result can be constant-folded. Likewise, we 5717 // don't care about INT_MIN lanes, those can be set to undef if appropriate. 5718 if (D.isOneValue()) { 5719 // Set P, A and K to a bogus values so we can try to splat them. 5720 P = 0; 5721 A = -1; 5722 K = -1; 5723 5724 // x ?% 1 == 0 <--> true <--> x u<= -1 5725 Q = -1; 5726 } 5727 5728 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 5729 AAmts.push_back(DAG.getConstant(A, DL, SVT)); 5730 KAmts.push_back( 5731 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 5732 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 5733 return true; 5734 }; 5735 5736 SDValue N = REMNode.getOperand(0); 5737 SDValue D = REMNode.getOperand(1); 5738 5739 // Collect the values from each element. 5740 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern)) 5741 return SDValue(); 5742 5743 // If this is a srem by a one, avoid the fold since it can be constant-folded. 5744 if (AllDivisorsAreOnes) 5745 return SDValue(); 5746 5747 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold 5748 // since it can be best implemented as a bit test. 5749 if (AllDivisorsArePowerOfTwo) 5750 return SDValue(); 5751 5752 SDValue PVal, AVal, KVal, QVal; 5753 if (VT.isFixedLengthVector()) { 5754 if (HadOneDivisor) { 5755 // Try to turn PAmts into a splat, since we don't care about the values 5756 // that are currently '0'. If we can't, just keep '0'`s. 5757 turnVectorIntoSplatVector(PAmts, isNullConstant); 5758 // Try to turn AAmts into a splat, since we don't care about the 5759 // values that are currently '-1'. If we can't, change them to '0'`s. 5760 turnVectorIntoSplatVector(AAmts, isAllOnesConstant, 5761 DAG.getConstant(0, DL, SVT)); 5762 // Try to turn KAmts into a splat, since we don't care about the values 5763 // that are currently '-1'. If we can't, change them to '0'`s. 5764 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 5765 DAG.getConstant(0, DL, ShSVT)); 5766 } 5767 5768 PVal = DAG.getBuildVector(VT, DL, PAmts); 5769 AVal = DAG.getBuildVector(VT, DL, AAmts); 5770 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 5771 QVal = DAG.getBuildVector(VT, DL, QAmts); 5772 } else if (VT.isScalableVector()) { 5773 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 && 5774 QAmts.size() == 1 && 5775 "Expected matchUnaryPredicate to return one element for scalable " 5776 "vectors"); 5777 PVal = DAG.getSplatVector(VT, DL, PAmts[0]); 5778 AVal = DAG.getSplatVector(VT, DL, AAmts[0]); 5779 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]); 5780 QVal = DAG.getSplatVector(VT, DL, QAmts[0]); 5781 } else { 5782 PVal = PAmts[0]; 5783 AVal = AAmts[0]; 5784 KVal = KAmts[0]; 5785 QVal = QAmts[0]; 5786 } 5787 5788 // (mul N, P) 5789 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 5790 Created.push_back(Op0.getNode()); 5791 5792 if (NeedToApplyOffset) { 5793 // We need ADD to do this. 5794 if (!isOperationLegalOrCustom(ISD::ADD, VT)) 5795 return SDValue(); 5796 5797 // (add (mul N, P), A) 5798 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal); 5799 Created.push_back(Op0.getNode()); 5800 } 5801 5802 // Rotate right only if any divisor was even. We avoid rotates for all-odd 5803 // divisors as a performance improvement, since rotating by 0 is a no-op. 5804 if (HadEvenDivisor) { 5805 // We need ROTR to do this. 5806 if (!isOperationLegalOrCustom(ISD::ROTR, VT)) 5807 return SDValue(); 5808 SDNodeFlags Flags; 5809 Flags.setExact(true); 5810 // SREM: (rotr (add (mul N, P), A), K) 5811 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal, Flags); 5812 Created.push_back(Op0.getNode()); 5813 } 5814 5815 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q) 5816 SDValue Fold = 5817 DAG.getSetCC(DL, SETCCVT, Op0, QVal, 5818 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 5819 5820 // If we didn't have lanes with INT_MIN divisor, then we're done. 5821 if (!HadIntMinDivisor) 5822 return Fold; 5823 5824 // That fold is only valid for positive divisors. Which effectively means, 5825 // it is invalid for INT_MIN divisors. So if we have such a lane, 5826 // we must fix-up results for said lanes. 5827 assert(VT.isVector() && "Can/should only get here for vectors."); 5828 5829 if (!isOperationLegalOrCustom(ISD::SETEQ, VT) || 5830 !isOperationLegalOrCustom(ISD::AND, VT) || 5831 !isOperationLegalOrCustom(Cond, VT) || 5832 !isOperationLegalOrCustom(ISD::VSELECT, VT)) 5833 return SDValue(); 5834 5835 Created.push_back(Fold.getNode()); 5836 5837 SDValue IntMin = DAG.getConstant( 5838 APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT); 5839 SDValue IntMax = DAG.getConstant( 5840 APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT); 5841 SDValue Zero = 5842 DAG.getConstant(APInt::getNullValue(SVT.getScalarSizeInBits()), DL, VT); 5843 5844 // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded. 5845 SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ); 5846 Created.push_back(DivisorIsIntMin.getNode()); 5847 5848 // (N s% INT_MIN) ==/!= 0 <--> (N & INT_MAX) ==/!= 0 5849 SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax); 5850 Created.push_back(Masked.getNode()); 5851 SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond); 5852 Created.push_back(MaskedIsZero.getNode()); 5853 5854 // To produce final result we need to blend 2 vectors: 'SetCC' and 5855 // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick 5856 // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is 5857 // constant-folded, select can get lowered to a shuffle with constant mask. 5858 SDValue Blended = 5859 DAG.getNode(ISD::VSELECT, DL, VT, DivisorIsIntMin, MaskedIsZero, Fold); 5860 5861 return Blended; 5862 } 5863 5864 bool TargetLowering:: 5865 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 5866 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 5867 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 5868 "be a constant integer"); 5869 return true; 5870 } 5871 5872 return false; 5873 } 5874 5875 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 5876 const DenormalMode &Mode) const { 5877 SDLoc DL(Op); 5878 EVT VT = Op.getValueType(); 5879 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 5880 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 5881 // Testing it with denormal inputs to avoid wrong estimate. 5882 if (Mode.Input == DenormalMode::IEEE) { 5883 // This is specifically a check for the handling of denormal inputs, 5884 // not the result. 5885 5886 // Test = fabs(X) < SmallestNormal 5887 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 5888 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 5889 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 5890 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 5891 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 5892 } 5893 // Test = X == 0.0 5894 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 5895 } 5896 5897 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 5898 bool LegalOps, bool OptForSize, 5899 NegatibleCost &Cost, 5900 unsigned Depth) const { 5901 // fneg is removable even if it has multiple uses. 5902 if (Op.getOpcode() == ISD::FNEG) { 5903 Cost = NegatibleCost::Cheaper; 5904 return Op.getOperand(0); 5905 } 5906 5907 // Don't recurse exponentially. 5908 if (Depth > SelectionDAG::MaxRecursionDepth) 5909 return SDValue(); 5910 5911 // Pre-increment recursion depth for use in recursive calls. 5912 ++Depth; 5913 const SDNodeFlags Flags = Op->getFlags(); 5914 const TargetOptions &Options = DAG.getTarget().Options; 5915 EVT VT = Op.getValueType(); 5916 unsigned Opcode = Op.getOpcode(); 5917 5918 // Don't allow anything with multiple uses unless we know it is free. 5919 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) { 5920 bool IsFreeExtend = Opcode == ISD::FP_EXTEND && 5921 isFPExtFree(VT, Op.getOperand(0).getValueType()); 5922 if (!IsFreeExtend) 5923 return SDValue(); 5924 } 5925 5926 auto RemoveDeadNode = [&](SDValue N) { 5927 if (N && N.getNode()->use_empty()) 5928 DAG.RemoveDeadNode(N.getNode()); 5929 }; 5930 5931 SDLoc DL(Op); 5932 5933 switch (Opcode) { 5934 case ISD::ConstantFP: { 5935 // Don't invert constant FP values after legalization unless the target says 5936 // the negated constant is legal. 5937 bool IsOpLegal = 5938 isOperationLegal(ISD::ConstantFP, VT) || 5939 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT, 5940 OptForSize); 5941 5942 if (LegalOps && !IsOpLegal) 5943 break; 5944 5945 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 5946 V.changeSign(); 5947 SDValue CFP = DAG.getConstantFP(V, DL, VT); 5948 5949 // If we already have the use of the negated floating constant, it is free 5950 // to negate it even it has multiple uses. 5951 if (!Op.hasOneUse() && CFP.use_empty()) 5952 break; 5953 Cost = NegatibleCost::Neutral; 5954 return CFP; 5955 } 5956 case ISD::BUILD_VECTOR: { 5957 // Only permit BUILD_VECTOR of constants. 5958 if (llvm::any_of(Op->op_values(), [&](SDValue N) { 5959 return !N.isUndef() && !isa<ConstantFPSDNode>(N); 5960 })) 5961 break; 5962 5963 bool IsOpLegal = 5964 (isOperationLegal(ISD::ConstantFP, VT) && 5965 isOperationLegal(ISD::BUILD_VECTOR, VT)) || 5966 llvm::all_of(Op->op_values(), [&](SDValue N) { 5967 return N.isUndef() || 5968 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT, 5969 OptForSize); 5970 }); 5971 5972 if (LegalOps && !IsOpLegal) 5973 break; 5974 5975 SmallVector<SDValue, 4> Ops; 5976 for (SDValue C : Op->op_values()) { 5977 if (C.isUndef()) { 5978 Ops.push_back(C); 5979 continue; 5980 } 5981 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF(); 5982 V.changeSign(); 5983 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType())); 5984 } 5985 Cost = NegatibleCost::Neutral; 5986 return DAG.getBuildVector(VT, DL, Ops); 5987 } 5988 case ISD::FADD: { 5989 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 5990 break; 5991 5992 // After operation legalization, it might not be legal to create new FSUBs. 5993 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT)) 5994 break; 5995 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 5996 5997 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y) 5998 NegatibleCost CostX = NegatibleCost::Expensive; 5999 SDValue NegX = 6000 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6001 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X) 6002 NegatibleCost CostY = NegatibleCost::Expensive; 6003 SDValue NegY = 6004 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6005 6006 // Negate the X if its cost is less or equal than Y. 6007 if (NegX && (CostX <= CostY)) { 6008 Cost = CostX; 6009 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags); 6010 if (NegY != N) 6011 RemoveDeadNode(NegY); 6012 return N; 6013 } 6014 6015 // Negate the Y if it is not expensive. 6016 if (NegY) { 6017 Cost = CostY; 6018 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags); 6019 if (NegX != N) 6020 RemoveDeadNode(NegX); 6021 return N; 6022 } 6023 break; 6024 } 6025 case ISD::FSUB: { 6026 // We can't turn -(A-B) into B-A when we honor signed zeros. 6027 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6028 break; 6029 6030 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6031 // fold (fneg (fsub 0, Y)) -> Y 6032 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true)) 6033 if (C->isZero()) { 6034 Cost = NegatibleCost::Cheaper; 6035 return Y; 6036 } 6037 6038 // fold (fneg (fsub X, Y)) -> (fsub Y, X) 6039 Cost = NegatibleCost::Neutral; 6040 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags); 6041 } 6042 case ISD::FMUL: 6043 case ISD::FDIV: { 6044 SDValue X = Op.getOperand(0), Y = Op.getOperand(1); 6045 6046 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 6047 NegatibleCost CostX = NegatibleCost::Expensive; 6048 SDValue NegX = 6049 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6050 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 6051 NegatibleCost CostY = NegatibleCost::Expensive; 6052 SDValue NegY = 6053 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6054 6055 // Negate the X if its cost is less or equal than Y. 6056 if (NegX && (CostX <= CostY)) { 6057 Cost = CostX; 6058 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags); 6059 if (NegY != N) 6060 RemoveDeadNode(NegY); 6061 return N; 6062 } 6063 6064 // Ignore X * 2.0 because that is expected to be canonicalized to X + X. 6065 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1))) 6066 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL) 6067 break; 6068 6069 // Negate the Y if it is not expensive. 6070 if (NegY) { 6071 Cost = CostY; 6072 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags); 6073 if (NegX != N) 6074 RemoveDeadNode(NegX); 6075 return N; 6076 } 6077 break; 6078 } 6079 case ISD::FMA: 6080 case ISD::FMAD: { 6081 if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros()) 6082 break; 6083 6084 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2); 6085 NegatibleCost CostZ = NegatibleCost::Expensive; 6086 SDValue NegZ = 6087 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth); 6088 // Give up if fail to negate the Z. 6089 if (!NegZ) 6090 break; 6091 6092 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z)) 6093 NegatibleCost CostX = NegatibleCost::Expensive; 6094 SDValue NegX = 6095 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth); 6096 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z)) 6097 NegatibleCost CostY = NegatibleCost::Expensive; 6098 SDValue NegY = 6099 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth); 6100 6101 // Negate the X if its cost is less or equal than Y. 6102 if (NegX && (CostX <= CostY)) { 6103 Cost = std::min(CostX, CostZ); 6104 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags); 6105 if (NegY != N) 6106 RemoveDeadNode(NegY); 6107 return N; 6108 } 6109 6110 // Negate the Y if it is not expensive. 6111 if (NegY) { 6112 Cost = std::min(CostY, CostZ); 6113 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags); 6114 if (NegX != N) 6115 RemoveDeadNode(NegX); 6116 return N; 6117 } 6118 break; 6119 } 6120 6121 case ISD::FP_EXTEND: 6122 case ISD::FSIN: 6123 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6124 OptForSize, Cost, Depth)) 6125 return DAG.getNode(Opcode, DL, VT, NegV); 6126 break; 6127 case ISD::FP_ROUND: 6128 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps, 6129 OptForSize, Cost, Depth)) 6130 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1)); 6131 break; 6132 } 6133 6134 return SDValue(); 6135 } 6136 6137 //===----------------------------------------------------------------------===// 6138 // Legalization Utilities 6139 //===----------------------------------------------------------------------===// 6140 6141 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, 6142 SDValue LHS, SDValue RHS, 6143 SmallVectorImpl<SDValue> &Result, 6144 EVT HiLoVT, SelectionDAG &DAG, 6145 MulExpansionKind Kind, SDValue LL, 6146 SDValue LH, SDValue RL, SDValue RH) const { 6147 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 6148 Opcode == ISD::SMUL_LOHI); 6149 6150 bool HasMULHS = (Kind == MulExpansionKind::Always) || 6151 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 6152 bool HasMULHU = (Kind == MulExpansionKind::Always) || 6153 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 6154 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 6155 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 6156 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 6157 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 6158 6159 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 6160 return false; 6161 6162 unsigned OuterBitSize = VT.getScalarSizeInBits(); 6163 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 6164 6165 // LL, LH, RL, and RH must be either all NULL or all set to a value. 6166 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 6167 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 6168 6169 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 6170 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 6171 bool Signed) -> bool { 6172 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 6173 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 6174 Hi = SDValue(Lo.getNode(), 1); 6175 return true; 6176 } 6177 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 6178 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 6179 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 6180 return true; 6181 } 6182 return false; 6183 }; 6184 6185 SDValue Lo, Hi; 6186 6187 if (!LL.getNode() && !RL.getNode() && 6188 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6189 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 6190 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 6191 } 6192 6193 if (!LL.getNode()) 6194 return false; 6195 6196 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 6197 if (DAG.MaskedValueIsZero(LHS, HighMask) && 6198 DAG.MaskedValueIsZero(RHS, HighMask)) { 6199 // The inputs are both zero-extended. 6200 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 6201 Result.push_back(Lo); 6202 Result.push_back(Hi); 6203 if (Opcode != ISD::MUL) { 6204 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6205 Result.push_back(Zero); 6206 Result.push_back(Zero); 6207 } 6208 return true; 6209 } 6210 } 6211 6212 if (!VT.isVector() && Opcode == ISD::MUL && 6213 DAG.ComputeNumSignBits(LHS) > InnerBitSize && 6214 DAG.ComputeNumSignBits(RHS) > InnerBitSize) { 6215 // The input values are both sign-extended. 6216 // TODO non-MUL case? 6217 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 6218 Result.push_back(Lo); 6219 Result.push_back(Hi); 6220 return true; 6221 } 6222 } 6223 6224 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 6225 EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout()); 6226 if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) { 6227 // FIXME getShiftAmountTy does not always return a sensible result when VT 6228 // is an illegal type, and so the type may be too small to fit the shift 6229 // amount. Override it with i32. The shift will have to be legalized. 6230 ShiftAmountTy = MVT::i32; 6231 } 6232 SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy); 6233 6234 if (!LH.getNode() && !RH.getNode() && 6235 isOperationLegalOrCustom(ISD::SRL, VT) && 6236 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 6237 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 6238 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 6239 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 6240 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 6241 } 6242 6243 if (!LH.getNode()) 6244 return false; 6245 6246 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 6247 return false; 6248 6249 Result.push_back(Lo); 6250 6251 if (Opcode == ISD::MUL) { 6252 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 6253 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 6254 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 6255 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 6256 Result.push_back(Hi); 6257 return true; 6258 } 6259 6260 // Compute the full width result. 6261 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 6262 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 6263 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6264 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 6265 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 6266 }; 6267 6268 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 6269 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 6270 return false; 6271 6272 // This is effectively the add part of a multiply-add of half-sized operands, 6273 // so it cannot overflow. 6274 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 6275 6276 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 6277 return false; 6278 6279 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 6280 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6281 6282 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) && 6283 isOperationLegalOrCustom(ISD::ADDE, VT)); 6284 if (UseGlue) 6285 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 6286 Merge(Lo, Hi)); 6287 else 6288 Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next, 6289 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType)); 6290 6291 SDValue Carry = Next.getValue(1); 6292 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6293 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 6294 6295 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 6296 return false; 6297 6298 if (UseGlue) 6299 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 6300 Carry); 6301 else 6302 Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi, 6303 Zero, Carry); 6304 6305 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 6306 6307 if (Opcode == ISD::SMUL_LOHI) { 6308 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 6309 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 6310 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 6311 6312 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 6313 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 6314 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 6315 } 6316 6317 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6318 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 6319 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 6320 return true; 6321 } 6322 6323 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 6324 SelectionDAG &DAG, MulExpansionKind Kind, 6325 SDValue LL, SDValue LH, SDValue RL, 6326 SDValue RH) const { 6327 SmallVector<SDValue, 2> Result; 6328 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N), 6329 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 6330 DAG, Kind, LL, LH, RL, RH); 6331 if (Ok) { 6332 assert(Result.size() == 2); 6333 Lo = Result[0]; 6334 Hi = Result[1]; 6335 } 6336 return Ok; 6337 } 6338 6339 // Check that (every element of) Z is undef or not an exact multiple of BW. 6340 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) { 6341 return ISD::matchUnaryPredicate( 6342 Z, 6343 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; }, 6344 true); 6345 } 6346 6347 bool TargetLowering::expandFunnelShift(SDNode *Node, SDValue &Result, 6348 SelectionDAG &DAG) const { 6349 EVT VT = Node->getValueType(0); 6350 6351 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 6352 !isOperationLegalOrCustom(ISD::SRL, VT) || 6353 !isOperationLegalOrCustom(ISD::SUB, VT) || 6354 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 6355 return false; 6356 6357 SDValue X = Node->getOperand(0); 6358 SDValue Y = Node->getOperand(1); 6359 SDValue Z = Node->getOperand(2); 6360 6361 unsigned BW = VT.getScalarSizeInBits(); 6362 bool IsFSHL = Node->getOpcode() == ISD::FSHL; 6363 SDLoc DL(SDValue(Node, 0)); 6364 6365 EVT ShVT = Z.getValueType(); 6366 6367 // If a funnel shift in the other direction is more supported, use it. 6368 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL; 6369 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) && 6370 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) { 6371 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 6372 // fshl X, Y, Z -> fshr X, Y, -Z 6373 // fshr X, Y, Z -> fshl X, Y, -Z 6374 SDValue Zero = DAG.getConstant(0, DL, ShVT); 6375 Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z); 6376 } else { 6377 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z 6378 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z 6379 SDValue One = DAG.getConstant(1, DL, ShVT); 6380 if (IsFSHL) { 6381 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 6382 X = DAG.getNode(ISD::SRL, DL, VT, X, One); 6383 } else { 6384 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One); 6385 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One); 6386 } 6387 Z = DAG.getNOT(DL, Z, ShVT); 6388 } 6389 Result = DAG.getNode(RevOpcode, DL, VT, X, Y, Z); 6390 return true; 6391 } 6392 6393 SDValue ShX, ShY; 6394 SDValue ShAmt, InvShAmt; 6395 if (isNonZeroModBitWidthOrUndef(Z, BW)) { 6396 // fshl: X << C | Y >> (BW - C) 6397 // fshr: X << (BW - C) | Y >> C 6398 // where C = Z % BW is not zero 6399 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 6400 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 6401 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt); 6402 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt); 6403 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6404 } else { 6405 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW)) 6406 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW) 6407 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT); 6408 if (isPowerOf2_32(BW)) { 6409 // Z % BW -> Z & (BW - 1) 6410 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask); 6411 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1) 6412 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask); 6413 } else { 6414 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT); 6415 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 6416 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt); 6417 } 6418 6419 SDValue One = DAG.getConstant(1, DL, ShVT); 6420 if (IsFSHL) { 6421 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt); 6422 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One); 6423 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt); 6424 } else { 6425 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One); 6426 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt); 6427 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt); 6428 } 6429 } 6430 Result = DAG.getNode(ISD::OR, DL, VT, ShX, ShY); 6431 return true; 6432 } 6433 6434 // TODO: Merge with expandFunnelShift. 6435 bool TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps, 6436 SDValue &Result, SelectionDAG &DAG) const { 6437 EVT VT = Node->getValueType(0); 6438 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 6439 bool IsLeft = Node->getOpcode() == ISD::ROTL; 6440 SDValue Op0 = Node->getOperand(0); 6441 SDValue Op1 = Node->getOperand(1); 6442 SDLoc DL(SDValue(Node, 0)); 6443 6444 EVT ShVT = Op1.getValueType(); 6445 SDValue Zero = DAG.getConstant(0, DL, ShVT); 6446 6447 // If a rotate in the other direction is supported, use it. 6448 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL; 6449 if (isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) { 6450 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 6451 Result = DAG.getNode(RevRot, DL, VT, Op0, Sub); 6452 return true; 6453 } 6454 6455 if (!AllowVectorOps && VT.isVector() && 6456 (!isOperationLegalOrCustom(ISD::SHL, VT) || 6457 !isOperationLegalOrCustom(ISD::SRL, VT) || 6458 !isOperationLegalOrCustom(ISD::SUB, VT) || 6459 !isOperationLegalOrCustomOrPromote(ISD::OR, VT) || 6460 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 6461 return false; 6462 6463 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL; 6464 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL; 6465 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 6466 SDValue ShVal; 6467 SDValue HsVal; 6468 if (isPowerOf2_32(EltSizeInBits)) { 6469 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1)) 6470 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1)) 6471 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1); 6472 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC); 6473 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 6474 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC); 6475 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt); 6476 } else { 6477 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w)) 6478 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w)) 6479 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 6480 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC); 6481 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt); 6482 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt); 6483 SDValue One = DAG.getConstant(1, DL, ShVT); 6484 HsVal = 6485 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt); 6486 } 6487 Result = DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal); 6488 return true; 6489 } 6490 6491 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 6492 SelectionDAG &DAG) const { 6493 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 6494 SDValue Src = Node->getOperand(OpNo); 6495 EVT SrcVT = Src.getValueType(); 6496 EVT DstVT = Node->getValueType(0); 6497 SDLoc dl(SDValue(Node, 0)); 6498 6499 // FIXME: Only f32 to i64 conversions are supported. 6500 if (SrcVT != MVT::f32 || DstVT != MVT::i64) 6501 return false; 6502 6503 if (Node->isStrictFPOpcode()) 6504 // When a NaN is converted to an integer a trap is allowed. We can't 6505 // use this expansion here because it would eliminate that trap. Other 6506 // traps are also allowed and cannot be eliminated. See 6507 // IEEE 754-2008 sec 5.8. 6508 return false; 6509 6510 // Expand f32 -> i64 conversion 6511 // This algorithm comes from compiler-rt's implementation of fixsfdi: 6512 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c 6513 unsigned SrcEltBits = SrcVT.getScalarSizeInBits(); 6514 EVT IntVT = SrcVT.changeTypeToInteger(); 6515 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout()); 6516 6517 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 6518 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 6519 SDValue Bias = DAG.getConstant(127, dl, IntVT); 6520 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT); 6521 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT); 6522 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 6523 6524 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src); 6525 6526 SDValue ExponentBits = DAG.getNode( 6527 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 6528 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT)); 6529 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 6530 6531 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT, 6532 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 6533 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT)); 6534 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT); 6535 6536 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 6537 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 6538 DAG.getConstant(0x00800000, dl, IntVT)); 6539 6540 R = DAG.getZExtOrTrunc(R, dl, DstVT); 6541 6542 R = DAG.getSelectCC( 6543 dl, Exponent, ExponentLoBit, 6544 DAG.getNode(ISD::SHL, dl, DstVT, R, 6545 DAG.getZExtOrTrunc( 6546 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 6547 dl, IntShVT)), 6548 DAG.getNode(ISD::SRL, dl, DstVT, R, 6549 DAG.getZExtOrTrunc( 6550 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 6551 dl, IntShVT)), 6552 ISD::SETGT); 6553 6554 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT, 6555 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign); 6556 6557 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 6558 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT); 6559 return true; 6560 } 6561 6562 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result, 6563 SDValue &Chain, 6564 SelectionDAG &DAG) const { 6565 SDLoc dl(SDValue(Node, 0)); 6566 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 6567 SDValue Src = Node->getOperand(OpNo); 6568 6569 EVT SrcVT = Src.getValueType(); 6570 EVT DstVT = Node->getValueType(0); 6571 EVT SetCCVT = 6572 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 6573 EVT DstSetCCVT = 6574 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 6575 6576 // Only expand vector types if we have the appropriate vector bit operations. 6577 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT : 6578 ISD::FP_TO_SINT; 6579 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) || 6580 !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT))) 6581 return false; 6582 6583 // If the maximum float value is smaller then the signed integer range, 6584 // the destination signmask can't be represented by the float, so we can 6585 // just use FP_TO_SINT directly. 6586 const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT); 6587 APFloat APF(APFSem, APInt::getNullValue(SrcVT.getScalarSizeInBits())); 6588 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits()); 6589 if (APFloat::opOverflow & 6590 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) { 6591 if (Node->isStrictFPOpcode()) { 6592 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 6593 { Node->getOperand(0), Src }); 6594 Chain = Result.getValue(1); 6595 } else 6596 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 6597 return true; 6598 } 6599 6600 // Don't expand it if there isn't cheap fsub instruction. 6601 if (!isOperationLegalOrCustom( 6602 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT)) 6603 return false; 6604 6605 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 6606 SDValue Sel; 6607 6608 if (Node->isStrictFPOpcode()) { 6609 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 6610 Node->getOperand(0), /*IsSignaling*/ true); 6611 Chain = Sel.getValue(1); 6612 } else { 6613 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT); 6614 } 6615 6616 bool Strict = Node->isStrictFPOpcode() || 6617 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false); 6618 6619 if (Strict) { 6620 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the 6621 // signmask then offset (the result of which should be fully representable). 6622 // Sel = Src < 0x8000000000000000 6623 // FltOfs = select Sel, 0, 0x8000000000000000 6624 // IntOfs = select Sel, 0, 0x8000000000000000 6625 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 6626 6627 // TODO: Should any fast-math-flags be set for the FSUB? 6628 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel, 6629 DAG.getConstantFP(0.0, dl, SrcVT), Cst); 6630 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 6631 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel, 6632 DAG.getConstant(0, dl, DstVT), 6633 DAG.getConstant(SignMask, dl, DstVT)); 6634 SDValue SInt; 6635 if (Node->isStrictFPOpcode()) { 6636 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other }, 6637 { Chain, Src, FltOfs }); 6638 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other }, 6639 { Val.getValue(1), Val }); 6640 Chain = SInt.getValue(1); 6641 } else { 6642 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs); 6643 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val); 6644 } 6645 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 6646 } else { 6647 // Expand based on maximum range of FP_TO_SINT: 6648 // True = fp_to_sint(Src) 6649 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000) 6650 // Result = select (Src < 0x8000000000000000), True, False 6651 6652 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 6653 // TODO: Should any fast-math-flags be set for the FSUB? 6654 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, 6655 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 6656 False = DAG.getNode(ISD::XOR, dl, DstVT, False, 6657 DAG.getConstant(SignMask, dl, DstVT)); 6658 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 6659 Result = DAG.getSelect(dl, DstVT, Sel, True, False); 6660 } 6661 return true; 6662 } 6663 6664 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result, 6665 SDValue &Chain, 6666 SelectionDAG &DAG) const { 6667 // This transform is not correct for converting 0 when rounding mode is set 6668 // to round toward negative infinity which will produce -0.0. So disable under 6669 // strictfp. 6670 if (Node->isStrictFPOpcode()) 6671 return false; 6672 6673 SDValue Src = Node->getOperand(0); 6674 EVT SrcVT = Src.getValueType(); 6675 EVT DstVT = Node->getValueType(0); 6676 6677 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64) 6678 return false; 6679 6680 // Only expand vector types if we have the appropriate vector bit operations. 6681 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 6682 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 6683 !isOperationLegalOrCustom(ISD::FSUB, DstVT) || 6684 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 6685 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 6686 return false; 6687 6688 SDLoc dl(SDValue(Node, 0)); 6689 EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout()); 6690 6691 // Implementation of unsigned i64 to f64 following the algorithm in 6692 // __floatundidf in compiler_rt. This implementation performs rounding 6693 // correctly in all rounding modes with the exception of converting 0 6694 // when rounding toward negative infinity. In that case the fsub will produce 6695 // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect. 6696 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT); 6697 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP( 6698 BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT); 6699 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT); 6700 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT); 6701 SDValue HiShift = DAG.getConstant(32, dl, ShiftVT); 6702 6703 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask); 6704 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift); 6705 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52); 6706 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84); 6707 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr); 6708 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr); 6709 SDValue HiSub = 6710 DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52); 6711 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub); 6712 return true; 6713 } 6714 6715 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node, 6716 SelectionDAG &DAG) const { 6717 SDLoc dl(Node); 6718 unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ? 6719 ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 6720 EVT VT = Node->getValueType(0); 6721 6722 if (VT.isScalableVector()) 6723 report_fatal_error( 6724 "Expanding fminnum/fmaxnum for scalable vectors is undefined."); 6725 6726 if (isOperationLegalOrCustom(NewOp, VT)) { 6727 SDValue Quiet0 = Node->getOperand(0); 6728 SDValue Quiet1 = Node->getOperand(1); 6729 6730 if (!Node->getFlags().hasNoNaNs()) { 6731 // Insert canonicalizes if it's possible we need to quiet to get correct 6732 // sNaN behavior. 6733 if (!DAG.isKnownNeverSNaN(Quiet0)) { 6734 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0, 6735 Node->getFlags()); 6736 } 6737 if (!DAG.isKnownNeverSNaN(Quiet1)) { 6738 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1, 6739 Node->getFlags()); 6740 } 6741 } 6742 6743 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags()); 6744 } 6745 6746 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that 6747 // instead if there are no NaNs. 6748 if (Node->getFlags().hasNoNaNs()) { 6749 unsigned IEEE2018Op = 6750 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM; 6751 if (isOperationLegalOrCustom(IEEE2018Op, VT)) { 6752 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0), 6753 Node->getOperand(1), Node->getFlags()); 6754 } 6755 } 6756 6757 // If none of the above worked, but there are no NaNs, then expand to 6758 // a compare/select sequence. This is required for correctness since 6759 // InstCombine might have canonicalized a fcmp+select sequence to a 6760 // FMINNUM/FMAXNUM node. If we were to fall through to the default 6761 // expansion to libcall, we might introduce a link-time dependency 6762 // on libm into a file that originally did not have one. 6763 if (Node->getFlags().hasNoNaNs()) { 6764 ISD::CondCode Pred = 6765 Node->getOpcode() == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT; 6766 SDValue Op1 = Node->getOperand(0); 6767 SDValue Op2 = Node->getOperand(1); 6768 SDValue SelCC = DAG.getSelectCC(dl, Op1, Op2, Op1, Op2, Pred); 6769 // Copy FMF flags, but always set the no-signed-zeros flag 6770 // as this is implied by the FMINNUM/FMAXNUM semantics. 6771 SDNodeFlags Flags = Node->getFlags(); 6772 Flags.setNoSignedZeros(true); 6773 SelCC->setFlags(Flags); 6774 return SelCC; 6775 } 6776 6777 return SDValue(); 6778 } 6779 6780 bool TargetLowering::expandCTPOP(SDNode *Node, SDValue &Result, 6781 SelectionDAG &DAG) const { 6782 SDLoc dl(Node); 6783 EVT VT = Node->getValueType(0); 6784 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6785 SDValue Op = Node->getOperand(0); 6786 unsigned Len = VT.getScalarSizeInBits(); 6787 assert(VT.isInteger() && "CTPOP not implemented for this type."); 6788 6789 // TODO: Add support for irregular type lengths. 6790 if (!(Len <= 128 && Len % 8 == 0)) 6791 return false; 6792 6793 // Only expand vector types if we have the appropriate vector bit operations. 6794 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::ADD, VT) || 6795 !isOperationLegalOrCustom(ISD::SUB, VT) || 6796 !isOperationLegalOrCustom(ISD::SRL, VT) || 6797 (Len != 8 && !isOperationLegalOrCustom(ISD::MUL, VT)) || 6798 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 6799 return false; 6800 6801 // This is the "best" algorithm from 6802 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 6803 SDValue Mask55 = 6804 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 6805 SDValue Mask33 = 6806 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 6807 SDValue Mask0F = 6808 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 6809 SDValue Mask01 = 6810 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 6811 6812 // v = v - ((v >> 1) & 0x55555555...) 6813 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 6814 DAG.getNode(ISD::AND, dl, VT, 6815 DAG.getNode(ISD::SRL, dl, VT, Op, 6816 DAG.getConstant(1, dl, ShVT)), 6817 Mask55)); 6818 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 6819 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 6820 DAG.getNode(ISD::AND, dl, VT, 6821 DAG.getNode(ISD::SRL, dl, VT, Op, 6822 DAG.getConstant(2, dl, ShVT)), 6823 Mask33)); 6824 // v = (v + (v >> 4)) & 0x0F0F0F0F... 6825 Op = DAG.getNode(ISD::AND, dl, VT, 6826 DAG.getNode(ISD::ADD, dl, VT, Op, 6827 DAG.getNode(ISD::SRL, dl, VT, Op, 6828 DAG.getConstant(4, dl, ShVT))), 6829 Mask0F); 6830 // v = (v * 0x01010101...) >> (Len - 8) 6831 if (Len > 8) 6832 Op = 6833 DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::MUL, dl, VT, Op, Mask01), 6834 DAG.getConstant(Len - 8, dl, ShVT)); 6835 6836 Result = Op; 6837 return true; 6838 } 6839 6840 bool TargetLowering::expandCTLZ(SDNode *Node, SDValue &Result, 6841 SelectionDAG &DAG) const { 6842 SDLoc dl(Node); 6843 EVT VT = Node->getValueType(0); 6844 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6845 SDValue Op = Node->getOperand(0); 6846 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 6847 6848 // If the non-ZERO_UNDEF version is supported we can use that instead. 6849 if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF && 6850 isOperationLegalOrCustom(ISD::CTLZ, VT)) { 6851 Result = DAG.getNode(ISD::CTLZ, dl, VT, Op); 6852 return true; 6853 } 6854 6855 // If the ZERO_UNDEF version is supported use that and handle the zero case. 6856 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 6857 EVT SetCCVT = 6858 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6859 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 6860 SDValue Zero = DAG.getConstant(0, dl, VT); 6861 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 6862 Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero, 6863 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ); 6864 return true; 6865 } 6866 6867 // Only expand vector types if we have the appropriate vector bit operations. 6868 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 6869 !isOperationLegalOrCustom(ISD::CTPOP, VT) || 6870 !isOperationLegalOrCustom(ISD::SRL, VT) || 6871 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 6872 return false; 6873 6874 // for now, we do this: 6875 // x = x | (x >> 1); 6876 // x = x | (x >> 2); 6877 // ... 6878 // x = x | (x >>16); 6879 // x = x | (x >>32); // for 64-bit input 6880 // return popcount(~x); 6881 // 6882 // Ref: "Hacker's Delight" by Henry Warren 6883 for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) { 6884 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 6885 Op = DAG.getNode(ISD::OR, dl, VT, Op, 6886 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp)); 6887 } 6888 Op = DAG.getNOT(dl, Op, VT); 6889 Result = DAG.getNode(ISD::CTPOP, dl, VT, Op); 6890 return true; 6891 } 6892 6893 bool TargetLowering::expandCTTZ(SDNode *Node, SDValue &Result, 6894 SelectionDAG &DAG) const { 6895 SDLoc dl(Node); 6896 EVT VT = Node->getValueType(0); 6897 SDValue Op = Node->getOperand(0); 6898 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 6899 6900 // If the non-ZERO_UNDEF version is supported we can use that instead. 6901 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF && 6902 isOperationLegalOrCustom(ISD::CTTZ, VT)) { 6903 Result = DAG.getNode(ISD::CTTZ, dl, VT, Op); 6904 return true; 6905 } 6906 6907 // If the ZERO_UNDEF version is supported use that and handle the zero case. 6908 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) { 6909 EVT SetCCVT = 6910 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6911 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op); 6912 SDValue Zero = DAG.getConstant(0, dl, VT); 6913 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 6914 Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero, 6915 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ); 6916 return true; 6917 } 6918 6919 // Only expand vector types if we have the appropriate vector bit operations. 6920 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 6921 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 6922 !isOperationLegalOrCustom(ISD::CTLZ, VT)) || 6923 !isOperationLegalOrCustom(ISD::SUB, VT) || 6924 !isOperationLegalOrCustomOrPromote(ISD::AND, VT) || 6925 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 6926 return false; 6927 6928 // for now, we use: { return popcount(~x & (x - 1)); } 6929 // unless the target has ctlz but not ctpop, in which case we use: 6930 // { return 32 - nlz(~x & (x-1)); } 6931 // Ref: "Hacker's Delight" by Henry Warren 6932 SDValue Tmp = DAG.getNode( 6933 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT), 6934 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT))); 6935 6936 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 6937 if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) { 6938 Result = 6939 DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT), 6940 DAG.getNode(ISD::CTLZ, dl, VT, Tmp)); 6941 return true; 6942 } 6943 6944 Result = DAG.getNode(ISD::CTPOP, dl, VT, Tmp); 6945 return true; 6946 } 6947 6948 bool TargetLowering::expandABS(SDNode *N, SDValue &Result, 6949 SelectionDAG &DAG, bool IsNegative) const { 6950 SDLoc dl(N); 6951 EVT VT = N->getValueType(0); 6952 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 6953 SDValue Op = N->getOperand(0); 6954 6955 // abs(x) -> smax(x,sub(0,x)) 6956 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 6957 isOperationLegal(ISD::SMAX, VT)) { 6958 SDValue Zero = DAG.getConstant(0, dl, VT); 6959 Result = DAG.getNode(ISD::SMAX, dl, VT, Op, 6960 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 6961 return true; 6962 } 6963 6964 // abs(x) -> umin(x,sub(0,x)) 6965 if (!IsNegative && isOperationLegal(ISD::SUB, VT) && 6966 isOperationLegal(ISD::UMIN, VT)) { 6967 SDValue Zero = DAG.getConstant(0, dl, VT); 6968 Result = DAG.getNode(ISD::UMIN, dl, VT, Op, 6969 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 6970 return true; 6971 } 6972 6973 // 0 - abs(x) -> smin(x, sub(0,x)) 6974 if (IsNegative && isOperationLegal(ISD::SUB, VT) && 6975 isOperationLegal(ISD::SMIN, VT)) { 6976 SDValue Zero = DAG.getConstant(0, dl, VT); 6977 Result = DAG.getNode(ISD::SMIN, dl, VT, Op, 6978 DAG.getNode(ISD::SUB, dl, VT, Zero, Op)); 6979 return true; 6980 } 6981 6982 // Only expand vector types if we have the appropriate vector operations. 6983 if (VT.isVector() && 6984 (!isOperationLegalOrCustom(ISD::SRA, VT) || 6985 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) || 6986 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) || 6987 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 6988 return false; 6989 6990 SDValue Shift = 6991 DAG.getNode(ISD::SRA, dl, VT, Op, 6992 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT)); 6993 if (!IsNegative) { 6994 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, Op, Shift); 6995 Result = DAG.getNode(ISD::XOR, dl, VT, Add, Shift); 6996 } else { 6997 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y)) 6998 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift); 6999 Result = DAG.getNode(ISD::SUB, dl, VT, Shift, Xor); 7000 } 7001 return true; 7002 } 7003 7004 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const { 7005 SDLoc dl(N); 7006 EVT VT = N->getValueType(0); 7007 SDValue Op = N->getOperand(0); 7008 7009 if (!VT.isSimple()) 7010 return SDValue(); 7011 7012 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout()); 7013 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 7014 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 7015 default: 7016 return SDValue(); 7017 case MVT::i16: 7018 // Use a rotate by 8. This can be further expanded if necessary. 7019 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7020 case MVT::i32: 7021 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7022 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7023 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7024 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7025 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 7026 DAG.getConstant(0xFF0000, dl, VT)); 7027 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT)); 7028 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 7029 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 7030 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 7031 case MVT::i64: 7032 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 7033 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 7034 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7035 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7036 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 7037 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 7038 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 7039 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 7040 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, 7041 DAG.getConstant(255ULL<<48, dl, VT)); 7042 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, 7043 DAG.getConstant(255ULL<<40, dl, VT)); 7044 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, 7045 DAG.getConstant(255ULL<<32, dl, VT)); 7046 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, 7047 DAG.getConstant(255ULL<<24, dl, VT)); 7048 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 7049 DAG.getConstant(255ULL<<16, dl, VT)); 7050 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, 7051 DAG.getConstant(255ULL<<8 , dl, VT)); 7052 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7); 7053 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5); 7054 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 7055 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 7056 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6); 7057 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 7058 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4); 7059 } 7060 } 7061 7062 std::pair<SDValue, SDValue> 7063 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 7064 SelectionDAG &DAG) const { 7065 SDLoc SL(LD); 7066 SDValue Chain = LD->getChain(); 7067 SDValue BasePTR = LD->getBasePtr(); 7068 EVT SrcVT = LD->getMemoryVT(); 7069 EVT DstVT = LD->getValueType(0); 7070 ISD::LoadExtType ExtType = LD->getExtensionType(); 7071 7072 if (SrcVT.isScalableVector()) 7073 report_fatal_error("Cannot scalarize scalable vector loads"); 7074 7075 unsigned NumElem = SrcVT.getVectorNumElements(); 7076 7077 EVT SrcEltVT = SrcVT.getScalarType(); 7078 EVT DstEltVT = DstVT.getScalarType(); 7079 7080 // A vector must always be stored in memory as-is, i.e. without any padding 7081 // between the elements, since various code depend on it, e.g. in the 7082 // handling of a bitcast of a vector type to int, which may be done with a 7083 // vector store followed by an integer load. A vector that does not have 7084 // elements that are byte-sized must therefore be stored as an integer 7085 // built out of the extracted vector elements. 7086 if (!SrcEltVT.isByteSized()) { 7087 unsigned NumLoadBits = SrcVT.getStoreSizeInBits(); 7088 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits); 7089 7090 unsigned NumSrcBits = SrcVT.getSizeInBits(); 7091 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits); 7092 7093 unsigned SrcEltBits = SrcEltVT.getSizeInBits(); 7094 SDValue SrcEltBitMask = DAG.getConstant( 7095 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT); 7096 7097 // Load the whole vector and avoid masking off the top bits as it makes 7098 // the codegen worse. 7099 SDValue Load = 7100 DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, 7101 LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(), 7102 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 7103 7104 SmallVector<SDValue, 8> Vals; 7105 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7106 unsigned ShiftIntoIdx = 7107 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 7108 SDValue ShiftAmount = 7109 DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(), 7110 LoadVT, SL, /*LegalTypes=*/false); 7111 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount); 7112 SDValue Elt = 7113 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask); 7114 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt); 7115 7116 if (ExtType != ISD::NON_EXTLOAD) { 7117 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType); 7118 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar); 7119 } 7120 7121 Vals.push_back(Scalar); 7122 } 7123 7124 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 7125 return std::make_pair(Value, Load.getValue(1)); 7126 } 7127 7128 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 7129 assert(SrcEltVT.isByteSized()); 7130 7131 SmallVector<SDValue, 8> Vals; 7132 SmallVector<SDValue, 8> LoadChains; 7133 7134 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7135 SDValue ScalarLoad = 7136 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 7137 LD->getPointerInfo().getWithOffset(Idx * Stride), 7138 SrcEltVT, LD->getOriginalAlign(), 7139 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 7140 7141 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride)); 7142 7143 Vals.push_back(ScalarLoad.getValue(0)); 7144 LoadChains.push_back(ScalarLoad.getValue(1)); 7145 } 7146 7147 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 7148 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals); 7149 7150 return std::make_pair(Value, NewChain); 7151 } 7152 7153 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 7154 SelectionDAG &DAG) const { 7155 SDLoc SL(ST); 7156 7157 SDValue Chain = ST->getChain(); 7158 SDValue BasePtr = ST->getBasePtr(); 7159 SDValue Value = ST->getValue(); 7160 EVT StVT = ST->getMemoryVT(); 7161 7162 if (StVT.isScalableVector()) 7163 report_fatal_error("Cannot scalarize scalable vector stores"); 7164 7165 // The type of the data we want to save 7166 EVT RegVT = Value.getValueType(); 7167 EVT RegSclVT = RegVT.getScalarType(); 7168 7169 // The type of data as saved in memory. 7170 EVT MemSclVT = StVT.getScalarType(); 7171 7172 unsigned NumElem = StVT.getVectorNumElements(); 7173 7174 // A vector must always be stored in memory as-is, i.e. without any padding 7175 // between the elements, since various code depend on it, e.g. in the 7176 // handling of a bitcast of a vector type to int, which may be done with a 7177 // vector store followed by an integer load. A vector that does not have 7178 // elements that are byte-sized must therefore be stored as an integer 7179 // built out of the extracted vector elements. 7180 if (!MemSclVT.isByteSized()) { 7181 unsigned NumBits = StVT.getSizeInBits(); 7182 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 7183 7184 SDValue CurrVal = DAG.getConstant(0, SL, IntVT); 7185 7186 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7187 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 7188 DAG.getVectorIdxConstant(Idx, SL)); 7189 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt); 7190 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc); 7191 unsigned ShiftIntoIdx = 7192 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 7193 SDValue ShiftAmount = 7194 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT); 7195 SDValue ShiftedElt = 7196 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount); 7197 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt); 7198 } 7199 7200 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(), 7201 ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 7202 ST->getAAInfo()); 7203 } 7204 7205 // Store Stride in bytes 7206 unsigned Stride = MemSclVT.getSizeInBits() / 8; 7207 assert(Stride && "Zero stride!"); 7208 // Extract each of the elements from the original vector and save them into 7209 // memory individually. 7210 SmallVector<SDValue, 8> Stores; 7211 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 7212 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 7213 DAG.getVectorIdxConstant(Idx, SL)); 7214 7215 SDValue Ptr = 7216 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride)); 7217 7218 // This scalar TruncStore may be illegal, but we legalize it later. 7219 SDValue Store = DAG.getTruncStore( 7220 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 7221 MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(), 7222 ST->getAAInfo()); 7223 7224 Stores.push_back(Store); 7225 } 7226 7227 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 7228 } 7229 7230 std::pair<SDValue, SDValue> 7231 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 7232 assert(LD->getAddressingMode() == ISD::UNINDEXED && 7233 "unaligned indexed loads not implemented!"); 7234 SDValue Chain = LD->getChain(); 7235 SDValue Ptr = LD->getBasePtr(); 7236 EVT VT = LD->getValueType(0); 7237 EVT LoadedVT = LD->getMemoryVT(); 7238 SDLoc dl(LD); 7239 auto &MF = DAG.getMachineFunction(); 7240 7241 if (VT.isFloatingPoint() || VT.isVector()) { 7242 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 7243 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 7244 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) && 7245 LoadedVT.isVector()) { 7246 // Scalarize the load and let the individual components be handled. 7247 return scalarizeVectorLoad(LD, DAG); 7248 } 7249 7250 // Expand to a (misaligned) integer load of the same size, 7251 // then bitconvert to floating point or vector. 7252 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 7253 LD->getMemOperand()); 7254 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 7255 if (LoadedVT != VT) 7256 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 7257 ISD::ANY_EXTEND, dl, VT, Result); 7258 7259 return std::make_pair(Result, newLoad.getValue(1)); 7260 } 7261 7262 // Copy the value to a (aligned) stack slot using (unaligned) integer 7263 // loads and stores, then do a (aligned) load from the stack slot. 7264 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 7265 unsigned LoadedBytes = LoadedVT.getStoreSize(); 7266 unsigned RegBytes = RegVT.getSizeInBits() / 8; 7267 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 7268 7269 // Make sure the stack slot is also aligned for the register type. 7270 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 7271 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex(); 7272 SmallVector<SDValue, 8> Stores; 7273 SDValue StackPtr = StackBase; 7274 unsigned Offset = 0; 7275 7276 EVT PtrVT = Ptr.getValueType(); 7277 EVT StackPtrVT = StackPtr.getValueType(); 7278 7279 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 7280 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 7281 7282 // Do all but one copies using the full register width. 7283 for (unsigned i = 1; i < NumRegs; i++) { 7284 // Load one integer register's worth from the original location. 7285 SDValue Load = DAG.getLoad( 7286 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 7287 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 7288 LD->getAAInfo()); 7289 // Follow the load with a store to the stack slot. Remember the store. 7290 Stores.push_back(DAG.getStore( 7291 Load.getValue(1), dl, Load, StackPtr, 7292 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset))); 7293 // Increment the pointers. 7294 Offset += RegBytes; 7295 7296 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 7297 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 7298 } 7299 7300 // The last copy may be partial. Do an extending load. 7301 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 7302 8 * (LoadedBytes - Offset)); 7303 SDValue Load = 7304 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 7305 LD->getPointerInfo().getWithOffset(Offset), MemVT, 7306 LD->getOriginalAlign(), LD->getMemOperand()->getFlags(), 7307 LD->getAAInfo()); 7308 // Follow the load with a store to the stack slot. Remember the store. 7309 // On big-endian machines this requires a truncating store to ensure 7310 // that the bits end up in the right place. 7311 Stores.push_back(DAG.getTruncStore( 7312 Load.getValue(1), dl, Load, StackPtr, 7313 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT)); 7314 7315 // The order of the stores doesn't matter - say it with a TokenFactor. 7316 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7317 7318 // Finally, perform the original load only redirected to the stack slot. 7319 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 7320 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), 7321 LoadedVT); 7322 7323 // Callers expect a MERGE_VALUES node. 7324 return std::make_pair(Load, TF); 7325 } 7326 7327 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 7328 "Unaligned load of unsupported type."); 7329 7330 // Compute the new VT that is half the size of the old one. This is an 7331 // integer MVT. 7332 unsigned NumBits = LoadedVT.getSizeInBits(); 7333 EVT NewLoadedVT; 7334 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 7335 NumBits >>= 1; 7336 7337 Align Alignment = LD->getOriginalAlign(); 7338 unsigned IncrementSize = NumBits / 8; 7339 ISD::LoadExtType HiExtType = LD->getExtensionType(); 7340 7341 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 7342 if (HiExtType == ISD::NON_EXTLOAD) 7343 HiExtType = ISD::ZEXTLOAD; 7344 7345 // Load the value in two parts 7346 SDValue Lo, Hi; 7347 if (DAG.getDataLayout().isLittleEndian()) { 7348 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 7349 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7350 LD->getAAInfo()); 7351 7352 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 7353 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 7354 LD->getPointerInfo().getWithOffset(IncrementSize), 7355 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7356 LD->getAAInfo()); 7357 } else { 7358 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 7359 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7360 LD->getAAInfo()); 7361 7362 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 7363 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 7364 LD->getPointerInfo().getWithOffset(IncrementSize), 7365 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 7366 LD->getAAInfo()); 7367 } 7368 7369 // aggregate the two parts 7370 SDValue ShiftAmount = 7371 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(), 7372 DAG.getDataLayout())); 7373 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 7374 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 7375 7376 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 7377 Hi.getValue(1)); 7378 7379 return std::make_pair(Result, TF); 7380 } 7381 7382 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 7383 SelectionDAG &DAG) const { 7384 assert(ST->getAddressingMode() == ISD::UNINDEXED && 7385 "unaligned indexed stores not implemented!"); 7386 SDValue Chain = ST->getChain(); 7387 SDValue Ptr = ST->getBasePtr(); 7388 SDValue Val = ST->getValue(); 7389 EVT VT = Val.getValueType(); 7390 Align Alignment = ST->getOriginalAlign(); 7391 auto &MF = DAG.getMachineFunction(); 7392 EVT StoreMemVT = ST->getMemoryVT(); 7393 7394 SDLoc dl(ST); 7395 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) { 7396 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7397 if (isTypeLegal(intVT)) { 7398 if (!isOperationLegalOrCustom(ISD::STORE, intVT) && 7399 StoreMemVT.isVector()) { 7400 // Scalarize the store and let the individual components be handled. 7401 SDValue Result = scalarizeVectorStore(ST, DAG); 7402 return Result; 7403 } 7404 // Expand to a bitconvert of the value to the integer type of the 7405 // same size, then a (misaligned) int store. 7406 // FIXME: Does not handle truncating floating point stores! 7407 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 7408 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 7409 Alignment, ST->getMemOperand()->getFlags()); 7410 return Result; 7411 } 7412 // Do a (aligned) store to a stack slot, then copy from the stack slot 7413 // to the final destination using (unaligned) integer loads and stores. 7414 MVT RegVT = getRegisterType( 7415 *DAG.getContext(), 7416 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits())); 7417 EVT PtrVT = Ptr.getValueType(); 7418 unsigned StoredBytes = StoreMemVT.getStoreSize(); 7419 unsigned RegBytes = RegVT.getSizeInBits() / 8; 7420 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 7421 7422 // Make sure the stack slot is also aligned for the register type. 7423 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT); 7424 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 7425 7426 // Perform the original store, only redirected to the stack slot. 7427 SDValue Store = DAG.getTruncStore( 7428 Chain, dl, Val, StackPtr, 7429 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT); 7430 7431 EVT StackPtrVT = StackPtr.getValueType(); 7432 7433 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 7434 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 7435 SmallVector<SDValue, 8> Stores; 7436 unsigned Offset = 0; 7437 7438 // Do all but one copies using the full register width. 7439 for (unsigned i = 1; i < NumRegs; i++) { 7440 // Load one integer register's worth from the stack slot. 7441 SDValue Load = DAG.getLoad( 7442 RegVT, dl, Store, StackPtr, 7443 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)); 7444 // Store it to the final location. Remember the store. 7445 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 7446 ST->getPointerInfo().getWithOffset(Offset), 7447 ST->getOriginalAlign(), 7448 ST->getMemOperand()->getFlags())); 7449 // Increment the pointers. 7450 Offset += RegBytes; 7451 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 7452 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 7453 } 7454 7455 // The last store may be partial. Do a truncating store. On big-endian 7456 // machines this requires an extending load from the stack slot to ensure 7457 // that the bits are in the right place. 7458 EVT LoadMemVT = 7459 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset)); 7460 7461 // Load from the stack slot. 7462 SDValue Load = DAG.getExtLoad( 7463 ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 7464 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT); 7465 7466 Stores.push_back( 7467 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 7468 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT, 7469 ST->getOriginalAlign(), 7470 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 7471 // The order of the stores doesn't matter - say it with a TokenFactor. 7472 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7473 return Result; 7474 } 7475 7476 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() && 7477 "Unaligned store of unknown type."); 7478 // Get the half-size VT 7479 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext()); 7480 unsigned NumBits = NewStoredVT.getFixedSizeInBits(); 7481 unsigned IncrementSize = NumBits / 8; 7482 7483 // Divide the stored value in two parts. 7484 SDValue ShiftAmount = DAG.getConstant( 7485 NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout())); 7486 SDValue Lo = Val; 7487 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 7488 7489 // Store the two parts 7490 SDValue Store1, Store2; 7491 Store1 = DAG.getTruncStore(Chain, dl, 7492 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 7493 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 7494 ST->getMemOperand()->getFlags()); 7495 7496 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize)); 7497 Store2 = DAG.getTruncStore( 7498 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 7499 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 7500 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 7501 7502 SDValue Result = 7503 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 7504 return Result; 7505 } 7506 7507 SDValue 7508 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 7509 const SDLoc &DL, EVT DataVT, 7510 SelectionDAG &DAG, 7511 bool IsCompressedMemory) const { 7512 SDValue Increment; 7513 EVT AddrVT = Addr.getValueType(); 7514 EVT MaskVT = Mask.getValueType(); 7515 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() && 7516 "Incompatible types of Data and Mask"); 7517 if (IsCompressedMemory) { 7518 if (DataVT.isScalableVector()) 7519 report_fatal_error( 7520 "Cannot currently handle compressed memory with scalable vectors"); 7521 // Incrementing the pointer according to number of '1's in the mask. 7522 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 7523 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 7524 if (MaskIntVT.getSizeInBits() < 32) { 7525 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 7526 MaskIntVT = MVT::i32; 7527 } 7528 7529 // Count '1's with POPCNT. 7530 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 7531 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 7532 // Scale is an element size in bytes. 7533 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 7534 AddrVT); 7535 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 7536 } else if (DataVT.isScalableVector()) { 7537 Increment = DAG.getVScale(DL, AddrVT, 7538 APInt(AddrVT.getFixedSizeInBits(), 7539 DataVT.getStoreSize().getKnownMinSize())); 7540 } else 7541 Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT); 7542 7543 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 7544 } 7545 7546 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, 7547 SDValue Idx, 7548 EVT VecVT, 7549 const SDLoc &dl) { 7550 if (!VecVT.isScalableVector() && isa<ConstantSDNode>(Idx)) 7551 return Idx; 7552 7553 EVT IdxVT = Idx.getValueType(); 7554 unsigned NElts = VecVT.getVectorMinNumElements(); 7555 if (VecVT.isScalableVector()) { 7556 SDValue VS = DAG.getVScale(dl, IdxVT, 7557 APInt(IdxVT.getFixedSizeInBits(), 7558 NElts)); 7559 SDValue Sub = DAG.getNode(ISD::SUB, dl, IdxVT, VS, 7560 DAG.getConstant(1, dl, IdxVT)); 7561 7562 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub); 7563 } else { 7564 if (isPowerOf2_32(NElts)) { 7565 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), 7566 Log2_32(NElts)); 7567 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 7568 DAG.getConstant(Imm, dl, IdxVT)); 7569 } 7570 } 7571 7572 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 7573 DAG.getConstant(NElts - 1, dl, IdxVT)); 7574 } 7575 7576 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 7577 SDValue VecPtr, EVT VecVT, 7578 SDValue Index) const { 7579 SDLoc dl(Index); 7580 // Make sure the index type is big enough to compute in. 7581 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType()); 7582 7583 EVT EltVT = VecVT.getVectorElementType(); 7584 7585 // Calculate the element offset and add it to the pointer. 7586 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size. 7587 assert(EltSize * 8 == EltVT.getFixedSizeInBits() && 7588 "Converting bits to bytes lost precision"); 7589 7590 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl); 7591 7592 EVT IdxVT = Index.getValueType(); 7593 7594 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 7595 DAG.getConstant(EltSize, dl, IdxVT)); 7596 return DAG.getMemBasePlusOffset(VecPtr, Index, dl); 7597 } 7598 7599 //===----------------------------------------------------------------------===// 7600 // Implementation of Emulated TLS Model 7601 //===----------------------------------------------------------------------===// 7602 7603 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 7604 SelectionDAG &DAG) const { 7605 // Access to address of TLS varialbe xyz is lowered to a function call: 7606 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 7607 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7608 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 7609 SDLoc dl(GA); 7610 7611 ArgListTy Args; 7612 ArgListEntry Entry; 7613 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 7614 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 7615 StringRef EmuTlsVarName(NameString); 7616 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 7617 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 7618 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 7619 Entry.Ty = VoidPtrType; 7620 Args.push_back(Entry); 7621 7622 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 7623 7624 TargetLowering::CallLoweringInfo CLI(DAG); 7625 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 7626 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 7627 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7628 7629 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 7630 // At last for X86 targets, maybe good for other targets too? 7631 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7632 MFI.setAdjustsStack(true); // Is this only for X86 target? 7633 MFI.setHasCalls(true); 7634 7635 assert((GA->getOffset() == 0) && 7636 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 7637 return CallResult.first; 7638 } 7639 7640 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 7641 SelectionDAG &DAG) const { 7642 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 7643 if (!isCtlzFast()) 7644 return SDValue(); 7645 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 7646 SDLoc dl(Op); 7647 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 7648 if (C->isNullValue() && CC == ISD::SETEQ) { 7649 EVT VT = Op.getOperand(0).getValueType(); 7650 SDValue Zext = Op.getOperand(0); 7651 if (VT.bitsLT(MVT::i32)) { 7652 VT = MVT::i32; 7653 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 7654 } 7655 unsigned Log2b = Log2_32(VT.getSizeInBits()); 7656 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 7657 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 7658 DAG.getConstant(Log2b, dl, MVT::i32)); 7659 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 7660 } 7661 } 7662 return SDValue(); 7663 } 7664 7665 // Convert redundant addressing modes (e.g. scaling is redundant 7666 // when accessing bytes). 7667 ISD::MemIndexType 7668 TargetLowering::getCanonicalIndexType(ISD::MemIndexType IndexType, EVT MemVT, 7669 SDValue Offsets) const { 7670 bool IsScaledIndex = 7671 (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::UNSIGNED_SCALED); 7672 bool IsSignedIndex = 7673 (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::SIGNED_UNSCALED); 7674 7675 // Scaling is unimportant for bytes, canonicalize to unscaled. 7676 if (IsScaledIndex && MemVT.getScalarType() == MVT::i8) { 7677 IsScaledIndex = false; 7678 IndexType = IsSignedIndex ? ISD::SIGNED_UNSCALED : ISD::UNSIGNED_UNSCALED; 7679 } 7680 7681 return IndexType; 7682 } 7683 7684 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const { 7685 SDValue Op0 = Node->getOperand(0); 7686 SDValue Op1 = Node->getOperand(1); 7687 EVT VT = Op0.getValueType(); 7688 unsigned Opcode = Node->getOpcode(); 7689 SDLoc DL(Node); 7690 7691 // umin(x,y) -> sub(x,usubsat(x,y)) 7692 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) && 7693 isOperationLegal(ISD::USUBSAT, VT)) { 7694 return DAG.getNode(ISD::SUB, DL, VT, Op0, 7695 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1)); 7696 } 7697 7698 // umax(x,y) -> add(x,usubsat(y,x)) 7699 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) && 7700 isOperationLegal(ISD::USUBSAT, VT)) { 7701 return DAG.getNode(ISD::ADD, DL, VT, Op0, 7702 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0)); 7703 } 7704 7705 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 7706 ISD::CondCode CC; 7707 switch (Opcode) { 7708 default: llvm_unreachable("How did we get here?"); 7709 case ISD::SMAX: CC = ISD::SETGT; break; 7710 case ISD::SMIN: CC = ISD::SETLT; break; 7711 case ISD::UMAX: CC = ISD::SETUGT; break; 7712 case ISD::UMIN: CC = ISD::SETULT; break; 7713 } 7714 7715 // FIXME: Should really try to split the vector in case it's legal on a 7716 // subvector. 7717 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 7718 return DAG.UnrollVectorOp(Node); 7719 7720 SDValue Cond = DAG.getSetCC(DL, VT, Op0, Op1, CC); 7721 return DAG.getSelect(DL, VT, Cond, Op0, Op1); 7722 } 7723 7724 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const { 7725 unsigned Opcode = Node->getOpcode(); 7726 SDValue LHS = Node->getOperand(0); 7727 SDValue RHS = Node->getOperand(1); 7728 EVT VT = LHS.getValueType(); 7729 SDLoc dl(Node); 7730 7731 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 7732 assert(VT.isInteger() && "Expected operands to be integers"); 7733 7734 // usub.sat(a, b) -> umax(a, b) - b 7735 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) { 7736 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS); 7737 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS); 7738 } 7739 7740 // uadd.sat(a, b) -> umin(a, ~b) + b 7741 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) { 7742 SDValue InvRHS = DAG.getNOT(dl, RHS, VT); 7743 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS); 7744 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS); 7745 } 7746 7747 unsigned OverflowOp; 7748 switch (Opcode) { 7749 case ISD::SADDSAT: 7750 OverflowOp = ISD::SADDO; 7751 break; 7752 case ISD::UADDSAT: 7753 OverflowOp = ISD::UADDO; 7754 break; 7755 case ISD::SSUBSAT: 7756 OverflowOp = ISD::SSUBO; 7757 break; 7758 case ISD::USUBSAT: 7759 OverflowOp = ISD::USUBO; 7760 break; 7761 default: 7762 llvm_unreachable("Expected method to receive signed or unsigned saturation " 7763 "addition or subtraction node."); 7764 } 7765 7766 // FIXME: Should really try to split the vector in case it's legal on a 7767 // subvector. 7768 if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT)) 7769 return DAG.UnrollVectorOp(Node); 7770 7771 unsigned BitWidth = LHS.getScalarValueSizeInBits(); 7772 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7773 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), 7774 LHS, RHS); 7775 SDValue SumDiff = Result.getValue(0); 7776 SDValue Overflow = Result.getValue(1); 7777 SDValue Zero = DAG.getConstant(0, dl, VT); 7778 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT); 7779 7780 if (Opcode == ISD::UADDSAT) { 7781 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 7782 // (LHS + RHS) | OverflowMask 7783 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 7784 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask); 7785 } 7786 // Overflow ? 0xffff.... : (LHS + RHS) 7787 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff); 7788 } else if (Opcode == ISD::USUBSAT) { 7789 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 7790 // (LHS - RHS) & ~OverflowMask 7791 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 7792 SDValue Not = DAG.getNOT(dl, OverflowMask, VT); 7793 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not); 7794 } 7795 // Overflow ? 0 : (LHS - RHS) 7796 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff); 7797 } else { 7798 // SatMax -> Overflow && SumDiff < 0 7799 // SatMin -> Overflow && SumDiff >= 0 7800 APInt MinVal = APInt::getSignedMinValue(BitWidth); 7801 APInt MaxVal = APInt::getSignedMaxValue(BitWidth); 7802 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 7803 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 7804 SDValue SumNeg = DAG.getSetCC(dl, BoolVT, SumDiff, Zero, ISD::SETLT); 7805 Result = DAG.getSelect(dl, VT, SumNeg, SatMax, SatMin); 7806 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff); 7807 } 7808 } 7809 7810 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const { 7811 unsigned Opcode = Node->getOpcode(); 7812 bool IsSigned = Opcode == ISD::SSHLSAT; 7813 SDValue LHS = Node->getOperand(0); 7814 SDValue RHS = Node->getOperand(1); 7815 EVT VT = LHS.getValueType(); 7816 SDLoc dl(Node); 7817 7818 assert((Node->getOpcode() == ISD::SSHLSAT || 7819 Node->getOpcode() == ISD::USHLSAT) && 7820 "Expected a SHLSAT opcode"); 7821 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 7822 assert(VT.isInteger() && "Expected operands to be integers"); 7823 7824 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate. 7825 7826 unsigned BW = VT.getScalarSizeInBits(); 7827 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS); 7828 SDValue Orig = 7829 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS); 7830 7831 SDValue SatVal; 7832 if (IsSigned) { 7833 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT); 7834 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT); 7835 SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT), 7836 SatMin, SatMax, ISD::SETLT); 7837 } else { 7838 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT); 7839 } 7840 Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE); 7841 7842 return Result; 7843 } 7844 7845 SDValue 7846 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const { 7847 assert((Node->getOpcode() == ISD::SMULFIX || 7848 Node->getOpcode() == ISD::UMULFIX || 7849 Node->getOpcode() == ISD::SMULFIXSAT || 7850 Node->getOpcode() == ISD::UMULFIXSAT) && 7851 "Expected a fixed point multiplication opcode"); 7852 7853 SDLoc dl(Node); 7854 SDValue LHS = Node->getOperand(0); 7855 SDValue RHS = Node->getOperand(1); 7856 EVT VT = LHS.getValueType(); 7857 unsigned Scale = Node->getConstantOperandVal(2); 7858 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT || 7859 Node->getOpcode() == ISD::UMULFIXSAT); 7860 bool Signed = (Node->getOpcode() == ISD::SMULFIX || 7861 Node->getOpcode() == ISD::SMULFIXSAT); 7862 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7863 unsigned VTSize = VT.getScalarSizeInBits(); 7864 7865 if (!Scale) { 7866 // [us]mul.fix(a, b, 0) -> mul(a, b) 7867 if (!Saturating) { 7868 if (isOperationLegalOrCustom(ISD::MUL, VT)) 7869 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 7870 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) { 7871 SDValue Result = 7872 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 7873 SDValue Product = Result.getValue(0); 7874 SDValue Overflow = Result.getValue(1); 7875 SDValue Zero = DAG.getConstant(0, dl, VT); 7876 7877 APInt MinVal = APInt::getSignedMinValue(VTSize); 7878 APInt MaxVal = APInt::getSignedMaxValue(VTSize); 7879 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 7880 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 7881 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Product, Zero, ISD::SETLT); 7882 Result = DAG.getSelect(dl, VT, ProdNeg, SatMax, SatMin); 7883 return DAG.getSelect(dl, VT, Overflow, Result, Product); 7884 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) { 7885 SDValue Result = 7886 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 7887 SDValue Product = Result.getValue(0); 7888 SDValue Overflow = Result.getValue(1); 7889 7890 APInt MaxVal = APInt::getMaxValue(VTSize); 7891 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 7892 return DAG.getSelect(dl, VT, Overflow, SatMax, Product); 7893 } 7894 } 7895 7896 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) && 7897 "Expected scale to be less than the number of bits if signed or at " 7898 "most the number of bits if unsigned."); 7899 assert(LHS.getValueType() == RHS.getValueType() && 7900 "Expected both operands to be the same type"); 7901 7902 // Get the upper and lower bits of the result. 7903 SDValue Lo, Hi; 7904 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI; 7905 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU; 7906 if (isOperationLegalOrCustom(LoHiOp, VT)) { 7907 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS); 7908 Lo = Result.getValue(0); 7909 Hi = Result.getValue(1); 7910 } else if (isOperationLegalOrCustom(HiOp, VT)) { 7911 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 7912 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS); 7913 } else if (VT.isVector()) { 7914 return SDValue(); 7915 } else { 7916 report_fatal_error("Unable to expand fixed point multiplication."); 7917 } 7918 7919 if (Scale == VTSize) 7920 // Result is just the top half since we'd be shifting by the width of the 7921 // operand. Overflow impossible so this works for both UMULFIX and 7922 // UMULFIXSAT. 7923 return Hi; 7924 7925 // The result will need to be shifted right by the scale since both operands 7926 // are scaled. The result is given to us in 2 halves, so we only want part of 7927 // both in the result. 7928 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 7929 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo, 7930 DAG.getConstant(Scale, dl, ShiftTy)); 7931 if (!Saturating) 7932 return Result; 7933 7934 if (!Signed) { 7935 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the 7936 // widened multiplication) aren't all zeroes. 7937 7938 // Saturate to max if ((Hi >> Scale) != 0), 7939 // which is the same as if (Hi > ((1 << Scale) - 1)) 7940 APInt MaxVal = APInt::getMaxValue(VTSize); 7941 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), 7942 dl, VT); 7943 Result = DAG.getSelectCC(dl, Hi, LowMask, 7944 DAG.getConstant(MaxVal, dl, VT), Result, 7945 ISD::SETUGT); 7946 7947 return Result; 7948 } 7949 7950 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the 7951 // widened multiplication) aren't all ones or all zeroes. 7952 7953 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT); 7954 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT); 7955 7956 if (Scale == 0) { 7957 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo, 7958 DAG.getConstant(VTSize - 1, dl, ShiftTy)); 7959 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE); 7960 // Saturated to SatMin if wide product is negative, and SatMax if wide 7961 // product is positive ... 7962 SDValue Zero = DAG.getConstant(0, dl, VT); 7963 SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax, 7964 ISD::SETLT); 7965 // ... but only if we overflowed. 7966 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result); 7967 } 7968 7969 // We handled Scale==0 above so all the bits to examine is in Hi. 7970 7971 // Saturate to max if ((Hi >> (Scale - 1)) > 0), 7972 // which is the same as if (Hi > (1 << (Scale - 1)) - 1) 7973 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), 7974 dl, VT); 7975 Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT); 7976 // Saturate to min if (Hi >> (Scale - 1)) < -1), 7977 // which is the same as if (HI < (-1 << (Scale - 1)) 7978 SDValue HighMask = 7979 DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), 7980 dl, VT); 7981 Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT); 7982 return Result; 7983 } 7984 7985 SDValue 7986 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, 7987 SDValue LHS, SDValue RHS, 7988 unsigned Scale, SelectionDAG &DAG) const { 7989 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT || 7990 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) && 7991 "Expected a fixed point division opcode"); 7992 7993 EVT VT = LHS.getValueType(); 7994 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 7995 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 7996 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 7997 7998 // If there is enough room in the type to upscale the LHS or downscale the 7999 // RHS before the division, we can perform it in this type without having to 8000 // resize. For signed operations, the LHS headroom is the number of 8001 // redundant sign bits, and for unsigned ones it is the number of zeroes. 8002 // The headroom for the RHS is the number of trailing zeroes. 8003 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1 8004 : DAG.computeKnownBits(LHS).countMinLeadingZeros(); 8005 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros(); 8006 8007 // For signed saturating operations, we need to be able to detect true integer 8008 // division overflow; that is, when you have MIN / -EPS. However, this 8009 // is undefined behavior and if we emit divisions that could take such 8010 // values it may cause undesired behavior (arithmetic exceptions on x86, for 8011 // example). 8012 // Avoid this by requiring an extra bit so that we never get this case. 8013 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale 8014 // signed saturating division, we need to emit a whopping 32-bit division. 8015 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed)) 8016 return SDValue(); 8017 8018 unsigned LHSShift = std::min(LHSLead, Scale); 8019 unsigned RHSShift = Scale - LHSShift; 8020 8021 // At this point, we know that if we shift the LHS up by LHSShift and the 8022 // RHS down by RHSShift, we can emit a regular division with a final scaling 8023 // factor of Scale. 8024 8025 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 8026 if (LHSShift) 8027 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS, 8028 DAG.getConstant(LHSShift, dl, ShiftTy)); 8029 if (RHSShift) 8030 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS, 8031 DAG.getConstant(RHSShift, dl, ShiftTy)); 8032 8033 SDValue Quot; 8034 if (Signed) { 8035 // For signed operations, if the resulting quotient is negative and the 8036 // remainder is nonzero, subtract 1 from the quotient to round towards 8037 // negative infinity. 8038 SDValue Rem; 8039 // FIXME: Ideally we would always produce an SDIVREM here, but if the 8040 // type isn't legal, SDIVREM cannot be expanded. There is no reason why 8041 // we couldn't just form a libcall, but the type legalizer doesn't do it. 8042 if (isTypeLegal(VT) && 8043 isOperationLegalOrCustom(ISD::SDIVREM, VT)) { 8044 Quot = DAG.getNode(ISD::SDIVREM, dl, 8045 DAG.getVTList(VT, VT), 8046 LHS, RHS); 8047 Rem = Quot.getValue(1); 8048 Quot = Quot.getValue(0); 8049 } else { 8050 Quot = DAG.getNode(ISD::SDIV, dl, VT, 8051 LHS, RHS); 8052 Rem = DAG.getNode(ISD::SREM, dl, VT, 8053 LHS, RHS); 8054 } 8055 SDValue Zero = DAG.getConstant(0, dl, VT); 8056 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE); 8057 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT); 8058 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT); 8059 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg); 8060 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot, 8061 DAG.getConstant(1, dl, VT)); 8062 Quot = DAG.getSelect(dl, VT, 8063 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg), 8064 Sub1, Quot); 8065 } else 8066 Quot = DAG.getNode(ISD::UDIV, dl, VT, 8067 LHS, RHS); 8068 8069 return Quot; 8070 } 8071 8072 void TargetLowering::expandUADDSUBO( 8073 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 8074 SDLoc dl(Node); 8075 SDValue LHS = Node->getOperand(0); 8076 SDValue RHS = Node->getOperand(1); 8077 bool IsAdd = Node->getOpcode() == ISD::UADDO; 8078 8079 // If ADD/SUBCARRY is legal, use that instead. 8080 unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY; 8081 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) { 8082 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1)); 8083 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(), 8084 { LHS, RHS, CarryIn }); 8085 Result = SDValue(NodeCarry.getNode(), 0); 8086 Overflow = SDValue(NodeCarry.getNode(), 1); 8087 return; 8088 } 8089 8090 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 8091 LHS.getValueType(), LHS, RHS); 8092 8093 EVT ResultType = Node->getValueType(1); 8094 EVT SetCCType = getSetCCResultType( 8095 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 8096 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 8097 SDValue SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC); 8098 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 8099 } 8100 8101 void TargetLowering::expandSADDSUBO( 8102 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 8103 SDLoc dl(Node); 8104 SDValue LHS = Node->getOperand(0); 8105 SDValue RHS = Node->getOperand(1); 8106 bool IsAdd = Node->getOpcode() == ISD::SADDO; 8107 8108 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 8109 LHS.getValueType(), LHS, RHS); 8110 8111 EVT ResultType = Node->getValueType(1); 8112 EVT OType = getSetCCResultType( 8113 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 8114 8115 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow. 8116 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT; 8117 if (isOperationLegalOrCustom(OpcSat, LHS.getValueType())) { 8118 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS); 8119 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE); 8120 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 8121 return; 8122 } 8123 8124 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 8125 8126 // For an addition, the result should be less than one of the operands (LHS) 8127 // if and only if the other operand (RHS) is negative, otherwise there will 8128 // be overflow. 8129 // For a subtraction, the result should be less than one of the operands 8130 // (LHS) if and only if the other operand (RHS) is (non-zero) positive, 8131 // otherwise there will be overflow. 8132 SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT); 8133 SDValue ConditionRHS = 8134 DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT); 8135 8136 Overflow = DAG.getBoolExtOrTrunc( 8137 DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl, 8138 ResultType, ResultType); 8139 } 8140 8141 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result, 8142 SDValue &Overflow, SelectionDAG &DAG) const { 8143 SDLoc dl(Node); 8144 EVT VT = Node->getValueType(0); 8145 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 8146 SDValue LHS = Node->getOperand(0); 8147 SDValue RHS = Node->getOperand(1); 8148 bool isSigned = Node->getOpcode() == ISD::SMULO; 8149 8150 // For power-of-two multiplications we can use a simpler shift expansion. 8151 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 8152 const APInt &C = RHSC->getAPIntValue(); 8153 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 8154 if (C.isPowerOf2()) { 8155 // smulo(x, signed_min) is same as umulo(x, signed_min). 8156 bool UseArithShift = isSigned && !C.isMinSignedValue(); 8157 EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout()); 8158 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy); 8159 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt); 8160 Overflow = DAG.getSetCC(dl, SetCCVT, 8161 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 8162 dl, VT, Result, ShiftAmt), 8163 LHS, ISD::SETNE); 8164 return true; 8165 } 8166 } 8167 8168 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2); 8169 if (VT.isVector()) 8170 WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT, 8171 VT.getVectorNumElements()); 8172 8173 SDValue BottomHalf; 8174 SDValue TopHalf; 8175 static const unsigned Ops[2][3] = 8176 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 8177 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 8178 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 8179 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 8180 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 8181 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 8182 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 8183 RHS); 8184 TopHalf = BottomHalf.getValue(1); 8185 } else if (isTypeLegal(WideVT)) { 8186 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 8187 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 8188 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 8189 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul); 8190 SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl, 8191 getShiftAmountTy(WideVT, DAG.getDataLayout())); 8192 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, 8193 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt)); 8194 } else { 8195 if (VT.isVector()) 8196 return false; 8197 8198 // We can fall back to a libcall with an illegal type for the MUL if we 8199 // have a libcall big enough. 8200 // Also, we can fall back to a division in some cases, but that's a big 8201 // performance hit in the general case. 8202 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 8203 if (WideVT == MVT::i16) 8204 LC = RTLIB::MUL_I16; 8205 else if (WideVT == MVT::i32) 8206 LC = RTLIB::MUL_I32; 8207 else if (WideVT == MVT::i64) 8208 LC = RTLIB::MUL_I64; 8209 else if (WideVT == MVT::i128) 8210 LC = RTLIB::MUL_I128; 8211 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!"); 8212 8213 SDValue HiLHS; 8214 SDValue HiRHS; 8215 if (isSigned) { 8216 // The high part is obtained by SRA'ing all but one of the bits of low 8217 // part. 8218 unsigned LoSize = VT.getFixedSizeInBits(); 8219 HiLHS = 8220 DAG.getNode(ISD::SRA, dl, VT, LHS, 8221 DAG.getConstant(LoSize - 1, dl, 8222 getPointerTy(DAG.getDataLayout()))); 8223 HiRHS = 8224 DAG.getNode(ISD::SRA, dl, VT, RHS, 8225 DAG.getConstant(LoSize - 1, dl, 8226 getPointerTy(DAG.getDataLayout()))); 8227 } else { 8228 HiLHS = DAG.getConstant(0, dl, VT); 8229 HiRHS = DAG.getConstant(0, dl, VT); 8230 } 8231 8232 // Here we're passing the 2 arguments explicitly as 4 arguments that are 8233 // pre-lowered to the correct types. This all depends upon WideVT not 8234 // being a legal type for the architecture and thus has to be split to 8235 // two arguments. 8236 SDValue Ret; 8237 TargetLowering::MakeLibCallOptions CallOptions; 8238 CallOptions.setSExt(isSigned); 8239 CallOptions.setIsPostTypeLegalization(true); 8240 if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) { 8241 // Halves of WideVT are packed into registers in different order 8242 // depending on platform endianness. This is usually handled by 8243 // the C calling convention, but we can't defer to it in 8244 // the legalizer. 8245 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS }; 8246 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 8247 } else { 8248 SDValue Args[] = { HiLHS, LHS, HiRHS, RHS }; 8249 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first; 8250 } 8251 assert(Ret.getOpcode() == ISD::MERGE_VALUES && 8252 "Ret value is a collection of constituent nodes holding result."); 8253 if (DAG.getDataLayout().isLittleEndian()) { 8254 // Same as above. 8255 BottomHalf = Ret.getOperand(0); 8256 TopHalf = Ret.getOperand(1); 8257 } else { 8258 BottomHalf = Ret.getOperand(1); 8259 TopHalf = Ret.getOperand(0); 8260 } 8261 } 8262 8263 Result = BottomHalf; 8264 if (isSigned) { 8265 SDValue ShiftAmt = DAG.getConstant( 8266 VT.getScalarSizeInBits() - 1, dl, 8267 getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout())); 8268 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt); 8269 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE); 8270 } else { 8271 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, 8272 DAG.getConstant(0, dl, VT), ISD::SETNE); 8273 } 8274 8275 // Truncate the result if SetCC returns a larger type than needed. 8276 EVT RType = Node->getValueType(1); 8277 if (RType.bitsLT(Overflow.getValueType())) 8278 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow); 8279 8280 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() && 8281 "Unexpected result type for S/UMULO legalization"); 8282 return true; 8283 } 8284 8285 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const { 8286 SDLoc dl(Node); 8287 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 8288 SDValue Op = Node->getOperand(0); 8289 EVT VT = Op.getValueType(); 8290 8291 if (VT.isScalableVector()) 8292 report_fatal_error( 8293 "Expanding reductions for scalable vectors is undefined."); 8294 8295 // Try to use a shuffle reduction for power of two vectors. 8296 if (VT.isPow2VectorType()) { 8297 while (VT.getVectorNumElements() > 1) { 8298 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 8299 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) 8300 break; 8301 8302 SDValue Lo, Hi; 8303 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl); 8304 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi); 8305 VT = HalfVT; 8306 } 8307 } 8308 8309 EVT EltVT = VT.getVectorElementType(); 8310 unsigned NumElts = VT.getVectorNumElements(); 8311 8312 SmallVector<SDValue, 8> Ops; 8313 DAG.ExtractVectorElements(Op, Ops, 0, NumElts); 8314 8315 SDValue Res = Ops[0]; 8316 for (unsigned i = 1; i < NumElts; i++) 8317 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags()); 8318 8319 // Result type may be wider than element type. 8320 if (EltVT != Node->getValueType(0)) 8321 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res); 8322 return Res; 8323 } 8324 8325 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const { 8326 SDLoc dl(Node); 8327 SDValue AccOp = Node->getOperand(0); 8328 SDValue VecOp = Node->getOperand(1); 8329 SDNodeFlags Flags = Node->getFlags(); 8330 8331 EVT VT = VecOp.getValueType(); 8332 EVT EltVT = VT.getVectorElementType(); 8333 8334 if (VT.isScalableVector()) 8335 report_fatal_error( 8336 "Expanding reductions for scalable vectors is undefined."); 8337 8338 unsigned NumElts = VT.getVectorNumElements(); 8339 8340 SmallVector<SDValue, 8> Ops; 8341 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts); 8342 8343 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode()); 8344 8345 SDValue Res = AccOp; 8346 for (unsigned i = 0; i < NumElts; i++) 8347 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags); 8348 8349 return Res; 8350 } 8351 8352 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result, 8353 SelectionDAG &DAG) const { 8354 EVT VT = Node->getValueType(0); 8355 SDLoc dl(Node); 8356 bool isSigned = Node->getOpcode() == ISD::SREM; 8357 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV; 8358 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 8359 SDValue Dividend = Node->getOperand(0); 8360 SDValue Divisor = Node->getOperand(1); 8361 if (isOperationLegalOrCustom(DivRemOpc, VT)) { 8362 SDVTList VTs = DAG.getVTList(VT, VT); 8363 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1); 8364 return true; 8365 } else if (isOperationLegalOrCustom(DivOpc, VT)) { 8366 // X % Y -> X-X/Y*Y 8367 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor); 8368 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor); 8369 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 8370 return true; 8371 } 8372 return false; 8373 } 8374 8375 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node, 8376 SelectionDAG &DAG) const { 8377 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT; 8378 SDLoc dl(SDValue(Node, 0)); 8379 SDValue Src = Node->getOperand(0); 8380 8381 // DstVT is the result type, while SatVT is the size to which we saturate 8382 EVT SrcVT = Src.getValueType(); 8383 EVT DstVT = Node->getValueType(0); 8384 8385 unsigned SatWidth = Node->getConstantOperandVal(1); 8386 unsigned DstWidth = DstVT.getScalarSizeInBits(); 8387 assert(SatWidth <= DstWidth && 8388 "Expected saturation width smaller than result width"); 8389 8390 // Determine minimum and maximum integer values and their corresponding 8391 // floating-point values. 8392 APInt MinInt, MaxInt; 8393 if (IsSigned) { 8394 MinInt = APInt::getSignedMinValue(SatWidth).sextOrSelf(DstWidth); 8395 MaxInt = APInt::getSignedMaxValue(SatWidth).sextOrSelf(DstWidth); 8396 } else { 8397 MinInt = APInt::getMinValue(SatWidth).zextOrSelf(DstWidth); 8398 MaxInt = APInt::getMaxValue(SatWidth).zextOrSelf(DstWidth); 8399 } 8400 8401 // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as 8402 // libcall emission cannot handle this. Large result types will fail. 8403 if (SrcVT == MVT::f16) { 8404 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src); 8405 SrcVT = Src.getValueType(); 8406 } 8407 8408 APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 8409 APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT)); 8410 8411 APFloat::opStatus MinStatus = 8412 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero); 8413 APFloat::opStatus MaxStatus = 8414 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero); 8415 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) && 8416 !(MaxStatus & APFloat::opStatus::opInexact); 8417 8418 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT); 8419 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT); 8420 8421 // If the integer bounds are exactly representable as floats and min/max are 8422 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence 8423 // of comparisons and selects. 8424 bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) && 8425 isOperationLegal(ISD::FMAXNUM, SrcVT); 8426 if (AreExactFloatBounds && MinMaxLegal) { 8427 SDValue Clamped = Src; 8428 8429 // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat. 8430 Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode); 8431 // Clamp by MaxFloat from above. NaN cannot occur. 8432 Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode); 8433 // Convert clamped value to integer. 8434 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, 8435 dl, DstVT, Clamped); 8436 8437 // In the unsigned case we're done, because we mapped NaN to MinFloat, 8438 // which will cast to zero. 8439 if (!IsSigned) 8440 return FpToInt; 8441 8442 // Otherwise, select 0 if Src is NaN. 8443 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 8444 return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt, 8445 ISD::CondCode::SETUO); 8446 } 8447 8448 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT); 8449 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT); 8450 8451 // Result of direct conversion. The assumption here is that the operation is 8452 // non-trapping and it's fine to apply it to an out-of-range value if we 8453 // select it away later. 8454 SDValue FpToInt = 8455 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src); 8456 8457 SDValue Select = FpToInt; 8458 8459 // If Src ULT MinFloat, select MinInt. In particular, this also selects 8460 // MinInt if Src is NaN. 8461 Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select, 8462 ISD::CondCode::SETULT); 8463 // If Src OGT MaxFloat, select MaxInt. 8464 Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select, 8465 ISD::CondCode::SETOGT); 8466 8467 // In the unsigned case we are done, because we mapped NaN to MinInt, which 8468 // is already zero. 8469 if (!IsSigned) 8470 return Select; 8471 8472 // Otherwise, select 0 if Src is NaN. 8473 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT); 8474 return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO); 8475 } 8476