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