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