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