1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This implements the TargetLowering class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Target/TargetLowering.h" 15 #include "llvm/ADT/BitVector.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/CodeGen/CallingConvLower.h" 18 #include "llvm/CodeGen/MachineFrameInfo.h" 19 #include "llvm/CodeGen/MachineFunction.h" 20 #include "llvm/CodeGen/MachineJumpTableInfo.h" 21 #include "llvm/CodeGen/MachineRegisterInfo.h" 22 #include "llvm/CodeGen/SelectionDAG.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/DerivedTypes.h" 25 #include "llvm/IR/GlobalVariable.h" 26 #include "llvm/IR/LLVMContext.h" 27 #include "llvm/MC/MCAsmInfo.h" 28 #include "llvm/MC/MCExpr.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/MathExtras.h" 31 #include "llvm/Target/TargetLoweringObjectFile.h" 32 #include "llvm/Target/TargetMachine.h" 33 #include "llvm/Target/TargetRegisterInfo.h" 34 #include "llvm/Target/TargetSubtargetInfo.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 because it doesn't affect the call sequence. 58 AttributeSet CallerAttrs = F->getAttributes(); 59 if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex) 60 .removeAttribute(Attribute::NoAlias).hasAttributes()) 61 return false; 62 63 // It's not safe to eliminate the sign / zero extension of the return value. 64 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) || 65 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt)) 66 return false; 67 68 // Check if the only use is a function return node. 69 return isUsedByReturnOnly(Node, Chain); 70 } 71 72 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI, 73 const uint32_t *CallerPreservedMask, 74 const SmallVectorImpl<CCValAssign> &ArgLocs, 75 const SmallVectorImpl<SDValue> &OutVals) const { 76 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 77 const CCValAssign &ArgLoc = ArgLocs[I]; 78 if (!ArgLoc.isRegLoc()) 79 continue; 80 unsigned Reg = ArgLoc.getLocReg(); 81 // Only look at callee saved registers. 82 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg)) 83 continue; 84 // Check that we pass the value used for the caller. 85 // (We look for a CopyFromReg reading a virtual register that is used 86 // for the function live-in value of register Reg) 87 SDValue Value = OutVals[I]; 88 if (Value->getOpcode() != ISD::CopyFromReg) 89 return false; 90 unsigned ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg(); 91 if (MRI.getLiveInPhysReg(ArgReg) != Reg) 92 return false; 93 } 94 return true; 95 } 96 97 /// \brief Set CallLoweringInfo attribute flags based on a call instruction 98 /// and called function attributes. 99 void TargetLoweringBase::ArgListEntry::setAttributes(ImmutableCallSite *CS, 100 unsigned AttrIdx) { 101 IsSExt = CS->paramHasAttr(AttrIdx, Attribute::SExt); 102 IsZExt = CS->paramHasAttr(AttrIdx, Attribute::ZExt); 103 IsInReg = CS->paramHasAttr(AttrIdx, Attribute::InReg); 104 IsSRet = CS->paramHasAttr(AttrIdx, Attribute::StructRet); 105 IsNest = CS->paramHasAttr(AttrIdx, Attribute::Nest); 106 IsByVal = CS->paramHasAttr(AttrIdx, Attribute::ByVal); 107 IsInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca); 108 IsReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned); 109 IsSwiftSelf = CS->paramHasAttr(AttrIdx, Attribute::SwiftSelf); 110 IsSwiftError = CS->paramHasAttr(AttrIdx, Attribute::SwiftError); 111 Alignment = CS->getParamAlignment(AttrIdx); 112 } 113 114 /// Generate a libcall taking the given operands as arguments and returning a 115 /// result of type RetVT. 116 std::pair<SDValue, SDValue> 117 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, 118 ArrayRef<SDValue> Ops, bool isSigned, 119 const SDLoc &dl, bool doesNotReturn, 120 bool isReturnValueUsed) const { 121 TargetLowering::ArgListTy Args; 122 Args.reserve(Ops.size()); 123 124 TargetLowering::ArgListEntry Entry; 125 for (SDValue Op : Ops) { 126 Entry.Node = Op; 127 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 128 Entry.IsSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned); 129 Entry.IsZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned); 130 Args.push_back(Entry); 131 } 132 133 if (LC == RTLIB::UNKNOWN_LIBCALL) 134 report_fatal_error("Unsupported library call operation!"); 135 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 136 getPointerTy(DAG.getDataLayout())); 137 138 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 139 TargetLowering::CallLoweringInfo CLI(DAG); 140 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned); 141 CLI.setDebugLoc(dl) 142 .setChain(DAG.getEntryNode()) 143 .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 144 .setNoReturn(doesNotReturn) 145 .setDiscardResult(!isReturnValueUsed) 146 .setSExtResult(signExtend) 147 .setZExtResult(!signExtend); 148 return LowerCallTo(CLI); 149 } 150 151 /// Soften the operands of a comparison. This code is shared among BR_CC, 152 /// SELECT_CC, and SETCC handlers. 153 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 154 SDValue &NewLHS, SDValue &NewRHS, 155 ISD::CondCode &CCCode, 156 const SDLoc &dl) const { 157 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128) 158 && "Unsupported setcc type!"); 159 160 // Expand into one or more soft-fp libcall(s). 161 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL; 162 bool ShouldInvertCC = false; 163 switch (CCCode) { 164 case ISD::SETEQ: 165 case ISD::SETOEQ: 166 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 167 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 168 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 169 break; 170 case ISD::SETNE: 171 case ISD::SETUNE: 172 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : 173 (VT == MVT::f64) ? RTLIB::UNE_F64 : 174 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128; 175 break; 176 case ISD::SETGE: 177 case ISD::SETOGE: 178 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 179 (VT == MVT::f64) ? RTLIB::OGE_F64 : 180 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 181 break; 182 case ISD::SETLT: 183 case ISD::SETOLT: 184 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 185 (VT == MVT::f64) ? RTLIB::OLT_F64 : 186 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 187 break; 188 case ISD::SETLE: 189 case ISD::SETOLE: 190 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 191 (VT == MVT::f64) ? RTLIB::OLE_F64 : 192 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 193 break; 194 case ISD::SETGT: 195 case ISD::SETOGT: 196 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 197 (VT == MVT::f64) ? RTLIB::OGT_F64 : 198 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 199 break; 200 case ISD::SETUO: 201 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 202 (VT == MVT::f64) ? RTLIB::UO_F64 : 203 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 204 break; 205 case ISD::SETO: 206 LC1 = (VT == MVT::f32) ? RTLIB::O_F32 : 207 (VT == MVT::f64) ? RTLIB::O_F64 : 208 (VT == MVT::f128) ? RTLIB::O_F128 : RTLIB::O_PPCF128; 209 break; 210 case ISD::SETONE: 211 // SETONE = SETOLT | SETOGT 212 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 213 (VT == MVT::f64) ? RTLIB::OLT_F64 : 214 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 215 LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 216 (VT == MVT::f64) ? RTLIB::OGT_F64 : 217 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 218 break; 219 case ISD::SETUEQ: 220 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 221 (VT == MVT::f64) ? RTLIB::UO_F64 : 222 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 223 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 224 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 225 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 226 break; 227 default: 228 // Invert CC for unordered comparisons 229 ShouldInvertCC = true; 230 switch (CCCode) { 231 case ISD::SETULT: 232 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 233 (VT == MVT::f64) ? RTLIB::OGE_F64 : 234 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 235 break; 236 case ISD::SETULE: 237 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 238 (VT == MVT::f64) ? RTLIB::OGT_F64 : 239 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 240 break; 241 case ISD::SETUGT: 242 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 243 (VT == MVT::f64) ? RTLIB::OLE_F64 : 244 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 245 break; 246 case ISD::SETUGE: 247 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 248 (VT == MVT::f64) ? RTLIB::OLT_F64 : 249 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 250 break; 251 default: llvm_unreachable("Do not know how to soften this setcc!"); 252 } 253 } 254 255 // Use the target specific return value for comparions lib calls. 256 EVT RetVT = getCmpLibcallReturnType(); 257 SDValue Ops[2] = {NewLHS, NewRHS}; 258 NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/, 259 dl).first; 260 NewRHS = DAG.getConstant(0, dl, RetVT); 261 262 CCCode = getCmpLibcallCC(LC1); 263 if (ShouldInvertCC) 264 CCCode = getSetCCInverse(CCCode, /*isInteger=*/true); 265 266 if (LC2 != RTLIB::UNKNOWN_LIBCALL) { 267 SDValue Tmp = DAG.getNode( 268 ISD::SETCC, dl, 269 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT), 270 NewLHS, NewRHS, DAG.getCondCode(CCCode)); 271 NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/, 272 dl).first; 273 NewLHS = DAG.getNode( 274 ISD::SETCC, dl, 275 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT), 276 NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2))); 277 NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS); 278 NewRHS = SDValue(); 279 } 280 } 281 282 /// Return the entry encoding for a jump table in the current function. The 283 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum. 284 unsigned TargetLowering::getJumpTableEncoding() const { 285 // In non-pic modes, just use the address of a block. 286 if (!isPositionIndependent()) 287 return MachineJumpTableInfo::EK_BlockAddress; 288 289 // In PIC mode, if the target supports a GPRel32 directive, use it. 290 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr) 291 return MachineJumpTableInfo::EK_GPRel32BlockAddress; 292 293 // Otherwise, use a label difference. 294 return MachineJumpTableInfo::EK_LabelDifference32; 295 } 296 297 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table, 298 SelectionDAG &DAG) const { 299 // If our PIC model is GP relative, use the global offset table as the base. 300 unsigned JTEncoding = getJumpTableEncoding(); 301 302 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) || 303 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress)) 304 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout())); 305 306 return Table; 307 } 308 309 /// This returns the relocation base for the given PIC jumptable, the same as 310 /// getPICJumpTableRelocBase, but as an MCExpr. 311 const MCExpr * 312 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 313 unsigned JTI,MCContext &Ctx) const{ 314 // The normal PIC reloc base is the label at the start of the jump table. 315 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx); 316 } 317 318 bool 319 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 320 const TargetMachine &TM = getTargetMachine(); 321 const GlobalValue *GV = GA->getGlobal(); 322 323 // If the address is not even local to this DSO we will have to load it from 324 // a got and then add the offset. 325 if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 326 return false; 327 328 // If the code is position independent we will have to add a base register. 329 if (isPositionIndependent()) 330 return false; 331 332 // Otherwise we can do it. 333 return true; 334 } 335 336 //===----------------------------------------------------------------------===// 337 // Optimization Methods 338 //===----------------------------------------------------------------------===// 339 340 /// If the specified instruction has a constant integer operand and there are 341 /// bits set in that constant that are not demanded, then clear those bits and 342 /// return true. 343 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant( 344 SDValue Op, const APInt &Demanded) { 345 SDLoc DL(Op); 346 unsigned Opcode = Op.getOpcode(); 347 348 // FIXME: ISD::SELECT, ISD::SELECT_CC 349 switch (Opcode) { 350 default: 351 break; 352 case ISD::XOR: 353 case ISD::AND: 354 case ISD::OR: { 355 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 356 if (!Op1C) 357 return false; 358 359 // If this is a 'not' op, don't touch it because that's a canonical form. 360 const APInt &C = Op1C->getAPIntValue(); 361 if (Opcode == ISD::XOR && (C | ~Demanded).isAllOnesValue()) 362 return false; 363 364 if (C.intersects(~Demanded)) { 365 EVT VT = Op.getValueType(); 366 SDValue NewC = DAG.getConstant(Demanded & C, DL, VT); 367 SDValue NewOp = DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC); 368 return CombineTo(Op, NewOp); 369 } 370 371 break; 372 } 373 } 374 375 return false; 376 } 377 378 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. 379 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be 380 /// generalized for targets with other types of implicit widening casts. 381 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op, 382 unsigned BitWidth, 383 const APInt &Demanded, 384 const SDLoc &dl) { 385 assert(Op.getNumOperands() == 2 && 386 "ShrinkDemandedOp only supports binary operators!"); 387 assert(Op.getNode()->getNumValues() == 1 && 388 "ShrinkDemandedOp only supports nodes with one result!"); 389 390 // Early return, as this function cannot handle vector types. 391 if (Op.getValueType().isVector()) 392 return false; 393 394 // Don't do this if the node has another user, which may require the 395 // full value. 396 if (!Op.getNode()->hasOneUse()) 397 return false; 398 399 // Search for the smallest integer type with free casts to and from 400 // Op's type. For expedience, just check power-of-2 integer types. 401 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 402 unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros(); 403 unsigned SmallVTBits = DemandedSize; 404 if (!isPowerOf2_32(SmallVTBits)) 405 SmallVTBits = NextPowerOf2(SmallVTBits); 406 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) { 407 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits); 408 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) && 409 TLI.isZExtFree(SmallVT, Op.getValueType())) { 410 // We found a type with free casts. 411 SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT, 412 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, 413 Op.getNode()->getOperand(0)), 414 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, 415 Op.getNode()->getOperand(1))); 416 bool NeedZext = DemandedSize > SmallVTBits; 417 SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND, 418 dl, Op.getValueType(), X); 419 return CombineTo(Op, Z); 420 } 421 } 422 return false; 423 } 424 425 bool 426 TargetLowering::TargetLoweringOpt::SimplifyDemandedBits(SDNode *User, 427 unsigned OpIdx, 428 const APInt &Demanded, 429 DAGCombinerInfo &DCI) { 430 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 431 SDValue Op = User->getOperand(OpIdx); 432 APInt KnownZero, KnownOne; 433 434 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, 435 *this, 0, true)) 436 return false; 437 438 439 // Old will not always be the same as Op. For example: 440 // 441 // Demanded = 0xffffff 442 // Op = i64 truncate (i32 and x, 0xffffff) 443 // In this case simplify demand bits will want to replace the 'and' node 444 // with the value 'x', which will give us: 445 // Old = i32 and x, 0xffffff 446 // New = x 447 if (Old.hasOneUse()) { 448 // For the one use case, we just commit the change. 449 DCI.CommitTargetLoweringOpt(*this); 450 return true; 451 } 452 453 // If Old has more than one use then it must be Op, because the 454 // AssumeSingleUse flag is not propogated to recursive calls of 455 // SimplifyDemanded bits, so the only node with multiple use that 456 // it will attempt to combine will be opt. 457 assert(Old == Op); 458 459 SmallVector <SDValue, 4> NewOps; 460 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 461 if (i == OpIdx) { 462 NewOps.push_back(New); 463 continue; 464 } 465 NewOps.push_back(User->getOperand(i)); 466 } 467 DAG.UpdateNodeOperands(User, NewOps); 468 // Op has less users now, so we may be able to perform additional combines 469 // with it. 470 DCI.AddToWorklist(Op.getNode()); 471 // User's operands have been updated, so we may be able to do new combines 472 // with it. 473 DCI.AddToWorklist(User); 474 return true; 475 } 476 477 bool TargetLowering::SimplifyDemandedBits(SDValue Op, APInt &DemandedMask, 478 DAGCombinerInfo &DCI) const { 479 480 SelectionDAG &DAG = DCI.DAG; 481 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 482 !DCI.isBeforeLegalizeOps()); 483 APInt KnownZero, KnownOne; 484 485 bool Simplified = SimplifyDemandedBits(Op, DemandedMask, KnownZero, KnownOne, 486 TLO); 487 if (Simplified) 488 DCI.CommitTargetLoweringOpt(TLO); 489 return Simplified; 490 } 491 492 /// Look at Op. At this point, we know that only the DemandedMask bits of the 493 /// result of Op are ever used downstream. If we can use this information to 494 /// simplify Op, create a new simplified DAG node and return true, returning the 495 /// original and new nodes in Old and New. Otherwise, analyze the expression and 496 /// return a mask of KnownOne and KnownZero bits for the expression (used to 497 /// simplify the caller). The KnownZero/One bits may only be accurate for those 498 /// bits in the DemandedMask. 499 bool TargetLowering::SimplifyDemandedBits(SDValue Op, 500 const APInt &DemandedMask, 501 APInt &KnownZero, 502 APInt &KnownOne, 503 TargetLoweringOpt &TLO, 504 unsigned Depth, 505 bool AssumeSingleUse) const { 506 unsigned BitWidth = DemandedMask.getBitWidth(); 507 assert(Op.getScalarValueSizeInBits() == BitWidth && 508 "Mask size mismatches value type size!"); 509 APInt NewMask = DemandedMask; 510 SDLoc dl(Op); 511 auto &DL = TLO.DAG.getDataLayout(); 512 513 // Don't know anything. 514 KnownZero = KnownOne = APInt(BitWidth, 0); 515 516 // Other users may use these bits. 517 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) { 518 if (Depth != 0) { 519 // If not at the root, Just compute the KnownZero/KnownOne bits to 520 // simplify things downstream. 521 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth); 522 return false; 523 } 524 // If this is the root being simplified, allow it to have multiple uses, 525 // just set the NewMask to all bits. 526 NewMask = APInt::getAllOnesValue(BitWidth); 527 } else if (DemandedMask == 0) { 528 // Not demanding any bits from Op. 529 if (!Op.isUndef()) 530 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType())); 531 return false; 532 } else if (Depth == 6) { // Limit search depth. 533 return false; 534 } 535 536 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut; 537 switch (Op.getOpcode()) { 538 case ISD::Constant: 539 // We know all of the bits for a constant! 540 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue(); 541 KnownZero = ~KnownOne; 542 return false; // Don't fall through, will infinitely loop. 543 case ISD::BUILD_VECTOR: 544 // Collect the known bits that are shared by every constant vector element. 545 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth); 546 for (SDValue SrcOp : Op->ops()) { 547 if (!isa<ConstantSDNode>(SrcOp)) { 548 // We can only handle all constant values - bail out with no known bits. 549 KnownZero = KnownOne = APInt(BitWidth, 0); 550 return false; 551 } 552 KnownOne2 = cast<ConstantSDNode>(SrcOp)->getAPIntValue(); 553 KnownZero2 = ~KnownOne2; 554 555 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 556 if (KnownOne2.getBitWidth() != BitWidth) { 557 assert(KnownOne2.getBitWidth() > BitWidth && 558 KnownZero2.getBitWidth() > BitWidth && 559 "Expected BUILD_VECTOR implicit truncation"); 560 KnownOne2 = KnownOne2.trunc(BitWidth); 561 KnownZero2 = KnownZero2.trunc(BitWidth); 562 } 563 564 // Known bits are the values that are shared by every element. 565 // TODO: support per-element known bits. 566 KnownOne &= KnownOne2; 567 KnownZero &= KnownZero2; 568 } 569 return false; // Don't fall through, will infinitely loop. 570 case ISD::AND: 571 // If the RHS is a constant, check to see if the LHS would be zero without 572 // using the bits from the RHS. Below, we use knowledge about the RHS to 573 // simplify the LHS, here we're using information from the LHS to simplify 574 // the RHS. 575 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 576 SDValue Op0 = Op.getOperand(0); 577 APInt LHSZero, LHSOne; 578 // Do not increment Depth here; that can cause an infinite loop. 579 TLO.DAG.computeKnownBits(Op0, LHSZero, LHSOne, Depth); 580 // If the LHS already has zeros where RHSC does, this and is dead. 581 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask)) 582 return TLO.CombineTo(Op, Op0); 583 584 // If any of the set bits in the RHS are known zero on the LHS, shrink 585 // the constant. 586 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask)) 587 return true; 588 589 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its 590 // constant, but if this 'and' is only clearing bits that were just set by 591 // the xor, then this 'and' can be eliminated by shrinking the mask of 592 // the xor. For example, for a 32-bit X: 593 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1 594 if (isBitwiseNot(Op0) && Op0.hasOneUse() && 595 LHSOne == ~RHSC->getAPIntValue()) { 596 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, Op.getValueType(), 597 Op0.getOperand(0), Op.getOperand(1)); 598 return TLO.CombineTo(Op, Xor); 599 } 600 } 601 602 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero, 603 KnownOne, TLO, Depth+1)) 604 return true; 605 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 606 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask, 607 KnownZero2, KnownOne2, TLO, Depth+1)) 608 return true; 609 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 610 611 // If all of the demanded bits are known one on one side, return the other. 612 // These bits cannot contribute to the result of the 'and'. 613 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask)) 614 return TLO.CombineTo(Op, Op.getOperand(0)); 615 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask)) 616 return TLO.CombineTo(Op, Op.getOperand(1)); 617 // If all of the demanded bits in the inputs are known zeros, return zero. 618 if ((NewMask & (KnownZero|KnownZero2)) == NewMask) 619 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, Op.getValueType())); 620 // If the RHS is a constant, see if we can simplify it. 621 if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask)) 622 return true; 623 // If the operation can be done in a smaller type, do so. 624 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) 625 return true; 626 627 // Output known-1 bits are only known if set in both the LHS & RHS. 628 KnownOne &= KnownOne2; 629 // Output known-0 are known to be clear if zero in either the LHS | RHS. 630 KnownZero |= KnownZero2; 631 break; 632 case ISD::OR: 633 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero, 634 KnownOne, TLO, Depth+1)) 635 return true; 636 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 637 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask, 638 KnownZero2, KnownOne2, TLO, Depth+1)) 639 return true; 640 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 641 642 // If all of the demanded bits are known zero on one side, return the other. 643 // These bits cannot contribute to the result of the 'or'. 644 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask)) 645 return TLO.CombineTo(Op, Op.getOperand(0)); 646 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask)) 647 return TLO.CombineTo(Op, Op.getOperand(1)); 648 // If all of the potentially set bits on one side are known to be set on 649 // the other side, just use the 'other' side. 650 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask)) 651 return TLO.CombineTo(Op, Op.getOperand(0)); 652 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask)) 653 return TLO.CombineTo(Op, Op.getOperand(1)); 654 // If the RHS is a constant, see if we can simplify it. 655 if (TLO.ShrinkDemandedConstant(Op, NewMask)) 656 return true; 657 // If the operation can be done in a smaller type, do so. 658 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) 659 return true; 660 661 // Output known-0 bits are only known if clear in both the LHS & RHS. 662 KnownZero &= KnownZero2; 663 // Output known-1 are known to be set if set in either the LHS | RHS. 664 KnownOne |= KnownOne2; 665 break; 666 case ISD::XOR: 667 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero, 668 KnownOne, TLO, Depth+1)) 669 return true; 670 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 671 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2, 672 KnownOne2, TLO, Depth+1)) 673 return true; 674 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 675 676 // If all of the demanded bits are known zero on one side, return the other. 677 // These bits cannot contribute to the result of the 'xor'. 678 if ((KnownZero & NewMask) == NewMask) 679 return TLO.CombineTo(Op, Op.getOperand(0)); 680 if ((KnownZero2 & NewMask) == NewMask) 681 return TLO.CombineTo(Op, Op.getOperand(1)); 682 // If the operation can be done in a smaller type, do so. 683 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) 684 return true; 685 686 // If all of the unknown bits are known to be zero on one side or the other 687 // (but not both) turn this into an *inclusive* or. 688 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 689 if ((NewMask & ~KnownZero & ~KnownZero2) == 0) 690 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(), 691 Op.getOperand(0), 692 Op.getOperand(1))); 693 694 // Output known-0 bits are known if clear or set in both the LHS & RHS. 695 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2); 696 // Output known-1 are known to be set if set in only one of the LHS, RHS. 697 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2); 698 699 // If all of the demanded bits on one side are known, and all of the set 700 // bits on that side are also known to be set on the other side, turn this 701 // into an AND, as we know the bits will be cleared. 702 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 703 // NB: it is okay if more bits are known than are requested 704 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side 705 if (KnownOne == KnownOne2) { // set bits are the same on both sides 706 EVT VT = Op.getValueType(); 707 SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, dl, VT); 708 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, 709 Op.getOperand(0), ANDC)); 710 } 711 } 712 713 // If the RHS is a constant, see if we can simplify it. 714 // for XOR, we prefer to force bits to 1 if they will make a -1. 715 // If we can't force bits, try to shrink the constant. 716 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 717 APInt Expanded = C->getAPIntValue() | (~NewMask); 718 // If we can expand it to have all bits set, do it. 719 if (Expanded.isAllOnesValue()) { 720 if (Expanded != C->getAPIntValue()) { 721 EVT VT = Op.getValueType(); 722 SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0), 723 TLO.DAG.getConstant(Expanded, dl, VT)); 724 return TLO.CombineTo(Op, New); 725 } 726 // If it already has all the bits set, nothing to change 727 // but don't shrink either! 728 } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) { 729 return true; 730 } 731 } 732 733 KnownZero = KnownZeroOut; 734 KnownOne = KnownOneOut; 735 break; 736 case ISD::SELECT: 737 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero, 738 KnownOne, TLO, Depth+1)) 739 return true; 740 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2, 741 KnownOne2, TLO, Depth+1)) 742 return true; 743 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 744 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 745 746 // If the operands are constants, see if we can simplify them. 747 if (TLO.ShrinkDemandedConstant(Op, NewMask)) 748 return true; 749 750 // Only known if known in both the LHS and RHS. 751 KnownOne &= KnownOne2; 752 KnownZero &= KnownZero2; 753 break; 754 case ISD::SELECT_CC: 755 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero, 756 KnownOne, TLO, Depth+1)) 757 return true; 758 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2, 759 KnownOne2, TLO, Depth+1)) 760 return true; 761 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 762 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 763 764 // If the operands are constants, see if we can simplify them. 765 if (TLO.ShrinkDemandedConstant(Op, NewMask)) 766 return true; 767 768 // Only known if known in both the LHS and RHS. 769 KnownOne &= KnownOne2; 770 KnownZero &= KnownZero2; 771 break; 772 case ISD::SETCC: { 773 SDValue Op0 = Op.getOperand(0); 774 SDValue Op1 = Op.getOperand(1); 775 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 776 // If (1) we only need the sign-bit, (2) the setcc operands are the same 777 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 778 // -1, we may be able to bypass the setcc. 779 if (NewMask.isSignBit() && Op0.getScalarValueSizeInBits() == BitWidth && 780 getBooleanContents(Op.getValueType()) == 781 BooleanContent::ZeroOrNegativeOneBooleanContent) { 782 // If we're testing X < 0, then this compare isn't needed - just use X! 783 // FIXME: We're limiting to integer types here, but this should also work 784 // if we don't care about FP signed-zero. The use of SETLT with FP means 785 // that we don't care about NaNs. 786 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 787 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 788 return TLO.CombineTo(Op, Op0); 789 790 // TODO: Should we check for other forms of sign-bit comparisons? 791 // Examples: X <= -1, X >= 0 792 } 793 break; 794 } 795 case ISD::SHL: 796 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 797 unsigned ShAmt = SA->getZExtValue(); 798 SDValue InOp = Op.getOperand(0); 799 800 // If the shift count is an invalid immediate, don't do anything. 801 if (ShAmt >= BitWidth) 802 break; 803 804 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 805 // single shift. We can do this if the bottom bits (which are shifted 806 // out) are never demanded. 807 if (InOp.getOpcode() == ISD::SRL && 808 isa<ConstantSDNode>(InOp.getOperand(1))) { 809 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) { 810 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue(); 811 unsigned Opc = ISD::SHL; 812 int Diff = ShAmt-C1; 813 if (Diff < 0) { 814 Diff = -Diff; 815 Opc = ISD::SRL; 816 } 817 818 SDValue NewSA = 819 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType()); 820 EVT VT = Op.getValueType(); 821 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, 822 InOp.getOperand(0), NewSA)); 823 } 824 } 825 826 if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt), 827 KnownZero, KnownOne, TLO, Depth+1)) 828 return true; 829 830 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 831 // are not demanded. This will likely allow the anyext to be folded away. 832 if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) { 833 SDValue InnerOp = InOp.getNode()->getOperand(0); 834 EVT InnerVT = InnerOp.getValueType(); 835 unsigned InnerBits = InnerVT.getSizeInBits(); 836 if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 && 837 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 838 EVT ShTy = getShiftAmountTy(InnerVT, DL); 839 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits())) 840 ShTy = InnerVT; 841 SDValue NarrowShl = 842 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp, 843 TLO.DAG.getConstant(ShAmt, dl, ShTy)); 844 return 845 TLO.CombineTo(Op, 846 TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), 847 NarrowShl)); 848 } 849 // Repeat the SHL optimization above in cases where an extension 850 // intervenes: (shl (anyext (shr x, c1)), c2) to 851 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 852 // aren't demanded (as above) and that the shifted upper c1 bits of 853 // x aren't demanded. 854 if (InOp.hasOneUse() && 855 InnerOp.getOpcode() == ISD::SRL && 856 InnerOp.hasOneUse() && 857 isa<ConstantSDNode>(InnerOp.getOperand(1))) { 858 uint64_t InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1)) 859 ->getZExtValue(); 860 if (InnerShAmt < ShAmt && 861 InnerShAmt < InnerBits && 862 NewMask.lshr(InnerBits - InnerShAmt + ShAmt) == 0 && 863 NewMask.trunc(ShAmt) == 0) { 864 SDValue NewSA = 865 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, 866 Op.getOperand(1).getValueType()); 867 EVT VT = Op.getValueType(); 868 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 869 InnerOp.getOperand(0)); 870 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, 871 NewExt, NewSA)); 872 } 873 } 874 } 875 876 KnownZero <<= SA->getZExtValue(); 877 KnownOne <<= SA->getZExtValue(); 878 // low bits known zero. 879 KnownZero.setLowBits(SA->getZExtValue()); 880 } 881 break; 882 case ISD::SRL: 883 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 884 EVT VT = Op.getValueType(); 885 unsigned ShAmt = SA->getZExtValue(); 886 unsigned VTSize = VT.getSizeInBits(); 887 SDValue InOp = Op.getOperand(0); 888 889 // If the shift count is an invalid immediate, don't do anything. 890 if (ShAmt >= BitWidth) 891 break; 892 893 APInt InDemandedMask = (NewMask << ShAmt); 894 895 // If the shift is exact, then it does demand the low bits (and knows that 896 // they are zero). 897 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact()) 898 InDemandedMask.setLowBits(ShAmt); 899 900 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 901 // single shift. We can do this if the top bits (which are shifted out) 902 // are never demanded. 903 if (InOp.getOpcode() == ISD::SHL && 904 isa<ConstantSDNode>(InOp.getOperand(1))) { 905 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) { 906 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue(); 907 unsigned Opc = ISD::SRL; 908 int Diff = ShAmt-C1; 909 if (Diff < 0) { 910 Diff = -Diff; 911 Opc = ISD::SHL; 912 } 913 914 SDValue NewSA = 915 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType()); 916 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, 917 InOp.getOperand(0), NewSA)); 918 } 919 } 920 921 // Compute the new bits that are at the top now. 922 if (SimplifyDemandedBits(InOp, InDemandedMask, 923 KnownZero, KnownOne, TLO, Depth+1)) 924 return true; 925 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 926 KnownZero = KnownZero.lshr(ShAmt); 927 KnownOne = KnownOne.lshr(ShAmt); 928 929 KnownZero.setHighBits(ShAmt); // High bits known zero. 930 } 931 break; 932 case ISD::SRA: 933 // If this is an arithmetic shift right and only the low-bit is set, we can 934 // always convert this into a logical shr, even if the shift amount is 935 // variable. The low bit of the shift cannot be an input sign bit unless 936 // the shift amount is >= the size of the datatype, which is undefined. 937 if (NewMask == 1) 938 return TLO.CombineTo(Op, 939 TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(), 940 Op.getOperand(0), Op.getOperand(1))); 941 942 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 943 EVT VT = Op.getValueType(); 944 unsigned ShAmt = SA->getZExtValue(); 945 946 // If the shift count is an invalid immediate, don't do anything. 947 if (ShAmt >= BitWidth) 948 break; 949 950 APInt InDemandedMask = (NewMask << ShAmt); 951 952 // If the shift is exact, then it does demand the low bits (and knows that 953 // they are zero). 954 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact()) 955 InDemandedMask.setLowBits(ShAmt); 956 957 // If any of the demanded bits are produced by the sign extension, we also 958 // demand the input sign bit. 959 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 960 if (HighBits.intersects(NewMask)) 961 InDemandedMask |= APInt::getSignBit(VT.getScalarSizeInBits()); 962 963 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask, 964 KnownZero, KnownOne, TLO, Depth+1)) 965 return true; 966 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 967 KnownZero = KnownZero.lshr(ShAmt); 968 KnownOne = KnownOne.lshr(ShAmt); 969 970 // Handle the sign bit, adjusted to where it is now in the mask. 971 APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt); 972 973 // If the input sign bit is known to be zero, or if none of the top bits 974 // are demanded, turn this into an unsigned shift right. 975 if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) { 976 SDNodeFlags Flags; 977 Flags.setExact(cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact()); 978 return TLO.CombineTo(Op, 979 TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0), 980 Op.getOperand(1), &Flags)); 981 } 982 983 int Log2 = NewMask.exactLogBase2(); 984 if (Log2 >= 0) { 985 // The bit must come from the sign. 986 SDValue NewSA = 987 TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, 988 Op.getOperand(1).getValueType()); 989 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, 990 Op.getOperand(0), NewSA)); 991 } 992 993 if (KnownOne.intersects(SignBit)) 994 // New bits are known one. 995 KnownOne |= HighBits; 996 } 997 break; 998 case ISD::SIGN_EXTEND_INREG: { 999 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1000 1001 APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1); 1002 // If we only care about the highest bit, don't bother shifting right. 1003 if (MsbMask == NewMask) { 1004 unsigned ShAmt = ExVT.getScalarSizeInBits(); 1005 SDValue InOp = Op.getOperand(0); 1006 unsigned VTBits = Op->getValueType(0).getScalarSizeInBits(); 1007 bool AlreadySignExtended = 1008 TLO.DAG.ComputeNumSignBits(InOp) >= VTBits-ShAmt+1; 1009 // However if the input is already sign extended we expect the sign 1010 // extension to be dropped altogether later and do not simplify. 1011 if (!AlreadySignExtended) { 1012 // Compute the correct shift amount type, which must be getShiftAmountTy 1013 // for scalar types after legalization. 1014 EVT ShiftAmtTy = Op.getValueType(); 1015 if (TLO.LegalTypes() && !ShiftAmtTy.isVector()) 1016 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL); 1017 1018 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, dl, 1019 ShiftAmtTy); 1020 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, 1021 Op.getValueType(), InOp, 1022 ShiftAmt)); 1023 } 1024 } 1025 1026 // Sign extension. Compute the demanded bits in the result that are not 1027 // present in the input. 1028 APInt NewBits = 1029 APInt::getHighBitsSet(BitWidth, 1030 BitWidth - ExVT.getScalarSizeInBits()); 1031 1032 // If none of the extended bits are demanded, eliminate the sextinreg. 1033 if ((NewBits & NewMask) == 0) 1034 return TLO.CombineTo(Op, Op.getOperand(0)); 1035 1036 APInt InSignBit = 1037 APInt::getSignBit(ExVT.getScalarSizeInBits()).zext(BitWidth); 1038 APInt InputDemandedBits = 1039 APInt::getLowBitsSet(BitWidth, 1040 ExVT.getScalarSizeInBits()) & 1041 NewMask; 1042 1043 // Since the sign extended bits are demanded, we know that the sign 1044 // bit is demanded. 1045 InputDemandedBits |= InSignBit; 1046 1047 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits, 1048 KnownZero, KnownOne, TLO, Depth+1)) 1049 return true; 1050 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1051 1052 // If the sign bit of the input is known set or clear, then we know the 1053 // top bits of the result. 1054 1055 // If the input sign bit is known zero, convert this into a zero extension. 1056 if (KnownZero.intersects(InSignBit)) 1057 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg( 1058 Op.getOperand(0), dl, ExVT.getScalarType())); 1059 1060 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set 1061 KnownOne |= NewBits; 1062 KnownZero &= ~NewBits; 1063 } else { // Input sign bit unknown 1064 KnownZero &= ~NewBits; 1065 KnownOne &= ~NewBits; 1066 } 1067 break; 1068 } 1069 case ISD::BUILD_PAIR: { 1070 EVT HalfVT = Op.getOperand(0).getValueType(); 1071 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 1072 1073 APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 1074 APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 1075 1076 APInt KnownZeroLo, KnownOneLo; 1077 APInt KnownZeroHi, KnownOneHi; 1078 1079 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownZeroLo, 1080 KnownOneLo, TLO, Depth + 1)) 1081 return true; 1082 1083 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownZeroHi, 1084 KnownOneHi, TLO, Depth + 1)) 1085 return true; 1086 1087 KnownZero = KnownZeroLo.zext(BitWidth) | 1088 KnownZeroHi.zext(BitWidth).shl(HalfBitWidth); 1089 1090 KnownOne = KnownOneLo.zext(BitWidth) | 1091 KnownOneHi.zext(BitWidth).shl(HalfBitWidth); 1092 break; 1093 } 1094 case ISD::ZERO_EXTEND: { 1095 unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 1096 APInt InMask = NewMask.trunc(OperandBitWidth); 1097 1098 // If none of the top bits are demanded, convert this into an any_extend. 1099 APInt NewBits = 1100 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask; 1101 if (!NewBits.intersects(NewMask)) 1102 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, 1103 Op.getValueType(), 1104 Op.getOperand(0))); 1105 1106 if (SimplifyDemandedBits(Op.getOperand(0), InMask, 1107 KnownZero, KnownOne, TLO, Depth+1)) 1108 return true; 1109 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1110 KnownZero = KnownZero.zext(BitWidth); 1111 KnownOne = KnownOne.zext(BitWidth); 1112 KnownZero |= NewBits; 1113 break; 1114 } 1115 case ISD::SIGN_EXTEND: { 1116 EVT InVT = Op.getOperand(0).getValueType(); 1117 unsigned InBits = InVT.getScalarSizeInBits(); 1118 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits); 1119 APInt InSignBit = APInt::getOneBitSet(BitWidth, InBits - 1); 1120 APInt NewBits = ~InMask & NewMask; 1121 1122 // If none of the top bits are demanded, convert this into an any_extend. 1123 if (NewBits == 0) 1124 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl, 1125 Op.getValueType(), 1126 Op.getOperand(0))); 1127 1128 // Since some of the sign extended bits are demanded, we know that the sign 1129 // bit is demanded. 1130 APInt InDemandedBits = InMask & NewMask; 1131 InDemandedBits |= InSignBit; 1132 InDemandedBits = InDemandedBits.trunc(InBits); 1133 1134 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero, 1135 KnownOne, TLO, Depth+1)) 1136 return true; 1137 KnownZero = KnownZero.zext(BitWidth); 1138 KnownOne = KnownOne.zext(BitWidth); 1139 1140 // If the sign bit is known zero, convert this to a zero extend. 1141 if (KnownZero.intersects(InSignBit)) 1142 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, 1143 Op.getValueType(), 1144 Op.getOperand(0))); 1145 1146 // If the sign bit is known one, the top bits match. 1147 if (KnownOne.intersects(InSignBit)) { 1148 KnownOne |= NewBits; 1149 assert((KnownZero & NewBits) == 0); 1150 } else { // Otherwise, top bits aren't known. 1151 assert((KnownOne & NewBits) == 0); 1152 assert((KnownZero & NewBits) == 0); 1153 } 1154 break; 1155 } 1156 case ISD::ANY_EXTEND: { 1157 unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 1158 APInt InMask = NewMask.trunc(OperandBitWidth); 1159 if (SimplifyDemandedBits(Op.getOperand(0), InMask, 1160 KnownZero, KnownOne, TLO, Depth+1)) 1161 return true; 1162 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1163 KnownZero = KnownZero.zext(BitWidth); 1164 KnownOne = KnownOne.zext(BitWidth); 1165 break; 1166 } 1167 case ISD::TRUNCATE: { 1168 // Simplify the input, using demanded bit information, and compute the known 1169 // zero/one bits live out. 1170 unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 1171 APInt TruncMask = NewMask.zext(OperandBitWidth); 1172 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask, 1173 KnownZero, KnownOne, TLO, Depth+1)) 1174 return true; 1175 KnownZero = KnownZero.trunc(BitWidth); 1176 KnownOne = KnownOne.trunc(BitWidth); 1177 1178 // If the input is only used by this truncate, see if we can shrink it based 1179 // on the known demanded bits. 1180 if (Op.getOperand(0).getNode()->hasOneUse()) { 1181 SDValue In = Op.getOperand(0); 1182 switch (In.getOpcode()) { 1183 default: break; 1184 case ISD::SRL: 1185 // Shrink SRL by a constant if none of the high bits shifted in are 1186 // demanded. 1187 if (TLO.LegalTypes() && 1188 !isTypeDesirableForOp(ISD::SRL, Op.getValueType())) 1189 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 1190 // undesirable. 1191 break; 1192 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1)); 1193 if (!ShAmt) 1194 break; 1195 SDValue Shift = In.getOperand(1); 1196 if (TLO.LegalTypes()) { 1197 uint64_t ShVal = ShAmt->getZExtValue(); 1198 Shift = TLO.DAG.getConstant(ShVal, dl, 1199 getShiftAmountTy(Op.getValueType(), DL)); 1200 } 1201 1202 APInt HighBits = APInt::getHighBitsSet(OperandBitWidth, 1203 OperandBitWidth - BitWidth); 1204 HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth); 1205 1206 if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) { 1207 // None of the shifted in bits are needed. Add a truncate of the 1208 // shift input, then shift it. 1209 SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl, 1210 Op.getValueType(), 1211 In.getOperand(0)); 1212 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, 1213 Op.getValueType(), 1214 NewTrunc, 1215 Shift)); 1216 } 1217 break; 1218 } 1219 } 1220 1221 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1222 break; 1223 } 1224 case ISD::AssertZext: { 1225 // AssertZext demands all of the high bits, plus any of the low bits 1226 // demanded by its users. 1227 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1228 APInt InMask = APInt::getLowBitsSet(BitWidth, 1229 VT.getSizeInBits()); 1230 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask, 1231 KnownZero, KnownOne, TLO, Depth+1)) 1232 return true; 1233 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1234 1235 KnownZero |= ~InMask & NewMask; 1236 break; 1237 } 1238 case ISD::BITCAST: 1239 // If this is an FP->Int bitcast and if the sign bit is the only 1240 // thing demanded, turn this into a FGETSIGN. 1241 if (!TLO.LegalOperations() && 1242 !Op.getValueType().isVector() && 1243 !Op.getOperand(0).getValueType().isVector() && 1244 NewMask == APInt::getSignBit(Op.getValueSizeInBits()) && 1245 Op.getOperand(0).getValueType().isFloatingPoint()) { 1246 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType()); 1247 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 1248 if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple() && 1249 Op.getOperand(0).getValueType() != MVT::f128) { 1250 // Cannot eliminate/lower SHL for f128 yet. 1251 EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32; 1252 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 1253 // place. We expect the SHL to be eliminated by other optimizations. 1254 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0)); 1255 unsigned OpVTSizeInBits = Op.getValueSizeInBits(); 1256 if (!OpVTLegal && OpVTSizeInBits > 32) 1257 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign); 1258 unsigned ShVal = Op.getValueSizeInBits() - 1; 1259 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, Op.getValueType()); 1260 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, 1261 Op.getValueType(), 1262 Sign, ShAmt)); 1263 } 1264 } 1265 break; 1266 case ISD::ADD: 1267 case ISD::MUL: 1268 case ISD::SUB: { 1269 // Add, Sub, and Mul don't demand any bits in positions beyond that 1270 // of the highest bit demanded of them. 1271 APInt LoMask = APInt::getLowBitsSet(BitWidth, 1272 BitWidth - NewMask.countLeadingZeros()); 1273 if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2, 1274 KnownOne2, TLO, Depth+1) || 1275 SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2, 1276 KnownOne2, TLO, Depth+1) || 1277 // See if the operation should be performed at a smaller bit width. 1278 TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) { 1279 const SDNodeFlags *Flags = Op.getNode()->getFlags(); 1280 if (Flags->hasNoSignedWrap() || Flags->hasNoUnsignedWrap()) { 1281 // Disable the nsw and nuw flags. We can no longer guarantee that we 1282 // won't wrap after simplification. 1283 SDNodeFlags NewFlags = *Flags; 1284 NewFlags.setNoSignedWrap(false); 1285 NewFlags.setNoUnsignedWrap(false); 1286 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), 1287 Op.getOperand(0), Op.getOperand(1), 1288 &NewFlags); 1289 return TLO.CombineTo(Op, NewOp); 1290 } 1291 return true; 1292 } 1293 LLVM_FALLTHROUGH; 1294 } 1295 default: 1296 // Just use computeKnownBits to compute output bits. 1297 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth); 1298 break; 1299 } 1300 1301 // If we know the value of all of the demanded bits, return this as a 1302 // constant. 1303 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { 1304 // Avoid folding to a constant if any OpaqueConstant is involved. 1305 const SDNode *N = Op.getNode(); 1306 for (SDNodeIterator I = SDNodeIterator::begin(N), 1307 E = SDNodeIterator::end(N); I != E; ++I) { 1308 SDNode *Op = *I; 1309 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 1310 if (C->isOpaque()) 1311 return false; 1312 } 1313 return TLO.CombineTo(Op, 1314 TLO.DAG.getConstant(KnownOne, dl, Op.getValueType())); 1315 } 1316 1317 return false; 1318 } 1319 1320 /// Determine which of the bits specified in Mask are known to be either zero or 1321 /// one and return them in the KnownZero/KnownOne bitsets. 1322 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 1323 APInt &KnownZero, 1324 APInt &KnownOne, 1325 const SelectionDAG &DAG, 1326 unsigned Depth) const { 1327 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 1328 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1329 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 1330 Op.getOpcode() == ISD::INTRINSIC_VOID) && 1331 "Should use MaskedValueIsZero if you don't know whether Op" 1332 " is a target node!"); 1333 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0); 1334 } 1335 1336 /// This method can be implemented by targets that want to expose additional 1337 /// information about sign bits to the DAG Combiner. 1338 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 1339 const SelectionDAG &, 1340 unsigned Depth) const { 1341 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 1342 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1343 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 1344 Op.getOpcode() == ISD::INTRINSIC_VOID) && 1345 "Should use ComputeNumSignBits if you don't know whether Op" 1346 " is a target node!"); 1347 return 1; 1348 } 1349 1350 bool TargetLowering::isConstTrueVal(const SDNode *N) const { 1351 if (!N) 1352 return false; 1353 1354 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 1355 if (!CN) { 1356 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 1357 if (!BV) 1358 return false; 1359 1360 // Only interested in constant splats, we don't care about undef 1361 // elements in identifying boolean constants and getConstantSplatNode 1362 // returns NULL if all ops are undef; 1363 CN = BV->getConstantSplatNode(); 1364 if (!CN) 1365 return false; 1366 } 1367 1368 switch (getBooleanContents(N->getValueType(0))) { 1369 case UndefinedBooleanContent: 1370 return CN->getAPIntValue()[0]; 1371 case ZeroOrOneBooleanContent: 1372 return CN->isOne(); 1373 case ZeroOrNegativeOneBooleanContent: 1374 return CN->isAllOnesValue(); 1375 } 1376 1377 llvm_unreachable("Invalid boolean contents"); 1378 } 1379 1380 SDValue TargetLowering::getConstTrueVal(SelectionDAG &DAG, EVT VT, 1381 const SDLoc &DL) const { 1382 unsigned ElementWidth = VT.getScalarSizeInBits(); 1383 APInt TrueInt = 1384 getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent 1385 ? APInt(ElementWidth, 1) 1386 : APInt::getAllOnesValue(ElementWidth); 1387 return DAG.getConstant(TrueInt, DL, VT); 1388 } 1389 1390 bool TargetLowering::isConstFalseVal(const SDNode *N) const { 1391 if (!N) 1392 return false; 1393 1394 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 1395 if (!CN) { 1396 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 1397 if (!BV) 1398 return false; 1399 1400 // Only interested in constant splats, we don't care about undef 1401 // elements in identifying boolean constants and getConstantSplatNode 1402 // returns NULL if all ops are undef; 1403 CN = BV->getConstantSplatNode(); 1404 if (!CN) 1405 return false; 1406 } 1407 1408 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 1409 return !CN->getAPIntValue()[0]; 1410 1411 return CN->isNullValue(); 1412 } 1413 1414 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 1415 bool SExt) const { 1416 if (VT == MVT::i1) 1417 return N->isOne(); 1418 1419 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 1420 switch (Cnt) { 1421 case TargetLowering::ZeroOrOneBooleanContent: 1422 // An extended value of 1 is always true, unless its original type is i1, 1423 // in which case it will be sign extended to -1. 1424 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 1425 case TargetLowering::UndefinedBooleanContent: 1426 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1427 return N->isAllOnesValue() && SExt; 1428 } 1429 llvm_unreachable("Unexpected enumeration."); 1430 } 1431 1432 /// This helper function of SimplifySetCC tries to optimize the comparison when 1433 /// either operand of the SetCC node is a bitwise-and instruction. 1434 SDValue TargetLowering::simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 1435 ISD::CondCode Cond, 1436 DAGCombinerInfo &DCI, 1437 const SDLoc &DL) const { 1438 // Match these patterns in any of their permutations: 1439 // (X & Y) == Y 1440 // (X & Y) != Y 1441 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 1442 std::swap(N0, N1); 1443 1444 EVT OpVT = N0.getValueType(); 1445 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 1446 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 1447 return SDValue(); 1448 1449 SDValue X, Y; 1450 if (N0.getOperand(0) == N1) { 1451 X = N0.getOperand(1); 1452 Y = N0.getOperand(0); 1453 } else if (N0.getOperand(1) == N1) { 1454 X = N0.getOperand(0); 1455 Y = N0.getOperand(1); 1456 } else { 1457 return SDValue(); 1458 } 1459 1460 SelectionDAG &DAG = DCI.DAG; 1461 SDValue Zero = DAG.getConstant(0, DL, OpVT); 1462 if (DAG.isKnownToBeAPowerOfTwo(Y)) { 1463 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 1464 // Note that where Y is variable and is known to have at most one bit set 1465 // (for example, if it is Z & 1) we cannot do this; the expressions are not 1466 // equivalent when Y == 0. 1467 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true); 1468 if (DCI.isBeforeLegalizeOps() || 1469 isCondCodeLegal(Cond, N0.getSimpleValueType())) 1470 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 1471 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 1472 // If the target supports an 'and-not' or 'and-complement' logic operation, 1473 // try to use that to make a comparison operation more efficient. 1474 // But don't do this transform if the mask is a single bit because there are 1475 // more efficient ways to deal with that case (for example, 'bt' on x86 or 1476 // 'rlwinm' on PPC). 1477 1478 // Bail out if the compare operand that we want to turn into a zero is 1479 // already a zero (otherwise, infinite loop). 1480 auto *YConst = dyn_cast<ConstantSDNode>(Y); 1481 if (YConst && YConst->isNullValue()) 1482 return SDValue(); 1483 1484 // Transform this into: ~X & Y == 0. 1485 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 1486 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 1487 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 1488 } 1489 1490 return SDValue(); 1491 } 1492 1493 /// Try to simplify a setcc built with the specified operands and cc. If it is 1494 /// unable to simplify it, return a null SDValue. 1495 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 1496 ISD::CondCode Cond, bool foldBooleans, 1497 DAGCombinerInfo &DCI, 1498 const SDLoc &dl) const { 1499 SelectionDAG &DAG = DCI.DAG; 1500 1501 // These setcc operations always fold. 1502 switch (Cond) { 1503 default: break; 1504 case ISD::SETFALSE: 1505 case ISD::SETFALSE2: return DAG.getConstant(0, dl, VT); 1506 case ISD::SETTRUE: 1507 case ISD::SETTRUE2: { 1508 TargetLowering::BooleanContent Cnt = 1509 getBooleanContents(N0->getValueType(0)); 1510 return DAG.getConstant( 1511 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl, 1512 VT); 1513 } 1514 } 1515 1516 // Ensure that the constant occurs on the RHS, and fold constant 1517 // comparisons. 1518 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 1519 if (isa<ConstantSDNode>(N0.getNode()) && 1520 (DCI.isBeforeLegalizeOps() || 1521 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 1522 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 1523 1524 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 1525 const APInt &C1 = N1C->getAPIntValue(); 1526 1527 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 1528 // equality comparison, then we're just comparing whether X itself is 1529 // zero. 1530 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) && 1531 N0.getOperand(0).getOpcode() == ISD::CTLZ && 1532 N0.getOperand(1).getOpcode() == ISD::Constant) { 1533 const APInt &ShAmt 1534 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 1535 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1536 ShAmt == Log2_32(N0.getValueSizeInBits())) { 1537 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 1538 // (srl (ctlz x), 5) == 0 -> X != 0 1539 // (srl (ctlz x), 5) != 1 -> X != 0 1540 Cond = ISD::SETNE; 1541 } else { 1542 // (srl (ctlz x), 5) != 0 -> X == 0 1543 // (srl (ctlz x), 5) == 1 -> X == 0 1544 Cond = ISD::SETEQ; 1545 } 1546 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 1547 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), 1548 Zero, Cond); 1549 } 1550 } 1551 1552 SDValue CTPOP = N0; 1553 // Look through truncs that don't change the value of a ctpop. 1554 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE) 1555 CTPOP = N0.getOperand(0); 1556 1557 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP && 1558 (N0 == CTPOP || 1559 N0.getValueSizeInBits() > Log2_32_Ceil(CTPOP.getValueSizeInBits()))) { 1560 EVT CTVT = CTPOP.getValueType(); 1561 SDValue CTOp = CTPOP.getOperand(0); 1562 1563 // (ctpop x) u< 2 -> (x & x-1) == 0 1564 // (ctpop x) u> 1 -> (x & x-1) != 0 1565 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){ 1566 SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp, 1567 DAG.getConstant(1, dl, CTVT)); 1568 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub); 1569 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 1570 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC); 1571 } 1572 1573 // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal. 1574 } 1575 1576 // (zext x) == C --> x == (trunc C) 1577 // (sext x) == C --> x == (trunc C) 1578 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1579 DCI.isBeforeLegalize() && N0->hasOneUse()) { 1580 unsigned MinBits = N0.getValueSizeInBits(); 1581 SDValue PreExt; 1582 bool Signed = false; 1583 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 1584 // ZExt 1585 MinBits = N0->getOperand(0).getValueSizeInBits(); 1586 PreExt = N0->getOperand(0); 1587 } else if (N0->getOpcode() == ISD::AND) { 1588 // DAGCombine turns costly ZExts into ANDs 1589 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 1590 if ((C->getAPIntValue()+1).isPowerOf2()) { 1591 MinBits = C->getAPIntValue().countTrailingOnes(); 1592 PreExt = N0->getOperand(0); 1593 } 1594 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 1595 // SExt 1596 MinBits = N0->getOperand(0).getValueSizeInBits(); 1597 PreExt = N0->getOperand(0); 1598 Signed = true; 1599 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 1600 // ZEXTLOAD / SEXTLOAD 1601 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 1602 MinBits = LN0->getMemoryVT().getSizeInBits(); 1603 PreExt = N0; 1604 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 1605 Signed = true; 1606 MinBits = LN0->getMemoryVT().getSizeInBits(); 1607 PreExt = N0; 1608 } 1609 } 1610 1611 // Figure out how many bits we need to preserve this constant. 1612 unsigned ReqdBits = Signed ? 1613 C1.getBitWidth() - C1.getNumSignBits() + 1 : 1614 C1.getActiveBits(); 1615 1616 // Make sure we're not losing bits from the constant. 1617 if (MinBits > 0 && 1618 MinBits < C1.getBitWidth() && 1619 MinBits >= ReqdBits) { 1620 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 1621 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 1622 // Will get folded away. 1623 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 1624 if (MinBits == 1 && C1 == 1) 1625 // Invert the condition. 1626 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 1627 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1628 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 1629 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 1630 } 1631 1632 // If truncating the setcc operands is not desirable, we can still 1633 // simplify the expression in some cases: 1634 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 1635 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 1636 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 1637 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 1638 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 1639 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 1640 SDValue TopSetCC = N0->getOperand(0); 1641 unsigned N0Opc = N0->getOpcode(); 1642 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 1643 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 1644 TopSetCC.getOpcode() == ISD::SETCC && 1645 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 1646 (isConstFalseVal(N1C) || 1647 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 1648 1649 bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) || 1650 (!N1C->isNullValue() && Cond == ISD::SETNE); 1651 1652 if (!Inverse) 1653 return TopSetCC; 1654 1655 ISD::CondCode InvCond = ISD::getSetCCInverse( 1656 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 1657 TopSetCC.getOperand(0).getValueType().isInteger()); 1658 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 1659 TopSetCC.getOperand(1), 1660 InvCond); 1661 1662 } 1663 } 1664 } 1665 1666 // If the LHS is '(and load, const)', the RHS is 0, 1667 // the test is for equality or unsigned, and all 1 bits of the const are 1668 // in the same partial word, see if we can shorten the load. 1669 if (DCI.isBeforeLegalize() && 1670 !ISD::isSignedIntSetCC(Cond) && 1671 N0.getOpcode() == ISD::AND && C1 == 0 && 1672 N0.getNode()->hasOneUse() && 1673 isa<LoadSDNode>(N0.getOperand(0)) && 1674 N0.getOperand(0).getNode()->hasOneUse() && 1675 isa<ConstantSDNode>(N0.getOperand(1))) { 1676 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 1677 APInt bestMask; 1678 unsigned bestWidth = 0, bestOffset = 0; 1679 if (!Lod->isVolatile() && Lod->isUnindexed()) { 1680 unsigned origWidth = N0.getValueSizeInBits(); 1681 unsigned maskWidth = origWidth; 1682 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 1683 // 8 bits, but have to be careful... 1684 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 1685 origWidth = Lod->getMemoryVT().getSizeInBits(); 1686 const APInt &Mask = 1687 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 1688 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 1689 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 1690 for (unsigned offset=0; offset<origWidth/width; offset++) { 1691 if ((newMask & Mask) == Mask) { 1692 if (!DAG.getDataLayout().isLittleEndian()) 1693 bestOffset = (origWidth/width - offset - 1) * (width/8); 1694 else 1695 bestOffset = (uint64_t)offset * (width/8); 1696 bestMask = Mask.lshr(offset * (width/8) * 8); 1697 bestWidth = width; 1698 break; 1699 } 1700 newMask = newMask << width; 1701 } 1702 } 1703 } 1704 if (bestWidth) { 1705 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 1706 if (newVT.isRound()) { 1707 EVT PtrType = Lod->getOperand(1).getValueType(); 1708 SDValue Ptr = Lod->getBasePtr(); 1709 if (bestOffset != 0) 1710 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(), 1711 DAG.getConstant(bestOffset, dl, PtrType)); 1712 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset); 1713 SDValue NewLoad = DAG.getLoad( 1714 newVT, dl, Lod->getChain(), Ptr, 1715 Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign); 1716 return DAG.getSetCC(dl, VT, 1717 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 1718 DAG.getConstant(bestMask.trunc(bestWidth), 1719 dl, newVT)), 1720 DAG.getConstant(0LL, dl, newVT), Cond); 1721 } 1722 } 1723 } 1724 1725 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 1726 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 1727 unsigned InSize = N0.getOperand(0).getValueSizeInBits(); 1728 1729 // If the comparison constant has bits in the upper part, the 1730 // zero-extended value could never match. 1731 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 1732 C1.getBitWidth() - InSize))) { 1733 switch (Cond) { 1734 case ISD::SETUGT: 1735 case ISD::SETUGE: 1736 case ISD::SETEQ: return DAG.getConstant(0, dl, VT); 1737 case ISD::SETULT: 1738 case ISD::SETULE: 1739 case ISD::SETNE: return DAG.getConstant(1, dl, VT); 1740 case ISD::SETGT: 1741 case ISD::SETGE: 1742 // True if the sign bit of C1 is set. 1743 return DAG.getConstant(C1.isNegative(), dl, VT); 1744 case ISD::SETLT: 1745 case ISD::SETLE: 1746 // True if the sign bit of C1 isn't set. 1747 return DAG.getConstant(C1.isNonNegative(), dl, VT); 1748 default: 1749 break; 1750 } 1751 } 1752 1753 // Otherwise, we can perform the comparison with the low bits. 1754 switch (Cond) { 1755 case ISD::SETEQ: 1756 case ISD::SETNE: 1757 case ISD::SETUGT: 1758 case ISD::SETUGE: 1759 case ISD::SETULT: 1760 case ISD::SETULE: { 1761 EVT newVT = N0.getOperand(0).getValueType(); 1762 if (DCI.isBeforeLegalizeOps() || 1763 (isOperationLegal(ISD::SETCC, newVT) && 1764 getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) { 1765 EVT NewSetCCVT = 1766 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT); 1767 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 1768 1769 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 1770 NewConst, Cond); 1771 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 1772 } 1773 break; 1774 } 1775 default: 1776 break; // todo, be more careful with signed comparisons 1777 } 1778 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 1779 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 1780 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 1781 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 1782 EVT ExtDstTy = N0.getValueType(); 1783 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 1784 1785 // If the constant doesn't fit into the number of bits for the source of 1786 // the sign extension, it is impossible for both sides to be equal. 1787 if (C1.getMinSignedBits() > ExtSrcTyBits) 1788 return DAG.getConstant(Cond == ISD::SETNE, dl, VT); 1789 1790 SDValue ZextOp; 1791 EVT Op0Ty = N0.getOperand(0).getValueType(); 1792 if (Op0Ty == ExtSrcTy) { 1793 ZextOp = N0.getOperand(0); 1794 } else { 1795 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 1796 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0), 1797 DAG.getConstant(Imm, dl, Op0Ty)); 1798 } 1799 if (!DCI.isCalledByLegalizer()) 1800 DCI.AddToWorklist(ZextOp.getNode()); 1801 // Otherwise, make this a use of a zext. 1802 return DAG.getSetCC(dl, VT, ZextOp, 1803 DAG.getConstant(C1 & APInt::getLowBitsSet( 1804 ExtDstTyBits, 1805 ExtSrcTyBits), 1806 dl, ExtDstTy), 1807 Cond); 1808 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) && 1809 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 1810 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 1811 if (N0.getOpcode() == ISD::SETCC && 1812 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) { 1813 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1); 1814 if (TrueWhenTrue) 1815 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 1816 // Invert the condition. 1817 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 1818 CC = ISD::getSetCCInverse(CC, 1819 N0.getOperand(0).getValueType().isInteger()); 1820 if (DCI.isBeforeLegalizeOps() || 1821 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 1822 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 1823 } 1824 1825 if ((N0.getOpcode() == ISD::XOR || 1826 (N0.getOpcode() == ISD::AND && 1827 N0.getOperand(0).getOpcode() == ISD::XOR && 1828 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 1829 isa<ConstantSDNode>(N0.getOperand(1)) && 1830 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) { 1831 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 1832 // can only do this if the top bits are known zero. 1833 unsigned BitWidth = N0.getValueSizeInBits(); 1834 if (DAG.MaskedValueIsZero(N0, 1835 APInt::getHighBitsSet(BitWidth, 1836 BitWidth-1))) { 1837 // Okay, get the un-inverted input value. 1838 SDValue Val; 1839 if (N0.getOpcode() == ISD::XOR) 1840 Val = N0.getOperand(0); 1841 else { 1842 assert(N0.getOpcode() == ISD::AND && 1843 N0.getOperand(0).getOpcode() == ISD::XOR); 1844 // ((X^1)&1)^1 -> X & 1 1845 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 1846 N0.getOperand(0).getOperand(0), 1847 N0.getOperand(1)); 1848 } 1849 1850 return DAG.getSetCC(dl, VT, Val, N1, 1851 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1852 } 1853 } else if (N1C->getAPIntValue() == 1 && 1854 (VT == MVT::i1 || 1855 getBooleanContents(N0->getValueType(0)) == 1856 ZeroOrOneBooleanContent)) { 1857 SDValue Op0 = N0; 1858 if (Op0.getOpcode() == ISD::TRUNCATE) 1859 Op0 = Op0.getOperand(0); 1860 1861 if ((Op0.getOpcode() == ISD::XOR) && 1862 Op0.getOperand(0).getOpcode() == ISD::SETCC && 1863 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 1864 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 1865 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 1866 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1), 1867 Cond); 1868 } 1869 if (Op0.getOpcode() == ISD::AND && 1870 isa<ConstantSDNode>(Op0.getOperand(1)) && 1871 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) { 1872 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 1873 if (Op0.getValueType().bitsGT(VT)) 1874 Op0 = DAG.getNode(ISD::AND, dl, VT, 1875 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 1876 DAG.getConstant(1, dl, VT)); 1877 else if (Op0.getValueType().bitsLT(VT)) 1878 Op0 = DAG.getNode(ISD::AND, dl, VT, 1879 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 1880 DAG.getConstant(1, dl, VT)); 1881 1882 return DAG.getSetCC(dl, VT, Op0, 1883 DAG.getConstant(0, dl, Op0.getValueType()), 1884 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1885 } 1886 if (Op0.getOpcode() == ISD::AssertZext && 1887 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 1888 return DAG.getSetCC(dl, VT, Op0, 1889 DAG.getConstant(0, dl, Op0.getValueType()), 1890 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1891 } 1892 } 1893 1894 APInt MinVal, MaxVal; 1895 unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits(); 1896 if (ISD::isSignedIntSetCC(Cond)) { 1897 MinVal = APInt::getSignedMinValue(OperandBitSize); 1898 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 1899 } else { 1900 MinVal = APInt::getMinValue(OperandBitSize); 1901 MaxVal = APInt::getMaxValue(OperandBitSize); 1902 } 1903 1904 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 1905 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 1906 if (C1 == MinVal) return DAG.getConstant(1, dl, VT); // X >= MIN --> true 1907 // X >= C0 --> X > (C0 - 1) 1908 APInt C = C1 - 1; 1909 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 1910 if ((DCI.isBeforeLegalizeOps() || 1911 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 1912 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 && 1913 isLegalICmpImmediate(C.getSExtValue())))) { 1914 return DAG.getSetCC(dl, VT, N0, 1915 DAG.getConstant(C, dl, N1.getValueType()), 1916 NewCC); 1917 } 1918 } 1919 1920 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 1921 if (C1 == MaxVal) return DAG.getConstant(1, dl, VT); // X <= MAX --> true 1922 // X <= C0 --> X < (C0 + 1) 1923 APInt C = C1 + 1; 1924 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 1925 if ((DCI.isBeforeLegalizeOps() || 1926 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 1927 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 && 1928 isLegalICmpImmediate(C.getSExtValue())))) { 1929 return DAG.getSetCC(dl, VT, N0, 1930 DAG.getConstant(C, dl, N1.getValueType()), 1931 NewCC); 1932 } 1933 } 1934 1935 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal) 1936 return DAG.getConstant(0, dl, VT); // X < MIN --> false 1937 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal) 1938 return DAG.getConstant(1, dl, VT); // X >= MIN --> true 1939 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal) 1940 return DAG.getConstant(0, dl, VT); // X > MAX --> false 1941 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal) 1942 return DAG.getConstant(1, dl, VT); // X <= MAX --> true 1943 1944 // Canonicalize setgt X, Min --> setne X, Min 1945 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal) 1946 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 1947 // Canonicalize setlt X, Max --> setne X, Max 1948 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal) 1949 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 1950 1951 // If we have setult X, 1, turn it into seteq X, 0 1952 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1) 1953 return DAG.getSetCC(dl, VT, N0, 1954 DAG.getConstant(MinVal, dl, N0.getValueType()), 1955 ISD::SETEQ); 1956 // If we have setugt X, Max-1, turn it into seteq X, Max 1957 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1) 1958 return DAG.getSetCC(dl, VT, N0, 1959 DAG.getConstant(MaxVal, dl, N0.getValueType()), 1960 ISD::SETEQ); 1961 1962 // If we have "setcc X, C0", check to see if we can shrink the immediate 1963 // by changing cc. 1964 1965 // SETUGT X, SINTMAX -> SETLT X, 0 1966 if (Cond == ISD::SETUGT && 1967 C1 == APInt::getSignedMaxValue(OperandBitSize)) 1968 return DAG.getSetCC(dl, VT, N0, 1969 DAG.getConstant(0, dl, N1.getValueType()), 1970 ISD::SETLT); 1971 1972 // SETULT X, SINTMIN -> SETGT X, -1 1973 if (Cond == ISD::SETULT && 1974 C1 == APInt::getSignedMinValue(OperandBitSize)) { 1975 SDValue ConstMinusOne = 1976 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl, 1977 N1.getValueType()); 1978 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT); 1979 } 1980 1981 // Fold bit comparisons when we can. 1982 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1983 (VT == N0.getValueType() || 1984 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) && 1985 N0.getOpcode() == ISD::AND) { 1986 auto &DL = DAG.getDataLayout(); 1987 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 1988 EVT ShiftTy = DCI.isBeforeLegalize() 1989 ? getPointerTy(DL) 1990 : getShiftAmountTy(N0.getValueType(), DL); 1991 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 1992 // Perform the xform if the AND RHS is a single bit. 1993 if (AndRHS->getAPIntValue().isPowerOf2()) { 1994 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1995 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0, 1996 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl, 1997 ShiftTy))); 1998 } 1999 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 2000 // (X & 8) == 8 --> (X & 8) >> 3 2001 // Perform the xform if C1 is a single bit. 2002 if (C1.isPowerOf2()) { 2003 return DAG.getNode(ISD::TRUNCATE, dl, VT, 2004 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0, 2005 DAG.getConstant(C1.logBase2(), dl, 2006 ShiftTy))); 2007 } 2008 } 2009 } 2010 } 2011 2012 if (C1.getMinSignedBits() <= 64 && 2013 !isLegalICmpImmediate(C1.getSExtValue())) { 2014 // (X & -256) == 256 -> (X >> 8) == 1 2015 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 2016 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 2017 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2018 const APInt &AndRHSC = AndRHS->getAPIntValue(); 2019 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) { 2020 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 2021 auto &DL = DAG.getDataLayout(); 2022 EVT ShiftTy = DCI.isBeforeLegalize() 2023 ? getPointerTy(DL) 2024 : getShiftAmountTy(N0.getValueType(), DL); 2025 EVT CmpTy = N0.getValueType(); 2026 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0), 2027 DAG.getConstant(ShiftBits, dl, 2028 ShiftTy)); 2029 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy); 2030 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 2031 } 2032 } 2033 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 2034 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 2035 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 2036 // X < 0x100000000 -> (X >> 32) < 1 2037 // X >= 0x100000000 -> (X >> 32) >= 1 2038 // X <= 0x0ffffffff -> (X >> 32) < 1 2039 // X > 0x0ffffffff -> (X >> 32) >= 1 2040 unsigned ShiftBits; 2041 APInt NewC = C1; 2042 ISD::CondCode NewCond = Cond; 2043 if (AdjOne) { 2044 ShiftBits = C1.countTrailingOnes(); 2045 NewC = NewC + 1; 2046 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 2047 } else { 2048 ShiftBits = C1.countTrailingZeros(); 2049 } 2050 NewC = NewC.lshr(ShiftBits); 2051 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 2052 isLegalICmpImmediate(NewC.getSExtValue())) { 2053 auto &DL = DAG.getDataLayout(); 2054 EVT ShiftTy = DCI.isBeforeLegalize() 2055 ? getPointerTy(DL) 2056 : getShiftAmountTy(N0.getValueType(), DL); 2057 EVT CmpTy = N0.getValueType(); 2058 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0, 2059 DAG.getConstant(ShiftBits, dl, ShiftTy)); 2060 SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy); 2061 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 2062 } 2063 } 2064 } 2065 } 2066 2067 if (isa<ConstantFPSDNode>(N0.getNode())) { 2068 // Constant fold or commute setcc. 2069 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl); 2070 if (O.getNode()) return O; 2071 } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) { 2072 // If the RHS of an FP comparison is a constant, simplify it away in 2073 // some cases. 2074 if (CFP->getValueAPF().isNaN()) { 2075 // If an operand is known to be a nan, we can fold it. 2076 switch (ISD::getUnorderedFlavor(Cond)) { 2077 default: llvm_unreachable("Unknown flavor!"); 2078 case 0: // Known false. 2079 return DAG.getConstant(0, dl, VT); 2080 case 1: // Known true. 2081 return DAG.getConstant(1, dl, VT); 2082 case 2: // Undefined. 2083 return DAG.getUNDEF(VT); 2084 } 2085 } 2086 2087 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 2088 // constant if knowing that the operand is non-nan is enough. We prefer to 2089 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 2090 // materialize 0.0. 2091 if (Cond == ISD::SETO || Cond == ISD::SETUO) 2092 return DAG.getSetCC(dl, VT, N0, N0, Cond); 2093 2094 // setcc (fneg x), C -> setcc swap(pred) x, -C 2095 if (N0.getOpcode() == ISD::FNEG) { 2096 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 2097 if (DCI.isBeforeLegalizeOps() || 2098 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 2099 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 2100 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 2101 } 2102 } 2103 2104 // If the condition is not legal, see if we can find an equivalent one 2105 // which is legal. 2106 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 2107 // If the comparison was an awkward floating-point == or != and one of 2108 // the comparison operands is infinity or negative infinity, convert the 2109 // condition to a less-awkward <= or >=. 2110 if (CFP->getValueAPF().isInfinity()) { 2111 if (CFP->getValueAPF().isNegative()) { 2112 if (Cond == ISD::SETOEQ && 2113 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType())) 2114 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE); 2115 if (Cond == ISD::SETUEQ && 2116 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType())) 2117 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE); 2118 if (Cond == ISD::SETUNE && 2119 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType())) 2120 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT); 2121 if (Cond == ISD::SETONE && 2122 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType())) 2123 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT); 2124 } else { 2125 if (Cond == ISD::SETOEQ && 2126 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType())) 2127 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE); 2128 if (Cond == ISD::SETUEQ && 2129 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType())) 2130 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE); 2131 if (Cond == ISD::SETUNE && 2132 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType())) 2133 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT); 2134 if (Cond == ISD::SETONE && 2135 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType())) 2136 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT); 2137 } 2138 } 2139 } 2140 } 2141 2142 if (N0 == N1) { 2143 // The sext(setcc()) => setcc() optimization relies on the appropriate 2144 // constant being emitted. 2145 uint64_t EqVal = 0; 2146 switch (getBooleanContents(N0.getValueType())) { 2147 case UndefinedBooleanContent: 2148 case ZeroOrOneBooleanContent: 2149 EqVal = ISD::isTrueWhenEqual(Cond); 2150 break; 2151 case ZeroOrNegativeOneBooleanContent: 2152 EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0; 2153 break; 2154 } 2155 2156 // We can always fold X == X for integer setcc's. 2157 if (N0.getValueType().isInteger()) { 2158 return DAG.getConstant(EqVal, dl, VT); 2159 } 2160 unsigned UOF = ISD::getUnorderedFlavor(Cond); 2161 if (UOF == 2) // FP operators that are undefined on NaNs. 2162 return DAG.getConstant(EqVal, dl, VT); 2163 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond))) 2164 return DAG.getConstant(EqVal, dl, VT); 2165 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 2166 // if it is not already. 2167 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 2168 if (NewCond != Cond && (DCI.isBeforeLegalizeOps() || 2169 getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal)) 2170 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 2171 } 2172 2173 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 2174 N0.getValueType().isInteger()) { 2175 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 2176 N0.getOpcode() == ISD::XOR) { 2177 // Simplify (X+Y) == (X+Z) --> Y == Z 2178 if (N0.getOpcode() == N1.getOpcode()) { 2179 if (N0.getOperand(0) == N1.getOperand(0)) 2180 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 2181 if (N0.getOperand(1) == N1.getOperand(1)) 2182 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 2183 if (DAG.isCommutativeBinOp(N0.getOpcode())) { 2184 // If X op Y == Y op X, try other combinations. 2185 if (N0.getOperand(0) == N1.getOperand(1)) 2186 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 2187 Cond); 2188 if (N0.getOperand(1) == N1.getOperand(0)) 2189 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 2190 Cond); 2191 } 2192 } 2193 2194 // If RHS is a legal immediate value for a compare instruction, we need 2195 // to be careful about increasing register pressure needlessly. 2196 bool LegalRHSImm = false; 2197 2198 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 2199 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2200 // Turn (X+C1) == C2 --> X == C2-C1 2201 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) { 2202 return DAG.getSetCC(dl, VT, N0.getOperand(0), 2203 DAG.getConstant(RHSC->getAPIntValue()- 2204 LHSR->getAPIntValue(), 2205 dl, N0.getValueType()), Cond); 2206 } 2207 2208 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0. 2209 if (N0.getOpcode() == ISD::XOR) 2210 // If we know that all of the inverted bits are zero, don't bother 2211 // performing the inversion. 2212 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue())) 2213 return 2214 DAG.getSetCC(dl, VT, N0.getOperand(0), 2215 DAG.getConstant(LHSR->getAPIntValue() ^ 2216 RHSC->getAPIntValue(), 2217 dl, N0.getValueType()), 2218 Cond); 2219 } 2220 2221 // Turn (C1-X) == C2 --> X == C1-C2 2222 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) { 2223 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) { 2224 return 2225 DAG.getSetCC(dl, VT, N0.getOperand(1), 2226 DAG.getConstant(SUBC->getAPIntValue() - 2227 RHSC->getAPIntValue(), 2228 dl, N0.getValueType()), 2229 Cond); 2230 } 2231 } 2232 2233 // Could RHSC fold directly into a compare? 2234 if (RHSC->getValueType(0).getSizeInBits() <= 64) 2235 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 2236 } 2237 2238 // Simplify (X+Z) == X --> Z == 0 2239 // Don't do this if X is an immediate that can fold into a cmp 2240 // instruction and X+Z has other uses. It could be an induction variable 2241 // chain, and the transform would increase register pressure. 2242 if (!LegalRHSImm || N0.getNode()->hasOneUse()) { 2243 if (N0.getOperand(0) == N1) 2244 return DAG.getSetCC(dl, VT, N0.getOperand(1), 2245 DAG.getConstant(0, dl, N0.getValueType()), Cond); 2246 if (N0.getOperand(1) == N1) { 2247 if (DAG.isCommutativeBinOp(N0.getOpcode())) 2248 return DAG.getSetCC(dl, VT, N0.getOperand(0), 2249 DAG.getConstant(0, dl, N0.getValueType()), 2250 Cond); 2251 if (N0.getNode()->hasOneUse()) { 2252 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!"); 2253 auto &DL = DAG.getDataLayout(); 2254 // (Z-X) == X --> Z == X<<1 2255 SDValue SH = DAG.getNode( 2256 ISD::SHL, dl, N1.getValueType(), N1, 2257 DAG.getConstant(1, dl, 2258 getShiftAmountTy(N1.getValueType(), DL))); 2259 if (!DCI.isCalledByLegalizer()) 2260 DCI.AddToWorklist(SH.getNode()); 2261 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond); 2262 } 2263 } 2264 } 2265 } 2266 2267 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 2268 N1.getOpcode() == ISD::XOR) { 2269 // Simplify X == (X+Z) --> Z == 0 2270 if (N1.getOperand(0) == N0) 2271 return DAG.getSetCC(dl, VT, N1.getOperand(1), 2272 DAG.getConstant(0, dl, N1.getValueType()), Cond); 2273 if (N1.getOperand(1) == N0) { 2274 if (DAG.isCommutativeBinOp(N1.getOpcode())) 2275 return DAG.getSetCC(dl, VT, N1.getOperand(0), 2276 DAG.getConstant(0, dl, N1.getValueType()), Cond); 2277 if (N1.getNode()->hasOneUse()) { 2278 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!"); 2279 auto &DL = DAG.getDataLayout(); 2280 // X == (Z-X) --> X<<1 == Z 2281 SDValue SH = DAG.getNode( 2282 ISD::SHL, dl, N1.getValueType(), N0, 2283 DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL))); 2284 if (!DCI.isCalledByLegalizer()) 2285 DCI.AddToWorklist(SH.getNode()); 2286 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond); 2287 } 2288 } 2289 } 2290 2291 if (SDValue V = simplifySetCCWithAnd(VT, N0, N1, Cond, DCI, dl)) 2292 return V; 2293 } 2294 2295 // Fold away ALL boolean setcc's. 2296 SDValue Temp; 2297 if (N0.getValueType() == MVT::i1 && foldBooleans) { 2298 switch (Cond) { 2299 default: llvm_unreachable("Unknown integer setcc!"); 2300 case ISD::SETEQ: // X == Y -> ~(X^Y) 2301 Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1); 2302 N0 = DAG.getNOT(dl, Temp, MVT::i1); 2303 if (!DCI.isCalledByLegalizer()) 2304 DCI.AddToWorklist(Temp.getNode()); 2305 break; 2306 case ISD::SETNE: // X != Y --> (X^Y) 2307 N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1); 2308 break; 2309 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 2310 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 2311 Temp = DAG.getNOT(dl, N0, MVT::i1); 2312 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp); 2313 if (!DCI.isCalledByLegalizer()) 2314 DCI.AddToWorklist(Temp.getNode()); 2315 break; 2316 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 2317 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 2318 Temp = DAG.getNOT(dl, N1, MVT::i1); 2319 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp); 2320 if (!DCI.isCalledByLegalizer()) 2321 DCI.AddToWorklist(Temp.getNode()); 2322 break; 2323 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 2324 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 2325 Temp = DAG.getNOT(dl, N0, MVT::i1); 2326 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp); 2327 if (!DCI.isCalledByLegalizer()) 2328 DCI.AddToWorklist(Temp.getNode()); 2329 break; 2330 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 2331 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 2332 Temp = DAG.getNOT(dl, N1, MVT::i1); 2333 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp); 2334 break; 2335 } 2336 if (VT != MVT::i1) { 2337 if (!DCI.isCalledByLegalizer()) 2338 DCI.AddToWorklist(N0.getNode()); 2339 // FIXME: If running after legalize, we probably can't do this. 2340 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0); 2341 } 2342 return N0; 2343 } 2344 2345 // Could not fold it. 2346 return SDValue(); 2347 } 2348 2349 /// Returns true (and the GlobalValue and the offset) if the node is a 2350 /// GlobalAddress + offset. 2351 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA, 2352 int64_t &Offset) const { 2353 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 2354 GA = GASD->getGlobal(); 2355 Offset += GASD->getOffset(); 2356 return true; 2357 } 2358 2359 if (N->getOpcode() == ISD::ADD) { 2360 SDValue N1 = N->getOperand(0); 2361 SDValue N2 = N->getOperand(1); 2362 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 2363 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 2364 Offset += V->getSExtValue(); 2365 return true; 2366 } 2367 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 2368 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 2369 Offset += V->getSExtValue(); 2370 return true; 2371 } 2372 } 2373 } 2374 2375 return false; 2376 } 2377 2378 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 2379 DAGCombinerInfo &DCI) const { 2380 // Default implementation: no optimization. 2381 return SDValue(); 2382 } 2383 2384 //===----------------------------------------------------------------------===// 2385 // Inline Assembler Implementation Methods 2386 //===----------------------------------------------------------------------===// 2387 2388 TargetLowering::ConstraintType 2389 TargetLowering::getConstraintType(StringRef Constraint) const { 2390 unsigned S = Constraint.size(); 2391 2392 if (S == 1) { 2393 switch (Constraint[0]) { 2394 default: break; 2395 case 'r': return C_RegisterClass; 2396 case 'm': // memory 2397 case 'o': // offsetable 2398 case 'V': // not offsetable 2399 return C_Memory; 2400 case 'i': // Simple Integer or Relocatable Constant 2401 case 'n': // Simple Integer 2402 case 'E': // Floating Point Constant 2403 case 'F': // Floating Point Constant 2404 case 's': // Relocatable Constant 2405 case 'p': // Address. 2406 case 'X': // Allow ANY value. 2407 case 'I': // Target registers. 2408 case 'J': 2409 case 'K': 2410 case 'L': 2411 case 'M': 2412 case 'N': 2413 case 'O': 2414 case 'P': 2415 case '<': 2416 case '>': 2417 return C_Other; 2418 } 2419 } 2420 2421 if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') { 2422 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 2423 return C_Memory; 2424 return C_Register; 2425 } 2426 return C_Unknown; 2427 } 2428 2429 /// Try to replace an X constraint, which matches anything, with another that 2430 /// has more specific requirements based on the type of the corresponding 2431 /// operand. 2432 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{ 2433 if (ConstraintVT.isInteger()) 2434 return "r"; 2435 if (ConstraintVT.isFloatingPoint()) 2436 return "f"; // works for many targets 2437 return nullptr; 2438 } 2439 2440 /// Lower the specified operand into the Ops vector. 2441 /// If it is invalid, don't add anything to Ops. 2442 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 2443 std::string &Constraint, 2444 std::vector<SDValue> &Ops, 2445 SelectionDAG &DAG) const { 2446 2447 if (Constraint.length() > 1) return; 2448 2449 char ConstraintLetter = Constraint[0]; 2450 switch (ConstraintLetter) { 2451 default: break; 2452 case 'X': // Allows any operand; labels (basic block) use this. 2453 if (Op.getOpcode() == ISD::BasicBlock) { 2454 Ops.push_back(Op); 2455 return; 2456 } 2457 LLVM_FALLTHROUGH; 2458 case 'i': // Simple Integer or Relocatable Constant 2459 case 'n': // Simple Integer 2460 case 's': { // Relocatable Constant 2461 // These operands are interested in values of the form (GV+C), where C may 2462 // be folded in as an offset of GV, or it may be explicitly added. Also, it 2463 // is possible and fine if either GV or C are missing. 2464 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 2465 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op); 2466 2467 // If we have "(add GV, C)", pull out GV/C 2468 if (Op.getOpcode() == ISD::ADD) { 2469 C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 2470 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0)); 2471 if (!C || !GA) { 2472 C = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 2473 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1)); 2474 } 2475 if (!C || !GA) { 2476 C = nullptr; 2477 GA = nullptr; 2478 } 2479 } 2480 2481 // If we find a valid operand, map to the TargetXXX version so that the 2482 // value itself doesn't get selected. 2483 if (GA) { // Either &GV or &GV+C 2484 if (ConstraintLetter != 'n') { 2485 int64_t Offs = GA->getOffset(); 2486 if (C) Offs += C->getZExtValue(); 2487 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), 2488 C ? SDLoc(C) : SDLoc(), 2489 Op.getValueType(), Offs)); 2490 } 2491 return; 2492 } 2493 if (C) { // just C, no GV. 2494 // Simple constants are not allowed for 's'. 2495 if (ConstraintLetter != 's') { 2496 // gcc prints these as sign extended. Sign extend value to 64 bits 2497 // now; without this it would get ZExt'd later in 2498 // ScheduleDAGSDNodes::EmitNode, which is very generic. 2499 Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(), 2500 SDLoc(C), MVT::i64)); 2501 } 2502 return; 2503 } 2504 break; 2505 } 2506 } 2507 } 2508 2509 std::pair<unsigned, const TargetRegisterClass *> 2510 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 2511 StringRef Constraint, 2512 MVT VT) const { 2513 if (Constraint.empty() || Constraint[0] != '{') 2514 return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr)); 2515 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?"); 2516 2517 // Remove the braces from around the name. 2518 StringRef RegName(Constraint.data()+1, Constraint.size()-2); 2519 2520 std::pair<unsigned, const TargetRegisterClass*> R = 2521 std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr)); 2522 2523 // Figure out which register class contains this reg. 2524 for (const TargetRegisterClass *RC : RI->regclasses()) { 2525 // If none of the value types for this register class are valid, we 2526 // can't use it. For example, 64-bit reg classes on 32-bit targets. 2527 if (!isLegalRC(RC)) 2528 continue; 2529 2530 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); 2531 I != E; ++I) { 2532 if (RegName.equals_lower(RI->getRegAsmName(*I))) { 2533 std::pair<unsigned, const TargetRegisterClass*> S = 2534 std::make_pair(*I, RC); 2535 2536 // If this register class has the requested value type, return it, 2537 // otherwise keep searching and return the first class found 2538 // if no other is found which explicitly has the requested type. 2539 if (RC->hasType(VT)) 2540 return S; 2541 else if (!R.second) 2542 R = S; 2543 } 2544 } 2545 } 2546 2547 return R; 2548 } 2549 2550 //===----------------------------------------------------------------------===// 2551 // Constraint Selection. 2552 2553 /// Return true of this is an input operand that is a matching constraint like 2554 /// "4". 2555 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 2556 assert(!ConstraintCode.empty() && "No known constraint!"); 2557 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 2558 } 2559 2560 /// If this is an input matching constraint, this method returns the output 2561 /// operand it matches. 2562 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 2563 assert(!ConstraintCode.empty() && "No known constraint!"); 2564 return atoi(ConstraintCode.c_str()); 2565 } 2566 2567 /// Split up the constraint string from the inline assembly value into the 2568 /// specific constraints and their prefixes, and also tie in the associated 2569 /// operand values. 2570 /// If this returns an empty vector, and if the constraint string itself 2571 /// isn't empty, there was an error parsing. 2572 TargetLowering::AsmOperandInfoVector 2573 TargetLowering::ParseConstraints(const DataLayout &DL, 2574 const TargetRegisterInfo *TRI, 2575 ImmutableCallSite CS) const { 2576 /// Information about all of the constraints. 2577 AsmOperandInfoVector ConstraintOperands; 2578 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 2579 unsigned maCount = 0; // Largest number of multiple alternative constraints. 2580 2581 // Do a prepass over the constraints, canonicalizing them, and building up the 2582 // ConstraintOperands list. 2583 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 2584 unsigned ResNo = 0; // ResNo - The result number of the next output. 2585 2586 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 2587 ConstraintOperands.emplace_back(std::move(CI)); 2588 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 2589 2590 // Update multiple alternative constraint count. 2591 if (OpInfo.multipleAlternatives.size() > maCount) 2592 maCount = OpInfo.multipleAlternatives.size(); 2593 2594 OpInfo.ConstraintVT = MVT::Other; 2595 2596 // Compute the value type for each operand. 2597 switch (OpInfo.Type) { 2598 case InlineAsm::isOutput: 2599 // Indirect outputs just consume an argument. 2600 if (OpInfo.isIndirect) { 2601 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 2602 break; 2603 } 2604 2605 // The return value of the call is this value. As such, there is no 2606 // corresponding argument. 2607 assert(!CS.getType()->isVoidTy() && 2608 "Bad inline asm!"); 2609 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 2610 OpInfo.ConstraintVT = 2611 getSimpleValueType(DL, STy->getElementType(ResNo)); 2612 } else { 2613 assert(ResNo == 0 && "Asm only has one result!"); 2614 OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType()); 2615 } 2616 ++ResNo; 2617 break; 2618 case InlineAsm::isInput: 2619 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 2620 break; 2621 case InlineAsm::isClobber: 2622 // Nothing to do. 2623 break; 2624 } 2625 2626 if (OpInfo.CallOperandVal) { 2627 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 2628 if (OpInfo.isIndirect) { 2629 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 2630 if (!PtrTy) 2631 report_fatal_error("Indirect operand for inline asm not a pointer!"); 2632 OpTy = PtrTy->getElementType(); 2633 } 2634 2635 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 2636 if (StructType *STy = dyn_cast<StructType>(OpTy)) 2637 if (STy->getNumElements() == 1) 2638 OpTy = STy->getElementType(0); 2639 2640 // If OpTy is not a single value, it may be a struct/union that we 2641 // can tile with integers. 2642 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 2643 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 2644 switch (BitSize) { 2645 default: break; 2646 case 1: 2647 case 8: 2648 case 16: 2649 case 32: 2650 case 64: 2651 case 128: 2652 OpInfo.ConstraintVT = 2653 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true); 2654 break; 2655 } 2656 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) { 2657 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace()); 2658 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize); 2659 } else { 2660 OpInfo.ConstraintVT = MVT::getVT(OpTy, true); 2661 } 2662 } 2663 } 2664 2665 // If we have multiple alternative constraints, select the best alternative. 2666 if (!ConstraintOperands.empty()) { 2667 if (maCount) { 2668 unsigned bestMAIndex = 0; 2669 int bestWeight = -1; 2670 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 2671 int weight = -1; 2672 unsigned maIndex; 2673 // Compute the sums of the weights for each alternative, keeping track 2674 // of the best (highest weight) one so far. 2675 for (maIndex = 0; maIndex < maCount; ++maIndex) { 2676 int weightSum = 0; 2677 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2678 cIndex != eIndex; ++cIndex) { 2679 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex]; 2680 if (OpInfo.Type == InlineAsm::isClobber) 2681 continue; 2682 2683 // If this is an output operand with a matching input operand, 2684 // look up the matching input. If their types mismatch, e.g. one 2685 // is an integer, the other is floating point, or their sizes are 2686 // different, flag it as an maCantMatch. 2687 if (OpInfo.hasMatchingInput()) { 2688 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 2689 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 2690 if ((OpInfo.ConstraintVT.isInteger() != 2691 Input.ConstraintVT.isInteger()) || 2692 (OpInfo.ConstraintVT.getSizeInBits() != 2693 Input.ConstraintVT.getSizeInBits())) { 2694 weightSum = -1; // Can't match. 2695 break; 2696 } 2697 } 2698 } 2699 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 2700 if (weight == -1) { 2701 weightSum = -1; 2702 break; 2703 } 2704 weightSum += weight; 2705 } 2706 // Update best. 2707 if (weightSum > bestWeight) { 2708 bestWeight = weightSum; 2709 bestMAIndex = maIndex; 2710 } 2711 } 2712 2713 // Now select chosen alternative in each constraint. 2714 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2715 cIndex != eIndex; ++cIndex) { 2716 AsmOperandInfo& cInfo = ConstraintOperands[cIndex]; 2717 if (cInfo.Type == InlineAsm::isClobber) 2718 continue; 2719 cInfo.selectAlternative(bestMAIndex); 2720 } 2721 } 2722 } 2723 2724 // Check and hook up tied operands, choose constraint code to use. 2725 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2726 cIndex != eIndex; ++cIndex) { 2727 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex]; 2728 2729 // If this is an output operand with a matching input operand, look up the 2730 // matching input. If their types mismatch, e.g. one is an integer, the 2731 // other is floating point, or their sizes are different, flag it as an 2732 // error. 2733 if (OpInfo.hasMatchingInput()) { 2734 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 2735 2736 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 2737 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 2738 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 2739 OpInfo.ConstraintVT); 2740 std::pair<unsigned, const TargetRegisterClass *> InputRC = 2741 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 2742 Input.ConstraintVT); 2743 if ((OpInfo.ConstraintVT.isInteger() != 2744 Input.ConstraintVT.isInteger()) || 2745 (MatchRC.second != InputRC.second)) { 2746 report_fatal_error("Unsupported asm: input constraint" 2747 " with a matching output constraint of" 2748 " incompatible type!"); 2749 } 2750 } 2751 } 2752 } 2753 2754 return ConstraintOperands; 2755 } 2756 2757 /// Return an integer indicating how general CT is. 2758 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 2759 switch (CT) { 2760 case TargetLowering::C_Other: 2761 case TargetLowering::C_Unknown: 2762 return 0; 2763 case TargetLowering::C_Register: 2764 return 1; 2765 case TargetLowering::C_RegisterClass: 2766 return 2; 2767 case TargetLowering::C_Memory: 2768 return 3; 2769 } 2770 llvm_unreachable("Invalid constraint type"); 2771 } 2772 2773 /// Examine constraint type and operand type and determine a weight value. 2774 /// This object must already have been set up with the operand type 2775 /// and the current alternative constraint selected. 2776 TargetLowering::ConstraintWeight 2777 TargetLowering::getMultipleConstraintMatchWeight( 2778 AsmOperandInfo &info, int maIndex) const { 2779 InlineAsm::ConstraintCodeVector *rCodes; 2780 if (maIndex >= (int)info.multipleAlternatives.size()) 2781 rCodes = &info.Codes; 2782 else 2783 rCodes = &info.multipleAlternatives[maIndex].Codes; 2784 ConstraintWeight BestWeight = CW_Invalid; 2785 2786 // Loop over the options, keeping track of the most general one. 2787 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) { 2788 ConstraintWeight weight = 2789 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str()); 2790 if (weight > BestWeight) 2791 BestWeight = weight; 2792 } 2793 2794 return BestWeight; 2795 } 2796 2797 /// Examine constraint type and operand type and determine a weight value. 2798 /// This object must already have been set up with the operand type 2799 /// and the current alternative constraint selected. 2800 TargetLowering::ConstraintWeight 2801 TargetLowering::getSingleConstraintMatchWeight( 2802 AsmOperandInfo &info, const char *constraint) const { 2803 ConstraintWeight weight = CW_Invalid; 2804 Value *CallOperandVal = info.CallOperandVal; 2805 // If we don't have a value, we can't do a match, 2806 // but allow it at the lowest weight. 2807 if (!CallOperandVal) 2808 return CW_Default; 2809 // Look at the constraint type. 2810 switch (*constraint) { 2811 case 'i': // immediate integer. 2812 case 'n': // immediate integer with a known value. 2813 if (isa<ConstantInt>(CallOperandVal)) 2814 weight = CW_Constant; 2815 break; 2816 case 's': // non-explicit intregal immediate. 2817 if (isa<GlobalValue>(CallOperandVal)) 2818 weight = CW_Constant; 2819 break; 2820 case 'E': // immediate float if host format. 2821 case 'F': // immediate float. 2822 if (isa<ConstantFP>(CallOperandVal)) 2823 weight = CW_Constant; 2824 break; 2825 case '<': // memory operand with autodecrement. 2826 case '>': // memory operand with autoincrement. 2827 case 'm': // memory operand. 2828 case 'o': // offsettable memory operand 2829 case 'V': // non-offsettable memory operand 2830 weight = CW_Memory; 2831 break; 2832 case 'r': // general register. 2833 case 'g': // general register, memory operand or immediate integer. 2834 // note: Clang converts "g" to "imr". 2835 if (CallOperandVal->getType()->isIntegerTy()) 2836 weight = CW_Register; 2837 break; 2838 case 'X': // any operand. 2839 default: 2840 weight = CW_Default; 2841 break; 2842 } 2843 return weight; 2844 } 2845 2846 /// If there are multiple different constraints that we could pick for this 2847 /// operand (e.g. "imr") try to pick the 'best' one. 2848 /// This is somewhat tricky: constraints fall into four classes: 2849 /// Other -> immediates and magic values 2850 /// Register -> one specific register 2851 /// RegisterClass -> a group of regs 2852 /// Memory -> memory 2853 /// Ideally, we would pick the most specific constraint possible: if we have 2854 /// something that fits into a register, we would pick it. The problem here 2855 /// is that if we have something that could either be in a register or in 2856 /// memory that use of the register could cause selection of *other* 2857 /// operands to fail: they might only succeed if we pick memory. Because of 2858 /// this the heuristic we use is: 2859 /// 2860 /// 1) If there is an 'other' constraint, and if the operand is valid for 2861 /// that constraint, use it. This makes us take advantage of 'i' 2862 /// constraints when available. 2863 /// 2) Otherwise, pick the most general constraint present. This prefers 2864 /// 'm' over 'r', for example. 2865 /// 2866 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 2867 const TargetLowering &TLI, 2868 SDValue Op, SelectionDAG *DAG) { 2869 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 2870 unsigned BestIdx = 0; 2871 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 2872 int BestGenerality = -1; 2873 2874 // Loop over the options, keeping track of the most general one. 2875 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 2876 TargetLowering::ConstraintType CType = 2877 TLI.getConstraintType(OpInfo.Codes[i]); 2878 2879 // If this is an 'other' constraint, see if the operand is valid for it. 2880 // For example, on X86 we might have an 'rI' constraint. If the operand 2881 // is an integer in the range [0..31] we want to use I (saving a load 2882 // of a register), otherwise we must use 'r'. 2883 if (CType == TargetLowering::C_Other && Op.getNode()) { 2884 assert(OpInfo.Codes[i].size() == 1 && 2885 "Unhandled multi-letter 'other' constraint"); 2886 std::vector<SDValue> ResultOps; 2887 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 2888 ResultOps, *DAG); 2889 if (!ResultOps.empty()) { 2890 BestType = CType; 2891 BestIdx = i; 2892 break; 2893 } 2894 } 2895 2896 // Things with matching constraints can only be registers, per gcc 2897 // documentation. This mainly affects "g" constraints. 2898 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 2899 continue; 2900 2901 // This constraint letter is more general than the previous one, use it. 2902 int Generality = getConstraintGenerality(CType); 2903 if (Generality > BestGenerality) { 2904 BestType = CType; 2905 BestIdx = i; 2906 BestGenerality = Generality; 2907 } 2908 } 2909 2910 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 2911 OpInfo.ConstraintType = BestType; 2912 } 2913 2914 /// Determines the constraint code and constraint type to use for the specific 2915 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 2916 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 2917 SDValue Op, 2918 SelectionDAG *DAG) const { 2919 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 2920 2921 // Single-letter constraints ('r') are very common. 2922 if (OpInfo.Codes.size() == 1) { 2923 OpInfo.ConstraintCode = OpInfo.Codes[0]; 2924 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 2925 } else { 2926 ChooseConstraint(OpInfo, *this, Op, DAG); 2927 } 2928 2929 // 'X' matches anything. 2930 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 2931 // Labels and constants are handled elsewhere ('X' is the only thing 2932 // that matches labels). For Functions, the type here is the type of 2933 // the result, which is not what we want to look at; leave them alone. 2934 Value *v = OpInfo.CallOperandVal; 2935 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) { 2936 OpInfo.CallOperandVal = v; 2937 return; 2938 } 2939 2940 // Otherwise, try to resolve it to something we know about by looking at 2941 // the actual operand type. 2942 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 2943 OpInfo.ConstraintCode = Repl; 2944 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 2945 } 2946 } 2947 } 2948 2949 /// \brief Given an exact SDIV by a constant, create a multiplication 2950 /// with the multiplicative inverse of the constant. 2951 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d, 2952 const SDLoc &dl, SelectionDAG &DAG, 2953 std::vector<SDNode *> &Created) { 2954 assert(d != 0 && "Division by zero!"); 2955 2956 // Shift the value upfront if it is even, so the LSB is one. 2957 unsigned ShAmt = d.countTrailingZeros(); 2958 if (ShAmt) { 2959 // TODO: For UDIV use SRL instead of SRA. 2960 SDValue Amt = 2961 DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(), 2962 DAG.getDataLayout())); 2963 SDNodeFlags Flags; 2964 Flags.setExact(true); 2965 Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, &Flags); 2966 Created.push_back(Op1.getNode()); 2967 d = d.ashr(ShAmt); 2968 } 2969 2970 // Calculate the multiplicative inverse, using Newton's method. 2971 APInt t, xn = d; 2972 while ((t = d*xn) != 1) 2973 xn *= APInt(d.getBitWidth(), 2) - t; 2974 2975 SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType()); 2976 SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2); 2977 Created.push_back(Mul.getNode()); 2978 return Mul; 2979 } 2980 2981 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 2982 SelectionDAG &DAG, 2983 std::vector<SDNode *> *Created) const { 2984 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2985 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2986 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 2987 return SDValue(N,0); // Lower SDIV as SDIV 2988 return SDValue(); 2989 } 2990 2991 /// \brief Given an ISD::SDIV node expressing a divide by constant, 2992 /// return a DAG expression to select that will generate the same value by 2993 /// multiplying by a magic number. 2994 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 2995 SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor, 2996 SelectionDAG &DAG, bool IsAfterLegalization, 2997 std::vector<SDNode *> *Created) const { 2998 assert(Created && "No vector to hold sdiv ops."); 2999 3000 EVT VT = N->getValueType(0); 3001 SDLoc dl(N); 3002 3003 // Check to see if we can do this. 3004 // FIXME: We should be more aggressive here. 3005 if (!isTypeLegal(VT)) 3006 return SDValue(); 3007 3008 // If the sdiv has an 'exact' bit we can use a simpler lowering. 3009 if (cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact()) 3010 return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created); 3011 3012 APInt::ms magics = Divisor.magic(); 3013 3014 // Multiply the numerator (operand 0) by the magic value 3015 // FIXME: We should support doing a MUL in a wider type 3016 SDValue Q; 3017 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) : 3018 isOperationLegalOrCustom(ISD::MULHS, VT)) 3019 Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0), 3020 DAG.getConstant(magics.m, dl, VT)); 3021 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) : 3022 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT)) 3023 Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), 3024 N->getOperand(0), 3025 DAG.getConstant(magics.m, dl, VT)).getNode(), 1); 3026 else 3027 return SDValue(); // No mulhs or equvialent 3028 // If d > 0 and m < 0, add the numerator 3029 if (Divisor.isStrictlyPositive() && magics.m.isNegative()) { 3030 Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0)); 3031 Created->push_back(Q.getNode()); 3032 } 3033 // If d < 0 and m > 0, subtract the numerator. 3034 if (Divisor.isNegative() && magics.m.isStrictlyPositive()) { 3035 Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0)); 3036 Created->push_back(Q.getNode()); 3037 } 3038 auto &DL = DAG.getDataLayout(); 3039 // Shift right algebraic if shift value is nonzero 3040 if (magics.s > 0) { 3041 Q = DAG.getNode( 3042 ISD::SRA, dl, VT, Q, 3043 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL))); 3044 Created->push_back(Q.getNode()); 3045 } 3046 // Extract the sign bit and add it to the quotient 3047 SDValue T = 3048 DAG.getNode(ISD::SRL, dl, VT, Q, 3049 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, 3050 getShiftAmountTy(Q.getValueType(), DL))); 3051 Created->push_back(T.getNode()); 3052 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 3053 } 3054 3055 /// \brief Given an ISD::UDIV node expressing a divide by constant, 3056 /// return a DAG expression to select that will generate the same value by 3057 /// multiplying by a magic number. 3058 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 3059 SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor, 3060 SelectionDAG &DAG, bool IsAfterLegalization, 3061 std::vector<SDNode *> *Created) const { 3062 assert(Created && "No vector to hold udiv ops."); 3063 3064 EVT VT = N->getValueType(0); 3065 SDLoc dl(N); 3066 auto &DL = DAG.getDataLayout(); 3067 3068 // Check to see if we can do this. 3069 // FIXME: We should be more aggressive here. 3070 if (!isTypeLegal(VT)) 3071 return SDValue(); 3072 3073 // FIXME: We should use a narrower constant when the upper 3074 // bits are known to be zero. 3075 APInt::mu magics = Divisor.magicu(); 3076 3077 SDValue Q = N->getOperand(0); 3078 3079 // If the divisor is even, we can avoid using the expensive fixup by shifting 3080 // the divided value upfront. 3081 if (magics.a != 0 && !Divisor[0]) { 3082 unsigned Shift = Divisor.countTrailingZeros(); 3083 Q = DAG.getNode( 3084 ISD::SRL, dl, VT, Q, 3085 DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL))); 3086 Created->push_back(Q.getNode()); 3087 3088 // Get magic number for the shifted divisor. 3089 magics = Divisor.lshr(Shift).magicu(Shift); 3090 assert(magics.a == 0 && "Should use cheap fixup now"); 3091 } 3092 3093 // Multiply the numerator (operand 0) by the magic value 3094 // FIXME: We should support doing a MUL in a wider type 3095 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) : 3096 isOperationLegalOrCustom(ISD::MULHU, VT)) 3097 Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT)); 3098 else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) : 3099 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT)) 3100 Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q, 3101 DAG.getConstant(magics.m, dl, VT)).getNode(), 1); 3102 else 3103 return SDValue(); // No mulhu or equivalent 3104 3105 Created->push_back(Q.getNode()); 3106 3107 if (magics.a == 0) { 3108 assert(magics.s < Divisor.getBitWidth() && 3109 "We shouldn't generate an undefined shift!"); 3110 return DAG.getNode( 3111 ISD::SRL, dl, VT, Q, 3112 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL))); 3113 } else { 3114 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q); 3115 Created->push_back(NPQ.getNode()); 3116 NPQ = DAG.getNode( 3117 ISD::SRL, dl, VT, NPQ, 3118 DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL))); 3119 Created->push_back(NPQ.getNode()); 3120 NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 3121 Created->push_back(NPQ.getNode()); 3122 return DAG.getNode( 3123 ISD::SRL, dl, VT, NPQ, 3124 DAG.getConstant(magics.s - 1, dl, 3125 getShiftAmountTy(NPQ.getValueType(), DL))); 3126 } 3127 } 3128 3129 bool TargetLowering:: 3130 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 3131 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 3132 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 3133 "be a constant integer"); 3134 return true; 3135 } 3136 3137 return false; 3138 } 3139 3140 //===----------------------------------------------------------------------===// 3141 // Legalization Utilities 3142 //===----------------------------------------------------------------------===// 3143 3144 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl, 3145 SDValue LHS, SDValue RHS, 3146 SmallVectorImpl<SDValue> &Result, 3147 EVT HiLoVT, SelectionDAG &DAG, 3148 MulExpansionKind Kind, SDValue LL, 3149 SDValue LH, SDValue RL, SDValue RH) const { 3150 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 3151 Opcode == ISD::SMUL_LOHI); 3152 3153 bool HasMULHS = (Kind == MulExpansionKind::Always) || 3154 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 3155 bool HasMULHU = (Kind == MulExpansionKind::Always) || 3156 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 3157 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 3158 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 3159 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 3160 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 3161 3162 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 3163 return false; 3164 3165 unsigned OuterBitSize = VT.getScalarSizeInBits(); 3166 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 3167 unsigned LHSSB = DAG.ComputeNumSignBits(LHS); 3168 unsigned RHSSB = DAG.ComputeNumSignBits(RHS); 3169 3170 // LL, LH, RL, and RH must be either all NULL or all set to a value. 3171 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 3172 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 3173 3174 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 3175 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 3176 bool Signed) -> bool { 3177 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 3178 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 3179 Hi = SDValue(Lo.getNode(), 1); 3180 return true; 3181 } 3182 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 3183 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 3184 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 3185 return true; 3186 } 3187 return false; 3188 }; 3189 3190 SDValue Lo, Hi; 3191 3192 if (!LL.getNode() && !RL.getNode() && 3193 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 3194 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 3195 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 3196 } 3197 3198 if (!LL.getNode()) 3199 return false; 3200 3201 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 3202 if (DAG.MaskedValueIsZero(LHS, HighMask) && 3203 DAG.MaskedValueIsZero(RHS, HighMask)) { 3204 // The inputs are both zero-extended. 3205 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 3206 Result.push_back(Lo); 3207 Result.push_back(Hi); 3208 if (Opcode != ISD::MUL) { 3209 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 3210 Result.push_back(Zero); 3211 Result.push_back(Zero); 3212 } 3213 return true; 3214 } 3215 } 3216 3217 if (!VT.isVector() && Opcode == ISD::MUL && LHSSB > InnerBitSize && 3218 RHSSB > InnerBitSize) { 3219 // The input values are both sign-extended. 3220 // TODO non-MUL case? 3221 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 3222 Result.push_back(Lo); 3223 Result.push_back(Hi); 3224 return true; 3225 } 3226 } 3227 3228 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 3229 EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout()); 3230 if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) { 3231 // FIXME getShiftAmountTy does not always return a sensible result when VT 3232 // is an illegal type, and so the type may be too small to fit the shift 3233 // amount. Override it with i32. The shift will have to be legalized. 3234 ShiftAmountTy = MVT::i32; 3235 } 3236 SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy); 3237 3238 if (!LH.getNode() && !RH.getNode() && 3239 isOperationLegalOrCustom(ISD::SRL, VT) && 3240 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 3241 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 3242 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 3243 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 3244 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 3245 } 3246 3247 if (!LH.getNode()) 3248 return false; 3249 3250 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 3251 return false; 3252 3253 Result.push_back(Lo); 3254 3255 if (Opcode == ISD::MUL) { 3256 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 3257 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 3258 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 3259 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 3260 Result.push_back(Hi); 3261 return true; 3262 } 3263 3264 // Compute the full width result. 3265 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 3266 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 3267 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 3268 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 3269 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 3270 }; 3271 3272 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 3273 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 3274 return false; 3275 3276 // This is effectively the add part of a multiply-add of half-sized operands, 3277 // so it cannot overflow. 3278 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 3279 3280 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 3281 return false; 3282 3283 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 3284 Merge(Lo, Hi)); 3285 3286 SDValue Carry = Next.getValue(1); 3287 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 3288 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 3289 3290 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 3291 return false; 3292 3293 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 3294 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 3295 Carry); 3296 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 3297 3298 if (Opcode == ISD::SMUL_LOHI) { 3299 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 3300 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 3301 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 3302 3303 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 3304 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 3305 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 3306 } 3307 3308 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 3309 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 3310 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 3311 return true; 3312 } 3313 3314 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 3315 SelectionDAG &DAG, MulExpansionKind Kind, 3316 SDValue LL, SDValue LH, SDValue RL, 3317 SDValue RH) const { 3318 SmallVector<SDValue, 2> Result; 3319 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), N, 3320 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 3321 DAG, Kind, LL, LH, RL, RH); 3322 if (Ok) { 3323 assert(Result.size() == 2); 3324 Lo = Result[0]; 3325 Hi = Result[1]; 3326 } 3327 return Ok; 3328 } 3329 3330 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 3331 SelectionDAG &DAG) const { 3332 EVT VT = Node->getOperand(0).getValueType(); 3333 EVT NVT = Node->getValueType(0); 3334 SDLoc dl(SDValue(Node, 0)); 3335 3336 // FIXME: Only f32 to i64 conversions are supported. 3337 if (VT != MVT::f32 || NVT != MVT::i64) 3338 return false; 3339 3340 // Expand f32 -> i64 conversion 3341 // This algorithm comes from compiler-rt's implementation of fixsfdi: 3342 // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c 3343 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), 3344 VT.getSizeInBits()); 3345 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 3346 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 3347 SDValue Bias = DAG.getConstant(127, dl, IntVT); 3348 SDValue SignMask = DAG.getConstant(APInt::getSignBit(VT.getSizeInBits()), dl, 3349 IntVT); 3350 SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT); 3351 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 3352 3353 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0)); 3354 3355 auto &DL = DAG.getDataLayout(); 3356 SDValue ExponentBits = DAG.getNode( 3357 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 3358 DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL))); 3359 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 3360 3361 SDValue Sign = DAG.getNode( 3362 ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 3363 DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL))); 3364 Sign = DAG.getSExtOrTrunc(Sign, dl, NVT); 3365 3366 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 3367 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 3368 DAG.getConstant(0x00800000, dl, IntVT)); 3369 3370 R = DAG.getZExtOrTrunc(R, dl, NVT); 3371 3372 R = DAG.getSelectCC( 3373 dl, Exponent, ExponentLoBit, 3374 DAG.getNode(ISD::SHL, dl, NVT, R, 3375 DAG.getZExtOrTrunc( 3376 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 3377 dl, getShiftAmountTy(IntVT, DL))), 3378 DAG.getNode(ISD::SRL, dl, NVT, R, 3379 DAG.getZExtOrTrunc( 3380 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 3381 dl, getShiftAmountTy(IntVT, DL))), 3382 ISD::SETGT); 3383 3384 SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT, 3385 DAG.getNode(ISD::XOR, dl, NVT, R, Sign), 3386 Sign); 3387 3388 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 3389 DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT); 3390 return true; 3391 } 3392 3393 SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 3394 SelectionDAG &DAG) const { 3395 SDLoc SL(LD); 3396 SDValue Chain = LD->getChain(); 3397 SDValue BasePTR = LD->getBasePtr(); 3398 EVT SrcVT = LD->getMemoryVT(); 3399 ISD::LoadExtType ExtType = LD->getExtensionType(); 3400 3401 unsigned NumElem = SrcVT.getVectorNumElements(); 3402 3403 EVT SrcEltVT = SrcVT.getScalarType(); 3404 EVT DstEltVT = LD->getValueType(0).getScalarType(); 3405 3406 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 3407 assert(SrcEltVT.isByteSized()); 3408 3409 EVT PtrVT = BasePTR.getValueType(); 3410 3411 SmallVector<SDValue, 8> Vals; 3412 SmallVector<SDValue, 8> LoadChains; 3413 3414 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 3415 SDValue ScalarLoad = 3416 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 3417 LD->getPointerInfo().getWithOffset(Idx * Stride), 3418 SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride), 3419 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 3420 3421 BasePTR = DAG.getNode(ISD::ADD, SL, PtrVT, BasePTR, 3422 DAG.getConstant(Stride, SL, PtrVT)); 3423 3424 Vals.push_back(ScalarLoad.getValue(0)); 3425 LoadChains.push_back(ScalarLoad.getValue(1)); 3426 } 3427 3428 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 3429 SDValue Value = DAG.getBuildVector(LD->getValueType(0), SL, Vals); 3430 3431 return DAG.getMergeValues({ Value, NewChain }, SL); 3432 } 3433 3434 // FIXME: This relies on each element having a byte size, otherwise the stride 3435 // is 0 and just overwrites the same location. ExpandStore currently expects 3436 // this broken behavior. 3437 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 3438 SelectionDAG &DAG) const { 3439 SDLoc SL(ST); 3440 3441 SDValue Chain = ST->getChain(); 3442 SDValue BasePtr = ST->getBasePtr(); 3443 SDValue Value = ST->getValue(); 3444 EVT StVT = ST->getMemoryVT(); 3445 3446 // The type of the data we want to save 3447 EVT RegVT = Value.getValueType(); 3448 EVT RegSclVT = RegVT.getScalarType(); 3449 3450 // The type of data as saved in memory. 3451 EVT MemSclVT = StVT.getScalarType(); 3452 3453 EVT PtrVT = BasePtr.getValueType(); 3454 3455 // Store Stride in bytes 3456 unsigned Stride = MemSclVT.getSizeInBits() / 8; 3457 EVT IdxVT = getVectorIdxTy(DAG.getDataLayout()); 3458 unsigned NumElem = StVT.getVectorNumElements(); 3459 3460 // Extract each of the elements from the original vector and save them into 3461 // memory individually. 3462 SmallVector<SDValue, 8> Stores; 3463 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 3464 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 3465 DAG.getConstant(Idx, SL, IdxVT)); 3466 3467 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr, 3468 DAG.getConstant(Idx * Stride, SL, PtrVT)); 3469 3470 // This scalar TruncStore may be illegal, but we legalize it later. 3471 SDValue Store = DAG.getTruncStore( 3472 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 3473 MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride), 3474 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 3475 3476 Stores.push_back(Store); 3477 } 3478 3479 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 3480 } 3481 3482 std::pair<SDValue, SDValue> 3483 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 3484 assert(LD->getAddressingMode() == ISD::UNINDEXED && 3485 "unaligned indexed loads not implemented!"); 3486 SDValue Chain = LD->getChain(); 3487 SDValue Ptr = LD->getBasePtr(); 3488 EVT VT = LD->getValueType(0); 3489 EVT LoadedVT = LD->getMemoryVT(); 3490 SDLoc dl(LD); 3491 if (VT.isFloatingPoint() || VT.isVector()) { 3492 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 3493 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 3494 if (!isOperationLegalOrCustom(ISD::LOAD, intVT)) { 3495 // Scalarize the load and let the individual components be handled. 3496 SDValue Scalarized = scalarizeVectorLoad(LD, DAG); 3497 return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1)); 3498 } 3499 3500 // Expand to a (misaligned) integer load of the same size, 3501 // then bitconvert to floating point or vector. 3502 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 3503 LD->getMemOperand()); 3504 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 3505 if (LoadedVT != VT) 3506 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 3507 ISD::ANY_EXTEND, dl, VT, Result); 3508 3509 return std::make_pair(Result, newLoad.getValue(1)); 3510 } 3511 3512 // Copy the value to a (aligned) stack slot using (unaligned) integer 3513 // loads and stores, then do a (aligned) load from the stack slot. 3514 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 3515 unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8; 3516 unsigned RegBytes = RegVT.getSizeInBits() / 8; 3517 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 3518 3519 // Make sure the stack slot is also aligned for the register type. 3520 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 3521 3522 SmallVector<SDValue, 8> Stores; 3523 SDValue StackPtr = StackBase; 3524 unsigned Offset = 0; 3525 3526 EVT PtrVT = Ptr.getValueType(); 3527 EVT StackPtrVT = StackPtr.getValueType(); 3528 3529 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 3530 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 3531 3532 // Do all but one copies using the full register width. 3533 for (unsigned i = 1; i < NumRegs; i++) { 3534 // Load one integer register's worth from the original location. 3535 SDValue Load = DAG.getLoad( 3536 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 3537 MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(), 3538 LD->getAAInfo()); 3539 // Follow the load with a store to the stack slot. Remember the store. 3540 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr, 3541 MachinePointerInfo())); 3542 // Increment the pointers. 3543 Offset += RegBytes; 3544 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement); 3545 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT, StackPtr, 3546 StackPtrIncrement); 3547 } 3548 3549 // The last copy may be partial. Do an extending load. 3550 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 3551 8 * (LoadedBytes - Offset)); 3552 SDValue Load = 3553 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 3554 LD->getPointerInfo().getWithOffset(Offset), MemVT, 3555 MinAlign(LD->getAlignment(), Offset), 3556 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 3557 // Follow the load with a store to the stack slot. Remember the store. 3558 // On big-endian machines this requires a truncating store to ensure 3559 // that the bits end up in the right place. 3560 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr, 3561 MachinePointerInfo(), MemVT)); 3562 3563 // The order of the stores doesn't matter - say it with a TokenFactor. 3564 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 3565 3566 // Finally, perform the original load only redirected to the stack slot. 3567 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 3568 MachinePointerInfo(), LoadedVT); 3569 3570 // Callers expect a MERGE_VALUES node. 3571 return std::make_pair(Load, TF); 3572 } 3573 3574 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 3575 "Unaligned load of unsupported type."); 3576 3577 // Compute the new VT that is half the size of the old one. This is an 3578 // integer MVT. 3579 unsigned NumBits = LoadedVT.getSizeInBits(); 3580 EVT NewLoadedVT; 3581 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 3582 NumBits >>= 1; 3583 3584 unsigned Alignment = LD->getAlignment(); 3585 unsigned IncrementSize = NumBits / 8; 3586 ISD::LoadExtType HiExtType = LD->getExtensionType(); 3587 3588 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 3589 if (HiExtType == ISD::NON_EXTLOAD) 3590 HiExtType = ISD::ZEXTLOAD; 3591 3592 // Load the value in two parts 3593 SDValue Lo, Hi; 3594 if (DAG.getDataLayout().isLittleEndian()) { 3595 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 3596 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 3597 LD->getAAInfo()); 3598 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 3599 DAG.getConstant(IncrementSize, dl, Ptr.getValueType())); 3600 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 3601 LD->getPointerInfo().getWithOffset(IncrementSize), 3602 NewLoadedVT, MinAlign(Alignment, IncrementSize), 3603 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 3604 } else { 3605 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 3606 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 3607 LD->getAAInfo()); 3608 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 3609 DAG.getConstant(IncrementSize, dl, Ptr.getValueType())); 3610 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 3611 LD->getPointerInfo().getWithOffset(IncrementSize), 3612 NewLoadedVT, MinAlign(Alignment, IncrementSize), 3613 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 3614 } 3615 3616 // aggregate the two parts 3617 SDValue ShiftAmount = 3618 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(), 3619 DAG.getDataLayout())); 3620 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 3621 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 3622 3623 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 3624 Hi.getValue(1)); 3625 3626 return std::make_pair(Result, TF); 3627 } 3628 3629 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 3630 SelectionDAG &DAG) const { 3631 assert(ST->getAddressingMode() == ISD::UNINDEXED && 3632 "unaligned indexed stores not implemented!"); 3633 SDValue Chain = ST->getChain(); 3634 SDValue Ptr = ST->getBasePtr(); 3635 SDValue Val = ST->getValue(); 3636 EVT VT = Val.getValueType(); 3637 int Alignment = ST->getAlignment(); 3638 3639 SDLoc dl(ST); 3640 if (ST->getMemoryVT().isFloatingPoint() || 3641 ST->getMemoryVT().isVector()) { 3642 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 3643 if (isTypeLegal(intVT)) { 3644 if (!isOperationLegalOrCustom(ISD::STORE, intVT)) { 3645 // Scalarize the store and let the individual components be handled. 3646 SDValue Result = scalarizeVectorStore(ST, DAG); 3647 3648 return Result; 3649 } 3650 // Expand to a bitconvert of the value to the integer type of the 3651 // same size, then a (misaligned) int store. 3652 // FIXME: Does not handle truncating floating point stores! 3653 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 3654 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 3655 Alignment, ST->getMemOperand()->getFlags()); 3656 return Result; 3657 } 3658 // Do a (aligned) store to a stack slot, then copy from the stack slot 3659 // to the final destination using (unaligned) integer loads and stores. 3660 EVT StoredVT = ST->getMemoryVT(); 3661 MVT RegVT = 3662 getRegisterType(*DAG.getContext(), 3663 EVT::getIntegerVT(*DAG.getContext(), 3664 StoredVT.getSizeInBits())); 3665 EVT PtrVT = Ptr.getValueType(); 3666 unsigned StoredBytes = StoredVT.getSizeInBits() / 8; 3667 unsigned RegBytes = RegVT.getSizeInBits() / 8; 3668 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 3669 3670 // Make sure the stack slot is also aligned for the register type. 3671 SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT); 3672 3673 // Perform the original store, only redirected to the stack slot. 3674 SDValue Store = DAG.getTruncStore(Chain, dl, Val, StackPtr, 3675 MachinePointerInfo(), StoredVT); 3676 3677 EVT StackPtrVT = StackPtr.getValueType(); 3678 3679 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 3680 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 3681 SmallVector<SDValue, 8> Stores; 3682 unsigned Offset = 0; 3683 3684 // Do all but one copies using the full register width. 3685 for (unsigned i = 1; i < NumRegs; i++) { 3686 // Load one integer register's worth from the stack slot. 3687 SDValue Load = 3688 DAG.getLoad(RegVT, dl, Store, StackPtr, MachinePointerInfo()); 3689 // Store it to the final location. Remember the store. 3690 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 3691 ST->getPointerInfo().getWithOffset(Offset), 3692 MinAlign(ST->getAlignment(), Offset), 3693 ST->getMemOperand()->getFlags())); 3694 // Increment the pointers. 3695 Offset += RegBytes; 3696 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT, 3697 StackPtr, StackPtrIncrement); 3698 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement); 3699 } 3700 3701 // The last store may be partial. Do a truncating store. On big-endian 3702 // machines this requires an extending load from the stack slot to ensure 3703 // that the bits are in the right place. 3704 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 3705 8 * (StoredBytes - Offset)); 3706 3707 // Load from the stack slot. 3708 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 3709 MachinePointerInfo(), MemVT); 3710 3711 Stores.push_back( 3712 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 3713 ST->getPointerInfo().getWithOffset(Offset), MemVT, 3714 MinAlign(ST->getAlignment(), Offset), 3715 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 3716 // The order of the stores doesn't matter - say it with a TokenFactor. 3717 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 3718 return Result; 3719 } 3720 3721 assert(ST->getMemoryVT().isInteger() && 3722 !ST->getMemoryVT().isVector() && 3723 "Unaligned store of unknown type."); 3724 // Get the half-size VT 3725 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext()); 3726 int NumBits = NewStoredVT.getSizeInBits(); 3727 int IncrementSize = NumBits / 8; 3728 3729 // Divide the stored value in two parts. 3730 SDValue ShiftAmount = 3731 DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(), 3732 DAG.getDataLayout())); 3733 SDValue Lo = Val; 3734 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 3735 3736 // Store the two parts 3737 SDValue Store1, Store2; 3738 Store1 = DAG.getTruncStore(Chain, dl, 3739 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 3740 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 3741 ST->getMemOperand()->getFlags()); 3742 3743 EVT PtrVT = Ptr.getValueType(); 3744 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3745 DAG.getConstant(IncrementSize, dl, PtrVT)); 3746 Alignment = MinAlign(Alignment, IncrementSize); 3747 Store2 = DAG.getTruncStore( 3748 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 3749 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 3750 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 3751 3752 SDValue Result = 3753 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 3754 return Result; 3755 } 3756 3757 SDValue 3758 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 3759 const SDLoc &DL, EVT DataVT, 3760 SelectionDAG &DAG, 3761 bool IsCompressedMemory) const { 3762 SDValue Increment; 3763 EVT AddrVT = Addr.getValueType(); 3764 EVT MaskVT = Mask.getValueType(); 3765 assert(DataVT.getVectorNumElements() == MaskVT.getVectorNumElements() && 3766 "Incompatible types of Data and Mask"); 3767 if (IsCompressedMemory) { 3768 // Incrementing the pointer according to number of '1's in the mask. 3769 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 3770 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 3771 if (MaskIntVT.getSizeInBits() < 32) { 3772 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 3773 MaskIntVT = MVT::i32; 3774 } 3775 3776 // Count '1's with POPCNT. 3777 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 3778 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 3779 // Scale is an element size in bytes. 3780 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 3781 AddrVT); 3782 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 3783 } else 3784 Increment = DAG.getConstant(DataVT.getSizeInBits() / 8, DL, AddrVT); 3785 3786 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 3787 } 3788 3789 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, 3790 SDValue Idx, 3791 EVT VecVT, 3792 const SDLoc &dl) { 3793 if (isa<ConstantSDNode>(Idx)) 3794 return Idx; 3795 3796 EVT IdxVT = Idx.getValueType(); 3797 unsigned NElts = VecVT.getVectorNumElements(); 3798 if (isPowerOf2_32(NElts)) { 3799 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), 3800 Log2_32(NElts)); 3801 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 3802 DAG.getConstant(Imm, dl, IdxVT)); 3803 } 3804 3805 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 3806 DAG.getConstant(NElts - 1, dl, IdxVT)); 3807 } 3808 3809 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 3810 SDValue VecPtr, EVT VecVT, 3811 SDValue Index) const { 3812 SDLoc dl(Index); 3813 // Make sure the index type is big enough to compute in. 3814 Index = DAG.getZExtOrTrunc(Index, dl, getPointerTy(DAG.getDataLayout())); 3815 3816 EVT EltVT = VecVT.getVectorElementType(); 3817 3818 // Calculate the element offset and add it to the pointer. 3819 unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size. 3820 assert(EltSize * 8 == EltVT.getSizeInBits() && 3821 "Converting bits to bytes lost precision"); 3822 3823 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl); 3824 3825 EVT IdxVT = Index.getValueType(); 3826 3827 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 3828 DAG.getConstant(EltSize, dl, IdxVT)); 3829 return DAG.getNode(ISD::ADD, dl, IdxVT, Index, VecPtr); 3830 } 3831 3832 //===----------------------------------------------------------------------===// 3833 // Implementation of Emulated TLS Model 3834 //===----------------------------------------------------------------------===// 3835 3836 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 3837 SelectionDAG &DAG) const { 3838 // Access to address of TLS varialbe xyz is lowered to a function call: 3839 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 3840 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3841 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 3842 SDLoc dl(GA); 3843 3844 ArgListTy Args; 3845 ArgListEntry Entry; 3846 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 3847 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 3848 StringRef EmuTlsVarName(NameString); 3849 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 3850 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 3851 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 3852 Entry.Ty = VoidPtrType; 3853 Args.push_back(Entry); 3854 3855 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 3856 3857 TargetLowering::CallLoweringInfo CLI(DAG); 3858 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 3859 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 3860 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3861 3862 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 3863 // At last for X86 targets, maybe good for other targets too? 3864 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 3865 MFI.setAdjustsStack(true); // Is this only for X86 target? 3866 MFI.setHasCalls(true); 3867 3868 assert((GA->getOffset() == 0) && 3869 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 3870 return CallResult.first; 3871 } 3872 3873 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 3874 SelectionDAG &DAG) const { 3875 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 3876 if (!isCtlzFast()) 3877 return SDValue(); 3878 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3879 SDLoc dl(Op); 3880 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3881 if (C->isNullValue() && CC == ISD::SETEQ) { 3882 EVT VT = Op.getOperand(0).getValueType(); 3883 SDValue Zext = Op.getOperand(0); 3884 if (VT.bitsLT(MVT::i32)) { 3885 VT = MVT::i32; 3886 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 3887 } 3888 unsigned Log2b = Log2_32(VT.getSizeInBits()); 3889 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 3890 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 3891 DAG.getConstant(Log2b, dl, MVT::i32)); 3892 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 3893 } 3894 } 3895 return SDValue(); 3896 } 3897