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