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