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