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 MVT VecVT = Vec.getSimpleValueType(); 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 if (SimplifyDemandedVectorElts(Base, BaseElts, KnownUndef, KnownZero, TLO, 2219 Depth + 1)) 2220 return true; 2221 KnownUndef.insertBits(SubUndef, SubIdx); 2222 KnownZero.insertBits(SubZero, SubIdx); 2223 break; 2224 } 2225 case ISD::EXTRACT_SUBVECTOR: { 2226 SDValue Src = Op.getOperand(0); 2227 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 2228 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2229 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) { 2230 // Offset the demanded elts by the subvector index. 2231 uint64_t Idx = SubIdx->getZExtValue(); 2232 APInt SrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2233 APInt SrcUndef, SrcZero; 2234 if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO, 2235 Depth + 1)) 2236 return true; 2237 KnownUndef = SrcUndef.extractBits(NumElts, Idx); 2238 KnownZero = SrcZero.extractBits(NumElts, Idx); 2239 } 2240 break; 2241 } 2242 case ISD::INSERT_VECTOR_ELT: { 2243 SDValue Vec = Op.getOperand(0); 2244 SDValue Scl = Op.getOperand(1); 2245 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 2246 2247 // For a legal, constant insertion index, if we don't need this insertion 2248 // then strip it, else remove it from the demanded elts. 2249 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) { 2250 unsigned Idx = CIdx->getZExtValue(); 2251 if (!DemandedElts[Idx]) 2252 return TLO.CombineTo(Op, Vec); 2253 2254 APInt DemandedVecElts(DemandedElts); 2255 DemandedVecElts.clearBit(Idx); 2256 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef, 2257 KnownZero, TLO, Depth + 1)) 2258 return true; 2259 2260 KnownUndef.clearBit(Idx); 2261 if (Scl.isUndef()) 2262 KnownUndef.setBit(Idx); 2263 2264 KnownZero.clearBit(Idx); 2265 if (isNullConstant(Scl) || isNullFPConstant(Scl)) 2266 KnownZero.setBit(Idx); 2267 break; 2268 } 2269 2270 APInt VecUndef, VecZero; 2271 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO, 2272 Depth + 1)) 2273 return true; 2274 // Without knowing the insertion index we can't set KnownUndef/KnownZero. 2275 break; 2276 } 2277 case ISD::VSELECT: { 2278 // Try to transform the select condition based on the current demanded 2279 // elements. 2280 // TODO: If a condition element is undef, we can choose from one arm of the 2281 // select (and if one arm is undef, then we can propagate that to the 2282 // result). 2283 // TODO - add support for constant vselect masks (see IR version of this). 2284 APInt UnusedUndef, UnusedZero; 2285 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef, 2286 UnusedZero, TLO, Depth + 1)) 2287 return true; 2288 2289 // See if we can simplify either vselect operand. 2290 APInt DemandedLHS(DemandedElts); 2291 APInt DemandedRHS(DemandedElts); 2292 APInt UndefLHS, ZeroLHS; 2293 APInt UndefRHS, ZeroRHS; 2294 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS, 2295 ZeroLHS, TLO, Depth + 1)) 2296 return true; 2297 if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS, 2298 ZeroRHS, TLO, Depth + 1)) 2299 return true; 2300 2301 KnownUndef = UndefLHS & UndefRHS; 2302 KnownZero = ZeroLHS & ZeroRHS; 2303 break; 2304 } 2305 case ISD::VECTOR_SHUFFLE: { 2306 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 2307 2308 // Collect demanded elements from shuffle operands.. 2309 APInt DemandedLHS(NumElts, 0); 2310 APInt DemandedRHS(NumElts, 0); 2311 for (unsigned i = 0; i != NumElts; ++i) { 2312 int M = ShuffleMask[i]; 2313 if (M < 0 || !DemandedElts[i]) 2314 continue; 2315 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 2316 if (M < (int)NumElts) 2317 DemandedLHS.setBit(M); 2318 else 2319 DemandedRHS.setBit(M - NumElts); 2320 } 2321 2322 // See if we can simplify either shuffle operand. 2323 APInt UndefLHS, ZeroLHS; 2324 APInt UndefRHS, ZeroRHS; 2325 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS, 2326 ZeroLHS, TLO, Depth + 1)) 2327 return true; 2328 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS, 2329 ZeroRHS, TLO, Depth + 1)) 2330 return true; 2331 2332 // Simplify mask using undef elements from LHS/RHS. 2333 bool Updated = false; 2334 bool IdentityLHS = true, IdentityRHS = true; 2335 SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end()); 2336 for (unsigned i = 0; i != NumElts; ++i) { 2337 int &M = NewMask[i]; 2338 if (M < 0) 2339 continue; 2340 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) || 2341 (M >= (int)NumElts && UndefRHS[M - NumElts])) { 2342 Updated = true; 2343 M = -1; 2344 } 2345 IdentityLHS &= (M < 0) || (M == (int)i); 2346 IdentityRHS &= (M < 0) || ((M - NumElts) == i); 2347 } 2348 2349 // Update legal shuffle masks based on demanded elements if it won't reduce 2350 // to Identity which can cause premature removal of the shuffle mask. 2351 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps && 2352 isShuffleMaskLegal(NewMask, VT)) 2353 return TLO.CombineTo(Op, 2354 TLO.DAG.getVectorShuffle(VT, DL, Op.getOperand(0), 2355 Op.getOperand(1), NewMask)); 2356 2357 // Propagate undef/zero elements from LHS/RHS. 2358 for (unsigned i = 0; i != NumElts; ++i) { 2359 int M = ShuffleMask[i]; 2360 if (M < 0) { 2361 KnownUndef.setBit(i); 2362 } else if (M < (int)NumElts) { 2363 if (UndefLHS[M]) 2364 KnownUndef.setBit(i); 2365 if (ZeroLHS[M]) 2366 KnownZero.setBit(i); 2367 } else { 2368 if (UndefRHS[M - NumElts]) 2369 KnownUndef.setBit(i); 2370 if (ZeroRHS[M - NumElts]) 2371 KnownZero.setBit(i); 2372 } 2373 } 2374 break; 2375 } 2376 case ISD::ANY_EXTEND_VECTOR_INREG: 2377 case ISD::SIGN_EXTEND_VECTOR_INREG: 2378 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2379 APInt SrcUndef, SrcZero; 2380 SDValue Src = Op.getOperand(0); 2381 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2382 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts); 2383 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO, 2384 Depth + 1)) 2385 return true; 2386 KnownZero = SrcZero.zextOrTrunc(NumElts); 2387 KnownUndef = SrcUndef.zextOrTrunc(NumElts); 2388 2389 if (Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG && 2390 Op.getValueSizeInBits() == Src.getValueSizeInBits() && 2391 DemandedSrcElts == 1 && TLO.DAG.getDataLayout().isLittleEndian()) { 2392 // aext - if we just need the bottom element then we can bitcast. 2393 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src)); 2394 } 2395 2396 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { 2397 // zext(undef) upper bits are guaranteed to be zero. 2398 if (DemandedElts.isSubsetOf(KnownUndef)) 2399 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 2400 KnownUndef.clearAllBits(); 2401 } 2402 break; 2403 } 2404 2405 // TODO: There are more binop opcodes that could be handled here - MUL, MIN, 2406 // MAX, saturated math, etc. 2407 case ISD::OR: 2408 case ISD::XOR: 2409 case ISD::ADD: 2410 case ISD::SUB: 2411 case ISD::FADD: 2412 case ISD::FSUB: 2413 case ISD::FMUL: 2414 case ISD::FDIV: 2415 case ISD::FREM: { 2416 APInt UndefRHS, ZeroRHS; 2417 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, UndefRHS, 2418 ZeroRHS, TLO, Depth + 1)) 2419 return true; 2420 APInt UndefLHS, ZeroLHS; 2421 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UndefLHS, 2422 ZeroLHS, TLO, Depth + 1)) 2423 return true; 2424 2425 KnownZero = ZeroLHS & ZeroRHS; 2426 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS); 2427 break; 2428 } 2429 case ISD::SHL: 2430 case ISD::SRL: 2431 case ISD::SRA: 2432 case ISD::ROTL: 2433 case ISD::ROTR: { 2434 APInt UndefRHS, ZeroRHS; 2435 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, UndefRHS, 2436 ZeroRHS, TLO, Depth + 1)) 2437 return true; 2438 APInt UndefLHS, ZeroLHS; 2439 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UndefLHS, 2440 ZeroLHS, TLO, Depth + 1)) 2441 return true; 2442 2443 KnownZero = ZeroLHS; 2444 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop? 2445 break; 2446 } 2447 case ISD::MUL: 2448 case ISD::AND: { 2449 APInt SrcUndef, SrcZero; 2450 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, SrcUndef, 2451 SrcZero, TLO, Depth + 1)) 2452 return true; 2453 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 2454 KnownZero, TLO, Depth + 1)) 2455 return true; 2456 2457 // If either side has a zero element, then the result element is zero, even 2458 // if the other is an UNDEF. 2459 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros 2460 // and then handle 'and' nodes with the rest of the binop opcodes. 2461 KnownZero |= SrcZero; 2462 KnownUndef &= SrcUndef; 2463 KnownUndef &= ~KnownZero; 2464 break; 2465 } 2466 case ISD::TRUNCATE: 2467 case ISD::SIGN_EXTEND: 2468 case ISD::ZERO_EXTEND: 2469 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 2470 KnownZero, TLO, Depth + 1)) 2471 return true; 2472 2473 if (Op.getOpcode() == ISD::ZERO_EXTEND) { 2474 // zext(undef) upper bits are guaranteed to be zero. 2475 if (DemandedElts.isSubsetOf(KnownUndef)) 2476 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 2477 KnownUndef.clearAllBits(); 2478 } 2479 break; 2480 default: { 2481 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 2482 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef, 2483 KnownZero, TLO, Depth)) 2484 return true; 2485 } else { 2486 KnownBits Known; 2487 APInt DemandedBits = APInt::getAllOnesValue(EltSizeInBits); 2488 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known, 2489 TLO, Depth, AssumeSingleUse)) 2490 return true; 2491 } 2492 break; 2493 } 2494 } 2495 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero"); 2496 2497 // Constant fold all undef cases. 2498 // TODO: Handle zero cases as well. 2499 if (DemandedElts.isSubsetOf(KnownUndef)) 2500 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 2501 2502 return false; 2503 } 2504 2505 /// Determine which of the bits specified in Mask are known to be either zero or 2506 /// one and return them in the Known. 2507 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 2508 KnownBits &Known, 2509 const APInt &DemandedElts, 2510 const SelectionDAG &DAG, 2511 unsigned Depth) const { 2512 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2513 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2514 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2515 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2516 "Should use MaskedValueIsZero if you don't know whether Op" 2517 " is a target node!"); 2518 Known.resetAll(); 2519 } 2520 2521 void TargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 2522 KnownBits &Known, 2523 const APInt &DemandedElts, 2524 const SelectionDAG &DAG, 2525 unsigned Depth) const { 2526 assert(isa<FrameIndexSDNode>(Op) && "expected FrameIndex"); 2527 2528 if (unsigned Align = DAG.InferPtrAlignment(Op)) { 2529 // The low bits are known zero if the pointer is aligned. 2530 Known.Zero.setLowBits(Log2_32(Align)); 2531 } 2532 } 2533 2534 /// This method can be implemented by targets that want to expose additional 2535 /// information about sign bits to the DAG Combiner. 2536 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 2537 const APInt &, 2538 const SelectionDAG &, 2539 unsigned Depth) const { 2540 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2541 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2542 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2543 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2544 "Should use ComputeNumSignBits if you don't know whether Op" 2545 " is a target node!"); 2546 return 1; 2547 } 2548 2549 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode( 2550 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero, 2551 TargetLoweringOpt &TLO, unsigned Depth) const { 2552 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2553 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2554 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2555 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2556 "Should use SimplifyDemandedVectorElts if you don't know whether Op" 2557 " is a target node!"); 2558 return false; 2559 } 2560 2561 bool TargetLowering::SimplifyDemandedBitsForTargetNode( 2562 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 2563 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const { 2564 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2565 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2566 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2567 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2568 "Should use SimplifyDemandedBits if you don't know whether Op" 2569 " is a target node!"); 2570 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth); 2571 return false; 2572 } 2573 2574 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode( 2575 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 2576 SelectionDAG &DAG, unsigned Depth) const { 2577 assert( 2578 (Op.getOpcode() >= ISD::BUILTIN_OP_END || 2579 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2580 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2581 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2582 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op" 2583 " is a target node!"); 2584 return SDValue(); 2585 } 2586 2587 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const { 2588 return nullptr; 2589 } 2590 2591 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 2592 const SelectionDAG &DAG, 2593 bool SNaN, 2594 unsigned Depth) const { 2595 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2596 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2597 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2598 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2599 "Should use isKnownNeverNaN if you don't know whether Op" 2600 " is a target node!"); 2601 return false; 2602 } 2603 2604 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must 2605 // work with truncating build vectors and vectors with elements of less than 2606 // 8 bits. 2607 bool TargetLowering::isConstTrueVal(const SDNode *N) const { 2608 if (!N) 2609 return false; 2610 2611 APInt CVal; 2612 if (auto *CN = dyn_cast<ConstantSDNode>(N)) { 2613 CVal = CN->getAPIntValue(); 2614 } else if (auto *BV = dyn_cast<BuildVectorSDNode>(N)) { 2615 auto *CN = BV->getConstantSplatNode(); 2616 if (!CN) 2617 return false; 2618 2619 // If this is a truncating build vector, truncate the splat value. 2620 // Otherwise, we may fail to match the expected values below. 2621 unsigned BVEltWidth = BV->getValueType(0).getScalarSizeInBits(); 2622 CVal = CN->getAPIntValue(); 2623 if (BVEltWidth < CVal.getBitWidth()) 2624 CVal = CVal.trunc(BVEltWidth); 2625 } else { 2626 return false; 2627 } 2628 2629 switch (getBooleanContents(N->getValueType(0))) { 2630 case UndefinedBooleanContent: 2631 return CVal[0]; 2632 case ZeroOrOneBooleanContent: 2633 return CVal.isOneValue(); 2634 case ZeroOrNegativeOneBooleanContent: 2635 return CVal.isAllOnesValue(); 2636 } 2637 2638 llvm_unreachable("Invalid boolean contents"); 2639 } 2640 2641 bool TargetLowering::isConstFalseVal(const SDNode *N) const { 2642 if (!N) 2643 return false; 2644 2645 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 2646 if (!CN) { 2647 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 2648 if (!BV) 2649 return false; 2650 2651 // Only interested in constant splats, we don't care about undef 2652 // elements in identifying boolean constants and getConstantSplatNode 2653 // returns NULL if all ops are undef; 2654 CN = BV->getConstantSplatNode(); 2655 if (!CN) 2656 return false; 2657 } 2658 2659 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 2660 return !CN->getAPIntValue()[0]; 2661 2662 return CN->isNullValue(); 2663 } 2664 2665 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 2666 bool SExt) const { 2667 if (VT == MVT::i1) 2668 return N->isOne(); 2669 2670 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 2671 switch (Cnt) { 2672 case TargetLowering::ZeroOrOneBooleanContent: 2673 // An extended value of 1 is always true, unless its original type is i1, 2674 // in which case it will be sign extended to -1. 2675 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 2676 case TargetLowering::UndefinedBooleanContent: 2677 case TargetLowering::ZeroOrNegativeOneBooleanContent: 2678 return N->isAllOnesValue() && SExt; 2679 } 2680 llvm_unreachable("Unexpected enumeration."); 2681 } 2682 2683 /// This helper function of SimplifySetCC tries to optimize the comparison when 2684 /// either operand of the SetCC node is a bitwise-and instruction. 2685 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 2686 ISD::CondCode Cond, const SDLoc &DL, 2687 DAGCombinerInfo &DCI) const { 2688 // Match these patterns in any of their permutations: 2689 // (X & Y) == Y 2690 // (X & Y) != Y 2691 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 2692 std::swap(N0, N1); 2693 2694 EVT OpVT = N0.getValueType(); 2695 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 2696 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 2697 return SDValue(); 2698 2699 SDValue X, Y; 2700 if (N0.getOperand(0) == N1) { 2701 X = N0.getOperand(1); 2702 Y = N0.getOperand(0); 2703 } else if (N0.getOperand(1) == N1) { 2704 X = N0.getOperand(0); 2705 Y = N0.getOperand(1); 2706 } else { 2707 return SDValue(); 2708 } 2709 2710 SelectionDAG &DAG = DCI.DAG; 2711 SDValue Zero = DAG.getConstant(0, DL, OpVT); 2712 if (DAG.isKnownToBeAPowerOfTwo(Y)) { 2713 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 2714 // Note that where Y is variable and is known to have at most one bit set 2715 // (for example, if it is Z & 1) we cannot do this; the expressions are not 2716 // equivalent when Y == 0. 2717 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true); 2718 if (DCI.isBeforeLegalizeOps() || 2719 isCondCodeLegal(Cond, N0.getSimpleValueType())) 2720 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 2721 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 2722 // If the target supports an 'and-not' or 'and-complement' logic operation, 2723 // try to use that to make a comparison operation more efficient. 2724 // But don't do this transform if the mask is a single bit because there are 2725 // more efficient ways to deal with that case (for example, 'bt' on x86 or 2726 // 'rlwinm' on PPC). 2727 2728 // Bail out if the compare operand that we want to turn into a zero is 2729 // already a zero (otherwise, infinite loop). 2730 auto *YConst = dyn_cast<ConstantSDNode>(Y); 2731 if (YConst && YConst->isNullValue()) 2732 return SDValue(); 2733 2734 // Transform this into: ~X & Y == 0. 2735 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 2736 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 2737 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 2738 } 2739 2740 return SDValue(); 2741 } 2742 2743 /// There are multiple IR patterns that could be checking whether certain 2744 /// truncation of a signed number would be lossy or not. The pattern which is 2745 /// best at IR level, may not lower optimally. Thus, we want to unfold it. 2746 /// We are looking for the following pattern: (KeptBits is a constant) 2747 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits) 2748 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false. 2749 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0 2750 /// We will unfold it into the natural trunc+sext pattern: 2751 /// ((%x << C) a>> C) dstcond %x 2752 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x) 2753 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck( 2754 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI, 2755 const SDLoc &DL) const { 2756 // We must be comparing with a constant. 2757 ConstantSDNode *C1; 2758 if (!(C1 = dyn_cast<ConstantSDNode>(N1))) 2759 return SDValue(); 2760 2761 // N0 should be: add %x, (1 << (KeptBits-1)) 2762 if (N0->getOpcode() != ISD::ADD) 2763 return SDValue(); 2764 2765 // And we must be 'add'ing a constant. 2766 ConstantSDNode *C01; 2767 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1)))) 2768 return SDValue(); 2769 2770 SDValue X = N0->getOperand(0); 2771 EVT XVT = X.getValueType(); 2772 2773 // Validate constants ... 2774 2775 APInt I1 = C1->getAPIntValue(); 2776 2777 ISD::CondCode NewCond; 2778 if (Cond == ISD::CondCode::SETULT) { 2779 NewCond = ISD::CondCode::SETEQ; 2780 } else if (Cond == ISD::CondCode::SETULE) { 2781 NewCond = ISD::CondCode::SETEQ; 2782 // But need to 'canonicalize' the constant. 2783 I1 += 1; 2784 } else if (Cond == ISD::CondCode::SETUGT) { 2785 NewCond = ISD::CondCode::SETNE; 2786 // But need to 'canonicalize' the constant. 2787 I1 += 1; 2788 } else if (Cond == ISD::CondCode::SETUGE) { 2789 NewCond = ISD::CondCode::SETNE; 2790 } else 2791 return SDValue(); 2792 2793 APInt I01 = C01->getAPIntValue(); 2794 2795 auto checkConstants = [&I1, &I01]() -> bool { 2796 // Both of them must be power-of-two, and the constant from setcc is bigger. 2797 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2(); 2798 }; 2799 2800 if (checkConstants()) { 2801 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256 2802 } else { 2803 // What if we invert constants? (and the target predicate) 2804 I1.negate(); 2805 I01.negate(); 2806 NewCond = getSetCCInverse(NewCond, /*isInteger=*/true); 2807 if (!checkConstants()) 2808 return SDValue(); 2809 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256 2810 } 2811 2812 // They are power-of-two, so which bit is set? 2813 const unsigned KeptBits = I1.logBase2(); 2814 const unsigned KeptBitsMinusOne = I01.logBase2(); 2815 2816 // Magic! 2817 if (KeptBits != (KeptBitsMinusOne + 1)) 2818 return SDValue(); 2819 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable"); 2820 2821 // We don't want to do this in every single case. 2822 SelectionDAG &DAG = DCI.DAG; 2823 if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck( 2824 XVT, KeptBits)) 2825 return SDValue(); 2826 2827 const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits; 2828 assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable"); 2829 2830 // Unfold into: ((%x << C) a>> C) cond %x 2831 // Where 'cond' will be either 'eq' or 'ne'. 2832 SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT); 2833 SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt); 2834 SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt); 2835 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond); 2836 2837 return T2; 2838 } 2839 2840 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 2841 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift( 2842 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond, 2843 DAGCombinerInfo &DCI, const SDLoc &DL) const { 2844 assert(isConstOrConstSplat(N1C) && 2845 isConstOrConstSplat(N1C)->getAPIntValue().isNullValue() && 2846 "Should be a comparison with 0."); 2847 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 2848 "Valid only for [in]equality comparisons."); 2849 2850 unsigned NewShiftOpcode; 2851 SDValue X, C, Y; 2852 2853 SelectionDAG &DAG = DCI.DAG; 2854 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2855 2856 // Look for '(C l>>/<< Y)'. 2857 auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) { 2858 // The shift should be one-use. 2859 if (!V.hasOneUse()) 2860 return false; 2861 unsigned OldShiftOpcode = V.getOpcode(); 2862 switch (OldShiftOpcode) { 2863 case ISD::SHL: 2864 NewShiftOpcode = ISD::SRL; 2865 break; 2866 case ISD::SRL: 2867 NewShiftOpcode = ISD::SHL; 2868 break; 2869 default: 2870 return false; // must be a logical shift. 2871 } 2872 // We should be shifting a constant. 2873 // FIXME: best to use isConstantOrConstantVector(). 2874 C = V.getOperand(0); 2875 ConstantSDNode *CC = 2876 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 2877 if (!CC) 2878 return false; 2879 Y = V.getOperand(1); 2880 2881 ConstantSDNode *XC = 2882 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true); 2883 return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 2884 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG); 2885 }; 2886 2887 // LHS of comparison should be an one-use 'and'. 2888 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 2889 return SDValue(); 2890 2891 X = N0.getOperand(0); 2892 SDValue Mask = N0.getOperand(1); 2893 2894 // 'and' is commutative! 2895 if (!Match(Mask)) { 2896 std::swap(X, Mask); 2897 if (!Match(Mask)) 2898 return SDValue(); 2899 } 2900 2901 EVT VT = X.getValueType(); 2902 2903 // Produce: 2904 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0 2905 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y); 2906 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C); 2907 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond); 2908 return T2; 2909 } 2910 2911 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as 2912 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to 2913 /// handle the commuted versions of these patterns. 2914 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, 2915 ISD::CondCode Cond, const SDLoc &DL, 2916 DAGCombinerInfo &DCI) const { 2917 unsigned BOpcode = N0.getOpcode(); 2918 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) && 2919 "Unexpected binop"); 2920 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode"); 2921 2922 // (X + Y) == X --> Y == 0 2923 // (X - Y) == X --> Y == 0 2924 // (X ^ Y) == X --> Y == 0 2925 SelectionDAG &DAG = DCI.DAG; 2926 EVT OpVT = N0.getValueType(); 2927 SDValue X = N0.getOperand(0); 2928 SDValue Y = N0.getOperand(1); 2929 if (X == N1) 2930 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond); 2931 2932 if (Y != N1) 2933 return SDValue(); 2934 2935 // (X + Y) == Y --> X == 0 2936 // (X ^ Y) == Y --> X == 0 2937 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR) 2938 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond); 2939 2940 // The shift would not be valid if the operands are boolean (i1). 2941 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1) 2942 return SDValue(); 2943 2944 // (X - Y) == Y --> X == Y << 1 2945 EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(), 2946 !DCI.isBeforeLegalize()); 2947 SDValue One = DAG.getConstant(1, DL, ShiftVT); 2948 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One); 2949 if (!DCI.isCalledByLegalizer()) 2950 DCI.AddToWorklist(YShl1.getNode()); 2951 return DAG.getSetCC(DL, VT, X, YShl1, Cond); 2952 } 2953 2954 /// Try to simplify a setcc built with the specified operands and cc. If it is 2955 /// unable to simplify it, return a null SDValue. 2956 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 2957 ISD::CondCode Cond, bool foldBooleans, 2958 DAGCombinerInfo &DCI, 2959 const SDLoc &dl) const { 2960 SelectionDAG &DAG = DCI.DAG; 2961 EVT OpVT = N0.getValueType(); 2962 2963 // Constant fold or commute setcc. 2964 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl)) 2965 return Fold; 2966 2967 // Ensure that the constant occurs on the RHS and fold constant comparisons. 2968 // TODO: Handle non-splat vector constants. All undef causes trouble. 2969 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 2970 if (isConstOrConstSplat(N0) && 2971 (DCI.isBeforeLegalizeOps() || 2972 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 2973 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 2974 2975 // If we have a subtract with the same 2 non-constant operands as this setcc 2976 // -- but in reverse order -- then try to commute the operands of this setcc 2977 // to match. A matching pair of setcc (cmp) and sub may be combined into 1 2978 // instruction on some targets. 2979 if (!isConstOrConstSplat(N0) && !isConstOrConstSplat(N1) && 2980 (DCI.isBeforeLegalizeOps() || 2981 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) && 2982 DAG.getNodeIfExists(ISD::SUB, DAG.getVTList(OpVT), { N1, N0 } ) && 2983 !DAG.getNodeIfExists(ISD::SUB, DAG.getVTList(OpVT), { N0, N1 } )) 2984 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 2985 2986 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 2987 const APInt &C1 = N1C->getAPIntValue(); 2988 2989 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 2990 // equality comparison, then we're just comparing whether X itself is 2991 // zero. 2992 if (N0.getOpcode() == ISD::SRL && (C1.isNullValue() || C1.isOneValue()) && 2993 N0.getOperand(0).getOpcode() == ISD::CTLZ && 2994 N0.getOperand(1).getOpcode() == ISD::Constant) { 2995 const APInt &ShAmt = N0.getConstantOperandAPInt(1); 2996 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 2997 ShAmt == Log2_32(N0.getValueSizeInBits())) { 2998 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 2999 // (srl (ctlz x), 5) == 0 -> X != 0 3000 // (srl (ctlz x), 5) != 1 -> X != 0 3001 Cond = ISD::SETNE; 3002 } else { 3003 // (srl (ctlz x), 5) != 0 -> X == 0 3004 // (srl (ctlz x), 5) == 1 -> X == 0 3005 Cond = ISD::SETEQ; 3006 } 3007 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 3008 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), 3009 Zero, Cond); 3010 } 3011 } 3012 3013 SDValue CTPOP = N0; 3014 // Look through truncs that don't change the value of a ctpop. 3015 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE) 3016 CTPOP = N0.getOperand(0); 3017 3018 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP && 3019 (N0 == CTPOP || 3020 N0.getValueSizeInBits() > Log2_32_Ceil(CTPOP.getValueSizeInBits()))) { 3021 EVT CTVT = CTPOP.getValueType(); 3022 SDValue CTOp = CTPOP.getOperand(0); 3023 3024 // (ctpop x) u< 2 -> (x & x-1) == 0 3025 // (ctpop x) u> 1 -> (x & x-1) != 0 3026 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){ 3027 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3028 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne); 3029 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add); 3030 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 3031 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC); 3032 } 3033 3034 // If ctpop is not supported, expand a power-of-2 comparison based on it. 3035 if (C1 == 1 && !isOperationLegalOrCustom(ISD::CTPOP, CTVT) && 3036 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 3037 // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0) 3038 // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0) 3039 SDValue Zero = DAG.getConstant(0, dl, CTVT); 3040 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT); 3041 ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, true); 3042 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne); 3043 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add); 3044 SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond); 3045 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond); 3046 unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR; 3047 return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS); 3048 } 3049 } 3050 3051 // (zext x) == C --> x == (trunc C) 3052 // (sext x) == C --> x == (trunc C) 3053 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3054 DCI.isBeforeLegalize() && N0->hasOneUse()) { 3055 unsigned MinBits = N0.getValueSizeInBits(); 3056 SDValue PreExt; 3057 bool Signed = false; 3058 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 3059 // ZExt 3060 MinBits = N0->getOperand(0).getValueSizeInBits(); 3061 PreExt = N0->getOperand(0); 3062 } else if (N0->getOpcode() == ISD::AND) { 3063 // DAGCombine turns costly ZExts into ANDs 3064 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 3065 if ((C->getAPIntValue()+1).isPowerOf2()) { 3066 MinBits = C->getAPIntValue().countTrailingOnes(); 3067 PreExt = N0->getOperand(0); 3068 } 3069 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 3070 // SExt 3071 MinBits = N0->getOperand(0).getValueSizeInBits(); 3072 PreExt = N0->getOperand(0); 3073 Signed = true; 3074 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 3075 // ZEXTLOAD / SEXTLOAD 3076 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 3077 MinBits = LN0->getMemoryVT().getSizeInBits(); 3078 PreExt = N0; 3079 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 3080 Signed = true; 3081 MinBits = LN0->getMemoryVT().getSizeInBits(); 3082 PreExt = N0; 3083 } 3084 } 3085 3086 // Figure out how many bits we need to preserve this constant. 3087 unsigned ReqdBits = Signed ? 3088 C1.getBitWidth() - C1.getNumSignBits() + 1 : 3089 C1.getActiveBits(); 3090 3091 // Make sure we're not losing bits from the constant. 3092 if (MinBits > 0 && 3093 MinBits < C1.getBitWidth() && 3094 MinBits >= ReqdBits) { 3095 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 3096 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 3097 // Will get folded away. 3098 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 3099 if (MinBits == 1 && C1 == 1) 3100 // Invert the condition. 3101 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 3102 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3103 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 3104 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 3105 } 3106 3107 // If truncating the setcc operands is not desirable, we can still 3108 // simplify the expression in some cases: 3109 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 3110 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 3111 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 3112 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 3113 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 3114 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 3115 SDValue TopSetCC = N0->getOperand(0); 3116 unsigned N0Opc = N0->getOpcode(); 3117 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 3118 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 3119 TopSetCC.getOpcode() == ISD::SETCC && 3120 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 3121 (isConstFalseVal(N1C) || 3122 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 3123 3124 bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) || 3125 (!N1C->isNullValue() && Cond == ISD::SETNE); 3126 3127 if (!Inverse) 3128 return TopSetCC; 3129 3130 ISD::CondCode InvCond = ISD::getSetCCInverse( 3131 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 3132 TopSetCC.getOperand(0).getValueType().isInteger()); 3133 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 3134 TopSetCC.getOperand(1), 3135 InvCond); 3136 } 3137 } 3138 } 3139 3140 // If the LHS is '(and load, const)', the RHS is 0, the test is for 3141 // equality or unsigned, and all 1 bits of the const are in the same 3142 // partial word, see if we can shorten the load. 3143 if (DCI.isBeforeLegalize() && 3144 !ISD::isSignedIntSetCC(Cond) && 3145 N0.getOpcode() == ISD::AND && C1 == 0 && 3146 N0.getNode()->hasOneUse() && 3147 isa<LoadSDNode>(N0.getOperand(0)) && 3148 N0.getOperand(0).getNode()->hasOneUse() && 3149 isa<ConstantSDNode>(N0.getOperand(1))) { 3150 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 3151 APInt bestMask; 3152 unsigned bestWidth = 0, bestOffset = 0; 3153 if (!Lod->isVolatile() && Lod->isUnindexed()) { 3154 unsigned origWidth = N0.getValueSizeInBits(); 3155 unsigned maskWidth = origWidth; 3156 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 3157 // 8 bits, but have to be careful... 3158 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 3159 origWidth = Lod->getMemoryVT().getSizeInBits(); 3160 const APInt &Mask = N0.getConstantOperandAPInt(1); 3161 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 3162 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 3163 for (unsigned offset=0; offset<origWidth/width; offset++) { 3164 if (Mask.isSubsetOf(newMask)) { 3165 if (DAG.getDataLayout().isLittleEndian()) 3166 bestOffset = (uint64_t)offset * (width/8); 3167 else 3168 bestOffset = (origWidth/width - offset - 1) * (width/8); 3169 bestMask = Mask.lshr(offset * (width/8) * 8); 3170 bestWidth = width; 3171 break; 3172 } 3173 newMask <<= width; 3174 } 3175 } 3176 } 3177 if (bestWidth) { 3178 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 3179 if (newVT.isRound() && 3180 shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) { 3181 EVT PtrType = Lod->getOperand(1).getValueType(); 3182 SDValue Ptr = Lod->getBasePtr(); 3183 if (bestOffset != 0) 3184 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(), 3185 DAG.getConstant(bestOffset, dl, PtrType)); 3186 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset); 3187 SDValue NewLoad = DAG.getLoad( 3188 newVT, dl, Lod->getChain(), Ptr, 3189 Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign); 3190 return DAG.getSetCC(dl, VT, 3191 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 3192 DAG.getConstant(bestMask.trunc(bestWidth), 3193 dl, newVT)), 3194 DAG.getConstant(0LL, dl, newVT), Cond); 3195 } 3196 } 3197 } 3198 3199 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 3200 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 3201 unsigned InSize = N0.getOperand(0).getValueSizeInBits(); 3202 3203 // If the comparison constant has bits in the upper part, the 3204 // zero-extended value could never match. 3205 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 3206 C1.getBitWidth() - InSize))) { 3207 switch (Cond) { 3208 case ISD::SETUGT: 3209 case ISD::SETUGE: 3210 case ISD::SETEQ: 3211 return DAG.getConstant(0, dl, VT); 3212 case ISD::SETULT: 3213 case ISD::SETULE: 3214 case ISD::SETNE: 3215 return DAG.getConstant(1, dl, VT); 3216 case ISD::SETGT: 3217 case ISD::SETGE: 3218 // True if the sign bit of C1 is set. 3219 return DAG.getConstant(C1.isNegative(), dl, VT); 3220 case ISD::SETLT: 3221 case ISD::SETLE: 3222 // True if the sign bit of C1 isn't set. 3223 return DAG.getConstant(C1.isNonNegative(), dl, VT); 3224 default: 3225 break; 3226 } 3227 } 3228 3229 // Otherwise, we can perform the comparison with the low bits. 3230 switch (Cond) { 3231 case ISD::SETEQ: 3232 case ISD::SETNE: 3233 case ISD::SETUGT: 3234 case ISD::SETUGE: 3235 case ISD::SETULT: 3236 case ISD::SETULE: { 3237 EVT newVT = N0.getOperand(0).getValueType(); 3238 if (DCI.isBeforeLegalizeOps() || 3239 (isOperationLegal(ISD::SETCC, newVT) && 3240 isCondCodeLegal(Cond, newVT.getSimpleVT()))) { 3241 EVT NewSetCCVT = 3242 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT); 3243 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 3244 3245 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 3246 NewConst, Cond); 3247 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 3248 } 3249 break; 3250 } 3251 default: 3252 break; // todo, be more careful with signed comparisons 3253 } 3254 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 3255 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 3256 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 3257 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 3258 EVT ExtDstTy = N0.getValueType(); 3259 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 3260 3261 // If the constant doesn't fit into the number of bits for the source of 3262 // the sign extension, it is impossible for both sides to be equal. 3263 if (C1.getMinSignedBits() > ExtSrcTyBits) 3264 return DAG.getConstant(Cond == ISD::SETNE, dl, VT); 3265 3266 SDValue ZextOp; 3267 EVT Op0Ty = N0.getOperand(0).getValueType(); 3268 if (Op0Ty == ExtSrcTy) { 3269 ZextOp = N0.getOperand(0); 3270 } else { 3271 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 3272 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0), 3273 DAG.getConstant(Imm, dl, Op0Ty)); 3274 } 3275 if (!DCI.isCalledByLegalizer()) 3276 DCI.AddToWorklist(ZextOp.getNode()); 3277 // Otherwise, make this a use of a zext. 3278 return DAG.getSetCC(dl, VT, ZextOp, 3279 DAG.getConstant(C1 & APInt::getLowBitsSet( 3280 ExtDstTyBits, 3281 ExtSrcTyBits), 3282 dl, ExtDstTy), 3283 Cond); 3284 } else if ((N1C->isNullValue() || N1C->isOne()) && 3285 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 3286 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 3287 if (N0.getOpcode() == ISD::SETCC && 3288 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) { 3289 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne()); 3290 if (TrueWhenTrue) 3291 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 3292 // Invert the condition. 3293 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 3294 CC = ISD::getSetCCInverse(CC, 3295 N0.getOperand(0).getValueType().isInteger()); 3296 if (DCI.isBeforeLegalizeOps() || 3297 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 3298 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 3299 } 3300 3301 if ((N0.getOpcode() == ISD::XOR || 3302 (N0.getOpcode() == ISD::AND && 3303 N0.getOperand(0).getOpcode() == ISD::XOR && 3304 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 3305 isa<ConstantSDNode>(N0.getOperand(1)) && 3306 cast<ConstantSDNode>(N0.getOperand(1))->isOne()) { 3307 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 3308 // can only do this if the top bits are known zero. 3309 unsigned BitWidth = N0.getValueSizeInBits(); 3310 if (DAG.MaskedValueIsZero(N0, 3311 APInt::getHighBitsSet(BitWidth, 3312 BitWidth-1))) { 3313 // Okay, get the un-inverted input value. 3314 SDValue Val; 3315 if (N0.getOpcode() == ISD::XOR) { 3316 Val = N0.getOperand(0); 3317 } else { 3318 assert(N0.getOpcode() == ISD::AND && 3319 N0.getOperand(0).getOpcode() == ISD::XOR); 3320 // ((X^1)&1)^1 -> X & 1 3321 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 3322 N0.getOperand(0).getOperand(0), 3323 N0.getOperand(1)); 3324 } 3325 3326 return DAG.getSetCC(dl, VT, Val, N1, 3327 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3328 } 3329 } else if (N1C->isOne() && 3330 (VT == MVT::i1 || 3331 getBooleanContents(N0->getValueType(0)) == 3332 ZeroOrOneBooleanContent)) { 3333 SDValue Op0 = N0; 3334 if (Op0.getOpcode() == ISD::TRUNCATE) 3335 Op0 = Op0.getOperand(0); 3336 3337 if ((Op0.getOpcode() == ISD::XOR) && 3338 Op0.getOperand(0).getOpcode() == ISD::SETCC && 3339 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 3340 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 3341 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 3342 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1), 3343 Cond); 3344 } 3345 if (Op0.getOpcode() == ISD::AND && 3346 isa<ConstantSDNode>(Op0.getOperand(1)) && 3347 cast<ConstantSDNode>(Op0.getOperand(1))->isOne()) { 3348 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 3349 if (Op0.getValueType().bitsGT(VT)) 3350 Op0 = DAG.getNode(ISD::AND, dl, VT, 3351 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 3352 DAG.getConstant(1, dl, VT)); 3353 else if (Op0.getValueType().bitsLT(VT)) 3354 Op0 = DAG.getNode(ISD::AND, dl, VT, 3355 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 3356 DAG.getConstant(1, dl, VT)); 3357 3358 return DAG.getSetCC(dl, VT, Op0, 3359 DAG.getConstant(0, dl, Op0.getValueType()), 3360 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3361 } 3362 if (Op0.getOpcode() == ISD::AssertZext && 3363 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 3364 return DAG.getSetCC(dl, VT, Op0, 3365 DAG.getConstant(0, dl, Op0.getValueType()), 3366 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 3367 } 3368 } 3369 3370 // Given: 3371 // icmp eq/ne (urem %x, %y), 0 3372 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem': 3373 // icmp eq/ne %x, 0 3374 if (N0.getOpcode() == ISD::UREM && N1C->isNullValue() && 3375 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 3376 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0)); 3377 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1)); 3378 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2) 3379 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond); 3380 } 3381 3382 if (SDValue V = 3383 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl)) 3384 return V; 3385 } 3386 3387 // These simplifications apply to splat vectors as well. 3388 // TODO: Handle more splat vector cases. 3389 if (auto *N1C = isConstOrConstSplat(N1)) { 3390 const APInt &C1 = N1C->getAPIntValue(); 3391 3392 APInt MinVal, MaxVal; 3393 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits(); 3394 if (ISD::isSignedIntSetCC(Cond)) { 3395 MinVal = APInt::getSignedMinValue(OperandBitSize); 3396 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 3397 } else { 3398 MinVal = APInt::getMinValue(OperandBitSize); 3399 MaxVal = APInt::getMaxValue(OperandBitSize); 3400 } 3401 3402 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 3403 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 3404 // X >= MIN --> true 3405 if (C1 == MinVal) 3406 return DAG.getBoolConstant(true, dl, VT, OpVT); 3407 3408 if (!VT.isVector()) { // TODO: Support this for vectors. 3409 // X >= C0 --> X > (C0 - 1) 3410 APInt C = C1 - 1; 3411 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 3412 if ((DCI.isBeforeLegalizeOps() || 3413 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 3414 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 3415 isLegalICmpImmediate(C.getSExtValue())))) { 3416 return DAG.getSetCC(dl, VT, N0, 3417 DAG.getConstant(C, dl, N1.getValueType()), 3418 NewCC); 3419 } 3420 } 3421 } 3422 3423 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 3424 // X <= MAX --> true 3425 if (C1 == MaxVal) 3426 return DAG.getBoolConstant(true, dl, VT, OpVT); 3427 3428 // X <= C0 --> X < (C0 + 1) 3429 if (!VT.isVector()) { // TODO: Support this for vectors. 3430 APInt C = C1 + 1; 3431 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 3432 if ((DCI.isBeforeLegalizeOps() || 3433 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 3434 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 3435 isLegalICmpImmediate(C.getSExtValue())))) { 3436 return DAG.getSetCC(dl, VT, N0, 3437 DAG.getConstant(C, dl, N1.getValueType()), 3438 NewCC); 3439 } 3440 } 3441 } 3442 3443 if (Cond == ISD::SETLT || Cond == ISD::SETULT) { 3444 if (C1 == MinVal) 3445 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false 3446 3447 // TODO: Support this for vectors after legalize ops. 3448 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 3449 // Canonicalize setlt X, Max --> setne X, Max 3450 if (C1 == MaxVal) 3451 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 3452 3453 // If we have setult X, 1, turn it into seteq X, 0 3454 if (C1 == MinVal+1) 3455 return DAG.getSetCC(dl, VT, N0, 3456 DAG.getConstant(MinVal, dl, N0.getValueType()), 3457 ISD::SETEQ); 3458 } 3459 } 3460 3461 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) { 3462 if (C1 == MaxVal) 3463 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false 3464 3465 // TODO: Support this for vectors after legalize ops. 3466 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 3467 // Canonicalize setgt X, Min --> setne X, Min 3468 if (C1 == MinVal) 3469 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 3470 3471 // If we have setugt X, Max-1, turn it into seteq X, Max 3472 if (C1 == MaxVal-1) 3473 return DAG.getSetCC(dl, VT, N0, 3474 DAG.getConstant(MaxVal, dl, N0.getValueType()), 3475 ISD::SETEQ); 3476 } 3477 } 3478 3479 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) { 3480 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0 3481 if (C1.isNullValue()) 3482 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift( 3483 VT, N0, N1, Cond, DCI, dl)) 3484 return CC; 3485 } 3486 3487 // If we have "setcc X, C0", check to see if we can shrink the immediate 3488 // by changing cc. 3489 // TODO: Support this for vectors after legalize ops. 3490 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 3491 // SETUGT X, SINTMAX -> SETLT X, 0 3492 if (Cond == ISD::SETUGT && 3493 C1 == APInt::getSignedMaxValue(OperandBitSize)) 3494 return DAG.getSetCC(dl, VT, N0, 3495 DAG.getConstant(0, dl, N1.getValueType()), 3496 ISD::SETLT); 3497 3498 // SETULT X, SINTMIN -> SETGT X, -1 3499 if (Cond == ISD::SETULT && 3500 C1 == APInt::getSignedMinValue(OperandBitSize)) { 3501 SDValue ConstMinusOne = 3502 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl, 3503 N1.getValueType()); 3504 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT); 3505 } 3506 } 3507 } 3508 3509 // Back to non-vector simplifications. 3510 // TODO: Can we do these for vector splats? 3511 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 3512 const APInt &C1 = N1C->getAPIntValue(); 3513 3514 // Fold bit comparisons when we can. 3515 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3516 (VT == N0.getValueType() || 3517 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) && 3518 N0.getOpcode() == ISD::AND) { 3519 auto &DL = DAG.getDataLayout(); 3520 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3521 EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL, 3522 !DCI.isBeforeLegalize()); 3523 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 3524 // Perform the xform if the AND RHS is a single bit. 3525 if (AndRHS->getAPIntValue().isPowerOf2()) { 3526 return DAG.getNode(ISD::TRUNCATE, dl, VT, 3527 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0, 3528 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl, 3529 ShiftTy))); 3530 } 3531 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 3532 // (X & 8) == 8 --> (X & 8) >> 3 3533 // Perform the xform if C1 is a single bit. 3534 if (C1.isPowerOf2()) { 3535 return DAG.getNode(ISD::TRUNCATE, dl, VT, 3536 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0, 3537 DAG.getConstant(C1.logBase2(), dl, 3538 ShiftTy))); 3539 } 3540 } 3541 } 3542 } 3543 3544 if (C1.getMinSignedBits() <= 64 && 3545 !isLegalICmpImmediate(C1.getSExtValue())) { 3546 // (X & -256) == 256 -> (X >> 8) == 1 3547 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3548 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 3549 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3550 const APInt &AndRHSC = AndRHS->getAPIntValue(); 3551 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) { 3552 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 3553 auto &DL = DAG.getDataLayout(); 3554 EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL, 3555 !DCI.isBeforeLegalize()); 3556 EVT CmpTy = N0.getValueType(); 3557 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0), 3558 DAG.getConstant(ShiftBits, dl, 3559 ShiftTy)); 3560 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy); 3561 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 3562 } 3563 } 3564 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 3565 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 3566 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 3567 // X < 0x100000000 -> (X >> 32) < 1 3568 // X >= 0x100000000 -> (X >> 32) >= 1 3569 // X <= 0x0ffffffff -> (X >> 32) < 1 3570 // X > 0x0ffffffff -> (X >> 32) >= 1 3571 unsigned ShiftBits; 3572 APInt NewC = C1; 3573 ISD::CondCode NewCond = Cond; 3574 if (AdjOne) { 3575 ShiftBits = C1.countTrailingOnes(); 3576 NewC = NewC + 1; 3577 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3578 } else { 3579 ShiftBits = C1.countTrailingZeros(); 3580 } 3581 NewC.lshrInPlace(ShiftBits); 3582 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 3583 isLegalICmpImmediate(NewC.getSExtValue())) { 3584 auto &DL = DAG.getDataLayout(); 3585 EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL, 3586 !DCI.isBeforeLegalize()); 3587 EVT CmpTy = N0.getValueType(); 3588 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0, 3589 DAG.getConstant(ShiftBits, dl, ShiftTy)); 3590 SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy); 3591 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 3592 } 3593 } 3594 } 3595 } 3596 3597 if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) { 3598 auto *CFP = cast<ConstantFPSDNode>(N1); 3599 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value"); 3600 3601 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 3602 // constant if knowing that the operand is non-nan is enough. We prefer to 3603 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 3604 // materialize 0.0. 3605 if (Cond == ISD::SETO || Cond == ISD::SETUO) 3606 return DAG.getSetCC(dl, VT, N0, N0, Cond); 3607 3608 // setcc (fneg x), C -> setcc swap(pred) x, -C 3609 if (N0.getOpcode() == ISD::FNEG) { 3610 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 3611 if (DCI.isBeforeLegalizeOps() || 3612 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 3613 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 3614 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 3615 } 3616 } 3617 3618 // If the condition is not legal, see if we can find an equivalent one 3619 // which is legal. 3620 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 3621 // If the comparison was an awkward floating-point == or != and one of 3622 // the comparison operands is infinity or negative infinity, convert the 3623 // condition to a less-awkward <= or >=. 3624 if (CFP->getValueAPF().isInfinity()) { 3625 if (CFP->getValueAPF().isNegative()) { 3626 if (Cond == ISD::SETOEQ && 3627 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType())) 3628 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE); 3629 if (Cond == ISD::SETUEQ && 3630 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType())) 3631 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE); 3632 if (Cond == ISD::SETUNE && 3633 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType())) 3634 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT); 3635 if (Cond == ISD::SETONE && 3636 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType())) 3637 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT); 3638 } else { 3639 if (Cond == ISD::SETOEQ && 3640 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType())) 3641 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE); 3642 if (Cond == ISD::SETUEQ && 3643 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType())) 3644 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE); 3645 if (Cond == ISD::SETUNE && 3646 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType())) 3647 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT); 3648 if (Cond == ISD::SETONE && 3649 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType())) 3650 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT); 3651 } 3652 } 3653 } 3654 } 3655 3656 if (N0 == N1) { 3657 // The sext(setcc()) => setcc() optimization relies on the appropriate 3658 // constant being emitted. 3659 assert(!N0.getValueType().isInteger() && 3660 "Integer types should be handled by FoldSetCC"); 3661 3662 bool EqTrue = ISD::isTrueWhenEqual(Cond); 3663 unsigned UOF = ISD::getUnorderedFlavor(Cond); 3664 if (UOF == 2) // FP operators that are undefined on NaNs. 3665 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 3666 if (UOF == unsigned(EqTrue)) 3667 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 3668 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 3669 // if it is not already. 3670 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 3671 if (NewCond != Cond && 3672 (DCI.isBeforeLegalizeOps() || 3673 isCondCodeLegal(NewCond, N0.getSimpleValueType()))) 3674 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 3675 } 3676 3677 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 3678 N0.getValueType().isInteger()) { 3679 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 3680 N0.getOpcode() == ISD::XOR) { 3681 // Simplify (X+Y) == (X+Z) --> Y == Z 3682 if (N0.getOpcode() == N1.getOpcode()) { 3683 if (N0.getOperand(0) == N1.getOperand(0)) 3684 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 3685 if (N0.getOperand(1) == N1.getOperand(1)) 3686 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 3687 if (isCommutativeBinOp(N0.getOpcode())) { 3688 // If X op Y == Y op X, try other combinations. 3689 if (N0.getOperand(0) == N1.getOperand(1)) 3690 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 3691 Cond); 3692 if (N0.getOperand(1) == N1.getOperand(0)) 3693 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 3694 Cond); 3695 } 3696 } 3697 3698 // If RHS is a legal immediate value for a compare instruction, we need 3699 // to be careful about increasing register pressure needlessly. 3700 bool LegalRHSImm = false; 3701 3702 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 3703 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3704 // Turn (X+C1) == C2 --> X == C2-C1 3705 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) { 3706 return DAG.getSetCC(dl, VT, N0.getOperand(0), 3707 DAG.getConstant(RHSC->getAPIntValue()- 3708 LHSR->getAPIntValue(), 3709 dl, N0.getValueType()), Cond); 3710 } 3711 3712 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0. 3713 if (N0.getOpcode() == ISD::XOR) 3714 // If we know that all of the inverted bits are zero, don't bother 3715 // performing the inversion. 3716 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue())) 3717 return 3718 DAG.getSetCC(dl, VT, N0.getOperand(0), 3719 DAG.getConstant(LHSR->getAPIntValue() ^ 3720 RHSC->getAPIntValue(), 3721 dl, N0.getValueType()), 3722 Cond); 3723 } 3724 3725 // Turn (C1-X) == C2 --> X == C1-C2 3726 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) { 3727 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) { 3728 return 3729 DAG.getSetCC(dl, VT, N0.getOperand(1), 3730 DAG.getConstant(SUBC->getAPIntValue() - 3731 RHSC->getAPIntValue(), 3732 dl, N0.getValueType()), 3733 Cond); 3734 } 3735 } 3736 3737 // Could RHSC fold directly into a compare? 3738 if (RHSC->getValueType(0).getSizeInBits() <= 64) 3739 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 3740 } 3741 3742 // (X+Y) == X --> Y == 0 and similar folds. 3743 // Don't do this if X is an immediate that can fold into a cmp 3744 // instruction and X+Y has other uses. It could be an induction variable 3745 // chain, and the transform would increase register pressure. 3746 if (!LegalRHSImm || N0.hasOneUse()) 3747 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI)) 3748 return V; 3749 } 3750 3751 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 3752 N1.getOpcode() == ISD::XOR) 3753 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI)) 3754 return V; 3755 3756 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI)) 3757 return V; 3758 } 3759 3760 // Fold remainder of division by a constant. 3761 if (N0.getOpcode() == ISD::UREM && N0.hasOneUse() && 3762 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 3763 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3764 3765 // When division is cheap or optimizing for minimum size, 3766 // fall through to DIVREM creation by skipping this fold. 3767 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttribute(Attribute::MinSize)) 3768 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl)) 3769 return Folded; 3770 } 3771 3772 // Fold away ALL boolean setcc's. 3773 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) { 3774 SDValue Temp; 3775 switch (Cond) { 3776 default: llvm_unreachable("Unknown integer setcc!"); 3777 case ISD::SETEQ: // X == Y -> ~(X^Y) 3778 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 3779 N0 = DAG.getNOT(dl, Temp, OpVT); 3780 if (!DCI.isCalledByLegalizer()) 3781 DCI.AddToWorklist(Temp.getNode()); 3782 break; 3783 case ISD::SETNE: // X != Y --> (X^Y) 3784 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 3785 break; 3786 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 3787 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 3788 Temp = DAG.getNOT(dl, N0, OpVT); 3789 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp); 3790 if (!DCI.isCalledByLegalizer()) 3791 DCI.AddToWorklist(Temp.getNode()); 3792 break; 3793 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 3794 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 3795 Temp = DAG.getNOT(dl, N1, OpVT); 3796 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp); 3797 if (!DCI.isCalledByLegalizer()) 3798 DCI.AddToWorklist(Temp.getNode()); 3799 break; 3800 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 3801 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 3802 Temp = DAG.getNOT(dl, N0, OpVT); 3803 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp); 3804 if (!DCI.isCalledByLegalizer()) 3805 DCI.AddToWorklist(Temp.getNode()); 3806 break; 3807 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 3808 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 3809 Temp = DAG.getNOT(dl, N1, OpVT); 3810 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp); 3811 break; 3812 } 3813 if (VT.getScalarType() != MVT::i1) { 3814 if (!DCI.isCalledByLegalizer()) 3815 DCI.AddToWorklist(N0.getNode()); 3816 // FIXME: If running after legalize, we probably can't do this. 3817 ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT)); 3818 N0 = DAG.getNode(ExtendCode, dl, VT, N0); 3819 } 3820 return N0; 3821 } 3822 3823 // Could not fold it. 3824 return SDValue(); 3825 } 3826 3827 /// Returns true (and the GlobalValue and the offset) if the node is a 3828 /// GlobalAddress + offset. 3829 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA, 3830 int64_t &Offset) const { 3831 3832 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode(); 3833 3834 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 3835 GA = GASD->getGlobal(); 3836 Offset += GASD->getOffset(); 3837 return true; 3838 } 3839 3840 if (N->getOpcode() == ISD::ADD) { 3841 SDValue N1 = N->getOperand(0); 3842 SDValue N2 = N->getOperand(1); 3843 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 3844 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 3845 Offset += V->getSExtValue(); 3846 return true; 3847 } 3848 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 3849 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 3850 Offset += V->getSExtValue(); 3851 return true; 3852 } 3853 } 3854 } 3855 3856 return false; 3857 } 3858 3859 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 3860 DAGCombinerInfo &DCI) const { 3861 // Default implementation: no optimization. 3862 return SDValue(); 3863 } 3864 3865 //===----------------------------------------------------------------------===// 3866 // Inline Assembler Implementation Methods 3867 //===----------------------------------------------------------------------===// 3868 3869 TargetLowering::ConstraintType 3870 TargetLowering::getConstraintType(StringRef Constraint) const { 3871 unsigned S = Constraint.size(); 3872 3873 if (S == 1) { 3874 switch (Constraint[0]) { 3875 default: break; 3876 case 'r': return C_RegisterClass; 3877 case 'm': // memory 3878 case 'o': // offsetable 3879 case 'V': // not offsetable 3880 return C_Memory; 3881 case 'i': // Simple Integer or Relocatable Constant 3882 case 'n': // Simple Integer 3883 case 'E': // Floating Point Constant 3884 case 'F': // Floating Point Constant 3885 case 's': // Relocatable Constant 3886 case 'p': // Address. 3887 case 'X': // Allow ANY value. 3888 case 'I': // Target registers. 3889 case 'J': 3890 case 'K': 3891 case 'L': 3892 case 'M': 3893 case 'N': 3894 case 'O': 3895 case 'P': 3896 case '<': 3897 case '>': 3898 return C_Other; 3899 } 3900 } 3901 3902 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') { 3903 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 3904 return C_Memory; 3905 return C_Register; 3906 } 3907 return C_Unknown; 3908 } 3909 3910 /// Try to replace an X constraint, which matches anything, with another that 3911 /// has more specific requirements based on the type of the corresponding 3912 /// operand. 3913 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 3914 if (ConstraintVT.isInteger()) 3915 return "r"; 3916 if (ConstraintVT.isFloatingPoint()) 3917 return "f"; // works for many targets 3918 return nullptr; 3919 } 3920 3921 SDValue TargetLowering::LowerAsmOutputForConstraint( 3922 SDValue &Chain, SDValue &Flag, SDLoc DL, const AsmOperandInfo &OpInfo, 3923 SelectionDAG &DAG) const { 3924 return SDValue(); 3925 } 3926 3927 /// Lower the specified operand into the Ops vector. 3928 /// If it is invalid, don't add anything to Ops. 3929 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 3930 std::string &Constraint, 3931 std::vector<SDValue> &Ops, 3932 SelectionDAG &DAG) const { 3933 3934 if (Constraint.length() > 1) return; 3935 3936 char ConstraintLetter = Constraint[0]; 3937 switch (ConstraintLetter) { 3938 default: break; 3939 case 'X': // Allows any operand; labels (basic block) use this. 3940 if (Op.getOpcode() == ISD::BasicBlock || 3941 Op.getOpcode() == ISD::TargetBlockAddress) { 3942 Ops.push_back(Op); 3943 return; 3944 } 3945 LLVM_FALLTHROUGH; 3946 case 'i': // Simple Integer or Relocatable Constant 3947 case 'n': // Simple Integer 3948 case 's': { // Relocatable Constant 3949 3950 GlobalAddressSDNode *GA; 3951 ConstantSDNode *C; 3952 BlockAddressSDNode *BA; 3953 uint64_t Offset = 0; 3954 3955 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C), 3956 // etc., since getelementpointer is variadic. We can't use 3957 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible 3958 // while in this case the GA may be furthest from the root node which is 3959 // likely an ISD::ADD. 3960 while (1) { 3961 if ((GA = dyn_cast<GlobalAddressSDNode>(Op)) && ConstraintLetter != 'n') { 3962 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 3963 GA->getValueType(0), 3964 Offset + GA->getOffset())); 3965 return; 3966 } else if ((C = dyn_cast<ConstantSDNode>(Op)) && 3967 ConstraintLetter != 's') { 3968 // gcc prints these as sign extended. Sign extend value to 64 bits 3969 // now; without this it would get ZExt'd later in 3970 // ScheduleDAGSDNodes::EmitNode, which is very generic. 3971 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1; 3972 BooleanContent BCont = getBooleanContents(MVT::i64); 3973 ISD::NodeType ExtOpc = IsBool ? getExtendForContent(BCont) 3974 : ISD::SIGN_EXTEND; 3975 int64_t ExtVal = ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() 3976 : C->getSExtValue(); 3977 Ops.push_back(DAG.getTargetConstant(Offset + ExtVal, 3978 SDLoc(C), MVT::i64)); 3979 return; 3980 } else if ((BA = dyn_cast<BlockAddressSDNode>(Op)) && 3981 ConstraintLetter != 'n') { 3982 Ops.push_back(DAG.getTargetBlockAddress( 3983 BA->getBlockAddress(), BA->getValueType(0), 3984 Offset + BA->getOffset(), BA->getTargetFlags())); 3985 return; 3986 } else { 3987 const unsigned OpCode = Op.getOpcode(); 3988 if (OpCode == ISD::ADD || OpCode == ISD::SUB) { 3989 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0)))) 3990 Op = Op.getOperand(1); 3991 // Subtraction is not commutative. 3992 else if (OpCode == ISD::ADD && 3993 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))) 3994 Op = Op.getOperand(0); 3995 else 3996 return; 3997 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue(); 3998 continue; 3999 } 4000 } 4001 return; 4002 } 4003 break; 4004 } 4005 } 4006 } 4007 4008 std::pair<unsigned, const TargetRegisterClass *> 4009 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 4010 StringRef Constraint, 4011 MVT VT) const { 4012 if (Constraint.empty() || Constraint[0] != '{') 4013 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr)); 4014 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?"); 4015 4016 // Remove the braces from around the name. 4017 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 4018 4019 std::pair<unsigned, const TargetRegisterClass *> R = 4020 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr)); 4021 4022 // Figure out which register class contains this reg. 4023 for (const TargetRegisterClass *RC : RI->regclasses()) { 4024 // If none of the value types for this register class are valid, we 4025 // can't use it. For example, 64-bit reg classes on 32-bit targets. 4026 if (!isLegalRC(*RI, *RC)) 4027 continue; 4028 4029 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); 4030 I != E; ++I) { 4031 if (RegName.equals_lower(RI->getRegAsmName(*I))) { 4032 std::pair<unsigned, const TargetRegisterClass *> S = 4033 std::make_pair(*I, RC); 4034 4035 // If this register class has the requested value type, return it, 4036 // otherwise keep searching and return the first class found 4037 // if no other is found which explicitly has the requested type. 4038 if (RI->isTypeLegalForClass(*RC, VT)) 4039 return S; 4040 if (!R.second) 4041 R = S; 4042 } 4043 } 4044 } 4045 4046 return R; 4047 } 4048 4049 //===----------------------------------------------------------------------===// 4050 // Constraint Selection. 4051 4052 /// Return true of this is an input operand that is a matching constraint like 4053 /// "4". 4054 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 4055 assert(!ConstraintCode.empty() && "No known constraint!"); 4056 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 4057 } 4058 4059 /// If this is an input matching constraint, this method returns the output 4060 /// operand it matches. 4061 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 4062 assert(!ConstraintCode.empty() && "No known constraint!"); 4063 return atoi(ConstraintCode.c_str()); 4064 } 4065 4066 /// Split up the constraint string from the inline assembly value into the 4067 /// specific constraints and their prefixes, and also tie in the associated 4068 /// operand values. 4069 /// If this returns an empty vector, and if the constraint string itself 4070 /// isn't empty, there was an error parsing. 4071 TargetLowering::AsmOperandInfoVector 4072 TargetLowering::ParseConstraints(const DataLayout &DL, 4073 const TargetRegisterInfo *TRI, 4074 ImmutableCallSite CS) const { 4075 /// Information about all of the constraints. 4076 AsmOperandInfoVector ConstraintOperands; 4077 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 4078 unsigned maCount = 0; // Largest number of multiple alternative constraints. 4079 4080 // Do a prepass over the constraints, canonicalizing them, and building up the 4081 // ConstraintOperands list. 4082 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 4083 unsigned ResNo = 0; // ResNo - The result number of the next output. 4084 4085 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 4086 ConstraintOperands.emplace_back(std::move(CI)); 4087 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 4088 4089 // Update multiple alternative constraint count. 4090 if (OpInfo.multipleAlternatives.size() > maCount) 4091 maCount = OpInfo.multipleAlternatives.size(); 4092 4093 OpInfo.ConstraintVT = MVT::Other; 4094 4095 // Compute the value type for each operand. 4096 switch (OpInfo.Type) { 4097 case InlineAsm::isOutput: 4098 // Indirect outputs just consume an argument. 4099 if (OpInfo.isIndirect) { 4100 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 4101 break; 4102 } 4103 4104 // The return value of the call is this value. As such, there is no 4105 // corresponding argument. 4106 assert(!CS.getType()->isVoidTy() && 4107 "Bad inline asm!"); 4108 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 4109 OpInfo.ConstraintVT = 4110 getSimpleValueType(DL, STy->getElementType(ResNo)); 4111 } else { 4112 assert(ResNo == 0 && "Asm only has one result!"); 4113 OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType()); 4114 } 4115 ++ResNo; 4116 break; 4117 case InlineAsm::isInput: 4118 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 4119 break; 4120 case InlineAsm::isClobber: 4121 // Nothing to do. 4122 break; 4123 } 4124 4125 if (OpInfo.CallOperandVal) { 4126 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 4127 if (OpInfo.isIndirect) { 4128 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 4129 if (!PtrTy) 4130 report_fatal_error("Indirect operand for inline asm not a pointer!"); 4131 OpTy = PtrTy->getElementType(); 4132 } 4133 4134 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 4135 if (StructType *STy = dyn_cast<StructType>(OpTy)) 4136 if (STy->getNumElements() == 1) 4137 OpTy = STy->getElementType(0); 4138 4139 // If OpTy is not a single value, it may be a struct/union that we 4140 // can tile with integers. 4141 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 4142 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 4143 switch (BitSize) { 4144 default: break; 4145 case 1: 4146 case 8: 4147 case 16: 4148 case 32: 4149 case 64: 4150 case 128: 4151 OpInfo.ConstraintVT = 4152 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true); 4153 break; 4154 } 4155 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) { 4156 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace()); 4157 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize); 4158 } else { 4159 OpInfo.ConstraintVT = MVT::getVT(OpTy, true); 4160 } 4161 } 4162 } 4163 4164 // If we have multiple alternative constraints, select the best alternative. 4165 if (!ConstraintOperands.empty()) { 4166 if (maCount) { 4167 unsigned bestMAIndex = 0; 4168 int bestWeight = -1; 4169 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 4170 int weight = -1; 4171 unsigned maIndex; 4172 // Compute the sums of the weights for each alternative, keeping track 4173 // of the best (highest weight) one so far. 4174 for (maIndex = 0; maIndex < maCount; ++maIndex) { 4175 int weightSum = 0; 4176 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 4177 cIndex != eIndex; ++cIndex) { 4178 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 4179 if (OpInfo.Type == InlineAsm::isClobber) 4180 continue; 4181 4182 // If this is an output operand with a matching input operand, 4183 // look up the matching input. If their types mismatch, e.g. one 4184 // is an integer, the other is floating point, or their sizes are 4185 // different, flag it as an maCantMatch. 4186 if (OpInfo.hasMatchingInput()) { 4187 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 4188 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 4189 if ((OpInfo.ConstraintVT.isInteger() != 4190 Input.ConstraintVT.isInteger()) || 4191 (OpInfo.ConstraintVT.getSizeInBits() != 4192 Input.ConstraintVT.getSizeInBits())) { 4193 weightSum = -1; // Can't match. 4194 break; 4195 } 4196 } 4197 } 4198 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 4199 if (weight == -1) { 4200 weightSum = -1; 4201 break; 4202 } 4203 weightSum += weight; 4204 } 4205 // Update best. 4206 if (weightSum > bestWeight) { 4207 bestWeight = weightSum; 4208 bestMAIndex = maIndex; 4209 } 4210 } 4211 4212 // Now select chosen alternative in each constraint. 4213 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 4214 cIndex != eIndex; ++cIndex) { 4215 AsmOperandInfo &cInfo = ConstraintOperands[cIndex]; 4216 if (cInfo.Type == InlineAsm::isClobber) 4217 continue; 4218 cInfo.selectAlternative(bestMAIndex); 4219 } 4220 } 4221 } 4222 4223 // Check and hook up tied operands, choose constraint code to use. 4224 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 4225 cIndex != eIndex; ++cIndex) { 4226 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex]; 4227 4228 // If this is an output operand with a matching input operand, look up the 4229 // matching input. If their types mismatch, e.g. one is an integer, the 4230 // other is floating point, or their sizes are different, flag it as an 4231 // error. 4232 if (OpInfo.hasMatchingInput()) { 4233 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 4234 4235 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 4236 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 4237 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 4238 OpInfo.ConstraintVT); 4239 std::pair<unsigned, const TargetRegisterClass *> InputRC = 4240 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 4241 Input.ConstraintVT); 4242 if ((OpInfo.ConstraintVT.isInteger() != 4243 Input.ConstraintVT.isInteger()) || 4244 (MatchRC.second != InputRC.second)) { 4245 report_fatal_error("Unsupported asm: input constraint" 4246 " with a matching output constraint of" 4247 " incompatible type!"); 4248 } 4249 } 4250 } 4251 } 4252 4253 return ConstraintOperands; 4254 } 4255 4256 /// Return an integer indicating how general CT is. 4257 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 4258 switch (CT) { 4259 case TargetLowering::C_Other: 4260 case TargetLowering::C_Unknown: 4261 return 0; 4262 case TargetLowering::C_Register: 4263 return 1; 4264 case TargetLowering::C_RegisterClass: 4265 return 2; 4266 case TargetLowering::C_Memory: 4267 return 3; 4268 } 4269 llvm_unreachable("Invalid constraint type"); 4270 } 4271 4272 /// Examine constraint type and operand type and determine a weight value. 4273 /// This object must already have been set up with the operand type 4274 /// and the current alternative constraint selected. 4275 TargetLowering::ConstraintWeight 4276 TargetLowering::getMultipleConstraintMatchWeight( 4277 AsmOperandInfo &info, int maIndex) const { 4278 InlineAsm::ConstraintCodeVector *rCodes; 4279 if (maIndex >= (int)info.multipleAlternatives.size()) 4280 rCodes = &info.Codes; 4281 else 4282 rCodes = &info.multipleAlternatives[maIndex].Codes; 4283 ConstraintWeight BestWeight = CW_Invalid; 4284 4285 // Loop over the options, keeping track of the most general one. 4286 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) { 4287 ConstraintWeight weight = 4288 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str()); 4289 if (weight > BestWeight) 4290 BestWeight = weight; 4291 } 4292 4293 return BestWeight; 4294 } 4295 4296 /// Examine constraint type and operand type and determine a weight value. 4297 /// This object must already have been set up with the operand type 4298 /// and the current alternative constraint selected. 4299 TargetLowering::ConstraintWeight 4300 TargetLowering::getSingleConstraintMatchWeight( 4301 AsmOperandInfo &info, const char *constraint) const { 4302 ConstraintWeight weight = CW_Invalid; 4303 Value *CallOperandVal = info.CallOperandVal; 4304 // If we don't have a value, we can't do a match, 4305 // but allow it at the lowest weight. 4306 if (!CallOperandVal) 4307 return CW_Default; 4308 // Look at the constraint type. 4309 switch (*constraint) { 4310 case 'i': // immediate integer. 4311 case 'n': // immediate integer with a known value. 4312 if (isa<ConstantInt>(CallOperandVal)) 4313 weight = CW_Constant; 4314 break; 4315 case 's': // non-explicit intregal immediate. 4316 if (isa<GlobalValue>(CallOperandVal)) 4317 weight = CW_Constant; 4318 break; 4319 case 'E': // immediate float if host format. 4320 case 'F': // immediate float. 4321 if (isa<ConstantFP>(CallOperandVal)) 4322 weight = CW_Constant; 4323 break; 4324 case '<': // memory operand with autodecrement. 4325 case '>': // memory operand with autoincrement. 4326 case 'm': // memory operand. 4327 case 'o': // offsettable memory operand 4328 case 'V': // non-offsettable memory operand 4329 weight = CW_Memory; 4330 break; 4331 case 'r': // general register. 4332 case 'g': // general register, memory operand or immediate integer. 4333 // note: Clang converts "g" to "imr". 4334 if (CallOperandVal->getType()->isIntegerTy()) 4335 weight = CW_Register; 4336 break; 4337 case 'X': // any operand. 4338 default: 4339 weight = CW_Default; 4340 break; 4341 } 4342 return weight; 4343 } 4344 4345 /// If there are multiple different constraints that we could pick for this 4346 /// operand (e.g. "imr") try to pick the 'best' one. 4347 /// This is somewhat tricky: constraints fall into four classes: 4348 /// Other -> immediates and magic values 4349 /// Register -> one specific register 4350 /// RegisterClass -> a group of regs 4351 /// Memory -> memory 4352 /// Ideally, we would pick the most specific constraint possible: if we have 4353 /// something that fits into a register, we would pick it. The problem here 4354 /// is that if we have something that could either be in a register or in 4355 /// memory that use of the register could cause selection of *other* 4356 /// operands to fail: they might only succeed if we pick memory. Because of 4357 /// this the heuristic we use is: 4358 /// 4359 /// 1) If there is an 'other' constraint, and if the operand is valid for 4360 /// that constraint, use it. This makes us take advantage of 'i' 4361 /// constraints when available. 4362 /// 2) Otherwise, pick the most general constraint present. This prefers 4363 /// 'm' over 'r', for example. 4364 /// 4365 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 4366 const TargetLowering &TLI, 4367 SDValue Op, SelectionDAG *DAG) { 4368 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 4369 unsigned BestIdx = 0; 4370 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 4371 int BestGenerality = -1; 4372 4373 // Loop over the options, keeping track of the most general one. 4374 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 4375 TargetLowering::ConstraintType CType = 4376 TLI.getConstraintType(OpInfo.Codes[i]); 4377 4378 // If this is an 'other' constraint, see if the operand is valid for it. 4379 // For example, on X86 we might have an 'rI' constraint. If the operand 4380 // is an integer in the range [0..31] we want to use I (saving a load 4381 // of a register), otherwise we must use 'r'. 4382 if (CType == TargetLowering::C_Other && Op.getNode()) { 4383 assert(OpInfo.Codes[i].size() == 1 && 4384 "Unhandled multi-letter 'other' constraint"); 4385 std::vector<SDValue> ResultOps; 4386 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 4387 ResultOps, *DAG); 4388 if (!ResultOps.empty()) { 4389 BestType = CType; 4390 BestIdx = i; 4391 break; 4392 } 4393 } 4394 4395 // Things with matching constraints can only be registers, per gcc 4396 // documentation. This mainly affects "g" constraints. 4397 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 4398 continue; 4399 4400 // This constraint letter is more general than the previous one, use it. 4401 int Generality = getConstraintGenerality(CType); 4402 if (Generality > BestGenerality) { 4403 BestType = CType; 4404 BestIdx = i; 4405 BestGenerality = Generality; 4406 } 4407 } 4408 4409 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 4410 OpInfo.ConstraintType = BestType; 4411 } 4412 4413 /// Determines the constraint code and constraint type to use for the specific 4414 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 4415 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 4416 SDValue Op, 4417 SelectionDAG *DAG) const { 4418 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 4419 4420 // Single-letter constraints ('r') are very common. 4421 if (OpInfo.Codes.size() == 1) { 4422 OpInfo.ConstraintCode = OpInfo.Codes[0]; 4423 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 4424 } else { 4425 ChooseConstraint(OpInfo, *this, Op, DAG); 4426 } 4427 4428 // 'X' matches anything. 4429 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 4430 // Labels and constants are handled elsewhere ('X' is the only thing 4431 // that matches labels). For Functions, the type here is the type of 4432 // the result, which is not what we want to look at; leave them alone. 4433 Value *v = OpInfo.CallOperandVal; 4434 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) { 4435 OpInfo.CallOperandVal = v; 4436 return; 4437 } 4438 4439 if (Op.getNode() && Op.getOpcode() == ISD::TargetBlockAddress) 4440 return; 4441 4442 // Otherwise, try to resolve it to something we know about by looking at 4443 // the actual operand type. 4444 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 4445 OpInfo.ConstraintCode = Repl; 4446 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 4447 } 4448 } 4449 } 4450 4451 /// Given an exact SDIV by a constant, create a multiplication 4452 /// with the multiplicative inverse of the constant. 4453 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, 4454 const SDLoc &dl, SelectionDAG &DAG, 4455 SmallVectorImpl<SDNode *> &Created) { 4456 SDValue Op0 = N->getOperand(0); 4457 SDValue Op1 = N->getOperand(1); 4458 EVT VT = N->getValueType(0); 4459 EVT SVT = VT.getScalarType(); 4460 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 4461 EVT ShSVT = ShVT.getScalarType(); 4462 4463 bool UseSRA = false; 4464 SmallVector<SDValue, 16> Shifts, Factors; 4465 4466 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 4467 if (C->isNullValue()) 4468 return false; 4469 APInt Divisor = C->getAPIntValue(); 4470 unsigned Shift = Divisor.countTrailingZeros(); 4471 if (Shift) { 4472 Divisor.ashrInPlace(Shift); 4473 UseSRA = true; 4474 } 4475 // Calculate the multiplicative inverse, using Newton's method. 4476 APInt t; 4477 APInt Factor = Divisor; 4478 while ((t = Divisor * Factor) != 1) 4479 Factor *= APInt(Divisor.getBitWidth(), 2) - t; 4480 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 4481 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 4482 return true; 4483 }; 4484 4485 // Collect all magic values from the build vector. 4486 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern)) 4487 return SDValue(); 4488 4489 SDValue Shift, Factor; 4490 if (VT.isVector()) { 4491 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 4492 Factor = DAG.getBuildVector(VT, dl, Factors); 4493 } else { 4494 Shift = Shifts[0]; 4495 Factor = Factors[0]; 4496 } 4497 4498 SDValue Res = Op0; 4499 4500 // Shift the value upfront if it is even, so the LSB is one. 4501 if (UseSRA) { 4502 // TODO: For UDIV use SRL instead of SRA. 4503 SDNodeFlags Flags; 4504 Flags.setExact(true); 4505 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags); 4506 Created.push_back(Res.getNode()); 4507 } 4508 4509 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 4510 } 4511 4512 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 4513 SelectionDAG &DAG, 4514 SmallVectorImpl<SDNode *> &Created) const { 4515 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4516 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4517 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 4518 return SDValue(N, 0); // Lower SDIV as SDIV 4519 return SDValue(); 4520 } 4521 4522 /// Given an ISD::SDIV node expressing a divide by constant, 4523 /// return a DAG expression to select that will generate the same value by 4524 /// multiplying by a magic number. 4525 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 4526 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 4527 bool IsAfterLegalization, 4528 SmallVectorImpl<SDNode *> &Created) const { 4529 SDLoc dl(N); 4530 EVT VT = N->getValueType(0); 4531 EVT SVT = VT.getScalarType(); 4532 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 4533 EVT ShSVT = ShVT.getScalarType(); 4534 unsigned EltBits = VT.getScalarSizeInBits(); 4535 4536 // Check to see if we can do this. 4537 // FIXME: We should be more aggressive here. 4538 if (!isTypeLegal(VT)) 4539 return SDValue(); 4540 4541 // If the sdiv has an 'exact' bit we can use a simpler lowering. 4542 if (N->getFlags().hasExact()) 4543 return BuildExactSDIV(*this, N, dl, DAG, Created); 4544 4545 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks; 4546 4547 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 4548 if (C->isNullValue()) 4549 return false; 4550 4551 const APInt &Divisor = C->getAPIntValue(); 4552 APInt::ms magics = Divisor.magic(); 4553 int NumeratorFactor = 0; 4554 int ShiftMask = -1; 4555 4556 if (Divisor.isOneValue() || Divisor.isAllOnesValue()) { 4557 // If d is +1/-1, we just multiply the numerator by +1/-1. 4558 NumeratorFactor = Divisor.getSExtValue(); 4559 magics.m = 0; 4560 magics.s = 0; 4561 ShiftMask = 0; 4562 } else if (Divisor.isStrictlyPositive() && magics.m.isNegative()) { 4563 // If d > 0 and m < 0, add the numerator. 4564 NumeratorFactor = 1; 4565 } else if (Divisor.isNegative() && magics.m.isStrictlyPositive()) { 4566 // If d < 0 and m > 0, subtract the numerator. 4567 NumeratorFactor = -1; 4568 } 4569 4570 MagicFactors.push_back(DAG.getConstant(magics.m, dl, SVT)); 4571 Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT)); 4572 Shifts.push_back(DAG.getConstant(magics.s, dl, ShSVT)); 4573 ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT)); 4574 return true; 4575 }; 4576 4577 SDValue N0 = N->getOperand(0); 4578 SDValue N1 = N->getOperand(1); 4579 4580 // Collect the shifts / magic values from each element. 4581 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern)) 4582 return SDValue(); 4583 4584 SDValue MagicFactor, Factor, Shift, ShiftMask; 4585 if (VT.isVector()) { 4586 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 4587 Factor = DAG.getBuildVector(VT, dl, Factors); 4588 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 4589 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks); 4590 } else { 4591 MagicFactor = MagicFactors[0]; 4592 Factor = Factors[0]; 4593 Shift = Shifts[0]; 4594 ShiftMask = ShiftMasks[0]; 4595 } 4596 4597 // Multiply the numerator (operand 0) by the magic value. 4598 // FIXME: We should support doing a MUL in a wider type. 4599 SDValue Q; 4600 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) 4601 : isOperationLegalOrCustom(ISD::MULHS, VT)) 4602 Q = DAG.getNode(ISD::MULHS, dl, VT, N0, MagicFactor); 4603 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) 4604 : isOperationLegalOrCustom(ISD::SMUL_LOHI, VT)) { 4605 SDValue LoHi = 4606 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), N0, MagicFactor); 4607 Q = SDValue(LoHi.getNode(), 1); 4608 } else 4609 return SDValue(); // No mulhs or equivalent. 4610 Created.push_back(Q.getNode()); 4611 4612 // (Optionally) Add/subtract the numerator using Factor. 4613 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor); 4614 Created.push_back(Factor.getNode()); 4615 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor); 4616 Created.push_back(Q.getNode()); 4617 4618 // Shift right algebraic by shift value. 4619 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift); 4620 Created.push_back(Q.getNode()); 4621 4622 // Extract the sign bit, mask it and add it to the quotient. 4623 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT); 4624 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift); 4625 Created.push_back(T.getNode()); 4626 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask); 4627 Created.push_back(T.getNode()); 4628 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 4629 } 4630 4631 /// Given an ISD::UDIV node expressing a divide by constant, 4632 /// return a DAG expression to select that will generate the same value by 4633 /// multiplying by a magic number. 4634 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 4635 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG, 4636 bool IsAfterLegalization, 4637 SmallVectorImpl<SDNode *> &Created) const { 4638 SDLoc dl(N); 4639 EVT VT = N->getValueType(0); 4640 EVT SVT = VT.getScalarType(); 4641 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 4642 EVT ShSVT = ShVT.getScalarType(); 4643 unsigned EltBits = VT.getScalarSizeInBits(); 4644 4645 // Check to see if we can do this. 4646 // FIXME: We should be more aggressive here. 4647 if (!isTypeLegal(VT)) 4648 return SDValue(); 4649 4650 bool UseNPQ = false; 4651 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors; 4652 4653 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 4654 if (C->isNullValue()) 4655 return false; 4656 // FIXME: We should use a narrower constant when the upper 4657 // bits are known to be zero. 4658 APInt Divisor = C->getAPIntValue(); 4659 APInt::mu magics = Divisor.magicu(); 4660 unsigned PreShift = 0, PostShift = 0; 4661 4662 // If the divisor is even, we can avoid using the expensive fixup by 4663 // shifting the divided value upfront. 4664 if (magics.a != 0 && !Divisor[0]) { 4665 PreShift = Divisor.countTrailingZeros(); 4666 // Get magic number for the shifted divisor. 4667 magics = Divisor.lshr(PreShift).magicu(PreShift); 4668 assert(magics.a == 0 && "Should use cheap fixup now"); 4669 } 4670 4671 APInt Magic = magics.m; 4672 4673 unsigned SelNPQ; 4674 if (magics.a == 0 || Divisor.isOneValue()) { 4675 assert(magics.s < Divisor.getBitWidth() && 4676 "We shouldn't generate an undefined shift!"); 4677 PostShift = magics.s; 4678 SelNPQ = false; 4679 } else { 4680 PostShift = magics.s - 1; 4681 SelNPQ = true; 4682 } 4683 4684 PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT)); 4685 MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT)); 4686 NPQFactors.push_back( 4687 DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1) 4688 : APInt::getNullValue(EltBits), 4689 dl, SVT)); 4690 PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT)); 4691 UseNPQ |= SelNPQ; 4692 return true; 4693 }; 4694 4695 SDValue N0 = N->getOperand(0); 4696 SDValue N1 = N->getOperand(1); 4697 4698 // Collect the shifts/magic values from each element. 4699 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern)) 4700 return SDValue(); 4701 4702 SDValue PreShift, PostShift, MagicFactor, NPQFactor; 4703 if (VT.isVector()) { 4704 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts); 4705 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 4706 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors); 4707 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts); 4708 } else { 4709 PreShift = PreShifts[0]; 4710 MagicFactor = MagicFactors[0]; 4711 PostShift = PostShifts[0]; 4712 } 4713 4714 SDValue Q = N0; 4715 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift); 4716 Created.push_back(Q.getNode()); 4717 4718 // FIXME: We should support doing a MUL in a wider type. 4719 auto GetMULHU = [&](SDValue X, SDValue Y) { 4720 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) 4721 : isOperationLegalOrCustom(ISD::MULHU, VT)) 4722 return DAG.getNode(ISD::MULHU, dl, VT, X, Y); 4723 if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) 4724 : isOperationLegalOrCustom(ISD::UMUL_LOHI, VT)) { 4725 SDValue LoHi = 4726 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 4727 return SDValue(LoHi.getNode(), 1); 4728 } 4729 return SDValue(); // No mulhu or equivalent 4730 }; 4731 4732 // Multiply the numerator (operand 0) by the magic value. 4733 Q = GetMULHU(Q, MagicFactor); 4734 if (!Q) 4735 return SDValue(); 4736 4737 Created.push_back(Q.getNode()); 4738 4739 if (UseNPQ) { 4740 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q); 4741 Created.push_back(NPQ.getNode()); 4742 4743 // For vectors we might have a mix of non-NPQ/NPQ paths, so use 4744 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero. 4745 if (VT.isVector()) 4746 NPQ = GetMULHU(NPQ, NPQFactor); 4747 else 4748 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT)); 4749 4750 Created.push_back(NPQ.getNode()); 4751 4752 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 4753 Created.push_back(Q.getNode()); 4754 } 4755 4756 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift); 4757 Created.push_back(Q.getNode()); 4758 4759 SDValue One = DAG.getConstant(1, dl, VT); 4760 SDValue IsOne = DAG.getSetCC(dl, VT, N1, One, ISD::SETEQ); 4761 return DAG.getSelect(dl, VT, IsOne, N0, Q); 4762 } 4763 4764 /// If all values in Values that *don't* match the predicate are same 'splat' 4765 /// value, then replace all values with that splat value. 4766 /// Else, if AlternativeReplacement was provided, then replace all values that 4767 /// do match predicate with AlternativeReplacement value. 4768 static void 4769 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values, 4770 std::function<bool(SDValue)> Predicate, 4771 SDValue AlternativeReplacement = SDValue()) { 4772 SDValue Replacement; 4773 // Is there a value for which the Predicate does *NOT* match? What is it? 4774 auto SplatValue = llvm::find_if_not(Values, Predicate); 4775 if (SplatValue != Values.end()) { 4776 // Does Values consist only of SplatValue's and values matching Predicate? 4777 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) { 4778 return Value == *SplatValue || Predicate(Value); 4779 })) // Then we shall replace values matching predicate with SplatValue. 4780 Replacement = *SplatValue; 4781 } 4782 if (!Replacement) { 4783 // Oops, we did not find the "baseline" splat value. 4784 if (!AlternativeReplacement) 4785 return; // Nothing to do. 4786 // Let's replace with provided value then. 4787 Replacement = AlternativeReplacement; 4788 } 4789 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement); 4790 } 4791 4792 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE 4793 /// where the divisor is constant and the comparison target is zero, 4794 /// return a DAG expression that will generate the same comparison result 4795 /// using only multiplications, additions and shifts/rotations. 4796 /// Ref: "Hacker's Delight" 10-17. 4797 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode, 4798 SDValue CompTargetNode, 4799 ISD::CondCode Cond, 4800 DAGCombinerInfo &DCI, 4801 const SDLoc &DL) const { 4802 SmallVector<SDNode *, 2> Built; 4803 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond, 4804 DCI, DL, Built)) { 4805 for (SDNode *N : Built) 4806 DCI.AddToWorklist(N); 4807 return Folded; 4808 } 4809 4810 return SDValue(); 4811 } 4812 4813 SDValue 4814 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode, 4815 SDValue CompTargetNode, ISD::CondCode Cond, 4816 DAGCombinerInfo &DCI, const SDLoc &DL, 4817 SmallVectorImpl<SDNode *> &Created) const { 4818 // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q) 4819 // - D must be constant, with D = D0 * 2^K where D0 is odd 4820 // - P is the multiplicative inverse of D0 modulo 2^W 4821 // - Q = floor((2^W - 1) / D0) 4822 // where W is the width of the common type of N and D. 4823 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 4824 "Only applicable for (in)equality comparisons."); 4825 4826 SelectionDAG &DAG = DCI.DAG; 4827 4828 EVT VT = REMNode.getValueType(); 4829 EVT SVT = VT.getScalarType(); 4830 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 4831 EVT ShSVT = ShVT.getScalarType(); 4832 4833 // If MUL is unavailable, we cannot proceed in any case. 4834 if (!isOperationLegalOrCustom(ISD::MUL, VT)) 4835 return SDValue(); 4836 4837 // TODO: Could support comparing with non-zero too. 4838 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode); 4839 if (!CompTarget || !CompTarget->isNullValue()) 4840 return SDValue(); 4841 4842 bool HadOneDivisor = false; 4843 bool AllDivisorsAreOnes = true; 4844 bool HadEvenDivisor = false; 4845 bool AllDivisorsArePowerOfTwo = true; 4846 SmallVector<SDValue, 16> PAmts, KAmts, QAmts; 4847 4848 auto BuildUREMPattern = [&](ConstantSDNode *C) { 4849 // Division by 0 is UB. Leave it to be constant-folded elsewhere. 4850 if (C->isNullValue()) 4851 return false; 4852 4853 const APInt &D = C->getAPIntValue(); 4854 // If all divisors are ones, we will prefer to avoid the fold. 4855 HadOneDivisor |= D.isOneValue(); 4856 AllDivisorsAreOnes &= D.isOneValue(); 4857 4858 // Decompose D into D0 * 2^K 4859 unsigned K = D.countTrailingZeros(); 4860 assert((!D.isOneValue() || (K == 0)) && "For divisor '1' we won't rotate."); 4861 APInt D0 = D.lshr(K); 4862 4863 // D is even if it has trailing zeros. 4864 HadEvenDivisor |= (K != 0); 4865 // D is a power-of-two if D0 is one. 4866 // If all divisors are power-of-two, we will prefer to avoid the fold. 4867 AllDivisorsArePowerOfTwo &= D0.isOneValue(); 4868 4869 // P = inv(D0, 2^W) 4870 // 2^W requires W + 1 bits, so we have to extend and then truncate. 4871 unsigned W = D.getBitWidth(); 4872 APInt P = D0.zext(W + 1) 4873 .multiplicativeInverse(APInt::getSignedMinValue(W + 1)) 4874 .trunc(W); 4875 assert(!P.isNullValue() && "No multiplicative inverse!"); // unreachable 4876 assert((D0 * P).isOneValue() && "Multiplicative inverse sanity check."); 4877 4878 // Q = floor((2^W - 1) / D) 4879 APInt Q = APInt::getAllOnesValue(W).udiv(D); 4880 4881 assert(APInt::getAllOnesValue(ShSVT.getSizeInBits()).ugt(K) && 4882 "We are expecting that K is always less than all-ones for ShSVT"); 4883 4884 // If the divisor is 1 the result can be constant-folded. 4885 if (D.isOneValue()) { 4886 // Set P and K amount to a bogus values so we can try to splat them. 4887 P = 0; 4888 K = -1; 4889 assert(Q.isAllOnesValue() && 4890 "Expecting all-ones comparison for one divisor"); 4891 } 4892 4893 PAmts.push_back(DAG.getConstant(P, DL, SVT)); 4894 KAmts.push_back( 4895 DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT)); 4896 QAmts.push_back(DAG.getConstant(Q, DL, SVT)); 4897 return true; 4898 }; 4899 4900 SDValue N = REMNode.getOperand(0); 4901 SDValue D = REMNode.getOperand(1); 4902 4903 // Collect the values from each element. 4904 if (!ISD::matchUnaryPredicate(D, BuildUREMPattern)) 4905 return SDValue(); 4906 4907 // If this is a urem by a one, avoid the fold since it can be constant-folded. 4908 if (AllDivisorsAreOnes) 4909 return SDValue(); 4910 4911 // If this is a urem by a powers-of-two, avoid the fold since it can be 4912 // best implemented as a bit test. 4913 if (AllDivisorsArePowerOfTwo) 4914 return SDValue(); 4915 4916 SDValue PVal, KVal, QVal; 4917 if (VT.isVector()) { 4918 if (HadOneDivisor) { 4919 // Try to turn PAmts into a splat, since we don't care about the values 4920 // that are currently '0'. If we can't, just keep '0'`s. 4921 turnVectorIntoSplatVector(PAmts, isNullConstant); 4922 // Try to turn KAmts into a splat, since we don't care about the values 4923 // that are currently '-1'. If we can't, change them to '0'`s. 4924 turnVectorIntoSplatVector(KAmts, isAllOnesConstant, 4925 DAG.getConstant(0, DL, ShSVT)); 4926 } 4927 4928 PVal = DAG.getBuildVector(VT, DL, PAmts); 4929 KVal = DAG.getBuildVector(ShVT, DL, KAmts); 4930 QVal = DAG.getBuildVector(VT, DL, QAmts); 4931 } else { 4932 PVal = PAmts[0]; 4933 KVal = KAmts[0]; 4934 QVal = QAmts[0]; 4935 } 4936 4937 // (mul N, P) 4938 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal); 4939 Created.push_back(Op0.getNode()); 4940 4941 // Rotate right only if any divisor was even. We avoid rotates for all-odd 4942 // divisors as a performance improvement, since rotating by 0 is a no-op. 4943 if (HadEvenDivisor) { 4944 // We need ROTR to do this. 4945 if (!isOperationLegalOrCustom(ISD::ROTR, VT)) 4946 return SDValue(); 4947 SDNodeFlags Flags; 4948 Flags.setExact(true); 4949 // UREM: (rotr (mul N, P), K) 4950 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal, Flags); 4951 Created.push_back(Op0.getNode()); 4952 } 4953 4954 // UREM: (setule/setugt (rotr (mul N, P), K), Q) 4955 return DAG.getSetCC(DL, SETCCVT, Op0, QVal, 4956 ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT)); 4957 } 4958 4959 bool TargetLowering:: 4960 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 4961 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 4962 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 4963 "be a constant integer"); 4964 return true; 4965 } 4966 4967 return false; 4968 } 4969 4970 //===----------------------------------------------------------------------===// 4971 // Legalization Utilities 4972 //===----------------------------------------------------------------------===// 4973 4974 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl, 4975 SDValue LHS, SDValue RHS, 4976 SmallVectorImpl<SDValue> &Result, 4977 EVT HiLoVT, SelectionDAG &DAG, 4978 MulExpansionKind Kind, SDValue LL, 4979 SDValue LH, SDValue RL, SDValue RH) const { 4980 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 4981 Opcode == ISD::SMUL_LOHI); 4982 4983 bool HasMULHS = (Kind == MulExpansionKind::Always) || 4984 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 4985 bool HasMULHU = (Kind == MulExpansionKind::Always) || 4986 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 4987 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 4988 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 4989 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 4990 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 4991 4992 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 4993 return false; 4994 4995 unsigned OuterBitSize = VT.getScalarSizeInBits(); 4996 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 4997 unsigned LHSSB = DAG.ComputeNumSignBits(LHS); 4998 unsigned RHSSB = DAG.ComputeNumSignBits(RHS); 4999 5000 // LL, LH, RL, and RH must be either all NULL or all set to a value. 5001 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 5002 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 5003 5004 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 5005 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 5006 bool Signed) -> bool { 5007 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 5008 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 5009 Hi = SDValue(Lo.getNode(), 1); 5010 return true; 5011 } 5012 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 5013 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 5014 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 5015 return true; 5016 } 5017 return false; 5018 }; 5019 5020 SDValue Lo, Hi; 5021 5022 if (!LL.getNode() && !RL.getNode() && 5023 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 5024 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 5025 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 5026 } 5027 5028 if (!LL.getNode()) 5029 return false; 5030 5031 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 5032 if (DAG.MaskedValueIsZero(LHS, HighMask) && 5033 DAG.MaskedValueIsZero(RHS, HighMask)) { 5034 // The inputs are both zero-extended. 5035 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 5036 Result.push_back(Lo); 5037 Result.push_back(Hi); 5038 if (Opcode != ISD::MUL) { 5039 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 5040 Result.push_back(Zero); 5041 Result.push_back(Zero); 5042 } 5043 return true; 5044 } 5045 } 5046 5047 if (!VT.isVector() && Opcode == ISD::MUL && LHSSB > InnerBitSize && 5048 RHSSB > InnerBitSize) { 5049 // The input values are both sign-extended. 5050 // TODO non-MUL case? 5051 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 5052 Result.push_back(Lo); 5053 Result.push_back(Hi); 5054 return true; 5055 } 5056 } 5057 5058 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 5059 EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout()); 5060 if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) { 5061 // FIXME getShiftAmountTy does not always return a sensible result when VT 5062 // is an illegal type, and so the type may be too small to fit the shift 5063 // amount. Override it with i32. The shift will have to be legalized. 5064 ShiftAmountTy = MVT::i32; 5065 } 5066 SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy); 5067 5068 if (!LH.getNode() && !RH.getNode() && 5069 isOperationLegalOrCustom(ISD::SRL, VT) && 5070 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 5071 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 5072 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 5073 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 5074 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 5075 } 5076 5077 if (!LH.getNode()) 5078 return false; 5079 5080 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 5081 return false; 5082 5083 Result.push_back(Lo); 5084 5085 if (Opcode == ISD::MUL) { 5086 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 5087 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 5088 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 5089 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 5090 Result.push_back(Hi); 5091 return true; 5092 } 5093 5094 // Compute the full width result. 5095 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 5096 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 5097 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 5098 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 5099 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 5100 }; 5101 5102 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 5103 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 5104 return false; 5105 5106 // This is effectively the add part of a multiply-add of half-sized operands, 5107 // so it cannot overflow. 5108 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 5109 5110 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 5111 return false; 5112 5113 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 5114 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 5115 5116 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) && 5117 isOperationLegalOrCustom(ISD::ADDE, VT)); 5118 if (UseGlue) 5119 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 5120 Merge(Lo, Hi)); 5121 else 5122 Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next, 5123 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType)); 5124 5125 SDValue Carry = Next.getValue(1); 5126 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 5127 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 5128 5129 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 5130 return false; 5131 5132 if (UseGlue) 5133 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 5134 Carry); 5135 else 5136 Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi, 5137 Zero, Carry); 5138 5139 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 5140 5141 if (Opcode == ISD::SMUL_LOHI) { 5142 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 5143 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 5144 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 5145 5146 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 5147 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 5148 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 5149 } 5150 5151 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 5152 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 5153 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 5154 return true; 5155 } 5156 5157 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 5158 SelectionDAG &DAG, MulExpansionKind Kind, 5159 SDValue LL, SDValue LH, SDValue RL, 5160 SDValue RH) const { 5161 SmallVector<SDValue, 2> Result; 5162 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), N, 5163 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 5164 DAG, Kind, LL, LH, RL, RH); 5165 if (Ok) { 5166 assert(Result.size() == 2); 5167 Lo = Result[0]; 5168 Hi = Result[1]; 5169 } 5170 return Ok; 5171 } 5172 5173 bool TargetLowering::expandFunnelShift(SDNode *Node, SDValue &Result, 5174 SelectionDAG &DAG) const { 5175 EVT VT = Node->getValueType(0); 5176 5177 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 5178 !isOperationLegalOrCustom(ISD::SRL, VT) || 5179 !isOperationLegalOrCustom(ISD::SUB, VT) || 5180 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 5181 return false; 5182 5183 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 5184 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 5185 SDValue X = Node->getOperand(0); 5186 SDValue Y = Node->getOperand(1); 5187 SDValue Z = Node->getOperand(2); 5188 5189 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 5190 bool IsFSHL = Node->getOpcode() == ISD::FSHL; 5191 SDLoc DL(SDValue(Node, 0)); 5192 5193 EVT ShVT = Z.getValueType(); 5194 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 5195 SDValue Zero = DAG.getConstant(0, DL, ShVT); 5196 5197 SDValue ShAmt; 5198 if (isPowerOf2_32(EltSizeInBits)) { 5199 SDValue Mask = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 5200 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask); 5201 } else { 5202 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 5203 } 5204 5205 SDValue InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt); 5206 SDValue ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt); 5207 SDValue ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt); 5208 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShX, ShY); 5209 5210 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 5211 // and that is undefined. We must compare and select to avoid UB. 5212 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShVT); 5213 5214 // For fshl, 0-shift returns the 1st arg (X). 5215 // For fshr, 0-shift returns the 2nd arg (Y). 5216 SDValue IsZeroShift = DAG.getSetCC(DL, CCVT, ShAmt, Zero, ISD::SETEQ); 5217 Result = DAG.getSelect(DL, VT, IsZeroShift, IsFSHL ? X : Y, Or); 5218 return true; 5219 } 5220 5221 // TODO: Merge with expandFunnelShift. 5222 bool TargetLowering::expandROT(SDNode *Node, SDValue &Result, 5223 SelectionDAG &DAG) const { 5224 EVT VT = Node->getValueType(0); 5225 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 5226 bool IsLeft = Node->getOpcode() == ISD::ROTL; 5227 SDValue Op0 = Node->getOperand(0); 5228 SDValue Op1 = Node->getOperand(1); 5229 SDLoc DL(SDValue(Node, 0)); 5230 5231 EVT ShVT = Op1.getValueType(); 5232 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 5233 5234 // If a rotate in the other direction is legal, use it. 5235 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL; 5236 if (isOperationLegal(RevRot, VT)) { 5237 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, Op1); 5238 Result = DAG.getNode(RevRot, DL, VT, Op0, Sub); 5239 return true; 5240 } 5241 5242 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 5243 !isOperationLegalOrCustom(ISD::SRL, VT) || 5244 !isOperationLegalOrCustom(ISD::SUB, VT) || 5245 !isOperationLegalOrCustomOrPromote(ISD::OR, VT) || 5246 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 5247 return false; 5248 5249 // Otherwise, 5250 // (rotl x, c) -> (or (shl x, (and c, w-1)), (srl x, (and w-c, w-1))) 5251 // (rotr x, c) -> (or (srl x, (and c, w-1)), (shl x, (and w-c, w-1))) 5252 // 5253 assert(isPowerOf2_32(EltSizeInBits) && EltSizeInBits > 1 && 5254 "Expecting the type bitwidth to be a power of 2"); 5255 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL; 5256 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL; 5257 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 5258 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, Op1); 5259 SDValue And0 = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC); 5260 SDValue And1 = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC); 5261 Result = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ShOpc, DL, VT, Op0, And0), 5262 DAG.getNode(HsOpc, DL, VT, Op0, And1)); 5263 return true; 5264 } 5265 5266 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 5267 SelectionDAG &DAG) const { 5268 SDValue Src = Node->getOperand(0); 5269 EVT SrcVT = Src.getValueType(); 5270 EVT DstVT = Node->getValueType(0); 5271 SDLoc dl(SDValue(Node, 0)); 5272 5273 // FIXME: Only f32 to i64 conversions are supported. 5274 if (SrcVT != MVT::f32 || DstVT != MVT::i64) 5275 return false; 5276 5277 // Expand f32 -> i64 conversion 5278 // This algorithm comes from compiler-rt's implementation of fixsfdi: 5279 // https://github.com/llvm/llvm-project/blob/master/compiler-rt/lib/builtins/fixsfdi.c 5280 unsigned SrcEltBits = SrcVT.getScalarSizeInBits(); 5281 EVT IntVT = SrcVT.changeTypeToInteger(); 5282 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout()); 5283 5284 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 5285 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 5286 SDValue Bias = DAG.getConstant(127, dl, IntVT); 5287 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT); 5288 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT); 5289 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 5290 5291 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src); 5292 5293 SDValue ExponentBits = DAG.getNode( 5294 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 5295 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT)); 5296 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 5297 5298 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT, 5299 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 5300 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT)); 5301 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT); 5302 5303 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 5304 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 5305 DAG.getConstant(0x00800000, dl, IntVT)); 5306 5307 R = DAG.getZExtOrTrunc(R, dl, DstVT); 5308 5309 R = DAG.getSelectCC( 5310 dl, Exponent, ExponentLoBit, 5311 DAG.getNode(ISD::SHL, dl, DstVT, R, 5312 DAG.getZExtOrTrunc( 5313 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 5314 dl, IntShVT)), 5315 DAG.getNode(ISD::SRL, dl, DstVT, R, 5316 DAG.getZExtOrTrunc( 5317 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 5318 dl, IntShVT)), 5319 ISD::SETGT); 5320 5321 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT, 5322 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign); 5323 5324 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 5325 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT); 5326 return true; 5327 } 5328 5329 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result, 5330 SelectionDAG &DAG) const { 5331 SDLoc dl(SDValue(Node, 0)); 5332 SDValue Src = Node->getOperand(0); 5333 5334 EVT SrcVT = Src.getValueType(); 5335 EVT DstVT = Node->getValueType(0); 5336 EVT SetCCVT = 5337 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 5338 5339 // Only expand vector types if we have the appropriate vector bit operations. 5340 if (DstVT.isVector() && (!isOperationLegalOrCustom(ISD::FP_TO_SINT, DstVT) || 5341 !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT))) 5342 return false; 5343 5344 // If the maximum float value is smaller then the signed integer range, 5345 // the destination signmask can't be represented by the float, so we can 5346 // just use FP_TO_SINT directly. 5347 const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT); 5348 APFloat APF(APFSem, APInt::getNullValue(SrcVT.getScalarSizeInBits())); 5349 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits()); 5350 if (APFloat::opOverflow & 5351 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) { 5352 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 5353 return true; 5354 } 5355 5356 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 5357 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT); 5358 5359 bool Strict = shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false); 5360 if (Strict) { 5361 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the 5362 // signmask then offset (the result of which should be fully representable). 5363 // Sel = Src < 0x8000000000000000 5364 // Val = select Sel, Src, Src - 0x8000000000000000 5365 // Ofs = select Sel, 0, 0x8000000000000000 5366 // Result = fp_to_sint(Val) ^ Ofs 5367 5368 // TODO: Should any fast-math-flags be set for the FSUB? 5369 SDValue Val = DAG.getSelect(dl, SrcVT, Sel, Src, 5370 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 5371 SDValue Ofs = DAG.getSelect(dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), 5372 DAG.getConstant(SignMask, dl, DstVT)); 5373 Result = DAG.getNode(ISD::XOR, dl, DstVT, 5374 DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val), Ofs); 5375 } else { 5376 // Expand based on maximum range of FP_TO_SINT: 5377 // True = fp_to_sint(Src) 5378 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000) 5379 // Result = select (Src < 0x8000000000000000), True, False 5380 5381 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 5382 // TODO: Should any fast-math-flags be set for the FSUB? 5383 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, 5384 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 5385 False = DAG.getNode(ISD::XOR, dl, DstVT, False, 5386 DAG.getConstant(SignMask, dl, DstVT)); 5387 Result = DAG.getSelect(dl, DstVT, Sel, True, False); 5388 } 5389 return true; 5390 } 5391 5392 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result, 5393 SelectionDAG &DAG) const { 5394 SDValue Src = Node->getOperand(0); 5395 EVT SrcVT = Src.getValueType(); 5396 EVT DstVT = Node->getValueType(0); 5397 5398 if (SrcVT.getScalarType() != MVT::i64) 5399 return false; 5400 5401 SDLoc dl(SDValue(Node, 0)); 5402 EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout()); 5403 5404 if (DstVT.getScalarType() == MVT::f32) { 5405 // Only expand vector types if we have the appropriate vector bit 5406 // operations. 5407 if (SrcVT.isVector() && 5408 (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 5409 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 5410 !isOperationLegalOrCustom(ISD::SINT_TO_FP, SrcVT) || 5411 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 5412 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 5413 return false; 5414 5415 // For unsigned conversions, convert them to signed conversions using the 5416 // algorithm from the x86_64 __floatundidf in compiler_rt. 5417 SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Src); 5418 5419 SDValue ShiftConst = DAG.getConstant(1, dl, ShiftVT); 5420 SDValue Shr = DAG.getNode(ISD::SRL, dl, SrcVT, Src, ShiftConst); 5421 SDValue AndConst = DAG.getConstant(1, dl, SrcVT); 5422 SDValue And = DAG.getNode(ISD::AND, dl, SrcVT, Src, AndConst); 5423 SDValue Or = DAG.getNode(ISD::OR, dl, SrcVT, And, Shr); 5424 5425 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Or); 5426 SDValue Slow = DAG.getNode(ISD::FADD, dl, DstVT, SignCvt, SignCvt); 5427 5428 // TODO: This really should be implemented using a branch rather than a 5429 // select. We happen to get lucky and machinesink does the right 5430 // thing most of the time. This would be a good candidate for a 5431 // pseudo-op, or, even better, for whole-function isel. 5432 EVT SetCCVT = 5433 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 5434 5435 SDValue SignBitTest = DAG.getSetCC( 5436 dl, SetCCVT, Src, DAG.getConstant(0, dl, SrcVT), ISD::SETLT); 5437 Result = DAG.getSelect(dl, DstVT, SignBitTest, Slow, Fast); 5438 return true; 5439 } 5440 5441 if (DstVT.getScalarType() == MVT::f64) { 5442 // Only expand vector types if we have the appropriate vector bit 5443 // operations. 5444 if (SrcVT.isVector() && 5445 (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 5446 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 5447 !isOperationLegalOrCustom(ISD::FSUB, DstVT) || 5448 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 5449 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 5450 return false; 5451 5452 // Implementation of unsigned i64 to f64 following the algorithm in 5453 // __floatundidf in compiler_rt. This implementation has the advantage 5454 // of performing rounding correctly, both in the default rounding mode 5455 // and in all alternate rounding modes. 5456 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT); 5457 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP( 5458 BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT); 5459 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT); 5460 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT); 5461 SDValue HiShift = DAG.getConstant(32, dl, ShiftVT); 5462 5463 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask); 5464 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift); 5465 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52); 5466 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84); 5467 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr); 5468 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr); 5469 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52); 5470 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub); 5471 return true; 5472 } 5473 5474 return false; 5475 } 5476 5477 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node, 5478 SelectionDAG &DAG) const { 5479 SDLoc dl(Node); 5480 unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ? 5481 ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 5482 EVT VT = Node->getValueType(0); 5483 if (isOperationLegalOrCustom(NewOp, VT)) { 5484 SDValue Quiet0 = Node->getOperand(0); 5485 SDValue Quiet1 = Node->getOperand(1); 5486 5487 if (!Node->getFlags().hasNoNaNs()) { 5488 // Insert canonicalizes if it's possible we need to quiet to get correct 5489 // sNaN behavior. 5490 if (!DAG.isKnownNeverSNaN(Quiet0)) { 5491 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0, 5492 Node->getFlags()); 5493 } 5494 if (!DAG.isKnownNeverSNaN(Quiet1)) { 5495 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1, 5496 Node->getFlags()); 5497 } 5498 } 5499 5500 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags()); 5501 } 5502 5503 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that 5504 // instead if there are no NaNs. 5505 if (Node->getFlags().hasNoNaNs()) { 5506 unsigned IEEE2018Op = 5507 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM; 5508 if (isOperationLegalOrCustom(IEEE2018Op, VT)) { 5509 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0), 5510 Node->getOperand(1), Node->getFlags()); 5511 } 5512 } 5513 5514 return SDValue(); 5515 } 5516 5517 bool TargetLowering::expandCTPOP(SDNode *Node, SDValue &Result, 5518 SelectionDAG &DAG) const { 5519 SDLoc dl(Node); 5520 EVT VT = Node->getValueType(0); 5521 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5522 SDValue Op = Node->getOperand(0); 5523 unsigned Len = VT.getScalarSizeInBits(); 5524 assert(VT.isInteger() && "CTPOP not implemented for this type."); 5525 5526 // TODO: Add support for irregular type lengths. 5527 if (!(Len <= 128 && Len % 8 == 0)) 5528 return false; 5529 5530 // Only expand vector types if we have the appropriate vector bit operations. 5531 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::ADD, VT) || 5532 !isOperationLegalOrCustom(ISD::SUB, VT) || 5533 !isOperationLegalOrCustom(ISD::SRL, VT) || 5534 (Len != 8 && !isOperationLegalOrCustom(ISD::MUL, VT)) || 5535 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 5536 return false; 5537 5538 // This is the "best" algorithm from 5539 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 5540 SDValue Mask55 = 5541 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 5542 SDValue Mask33 = 5543 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 5544 SDValue Mask0F = 5545 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 5546 SDValue Mask01 = 5547 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 5548 5549 // v = v - ((v >> 1) & 0x55555555...) 5550 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 5551 DAG.getNode(ISD::AND, dl, VT, 5552 DAG.getNode(ISD::SRL, dl, VT, Op, 5553 DAG.getConstant(1, dl, ShVT)), 5554 Mask55)); 5555 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 5556 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 5557 DAG.getNode(ISD::AND, dl, VT, 5558 DAG.getNode(ISD::SRL, dl, VT, Op, 5559 DAG.getConstant(2, dl, ShVT)), 5560 Mask33)); 5561 // v = (v + (v >> 4)) & 0x0F0F0F0F... 5562 Op = DAG.getNode(ISD::AND, dl, VT, 5563 DAG.getNode(ISD::ADD, dl, VT, Op, 5564 DAG.getNode(ISD::SRL, dl, VT, Op, 5565 DAG.getConstant(4, dl, ShVT))), 5566 Mask0F); 5567 // v = (v * 0x01010101...) >> (Len - 8) 5568 if (Len > 8) 5569 Op = 5570 DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::MUL, dl, VT, Op, Mask01), 5571 DAG.getConstant(Len - 8, dl, ShVT)); 5572 5573 Result = Op; 5574 return true; 5575 } 5576 5577 bool TargetLowering::expandCTLZ(SDNode *Node, SDValue &Result, 5578 SelectionDAG &DAG) const { 5579 SDLoc dl(Node); 5580 EVT VT = Node->getValueType(0); 5581 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5582 SDValue Op = Node->getOperand(0); 5583 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 5584 5585 // If the non-ZERO_UNDEF version is supported we can use that instead. 5586 if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF && 5587 isOperationLegalOrCustom(ISD::CTLZ, VT)) { 5588 Result = DAG.getNode(ISD::CTLZ, dl, VT, Op); 5589 return true; 5590 } 5591 5592 // If the ZERO_UNDEF version is supported use that and handle the zero case. 5593 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 5594 EVT SetCCVT = 5595 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 5596 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 5597 SDValue Zero = DAG.getConstant(0, dl, VT); 5598 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 5599 Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero, 5600 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ); 5601 return true; 5602 } 5603 5604 // Only expand vector types if we have the appropriate vector bit operations. 5605 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 5606 !isOperationLegalOrCustom(ISD::CTPOP, VT) || 5607 !isOperationLegalOrCustom(ISD::SRL, VT) || 5608 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 5609 return false; 5610 5611 // for now, we do this: 5612 // x = x | (x >> 1); 5613 // x = x | (x >> 2); 5614 // ... 5615 // x = x | (x >>16); 5616 // x = x | (x >>32); // for 64-bit input 5617 // return popcount(~x); 5618 // 5619 // Ref: "Hacker's Delight" by Henry Warren 5620 for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) { 5621 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 5622 Op = DAG.getNode(ISD::OR, dl, VT, Op, 5623 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp)); 5624 } 5625 Op = DAG.getNOT(dl, Op, VT); 5626 Result = DAG.getNode(ISD::CTPOP, dl, VT, Op); 5627 return true; 5628 } 5629 5630 bool TargetLowering::expandCTTZ(SDNode *Node, SDValue &Result, 5631 SelectionDAG &DAG) const { 5632 SDLoc dl(Node); 5633 EVT VT = Node->getValueType(0); 5634 SDValue Op = Node->getOperand(0); 5635 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 5636 5637 // If the non-ZERO_UNDEF version is supported we can use that instead. 5638 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF && 5639 isOperationLegalOrCustom(ISD::CTTZ, VT)) { 5640 Result = DAG.getNode(ISD::CTTZ, dl, VT, Op); 5641 return true; 5642 } 5643 5644 // If the ZERO_UNDEF version is supported use that and handle the zero case. 5645 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) { 5646 EVT SetCCVT = 5647 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 5648 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op); 5649 SDValue Zero = DAG.getConstant(0, dl, VT); 5650 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 5651 Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero, 5652 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ); 5653 return true; 5654 } 5655 5656 // Only expand vector types if we have the appropriate vector bit operations. 5657 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 5658 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 5659 !isOperationLegalOrCustom(ISD::CTLZ, VT)) || 5660 !isOperationLegalOrCustom(ISD::SUB, VT) || 5661 !isOperationLegalOrCustomOrPromote(ISD::AND, VT) || 5662 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 5663 return false; 5664 5665 // for now, we use: { return popcount(~x & (x - 1)); } 5666 // unless the target has ctlz but not ctpop, in which case we use: 5667 // { return 32 - nlz(~x & (x-1)); } 5668 // Ref: "Hacker's Delight" by Henry Warren 5669 SDValue Tmp = DAG.getNode( 5670 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT), 5671 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT))); 5672 5673 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 5674 if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) { 5675 Result = 5676 DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT), 5677 DAG.getNode(ISD::CTLZ, dl, VT, Tmp)); 5678 return true; 5679 } 5680 5681 Result = DAG.getNode(ISD::CTPOP, dl, VT, Tmp); 5682 return true; 5683 } 5684 5685 bool TargetLowering::expandABS(SDNode *N, SDValue &Result, 5686 SelectionDAG &DAG) const { 5687 SDLoc dl(N); 5688 EVT VT = N->getValueType(0); 5689 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 5690 SDValue Op = N->getOperand(0); 5691 5692 // Only expand vector types if we have the appropriate vector operations. 5693 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SRA, VT) || 5694 !isOperationLegalOrCustom(ISD::ADD, VT) || 5695 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 5696 return false; 5697 5698 SDValue Shift = 5699 DAG.getNode(ISD::SRA, dl, VT, Op, 5700 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT)); 5701 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, Op, Shift); 5702 Result = DAG.getNode(ISD::XOR, dl, VT, Add, Shift); 5703 return true; 5704 } 5705 5706 SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 5707 SelectionDAG &DAG) const { 5708 SDLoc SL(LD); 5709 SDValue Chain = LD->getChain(); 5710 SDValue BasePTR = LD->getBasePtr(); 5711 EVT SrcVT = LD->getMemoryVT(); 5712 ISD::LoadExtType ExtType = LD->getExtensionType(); 5713 5714 unsigned NumElem = SrcVT.getVectorNumElements(); 5715 5716 EVT SrcEltVT = SrcVT.getScalarType(); 5717 EVT DstEltVT = LD->getValueType(0).getScalarType(); 5718 5719 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 5720 assert(SrcEltVT.isByteSized()); 5721 5722 SmallVector<SDValue, 8> Vals; 5723 SmallVector<SDValue, 8> LoadChains; 5724 5725 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 5726 SDValue ScalarLoad = 5727 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 5728 LD->getPointerInfo().getWithOffset(Idx * Stride), 5729 SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride), 5730 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 5731 5732 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, Stride); 5733 5734 Vals.push_back(ScalarLoad.getValue(0)); 5735 LoadChains.push_back(ScalarLoad.getValue(1)); 5736 } 5737 5738 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 5739 SDValue Value = DAG.getBuildVector(LD->getValueType(0), SL, Vals); 5740 5741 return DAG.getMergeValues({Value, NewChain}, SL); 5742 } 5743 5744 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 5745 SelectionDAG &DAG) const { 5746 SDLoc SL(ST); 5747 5748 SDValue Chain = ST->getChain(); 5749 SDValue BasePtr = ST->getBasePtr(); 5750 SDValue Value = ST->getValue(); 5751 EVT StVT = ST->getMemoryVT(); 5752 5753 // The type of the data we want to save 5754 EVT RegVT = Value.getValueType(); 5755 EVT RegSclVT = RegVT.getScalarType(); 5756 5757 // The type of data as saved in memory. 5758 EVT MemSclVT = StVT.getScalarType(); 5759 5760 EVT IdxVT = getVectorIdxTy(DAG.getDataLayout()); 5761 unsigned NumElem = StVT.getVectorNumElements(); 5762 5763 // A vector must always be stored in memory as-is, i.e. without any padding 5764 // between the elements, since various code depend on it, e.g. in the 5765 // handling of a bitcast of a vector type to int, which may be done with a 5766 // vector store followed by an integer load. A vector that does not have 5767 // elements that are byte-sized must therefore be stored as an integer 5768 // built out of the extracted vector elements. 5769 if (!MemSclVT.isByteSized()) { 5770 unsigned NumBits = StVT.getSizeInBits(); 5771 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 5772 5773 SDValue CurrVal = DAG.getConstant(0, SL, IntVT); 5774 5775 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 5776 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 5777 DAG.getConstant(Idx, SL, IdxVT)); 5778 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt); 5779 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc); 5780 unsigned ShiftIntoIdx = 5781 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 5782 SDValue ShiftAmount = 5783 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT); 5784 SDValue ShiftedElt = 5785 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount); 5786 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt); 5787 } 5788 5789 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(), 5790 ST->getAlignment(), ST->getMemOperand()->getFlags(), 5791 ST->getAAInfo()); 5792 } 5793 5794 // Store Stride in bytes 5795 unsigned Stride = MemSclVT.getSizeInBits() / 8; 5796 assert(Stride && "Zero stride!"); 5797 // Extract each of the elements from the original vector and save them into 5798 // memory individually. 5799 SmallVector<SDValue, 8> Stores; 5800 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 5801 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 5802 DAG.getConstant(Idx, SL, IdxVT)); 5803 5804 SDValue Ptr = DAG.getObjectPtrOffset(SL, BasePtr, Idx * Stride); 5805 5806 // This scalar TruncStore may be illegal, but we legalize it later. 5807 SDValue Store = DAG.getTruncStore( 5808 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 5809 MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride), 5810 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 5811 5812 Stores.push_back(Store); 5813 } 5814 5815 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 5816 } 5817 5818 std::pair<SDValue, SDValue> 5819 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 5820 assert(LD->getAddressingMode() == ISD::UNINDEXED && 5821 "unaligned indexed loads not implemented!"); 5822 SDValue Chain = LD->getChain(); 5823 SDValue Ptr = LD->getBasePtr(); 5824 EVT VT = LD->getValueType(0); 5825 EVT LoadedVT = LD->getMemoryVT(); 5826 SDLoc dl(LD); 5827 auto &MF = DAG.getMachineFunction(); 5828 5829 if (VT.isFloatingPoint() || VT.isVector()) { 5830 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 5831 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 5832 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) && 5833 LoadedVT.isVector()) { 5834 // Scalarize the load and let the individual components be handled. 5835 SDValue Scalarized = scalarizeVectorLoad(LD, DAG); 5836 if (Scalarized->getOpcode() == ISD::MERGE_VALUES) 5837 return std::make_pair(Scalarized.getOperand(0), Scalarized.getOperand(1)); 5838 return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1)); 5839 } 5840 5841 // Expand to a (misaligned) integer load of the same size, 5842 // then bitconvert to floating point or vector. 5843 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 5844 LD->getMemOperand()); 5845 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 5846 if (LoadedVT != VT) 5847 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 5848 ISD::ANY_EXTEND, dl, VT, Result); 5849 5850 return std::make_pair(Result, newLoad.getValue(1)); 5851 } 5852 5853 // Copy the value to a (aligned) stack slot using (unaligned) integer 5854 // loads and stores, then do a (aligned) load from the stack slot. 5855 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 5856 unsigned LoadedBytes = LoadedVT.getStoreSize(); 5857 unsigned RegBytes = RegVT.getSizeInBits() / 8; 5858 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 5859 5860 // Make sure the stack slot is also aligned for the register type. 5861 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 5862 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex(); 5863 SmallVector<SDValue, 8> Stores; 5864 SDValue StackPtr = StackBase; 5865 unsigned Offset = 0; 5866 5867 EVT PtrVT = Ptr.getValueType(); 5868 EVT StackPtrVT = StackPtr.getValueType(); 5869 5870 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 5871 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 5872 5873 // Do all but one copies using the full register width. 5874 for (unsigned i = 1; i < NumRegs; i++) { 5875 // Load one integer register's worth from the original location. 5876 SDValue Load = DAG.getLoad( 5877 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 5878 MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(), 5879 LD->getAAInfo()); 5880 // Follow the load with a store to the stack slot. Remember the store. 5881 Stores.push_back(DAG.getStore( 5882 Load.getValue(1), dl, Load, StackPtr, 5883 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset))); 5884 // Increment the pointers. 5885 Offset += RegBytes; 5886 5887 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 5888 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 5889 } 5890 5891 // The last copy may be partial. Do an extending load. 5892 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 5893 8 * (LoadedBytes - Offset)); 5894 SDValue Load = 5895 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 5896 LD->getPointerInfo().getWithOffset(Offset), MemVT, 5897 MinAlign(LD->getAlignment(), Offset), 5898 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 5899 // Follow the load with a store to the stack slot. Remember the store. 5900 // On big-endian machines this requires a truncating store to ensure 5901 // that the bits end up in the right place. 5902 Stores.push_back(DAG.getTruncStore( 5903 Load.getValue(1), dl, Load, StackPtr, 5904 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT)); 5905 5906 // The order of the stores doesn't matter - say it with a TokenFactor. 5907 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 5908 5909 // Finally, perform the original load only redirected to the stack slot. 5910 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 5911 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), 5912 LoadedVT); 5913 5914 // Callers expect a MERGE_VALUES node. 5915 return std::make_pair(Load, TF); 5916 } 5917 5918 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 5919 "Unaligned load of unsupported type."); 5920 5921 // Compute the new VT that is half the size of the old one. This is an 5922 // integer MVT. 5923 unsigned NumBits = LoadedVT.getSizeInBits(); 5924 EVT NewLoadedVT; 5925 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 5926 NumBits >>= 1; 5927 5928 unsigned Alignment = LD->getAlignment(); 5929 unsigned IncrementSize = NumBits / 8; 5930 ISD::LoadExtType HiExtType = LD->getExtensionType(); 5931 5932 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 5933 if (HiExtType == ISD::NON_EXTLOAD) 5934 HiExtType = ISD::ZEXTLOAD; 5935 5936 // Load the value in two parts 5937 SDValue Lo, Hi; 5938 if (DAG.getDataLayout().isLittleEndian()) { 5939 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 5940 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 5941 LD->getAAInfo()); 5942 5943 Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize); 5944 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 5945 LD->getPointerInfo().getWithOffset(IncrementSize), 5946 NewLoadedVT, MinAlign(Alignment, IncrementSize), 5947 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 5948 } else { 5949 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 5950 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 5951 LD->getAAInfo()); 5952 5953 Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize); 5954 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 5955 LD->getPointerInfo().getWithOffset(IncrementSize), 5956 NewLoadedVT, MinAlign(Alignment, IncrementSize), 5957 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 5958 } 5959 5960 // aggregate the two parts 5961 SDValue ShiftAmount = 5962 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(), 5963 DAG.getDataLayout())); 5964 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 5965 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 5966 5967 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 5968 Hi.getValue(1)); 5969 5970 return std::make_pair(Result, TF); 5971 } 5972 5973 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 5974 SelectionDAG &DAG) const { 5975 assert(ST->getAddressingMode() == ISD::UNINDEXED && 5976 "unaligned indexed stores not implemented!"); 5977 SDValue Chain = ST->getChain(); 5978 SDValue Ptr = ST->getBasePtr(); 5979 SDValue Val = ST->getValue(); 5980 EVT VT = Val.getValueType(); 5981 int Alignment = ST->getAlignment(); 5982 auto &MF = DAG.getMachineFunction(); 5983 EVT StoreMemVT = ST->getMemoryVT(); 5984 5985 SDLoc dl(ST); 5986 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) { 5987 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 5988 if (isTypeLegal(intVT)) { 5989 if (!isOperationLegalOrCustom(ISD::STORE, intVT) && 5990 StoreMemVT.isVector()) { 5991 // Scalarize the store and let the individual components be handled. 5992 SDValue Result = scalarizeVectorStore(ST, DAG); 5993 return Result; 5994 } 5995 // Expand to a bitconvert of the value to the integer type of the 5996 // same size, then a (misaligned) int store. 5997 // FIXME: Does not handle truncating floating point stores! 5998 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 5999 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 6000 Alignment, ST->getMemOperand()->getFlags()); 6001 return Result; 6002 } 6003 // Do a (aligned) store to a stack slot, then copy from the stack slot 6004 // to the final destination using (unaligned) integer loads and stores. 6005 MVT RegVT = getRegisterType( 6006 *DAG.getContext(), 6007 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits())); 6008 EVT PtrVT = Ptr.getValueType(); 6009 unsigned StoredBytes = StoreMemVT.getStoreSize(); 6010 unsigned RegBytes = RegVT.getSizeInBits() / 8; 6011 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 6012 6013 // Make sure the stack slot is also aligned for the register type. 6014 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT); 6015 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 6016 6017 // Perform the original store, only redirected to the stack slot. 6018 SDValue Store = DAG.getTruncStore( 6019 Chain, dl, Val, StackPtr, 6020 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT); 6021 6022 EVT StackPtrVT = StackPtr.getValueType(); 6023 6024 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 6025 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 6026 SmallVector<SDValue, 8> Stores; 6027 unsigned Offset = 0; 6028 6029 // Do all but one copies using the full register width. 6030 for (unsigned i = 1; i < NumRegs; i++) { 6031 // Load one integer register's worth from the stack slot. 6032 SDValue Load = DAG.getLoad( 6033 RegVT, dl, Store, StackPtr, 6034 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)); 6035 // Store it to the final location. Remember the store. 6036 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 6037 ST->getPointerInfo().getWithOffset(Offset), 6038 MinAlign(ST->getAlignment(), Offset), 6039 ST->getMemOperand()->getFlags())); 6040 // Increment the pointers. 6041 Offset += RegBytes; 6042 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 6043 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 6044 } 6045 6046 // The last store may be partial. Do a truncating store. On big-endian 6047 // machines this requires an extending load from the stack slot to ensure 6048 // that the bits are in the right place. 6049 EVT LoadMemVT = 6050 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset)); 6051 6052 // Load from the stack slot. 6053 SDValue Load = DAG.getExtLoad( 6054 ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 6055 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT); 6056 6057 Stores.push_back( 6058 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 6059 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT, 6060 MinAlign(ST->getAlignment(), Offset), 6061 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 6062 // The order of the stores doesn't matter - say it with a TokenFactor. 6063 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 6064 return Result; 6065 } 6066 6067 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() && 6068 "Unaligned store of unknown type."); 6069 // Get the half-size VT 6070 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext()); 6071 int NumBits = NewStoredVT.getSizeInBits(); 6072 int IncrementSize = NumBits / 8; 6073 6074 // Divide the stored value in two parts. 6075 SDValue ShiftAmount = DAG.getConstant( 6076 NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout())); 6077 SDValue Lo = Val; 6078 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 6079 6080 // Store the two parts 6081 SDValue Store1, Store2; 6082 Store1 = DAG.getTruncStore(Chain, dl, 6083 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 6084 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 6085 ST->getMemOperand()->getFlags()); 6086 6087 Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize); 6088 Alignment = MinAlign(Alignment, IncrementSize); 6089 Store2 = DAG.getTruncStore( 6090 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 6091 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 6092 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 6093 6094 SDValue Result = 6095 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 6096 return Result; 6097 } 6098 6099 SDValue 6100 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 6101 const SDLoc &DL, EVT DataVT, 6102 SelectionDAG &DAG, 6103 bool IsCompressedMemory) const { 6104 SDValue Increment; 6105 EVT AddrVT = Addr.getValueType(); 6106 EVT MaskVT = Mask.getValueType(); 6107 assert(DataVT.getVectorNumElements() == MaskVT.getVectorNumElements() && 6108 "Incompatible types of Data and Mask"); 6109 if (IsCompressedMemory) { 6110 // Incrementing the pointer according to number of '1's in the mask. 6111 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 6112 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 6113 if (MaskIntVT.getSizeInBits() < 32) { 6114 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 6115 MaskIntVT = MVT::i32; 6116 } 6117 6118 // Count '1's with POPCNT. 6119 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 6120 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 6121 // Scale is an element size in bytes. 6122 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 6123 AddrVT); 6124 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 6125 } else 6126 Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT); 6127 6128 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 6129 } 6130 6131 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, 6132 SDValue Idx, 6133 EVT VecVT, 6134 const SDLoc &dl) { 6135 if (isa<ConstantSDNode>(Idx)) 6136 return Idx; 6137 6138 EVT IdxVT = Idx.getValueType(); 6139 unsigned NElts = VecVT.getVectorNumElements(); 6140 if (isPowerOf2_32(NElts)) { 6141 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), 6142 Log2_32(NElts)); 6143 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 6144 DAG.getConstant(Imm, dl, IdxVT)); 6145 } 6146 6147 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 6148 DAG.getConstant(NElts - 1, dl, IdxVT)); 6149 } 6150 6151 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 6152 SDValue VecPtr, EVT VecVT, 6153 SDValue Index) const { 6154 SDLoc dl(Index); 6155 // Make sure the index type is big enough to compute in. 6156 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType()); 6157 6158 EVT EltVT = VecVT.getVectorElementType(); 6159 6160 // Calculate the element offset and add it to the pointer. 6161 unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size. 6162 assert(EltSize * 8 == EltVT.getSizeInBits() && 6163 "Converting bits to bytes lost precision"); 6164 6165 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl); 6166 6167 EVT IdxVT = Index.getValueType(); 6168 6169 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 6170 DAG.getConstant(EltSize, dl, IdxVT)); 6171 return DAG.getNode(ISD::ADD, dl, IdxVT, VecPtr, Index); 6172 } 6173 6174 //===----------------------------------------------------------------------===// 6175 // Implementation of Emulated TLS Model 6176 //===----------------------------------------------------------------------===// 6177 6178 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 6179 SelectionDAG &DAG) const { 6180 // Access to address of TLS varialbe xyz is lowered to a function call: 6181 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 6182 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6183 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 6184 SDLoc dl(GA); 6185 6186 ArgListTy Args; 6187 ArgListEntry Entry; 6188 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 6189 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 6190 StringRef EmuTlsVarName(NameString); 6191 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 6192 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 6193 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 6194 Entry.Ty = VoidPtrType; 6195 Args.push_back(Entry); 6196 6197 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 6198 6199 TargetLowering::CallLoweringInfo CLI(DAG); 6200 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 6201 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 6202 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 6203 6204 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 6205 // At last for X86 targets, maybe good for other targets too? 6206 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6207 MFI.setAdjustsStack(true); // Is this only for X86 target? 6208 MFI.setHasCalls(true); 6209 6210 assert((GA->getOffset() == 0) && 6211 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 6212 return CallResult.first; 6213 } 6214 6215 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 6216 SelectionDAG &DAG) const { 6217 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 6218 if (!isCtlzFast()) 6219 return SDValue(); 6220 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6221 SDLoc dl(Op); 6222 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 6223 if (C->isNullValue() && CC == ISD::SETEQ) { 6224 EVT VT = Op.getOperand(0).getValueType(); 6225 SDValue Zext = Op.getOperand(0); 6226 if (VT.bitsLT(MVT::i32)) { 6227 VT = MVT::i32; 6228 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 6229 } 6230 unsigned Log2b = Log2_32(VT.getSizeInBits()); 6231 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 6232 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 6233 DAG.getConstant(Log2b, dl, MVT::i32)); 6234 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 6235 } 6236 } 6237 return SDValue(); 6238 } 6239 6240 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const { 6241 unsigned Opcode = Node->getOpcode(); 6242 SDValue LHS = Node->getOperand(0); 6243 SDValue RHS = Node->getOperand(1); 6244 EVT VT = LHS.getValueType(); 6245 SDLoc dl(Node); 6246 6247 assert(VT == RHS.getValueType() && "Expected operands to be the same type"); 6248 assert(VT.isInteger() && "Expected operands to be integers"); 6249 6250 // usub.sat(a, b) -> umax(a, b) - b 6251 if (Opcode == ISD::USUBSAT && isOperationLegalOrCustom(ISD::UMAX, VT)) { 6252 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS); 6253 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS); 6254 } 6255 6256 if (Opcode == ISD::UADDSAT && isOperationLegalOrCustom(ISD::UMIN, VT)) { 6257 SDValue InvRHS = DAG.getNOT(dl, RHS, VT); 6258 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS); 6259 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS); 6260 } 6261 6262 unsigned OverflowOp; 6263 switch (Opcode) { 6264 case ISD::SADDSAT: 6265 OverflowOp = ISD::SADDO; 6266 break; 6267 case ISD::UADDSAT: 6268 OverflowOp = ISD::UADDO; 6269 break; 6270 case ISD::SSUBSAT: 6271 OverflowOp = ISD::SSUBO; 6272 break; 6273 case ISD::USUBSAT: 6274 OverflowOp = ISD::USUBO; 6275 break; 6276 default: 6277 llvm_unreachable("Expected method to receive signed or unsigned saturation " 6278 "addition or subtraction node."); 6279 } 6280 6281 unsigned BitWidth = LHS.getScalarValueSizeInBits(); 6282 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6283 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), 6284 LHS, RHS); 6285 SDValue SumDiff = Result.getValue(0); 6286 SDValue Overflow = Result.getValue(1); 6287 SDValue Zero = DAG.getConstant(0, dl, VT); 6288 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT); 6289 6290 if (Opcode == ISD::UADDSAT) { 6291 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 6292 // (LHS + RHS) | OverflowMask 6293 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 6294 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask); 6295 } 6296 // Overflow ? 0xffff.... : (LHS + RHS) 6297 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff); 6298 } else if (Opcode == ISD::USUBSAT) { 6299 if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) { 6300 // (LHS - RHS) & ~OverflowMask 6301 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT); 6302 SDValue Not = DAG.getNOT(dl, OverflowMask, VT); 6303 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not); 6304 } 6305 // Overflow ? 0 : (LHS - RHS) 6306 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff); 6307 } else { 6308 // SatMax -> Overflow && SumDiff < 0 6309 // SatMin -> Overflow && SumDiff >= 0 6310 APInt MinVal = APInt::getSignedMinValue(BitWidth); 6311 APInt MaxVal = APInt::getSignedMaxValue(BitWidth); 6312 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 6313 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 6314 SDValue SumNeg = DAG.getSetCC(dl, BoolVT, SumDiff, Zero, ISD::SETLT); 6315 Result = DAG.getSelect(dl, VT, SumNeg, SatMax, SatMin); 6316 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff); 6317 } 6318 } 6319 6320 SDValue 6321 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const { 6322 assert((Node->getOpcode() == ISD::SMULFIX || 6323 Node->getOpcode() == ISD::UMULFIX || 6324 Node->getOpcode() == ISD::SMULFIXSAT) && 6325 "Expected a fixed point multiplication opcode"); 6326 6327 SDLoc dl(Node); 6328 SDValue LHS = Node->getOperand(0); 6329 SDValue RHS = Node->getOperand(1); 6330 EVT VT = LHS.getValueType(); 6331 unsigned Scale = Node->getConstantOperandVal(2); 6332 bool Saturating = Node->getOpcode() == ISD::SMULFIXSAT; 6333 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6334 unsigned VTSize = VT.getScalarSizeInBits(); 6335 6336 if (!Scale) { 6337 // [us]mul.fix(a, b, 0) -> mul(a, b) 6338 if (!Saturating && isOperationLegalOrCustom(ISD::MUL, VT)) { 6339 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 6340 } else if (Saturating && isOperationLegalOrCustom(ISD::SMULO, VT)) { 6341 SDValue Result = 6342 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS); 6343 SDValue Product = Result.getValue(0); 6344 SDValue Overflow = Result.getValue(1); 6345 SDValue Zero = DAG.getConstant(0, dl, VT); 6346 6347 APInt MinVal = APInt::getSignedMinValue(VTSize); 6348 APInt MaxVal = APInt::getSignedMaxValue(VTSize); 6349 SDValue SatMin = DAG.getConstant(MinVal, dl, VT); 6350 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT); 6351 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Product, Zero, ISD::SETLT); 6352 Result = DAG.getSelect(dl, VT, ProdNeg, SatMax, SatMin); 6353 return DAG.getSelect(dl, VT, Overflow, Result, Product); 6354 } 6355 } 6356 6357 bool Signed = 6358 Node->getOpcode() == ISD::SMULFIX || Node->getOpcode() == ISD::SMULFIXSAT; 6359 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) && 6360 "Expected scale to be less than the number of bits if signed or at " 6361 "most the number of bits if unsigned."); 6362 assert(LHS.getValueType() == RHS.getValueType() && 6363 "Expected both operands to be the same type"); 6364 6365 // Get the upper and lower bits of the result. 6366 SDValue Lo, Hi; 6367 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI; 6368 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU; 6369 if (isOperationLegalOrCustom(LoHiOp, VT)) { 6370 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS); 6371 Lo = Result.getValue(0); 6372 Hi = Result.getValue(1); 6373 } else if (isOperationLegalOrCustom(HiOp, VT)) { 6374 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 6375 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS); 6376 } else if (VT.isVector()) { 6377 return SDValue(); 6378 } else { 6379 report_fatal_error("Unable to expand fixed point multiplication."); 6380 } 6381 6382 if (Scale == VTSize) 6383 // Result is just the top half since we'd be shifting by the width of the 6384 // operand. 6385 return Hi; 6386 6387 // The result will need to be shifted right by the scale since both operands 6388 // are scaled. The result is given to us in 2 halves, so we only want part of 6389 // both in the result. 6390 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 6391 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo, 6392 DAG.getConstant(Scale, dl, ShiftTy)); 6393 if (!Saturating) 6394 return Result; 6395 6396 unsigned OverflowBits = VTSize - Scale + 1; // +1 for the sign 6397 SDValue HiMask = 6398 DAG.getConstant(APInt::getHighBitsSet(VTSize, OverflowBits), dl, VT); 6399 SDValue LoMask = DAG.getConstant( 6400 APInt::getLowBitsSet(VTSize, VTSize - OverflowBits), dl, VT); 6401 APInt MaxVal = APInt::getSignedMaxValue(VTSize); 6402 APInt MinVal = APInt::getSignedMinValue(VTSize); 6403 6404 Result = DAG.getSelectCC(dl, Hi, LoMask, 6405 DAG.getConstant(MaxVal, dl, VT), Result, 6406 ISD::SETGT); 6407 return DAG.getSelectCC(dl, Hi, HiMask, 6408 DAG.getConstant(MinVal, dl, VT), Result, 6409 ISD::SETLT); 6410 } 6411 6412 void TargetLowering::expandUADDSUBO( 6413 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 6414 SDLoc dl(Node); 6415 SDValue LHS = Node->getOperand(0); 6416 SDValue RHS = Node->getOperand(1); 6417 bool IsAdd = Node->getOpcode() == ISD::UADDO; 6418 6419 // If ADD/SUBCARRY is legal, use that instead. 6420 unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY; 6421 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) { 6422 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1)); 6423 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(), 6424 { LHS, RHS, CarryIn }); 6425 Result = SDValue(NodeCarry.getNode(), 0); 6426 Overflow = SDValue(NodeCarry.getNode(), 1); 6427 return; 6428 } 6429 6430 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 6431 LHS.getValueType(), LHS, RHS); 6432 6433 EVT ResultType = Node->getValueType(1); 6434 EVT SetCCType = getSetCCResultType( 6435 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 6436 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 6437 SDValue SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC); 6438 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 6439 } 6440 6441 void TargetLowering::expandSADDSUBO( 6442 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const { 6443 SDLoc dl(Node); 6444 SDValue LHS = Node->getOperand(0); 6445 SDValue RHS = Node->getOperand(1); 6446 bool IsAdd = Node->getOpcode() == ISD::SADDO; 6447 6448 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 6449 LHS.getValueType(), LHS, RHS); 6450 6451 EVT ResultType = Node->getValueType(1); 6452 EVT OType = getSetCCResultType( 6453 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0)); 6454 6455 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow. 6456 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT; 6457 if (isOperationLegalOrCustom(OpcSat, LHS.getValueType())) { 6458 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS); 6459 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE); 6460 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType); 6461 return; 6462 } 6463 6464 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 6465 6466 // LHSSign -> LHS >= 0 6467 // RHSSign -> RHS >= 0 6468 // SumSign -> Result >= 0 6469 // 6470 // Add: 6471 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign) 6472 // Sub: 6473 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign) 6474 SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE); 6475 SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE); 6476 SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign, 6477 IsAdd ? ISD::SETEQ : ISD::SETNE); 6478 6479 SDValue SumSign = DAG.getSetCC(dl, OType, Result, Zero, ISD::SETGE); 6480 SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE); 6481 6482 SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE); 6483 Overflow = DAG.getBoolExtOrTrunc(Cmp, dl, ResultType, ResultType); 6484 } 6485 6486 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result, 6487 SDValue &Overflow, SelectionDAG &DAG) const { 6488 SDLoc dl(Node); 6489 EVT VT = Node->getValueType(0); 6490 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 6491 SDValue LHS = Node->getOperand(0); 6492 SDValue RHS = Node->getOperand(1); 6493 bool isSigned = Node->getOpcode() == ISD::SMULO; 6494 6495 // For power-of-two multiplications we can use a simpler shift expansion. 6496 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 6497 const APInt &C = RHSC->getAPIntValue(); 6498 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 6499 if (C.isPowerOf2()) { 6500 // smulo(x, signed_min) is same as umulo(x, signed_min). 6501 bool UseArithShift = isSigned && !C.isMinSignedValue(); 6502 EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout()); 6503 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy); 6504 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt); 6505 Overflow = DAG.getSetCC(dl, SetCCVT, 6506 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 6507 dl, VT, Result, ShiftAmt), 6508 LHS, ISD::SETNE); 6509 return true; 6510 } 6511 } 6512 6513 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2); 6514 if (VT.isVector()) 6515 WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT, 6516 VT.getVectorNumElements()); 6517 6518 SDValue BottomHalf; 6519 SDValue TopHalf; 6520 static const unsigned Ops[2][3] = 6521 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 6522 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 6523 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 6524 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 6525 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 6526 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 6527 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 6528 RHS); 6529 TopHalf = BottomHalf.getValue(1); 6530 } else if (isTypeLegal(WideVT)) { 6531 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 6532 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 6533 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 6534 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul); 6535 SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl, 6536 getShiftAmountTy(WideVT, DAG.getDataLayout())); 6537 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, 6538 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt)); 6539 } else { 6540 if (VT.isVector()) 6541 return false; 6542 6543 // We can fall back to a libcall with an illegal type for the MUL if we 6544 // have a libcall big enough. 6545 // Also, we can fall back to a division in some cases, but that's a big 6546 // performance hit in the general case. 6547 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 6548 if (WideVT == MVT::i16) 6549 LC = RTLIB::MUL_I16; 6550 else if (WideVT == MVT::i32) 6551 LC = RTLIB::MUL_I32; 6552 else if (WideVT == MVT::i64) 6553 LC = RTLIB::MUL_I64; 6554 else if (WideVT == MVT::i128) 6555 LC = RTLIB::MUL_I128; 6556 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!"); 6557 6558 SDValue HiLHS; 6559 SDValue HiRHS; 6560 if (isSigned) { 6561 // The high part is obtained by SRA'ing all but one of the bits of low 6562 // part. 6563 unsigned LoSize = VT.getSizeInBits(); 6564 HiLHS = 6565 DAG.getNode(ISD::SRA, dl, VT, LHS, 6566 DAG.getConstant(LoSize - 1, dl, 6567 getPointerTy(DAG.getDataLayout()))); 6568 HiRHS = 6569 DAG.getNode(ISD::SRA, dl, VT, RHS, 6570 DAG.getConstant(LoSize - 1, dl, 6571 getPointerTy(DAG.getDataLayout()))); 6572 } else { 6573 HiLHS = DAG.getConstant(0, dl, VT); 6574 HiRHS = DAG.getConstant(0, dl, VT); 6575 } 6576 6577 // Here we're passing the 2 arguments explicitly as 4 arguments that are 6578 // pre-lowered to the correct types. This all depends upon WideVT not 6579 // being a legal type for the architecture and thus has to be split to 6580 // two arguments. 6581 SDValue Ret; 6582 if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) { 6583 // Halves of WideVT are packed into registers in different order 6584 // depending on platform endianness. This is usually handled by 6585 // the C calling convention, but we can't defer to it in 6586 // the legalizer. 6587 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS }; 6588 Ret = makeLibCall(DAG, LC, WideVT, Args, isSigned, dl, 6589 /* doesNotReturn */ false, /* isReturnValueUsed */ true, 6590 /* isPostTypeLegalization */ true).first; 6591 } else { 6592 SDValue Args[] = { HiLHS, LHS, HiRHS, RHS }; 6593 Ret = makeLibCall(DAG, LC, WideVT, Args, isSigned, dl, 6594 /* doesNotReturn */ false, /* isReturnValueUsed */ true, 6595 /* isPostTypeLegalization */ true).first; 6596 } 6597 assert(Ret.getOpcode() == ISD::MERGE_VALUES && 6598 "Ret value is a collection of constituent nodes holding result."); 6599 if (DAG.getDataLayout().isLittleEndian()) { 6600 // Same as above. 6601 BottomHalf = Ret.getOperand(0); 6602 TopHalf = Ret.getOperand(1); 6603 } else { 6604 BottomHalf = Ret.getOperand(1); 6605 TopHalf = Ret.getOperand(0); 6606 } 6607 } 6608 6609 Result = BottomHalf; 6610 if (isSigned) { 6611 SDValue ShiftAmt = DAG.getConstant( 6612 VT.getScalarSizeInBits() - 1, dl, 6613 getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout())); 6614 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt); 6615 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE); 6616 } else { 6617 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, 6618 DAG.getConstant(0, dl, VT), ISD::SETNE); 6619 } 6620 6621 // Truncate the result if SetCC returns a larger type than needed. 6622 EVT RType = Node->getValueType(1); 6623 if (RType.getSizeInBits() < Overflow.getValueSizeInBits()) 6624 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow); 6625 6626 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() && 6627 "Unexpected result type for S/UMULO legalization"); 6628 return true; 6629 } 6630 6631 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const { 6632 SDLoc dl(Node); 6633 bool NoNaN = Node->getFlags().hasNoNaNs(); 6634 unsigned BaseOpcode = 0; 6635 switch (Node->getOpcode()) { 6636 default: llvm_unreachable("Expected VECREDUCE opcode"); 6637 case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break; 6638 case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break; 6639 case ISD::VECREDUCE_ADD: BaseOpcode = ISD::ADD; break; 6640 case ISD::VECREDUCE_MUL: BaseOpcode = ISD::MUL; break; 6641 case ISD::VECREDUCE_AND: BaseOpcode = ISD::AND; break; 6642 case ISD::VECREDUCE_OR: BaseOpcode = ISD::OR; break; 6643 case ISD::VECREDUCE_XOR: BaseOpcode = ISD::XOR; break; 6644 case ISD::VECREDUCE_SMAX: BaseOpcode = ISD::SMAX; break; 6645 case ISD::VECREDUCE_SMIN: BaseOpcode = ISD::SMIN; break; 6646 case ISD::VECREDUCE_UMAX: BaseOpcode = ISD::UMAX; break; 6647 case ISD::VECREDUCE_UMIN: BaseOpcode = ISD::UMIN; break; 6648 case ISD::VECREDUCE_FMAX: 6649 BaseOpcode = NoNaN ? ISD::FMAXNUM : ISD::FMAXIMUM; 6650 break; 6651 case ISD::VECREDUCE_FMIN: 6652 BaseOpcode = NoNaN ? ISD::FMINNUM : ISD::FMINIMUM; 6653 break; 6654 } 6655 6656 SDValue Op = Node->getOperand(0); 6657 EVT VT = Op.getValueType(); 6658 6659 // Try to use a shuffle reduction for power of two vectors. 6660 if (VT.isPow2VectorType()) { 6661 while (VT.getVectorNumElements() > 1) { 6662 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 6663 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) 6664 break; 6665 6666 SDValue Lo, Hi; 6667 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl); 6668 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi); 6669 VT = HalfVT; 6670 } 6671 } 6672 6673 EVT EltVT = VT.getVectorElementType(); 6674 unsigned NumElts = VT.getVectorNumElements(); 6675 6676 SmallVector<SDValue, 8> Ops; 6677 DAG.ExtractVectorElements(Op, Ops, 0, NumElts); 6678 6679 SDValue Res = Ops[0]; 6680 for (unsigned i = 1; i < NumElts; i++) 6681 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags()); 6682 6683 // Result type may be wider than element type. 6684 if (EltVT != Node->getValueType(0)) 6685 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res); 6686 return Res; 6687 } 6688