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