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