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