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