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