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