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