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