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