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