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