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