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