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