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