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