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