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