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/Analysis.h" 18 #include "llvm/CodeGen/MachineFrameInfo.h" 19 #include "llvm/CodeGen/MachineFunction.h" 20 #include "llvm/CodeGen/MachineJumpTableInfo.h" 21 #include "llvm/CodeGen/SelectionDAG.h" 22 #include "llvm/IR/DataLayout.h" 23 #include "llvm/IR/DerivedTypes.h" 24 #include "llvm/IR/GlobalVariable.h" 25 #include "llvm/IR/LLVMContext.h" 26 #include "llvm/MC/MCAsmInfo.h" 27 #include "llvm/MC/MCExpr.h" 28 #include "llvm/Support/CommandLine.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/MathExtras.h" 31 #include "llvm/Target/TargetLoweringObjectFile.h" 32 #include "llvm/Target/TargetMachine.h" 33 #include "llvm/Target/TargetRegisterInfo.h" 34 #include "llvm/Target/TargetSubtargetInfo.h" 35 #include <cctype> 36 using namespace llvm; 37 38 /// NOTE: The TargetMachine owns TLOF. 39 TargetLowering::TargetLowering(const TargetMachine &tm) 40 : TargetLoweringBase(tm) {} 41 42 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const { 43 return nullptr; 44 } 45 46 /// Check whether a given call node is in tail position within its function. If 47 /// so, it sets Chain to the input chain of the tail call. 48 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node, 49 SDValue &Chain) const { 50 const Function *F = DAG.getMachineFunction().getFunction(); 51 52 // Conservatively require the attributes of the call to match those of 53 // the return. Ignore noalias because it doesn't affect the call sequence. 54 AttributeSet CallerAttrs = F->getAttributes(); 55 if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex) 56 .removeAttribute(Attribute::NoAlias).hasAttributes()) 57 return false; 58 59 // It's not safe to eliminate the sign / zero extension of the return value. 60 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) || 61 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt)) 62 return false; 63 64 // Check if the only use is a function return node. 65 return isUsedByReturnOnly(Node, Chain); 66 } 67 68 /// \brief Set CallLoweringInfo attribute flags based on a call instruction 69 /// and called function attributes. 70 void TargetLowering::ArgListEntry::setAttributes(ImmutableCallSite *CS, 71 unsigned AttrIdx) { 72 isSExt = CS->paramHasAttr(AttrIdx, Attribute::SExt); 73 isZExt = CS->paramHasAttr(AttrIdx, Attribute::ZExt); 74 isInReg = CS->paramHasAttr(AttrIdx, Attribute::InReg); 75 isSRet = CS->paramHasAttr(AttrIdx, Attribute::StructRet); 76 isNest = CS->paramHasAttr(AttrIdx, Attribute::Nest); 77 isByVal = CS->paramHasAttr(AttrIdx, Attribute::ByVal); 78 isInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca); 79 isReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned); 80 Alignment = CS->getParamAlignment(AttrIdx); 81 } 82 83 /// Generate a libcall taking the given operands as arguments and returning a 84 /// result of type RetVT. 85 std::pair<SDValue, SDValue> 86 TargetLowering::makeLibCall(SelectionDAG &DAG, 87 RTLIB::Libcall LC, EVT RetVT, 88 ArrayRef<SDValue> Ops, 89 bool isSigned, SDLoc dl, 90 bool doesNotReturn, 91 bool isReturnValueUsed) const { 92 TargetLowering::ArgListTy Args; 93 Args.reserve(Ops.size()); 94 95 TargetLowering::ArgListEntry Entry; 96 for (SDValue Op : Ops) { 97 Entry.Node = Op; 98 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 99 Entry.isSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned); 100 Entry.isZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned); 101 Args.push_back(Entry); 102 } 103 104 if (LC == RTLIB::UNKNOWN_LIBCALL) 105 report_fatal_error("Unsupported library call operation!"); 106 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 107 getPointerTy(DAG.getDataLayout())); 108 109 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 110 TargetLowering::CallLoweringInfo CLI(DAG); 111 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned); 112 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()) 113 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0) 114 .setNoReturn(doesNotReturn).setDiscardResult(!isReturnValueUsed) 115 .setSExtResult(signExtend).setZExtResult(!signExtend); 116 return LowerCallTo(CLI); 117 } 118 119 /// Soften the operands of a comparison. This code is shared among BR_CC, 120 /// SELECT_CC, and SETCC handlers. 121 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 122 SDValue &NewLHS, SDValue &NewRHS, 123 ISD::CondCode &CCCode, 124 SDLoc dl) const { 125 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 126 && "Unsupported setcc type!"); 127 128 // Expand into one or more soft-fp libcall(s). 129 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL; 130 bool ShouldInvertCC = false; 131 switch (CCCode) { 132 case ISD::SETEQ: 133 case ISD::SETOEQ: 134 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 135 (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128; 136 break; 137 case ISD::SETNE: 138 case ISD::SETUNE: 139 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : 140 (VT == MVT::f64) ? RTLIB::UNE_F64 : RTLIB::UNE_F128; 141 break; 142 case ISD::SETGE: 143 case ISD::SETOGE: 144 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 145 (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128; 146 break; 147 case ISD::SETLT: 148 case ISD::SETOLT: 149 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 150 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128; 151 break; 152 case ISD::SETLE: 153 case ISD::SETOLE: 154 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 155 (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128; 156 break; 157 case ISD::SETGT: 158 case ISD::SETOGT: 159 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 160 (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128; 161 break; 162 case ISD::SETUO: 163 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 164 (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128; 165 break; 166 case ISD::SETO: 167 LC1 = (VT == MVT::f32) ? RTLIB::O_F32 : 168 (VT == MVT::f64) ? RTLIB::O_F64 : RTLIB::O_F128; 169 break; 170 case ISD::SETONE: 171 // SETONE = SETOLT | SETOGT 172 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 173 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128; 174 LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 175 (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128; 176 break; 177 case ISD::SETUEQ: 178 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 179 (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128; 180 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 181 (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128; 182 break; 183 default: 184 // Invert CC for unordered comparisons 185 ShouldInvertCC = true; 186 switch (CCCode) { 187 case ISD::SETULT: 188 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 189 (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128; 190 break; 191 case ISD::SETULE: 192 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 193 (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128; 194 break; 195 case ISD::SETUGT: 196 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 197 (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128; 198 break; 199 case ISD::SETUGE: 200 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 201 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128; 202 break; 203 default: llvm_unreachable("Do not know how to soften this setcc!"); 204 } 205 } 206 207 // Use the target specific return value for comparions lib calls. 208 EVT RetVT = getCmpLibcallReturnType(); 209 SDValue Ops[2] = {NewLHS, NewRHS}; 210 NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/, 211 dl).first; 212 NewRHS = DAG.getConstant(0, dl, RetVT); 213 214 CCCode = getCmpLibcallCC(LC1); 215 if (ShouldInvertCC) 216 CCCode = getSetCCInverse(CCCode, /*isInteger=*/true); 217 218 if (LC2 != RTLIB::UNKNOWN_LIBCALL) { 219 SDValue Tmp = DAG.getNode( 220 ISD::SETCC, dl, 221 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT), 222 NewLHS, NewRHS, DAG.getCondCode(CCCode)); 223 NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/, 224 dl).first; 225 NewLHS = DAG.getNode( 226 ISD::SETCC, dl, 227 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT), 228 NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2))); 229 NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS); 230 NewRHS = SDValue(); 231 } 232 } 233 234 /// Return the entry encoding for a jump table in the current function. The 235 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum. 236 unsigned TargetLowering::getJumpTableEncoding() const { 237 // In non-pic modes, just use the address of a block. 238 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 239 return MachineJumpTableInfo::EK_BlockAddress; 240 241 // In PIC mode, if the target supports a GPRel32 directive, use it. 242 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr) 243 return MachineJumpTableInfo::EK_GPRel32BlockAddress; 244 245 // Otherwise, use a label difference. 246 return MachineJumpTableInfo::EK_LabelDifference32; 247 } 248 249 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table, 250 SelectionDAG &DAG) const { 251 // If our PIC model is GP relative, use the global offset table as the base. 252 unsigned JTEncoding = getJumpTableEncoding(); 253 254 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) || 255 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress)) 256 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout())); 257 258 return Table; 259 } 260 261 /// This returns the relocation base for the given PIC jumptable, the same as 262 /// getPICJumpTableRelocBase, but as an MCExpr. 263 const MCExpr * 264 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 265 unsigned JTI,MCContext &Ctx) const{ 266 // The normal PIC reloc base is the label at the start of the jump table. 267 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx); 268 } 269 270 bool 271 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 272 // Assume that everything is safe in static mode. 273 if (getTargetMachine().getRelocationModel() == Reloc::Static) 274 return true; 275 276 // In dynamic-no-pic mode, assume that known defined values are safe. 277 if (getTargetMachine().getRelocationModel() == Reloc::DynamicNoPIC && 278 GA && GA->getGlobal()->isStrongDefinitionForLinker()) 279 return true; 280 281 // Otherwise assume nothing is safe. 282 return false; 283 } 284 285 //===----------------------------------------------------------------------===// 286 // Optimization Methods 287 //===----------------------------------------------------------------------===// 288 289 /// Check to see if the specified operand of the specified instruction is a 290 /// constant integer. If so, check to see if there are any bits set in the 291 /// constant that are not demanded. If so, shrink the constant and return true. 292 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op, 293 const APInt &Demanded) { 294 SDLoc dl(Op); 295 296 // FIXME: ISD::SELECT, ISD::SELECT_CC 297 switch (Op.getOpcode()) { 298 default: break; 299 case ISD::XOR: 300 case ISD::AND: 301 case ISD::OR: { 302 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 303 if (!C) return false; 304 305 if (Op.getOpcode() == ISD::XOR && 306 (C->getAPIntValue() | (~Demanded)).isAllOnesValue()) 307 return false; 308 309 // if we can expand it to have all bits set, do it 310 if (C->getAPIntValue().intersects(~Demanded)) { 311 EVT VT = Op.getValueType(); 312 SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0), 313 DAG.getConstant(Demanded & 314 C->getAPIntValue(), 315 dl, VT)); 316 return CombineTo(Op, New); 317 } 318 319 break; 320 } 321 } 322 323 return false; 324 } 325 326 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. 327 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be 328 /// generalized for targets with other types of implicit widening casts. 329 bool 330 TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op, 331 unsigned BitWidth, 332 const APInt &Demanded, 333 SDLoc dl) { 334 assert(Op.getNumOperands() == 2 && 335 "ShrinkDemandedOp only supports binary operators!"); 336 assert(Op.getNode()->getNumValues() == 1 && 337 "ShrinkDemandedOp only supports nodes with one result!"); 338 339 // Early return, as this function cannot handle vector types. 340 if (Op.getValueType().isVector()) 341 return false; 342 343 // Don't do this if the node has another user, which may require the 344 // full value. 345 if (!Op.getNode()->hasOneUse()) 346 return false; 347 348 // Search for the smallest integer type with free casts to and from 349 // Op's type. For expedience, just check power-of-2 integer types. 350 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 351 unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros(); 352 unsigned SmallVTBits = DemandedSize; 353 if (!isPowerOf2_32(SmallVTBits)) 354 SmallVTBits = NextPowerOf2(SmallVTBits); 355 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) { 356 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits); 357 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) && 358 TLI.isZExtFree(SmallVT, Op.getValueType())) { 359 // We found a type with free casts. 360 SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT, 361 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, 362 Op.getNode()->getOperand(0)), 363 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, 364 Op.getNode()->getOperand(1))); 365 bool NeedZext = DemandedSize > SmallVTBits; 366 SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND, 367 dl, Op.getValueType(), X); 368 return CombineTo(Op, Z); 369 } 370 } 371 return false; 372 } 373 374 /// Look at Op. At this point, we know that only the DemandedMask bits of the 375 /// result of Op are ever used downstream. If we can use this information to 376 /// simplify Op, create a new simplified DAG node and return true, returning the 377 /// original and new nodes in Old and New. Otherwise, analyze the expression and 378 /// return a mask of KnownOne and KnownZero bits for the expression (used to 379 /// simplify the caller). The KnownZero/One bits may only be accurate for those 380 /// bits in the DemandedMask. 381 bool TargetLowering::SimplifyDemandedBits(SDValue Op, 382 const APInt &DemandedMask, 383 APInt &KnownZero, 384 APInt &KnownOne, 385 TargetLoweringOpt &TLO, 386 unsigned Depth) const { 387 unsigned BitWidth = DemandedMask.getBitWidth(); 388 assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth && 389 "Mask size mismatches value type size!"); 390 APInt NewMask = DemandedMask; 391 SDLoc dl(Op); 392 auto &DL = TLO.DAG.getDataLayout(); 393 394 // Don't know anything. 395 KnownZero = KnownOne = APInt(BitWidth, 0); 396 397 // Other users may use these bits. 398 if (!Op.getNode()->hasOneUse()) { 399 if (Depth != 0) { 400 // If not at the root, Just compute the KnownZero/KnownOne bits to 401 // simplify things downstream. 402 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth); 403 return false; 404 } 405 // If this is the root being simplified, allow it to have multiple uses, 406 // just set the NewMask to all bits. 407 NewMask = APInt::getAllOnesValue(BitWidth); 408 } else if (DemandedMask == 0) { 409 // Not demanding any bits from Op. 410 if (Op.getOpcode() != ISD::UNDEF) 411 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType())); 412 return false; 413 } else if (Depth == 6) { // Limit search depth. 414 return false; 415 } 416 417 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut; 418 switch (Op.getOpcode()) { 419 case ISD::Constant: 420 // We know all of the bits for a constant! 421 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue(); 422 KnownZero = ~KnownOne; 423 return false; // Don't fall through, will infinitely loop. 424 case ISD::AND: 425 // If the RHS is a constant, check to see if the LHS would be zero without 426 // using the bits from the RHS. Below, we use knowledge about the RHS to 427 // simplify the LHS, here we're using information from the LHS to simplify 428 // the RHS. 429 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 430 APInt LHSZero, LHSOne; 431 // Do not increment Depth here; that can cause an infinite loop. 432 TLO.DAG.computeKnownBits(Op.getOperand(0), LHSZero, LHSOne, Depth); 433 // If the LHS already has zeros where RHSC does, this and is dead. 434 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask)) 435 return TLO.CombineTo(Op, Op.getOperand(0)); 436 // If any of the set bits in the RHS are known zero on the LHS, shrink 437 // the constant. 438 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask)) 439 return true; 440 } 441 442 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero, 443 KnownOne, TLO, Depth+1)) 444 return true; 445 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 446 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask, 447 KnownZero2, KnownOne2, TLO, Depth+1)) 448 return true; 449 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 450 451 // If all of the demanded bits are known one on one side, return the other. 452 // These bits cannot contribute to the result of the 'and'. 453 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask)) 454 return TLO.CombineTo(Op, Op.getOperand(0)); 455 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask)) 456 return TLO.CombineTo(Op, Op.getOperand(1)); 457 // If all of the demanded bits in the inputs are known zeros, return zero. 458 if ((NewMask & (KnownZero|KnownZero2)) == NewMask) 459 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, Op.getValueType())); 460 // If the RHS is a constant, see if we can simplify it. 461 if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask)) 462 return true; 463 // If the operation can be done in a smaller type, do so. 464 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) 465 return true; 466 467 // Output known-1 bits are only known if set in both the LHS & RHS. 468 KnownOne &= KnownOne2; 469 // Output known-0 are known to be clear if zero in either the LHS | RHS. 470 KnownZero |= KnownZero2; 471 break; 472 case ISD::OR: 473 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero, 474 KnownOne, TLO, Depth+1)) 475 return true; 476 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 477 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask, 478 KnownZero2, KnownOne2, TLO, Depth+1)) 479 return true; 480 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 481 482 // If all of the demanded bits are known zero on one side, return the other. 483 // These bits cannot contribute to the result of the 'or'. 484 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask)) 485 return TLO.CombineTo(Op, Op.getOperand(0)); 486 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask)) 487 return TLO.CombineTo(Op, Op.getOperand(1)); 488 // If all of the potentially set bits on one side are known to be set on 489 // the other side, just use the 'other' side. 490 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask)) 491 return TLO.CombineTo(Op, Op.getOperand(0)); 492 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask)) 493 return TLO.CombineTo(Op, Op.getOperand(1)); 494 // If the RHS is a constant, see if we can simplify it. 495 if (TLO.ShrinkDemandedConstant(Op, NewMask)) 496 return true; 497 // If the operation can be done in a smaller type, do so. 498 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) 499 return true; 500 501 // Output known-0 bits are only known if clear in both the LHS & RHS. 502 KnownZero &= KnownZero2; 503 // Output known-1 are known to be set if set in either the LHS | RHS. 504 KnownOne |= KnownOne2; 505 break; 506 case ISD::XOR: 507 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero, 508 KnownOne, TLO, Depth+1)) 509 return true; 510 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 511 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2, 512 KnownOne2, TLO, Depth+1)) 513 return true; 514 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 515 516 // If all of the demanded bits are known zero on one side, return the other. 517 // These bits cannot contribute to the result of the 'xor'. 518 if ((KnownZero & NewMask) == NewMask) 519 return TLO.CombineTo(Op, Op.getOperand(0)); 520 if ((KnownZero2 & NewMask) == NewMask) 521 return TLO.CombineTo(Op, Op.getOperand(1)); 522 // If the operation can be done in a smaller type, do so. 523 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) 524 return true; 525 526 // If all of the unknown bits are known to be zero on one side or the other 527 // (but not both) turn this into an *inclusive* or. 528 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 529 if ((NewMask & ~KnownZero & ~KnownZero2) == 0) 530 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(), 531 Op.getOperand(0), 532 Op.getOperand(1))); 533 534 // Output known-0 bits are known if clear or set in both the LHS & RHS. 535 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2); 536 // Output known-1 are known to be set if set in only one of the LHS, RHS. 537 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2); 538 539 // If all of the demanded bits on one side are known, and all of the set 540 // bits on that side are also known to be set on the other side, turn this 541 // into an AND, as we know the bits will be cleared. 542 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 543 // NB: it is okay if more bits are known than are requested 544 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side 545 if (KnownOne == KnownOne2) { // set bits are the same on both sides 546 EVT VT = Op.getValueType(); 547 SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, dl, VT); 548 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, 549 Op.getOperand(0), ANDC)); 550 } 551 } 552 553 // If the RHS is a constant, see if we can simplify it. 554 // for XOR, we prefer to force bits to 1 if they will make a -1. 555 // if we can't force bits, try to shrink constant 556 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 557 APInt Expanded = C->getAPIntValue() | (~NewMask); 558 // if we can expand it to have all bits set, do it 559 if (Expanded.isAllOnesValue()) { 560 if (Expanded != C->getAPIntValue()) { 561 EVT VT = Op.getValueType(); 562 SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0), 563 TLO.DAG.getConstant(Expanded, dl, VT)); 564 return TLO.CombineTo(Op, New); 565 } 566 // if it already has all the bits set, nothing to change 567 // but don't shrink either! 568 } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) { 569 return true; 570 } 571 } 572 573 KnownZero = KnownZeroOut; 574 KnownOne = KnownOneOut; 575 break; 576 case ISD::SELECT: 577 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero, 578 KnownOne, TLO, Depth+1)) 579 return true; 580 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2, 581 KnownOne2, TLO, Depth+1)) 582 return true; 583 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 584 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 585 586 // If the operands are constants, see if we can simplify them. 587 if (TLO.ShrinkDemandedConstant(Op, NewMask)) 588 return true; 589 590 // Only known if known in both the LHS and RHS. 591 KnownOne &= KnownOne2; 592 KnownZero &= KnownZero2; 593 break; 594 case ISD::SELECT_CC: 595 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero, 596 KnownOne, TLO, Depth+1)) 597 return true; 598 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2, 599 KnownOne2, TLO, Depth+1)) 600 return true; 601 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 602 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 603 604 // If the operands are constants, see if we can simplify them. 605 if (TLO.ShrinkDemandedConstant(Op, NewMask)) 606 return true; 607 608 // Only known if known in both the LHS and RHS. 609 KnownOne &= KnownOne2; 610 KnownZero &= KnownZero2; 611 break; 612 case ISD::SHL: 613 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 614 unsigned ShAmt = SA->getZExtValue(); 615 SDValue InOp = Op.getOperand(0); 616 617 // If the shift count is an invalid immediate, don't do anything. 618 if (ShAmt >= BitWidth) 619 break; 620 621 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 622 // single shift. We can do this if the bottom bits (which are shifted 623 // out) are never demanded. 624 if (InOp.getOpcode() == ISD::SRL && 625 isa<ConstantSDNode>(InOp.getOperand(1))) { 626 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) { 627 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue(); 628 unsigned Opc = ISD::SHL; 629 int Diff = ShAmt-C1; 630 if (Diff < 0) { 631 Diff = -Diff; 632 Opc = ISD::SRL; 633 } 634 635 SDValue NewSA = 636 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType()); 637 EVT VT = Op.getValueType(); 638 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, 639 InOp.getOperand(0), NewSA)); 640 } 641 } 642 643 if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt), 644 KnownZero, KnownOne, TLO, Depth+1)) 645 return true; 646 647 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 648 // are not demanded. This will likely allow the anyext to be folded away. 649 if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) { 650 SDValue InnerOp = InOp.getNode()->getOperand(0); 651 EVT InnerVT = InnerOp.getValueType(); 652 unsigned InnerBits = InnerVT.getSizeInBits(); 653 if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 && 654 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 655 EVT ShTy = getShiftAmountTy(InnerVT, DL); 656 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits())) 657 ShTy = InnerVT; 658 SDValue NarrowShl = 659 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp, 660 TLO.DAG.getConstant(ShAmt, dl, ShTy)); 661 return 662 TLO.CombineTo(Op, 663 TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), 664 NarrowShl)); 665 } 666 // Repeat the SHL optimization above in cases where an extension 667 // intervenes: (shl (anyext (shr x, c1)), c2) to 668 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 669 // aren't demanded (as above) and that the shifted upper c1 bits of 670 // x aren't demanded. 671 if (InOp.hasOneUse() && 672 InnerOp.getOpcode() == ISD::SRL && 673 InnerOp.hasOneUse() && 674 isa<ConstantSDNode>(InnerOp.getOperand(1))) { 675 uint64_t InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1)) 676 ->getZExtValue(); 677 if (InnerShAmt < ShAmt && 678 InnerShAmt < InnerBits && 679 NewMask.lshr(InnerBits - InnerShAmt + ShAmt) == 0 && 680 NewMask.trunc(ShAmt) == 0) { 681 SDValue NewSA = 682 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, 683 Op.getOperand(1).getValueType()); 684 EVT VT = Op.getValueType(); 685 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 686 InnerOp.getOperand(0)); 687 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, 688 NewExt, NewSA)); 689 } 690 } 691 } 692 693 KnownZero <<= SA->getZExtValue(); 694 KnownOne <<= SA->getZExtValue(); 695 // low bits known zero. 696 KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue()); 697 } 698 break; 699 case ISD::SRL: 700 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 701 EVT VT = Op.getValueType(); 702 unsigned ShAmt = SA->getZExtValue(); 703 unsigned VTSize = VT.getSizeInBits(); 704 SDValue InOp = Op.getOperand(0); 705 706 // If the shift count is an invalid immediate, don't do anything. 707 if (ShAmt >= BitWidth) 708 break; 709 710 APInt InDemandedMask = (NewMask << ShAmt); 711 712 // If the shift is exact, then it does demand the low bits (and knows that 713 // they are zero). 714 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact()) 715 InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt); 716 717 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 718 // single shift. We can do this if the top bits (which are shifted out) 719 // are never demanded. 720 if (InOp.getOpcode() == ISD::SHL && 721 isa<ConstantSDNode>(InOp.getOperand(1))) { 722 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) { 723 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue(); 724 unsigned Opc = ISD::SRL; 725 int Diff = ShAmt-C1; 726 if (Diff < 0) { 727 Diff = -Diff; 728 Opc = ISD::SHL; 729 } 730 731 SDValue NewSA = 732 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType()); 733 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, 734 InOp.getOperand(0), NewSA)); 735 } 736 } 737 738 // Compute the new bits that are at the top now. 739 if (SimplifyDemandedBits(InOp, InDemandedMask, 740 KnownZero, KnownOne, TLO, Depth+1)) 741 return true; 742 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 743 KnownZero = KnownZero.lshr(ShAmt); 744 KnownOne = KnownOne.lshr(ShAmt); 745 746 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 747 KnownZero |= HighBits; // High bits known zero. 748 } 749 break; 750 case ISD::SRA: 751 // If this is an arithmetic shift right and only the low-bit is set, we can 752 // always convert this into a logical shr, even if the shift amount is 753 // variable. The low bit of the shift cannot be an input sign bit unless 754 // the shift amount is >= the size of the datatype, which is undefined. 755 if (NewMask == 1) 756 return TLO.CombineTo(Op, 757 TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(), 758 Op.getOperand(0), Op.getOperand(1))); 759 760 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 761 EVT VT = Op.getValueType(); 762 unsigned ShAmt = SA->getZExtValue(); 763 764 // If the shift count is an invalid immediate, don't do anything. 765 if (ShAmt >= BitWidth) 766 break; 767 768 APInt InDemandedMask = (NewMask << ShAmt); 769 770 // If the shift is exact, then it does demand the low bits (and knows that 771 // they are zero). 772 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact()) 773 InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt); 774 775 // If any of the demanded bits are produced by the sign extension, we also 776 // demand the input sign bit. 777 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 778 if (HighBits.intersects(NewMask)) 779 InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits()); 780 781 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask, 782 KnownZero, KnownOne, TLO, Depth+1)) 783 return true; 784 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 785 KnownZero = KnownZero.lshr(ShAmt); 786 KnownOne = KnownOne.lshr(ShAmt); 787 788 // Handle the sign bit, adjusted to where it is now in the mask. 789 APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt); 790 791 // If the input sign bit is known to be zero, or if none of the top bits 792 // are demanded, turn this into an unsigned shift right. 793 if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) { 794 SDNodeFlags Flags; 795 Flags.setExact(cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact()); 796 return TLO.CombineTo(Op, 797 TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0), 798 Op.getOperand(1), &Flags)); 799 } 800 801 int Log2 = NewMask.exactLogBase2(); 802 if (Log2 >= 0) { 803 // The bit must come from the sign. 804 SDValue NewSA = 805 TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, 806 Op.getOperand(1).getValueType()); 807 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, 808 Op.getOperand(0), NewSA)); 809 } 810 811 if (KnownOne.intersects(SignBit)) 812 // New bits are known one. 813 KnownOne |= HighBits; 814 } 815 break; 816 case ISD::SIGN_EXTEND_INREG: { 817 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 818 819 APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1); 820 // If we only care about the highest bit, don't bother shifting right. 821 if (MsbMask == NewMask) { 822 unsigned ShAmt = ExVT.getScalarType().getSizeInBits(); 823 SDValue InOp = Op.getOperand(0); 824 unsigned VTBits = Op->getValueType(0).getScalarType().getSizeInBits(); 825 bool AlreadySignExtended = 826 TLO.DAG.ComputeNumSignBits(InOp) >= VTBits-ShAmt+1; 827 // However if the input is already sign extended we expect the sign 828 // extension to be dropped altogether later and do not simplify. 829 if (!AlreadySignExtended) { 830 // Compute the correct shift amount type, which must be getShiftAmountTy 831 // for scalar types after legalization. 832 EVT ShiftAmtTy = Op.getValueType(); 833 if (TLO.LegalTypes() && !ShiftAmtTy.isVector()) 834 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL); 835 836 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, dl, 837 ShiftAmtTy); 838 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, 839 Op.getValueType(), InOp, 840 ShiftAmt)); 841 } 842 } 843 844 // Sign extension. Compute the demanded bits in the result that are not 845 // present in the input. 846 APInt NewBits = 847 APInt::getHighBitsSet(BitWidth, 848 BitWidth - ExVT.getScalarType().getSizeInBits()); 849 850 // If none of the extended bits are demanded, eliminate the sextinreg. 851 if ((NewBits & NewMask) == 0) 852 return TLO.CombineTo(Op, Op.getOperand(0)); 853 854 APInt InSignBit = 855 APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidth); 856 APInt InputDemandedBits = 857 APInt::getLowBitsSet(BitWidth, 858 ExVT.getScalarType().getSizeInBits()) & 859 NewMask; 860 861 // Since the sign extended bits are demanded, we know that the sign 862 // bit is demanded. 863 InputDemandedBits |= InSignBit; 864 865 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits, 866 KnownZero, KnownOne, TLO, Depth+1)) 867 return true; 868 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 869 870 // If the sign bit of the input is known set or clear, then we know the 871 // top bits of the result. 872 873 // If the input sign bit is known zero, convert this into a zero extension. 874 if (KnownZero.intersects(InSignBit)) 875 return TLO.CombineTo(Op, 876 TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,ExVT)); 877 878 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set 879 KnownOne |= NewBits; 880 KnownZero &= ~NewBits; 881 } else { // Input sign bit unknown 882 KnownZero &= ~NewBits; 883 KnownOne &= ~NewBits; 884 } 885 break; 886 } 887 case ISD::BUILD_PAIR: { 888 EVT HalfVT = Op.getOperand(0).getValueType(); 889 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 890 891 APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 892 APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 893 894 APInt KnownZeroLo, KnownOneLo; 895 APInt KnownZeroHi, KnownOneHi; 896 897 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownZeroLo, 898 KnownOneLo, TLO, Depth + 1)) 899 return true; 900 901 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownZeroHi, 902 KnownOneHi, TLO, Depth + 1)) 903 return true; 904 905 KnownZero = KnownZeroLo.zext(BitWidth) | 906 KnownZeroHi.zext(BitWidth).shl(HalfBitWidth); 907 908 KnownOne = KnownOneLo.zext(BitWidth) | 909 KnownOneHi.zext(BitWidth).shl(HalfBitWidth); 910 break; 911 } 912 case ISD::ZERO_EXTEND: { 913 unsigned OperandBitWidth = 914 Op.getOperand(0).getValueType().getScalarType().getSizeInBits(); 915 APInt InMask = NewMask.trunc(OperandBitWidth); 916 917 // If none of the top bits are demanded, convert this into an any_extend. 918 APInt NewBits = 919 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask; 920 if (!NewBits.intersects(NewMask)) 921 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, 922 Op.getValueType(), 923 Op.getOperand(0))); 924 925 if (SimplifyDemandedBits(Op.getOperand(0), InMask, 926 KnownZero, KnownOne, TLO, Depth+1)) 927 return true; 928 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 929 KnownZero = KnownZero.zext(BitWidth); 930 KnownOne = KnownOne.zext(BitWidth); 931 KnownZero |= NewBits; 932 break; 933 } 934 case ISD::SIGN_EXTEND: { 935 EVT InVT = Op.getOperand(0).getValueType(); 936 unsigned InBits = InVT.getScalarType().getSizeInBits(); 937 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits); 938 APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits); 939 APInt NewBits = ~InMask & NewMask; 940 941 // If none of the top bits are demanded, convert this into an any_extend. 942 if (NewBits == 0) 943 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl, 944 Op.getValueType(), 945 Op.getOperand(0))); 946 947 // Since some of the sign extended bits are demanded, we know that the sign 948 // bit is demanded. 949 APInt InDemandedBits = InMask & NewMask; 950 InDemandedBits |= InSignBit; 951 InDemandedBits = InDemandedBits.trunc(InBits); 952 953 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero, 954 KnownOne, TLO, Depth+1)) 955 return true; 956 KnownZero = KnownZero.zext(BitWidth); 957 KnownOne = KnownOne.zext(BitWidth); 958 959 // If the sign bit is known zero, convert this to a zero extend. 960 if (KnownZero.intersects(InSignBit)) 961 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, 962 Op.getValueType(), 963 Op.getOperand(0))); 964 965 // If the sign bit is known one, the top bits match. 966 if (KnownOne.intersects(InSignBit)) { 967 KnownOne |= NewBits; 968 assert((KnownZero & NewBits) == 0); 969 } else { // Otherwise, top bits aren't known. 970 assert((KnownOne & NewBits) == 0); 971 assert((KnownZero & NewBits) == 0); 972 } 973 break; 974 } 975 case ISD::ANY_EXTEND: { 976 unsigned OperandBitWidth = 977 Op.getOperand(0).getValueType().getScalarType().getSizeInBits(); 978 APInt InMask = NewMask.trunc(OperandBitWidth); 979 if (SimplifyDemandedBits(Op.getOperand(0), InMask, 980 KnownZero, KnownOne, TLO, Depth+1)) 981 return true; 982 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 983 KnownZero = KnownZero.zext(BitWidth); 984 KnownOne = KnownOne.zext(BitWidth); 985 break; 986 } 987 case ISD::TRUNCATE: { 988 // Simplify the input, using demanded bit information, and compute the known 989 // zero/one bits live out. 990 unsigned OperandBitWidth = 991 Op.getOperand(0).getValueType().getScalarType().getSizeInBits(); 992 APInt TruncMask = NewMask.zext(OperandBitWidth); 993 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask, 994 KnownZero, KnownOne, TLO, Depth+1)) 995 return true; 996 KnownZero = KnownZero.trunc(BitWidth); 997 KnownOne = KnownOne.trunc(BitWidth); 998 999 // If the input is only used by this truncate, see if we can shrink it based 1000 // on the known demanded bits. 1001 if (Op.getOperand(0).getNode()->hasOneUse()) { 1002 SDValue In = Op.getOperand(0); 1003 switch (In.getOpcode()) { 1004 default: break; 1005 case ISD::SRL: 1006 // Shrink SRL by a constant if none of the high bits shifted in are 1007 // demanded. 1008 if (TLO.LegalTypes() && 1009 !isTypeDesirableForOp(ISD::SRL, Op.getValueType())) 1010 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 1011 // undesirable. 1012 break; 1013 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1)); 1014 if (!ShAmt) 1015 break; 1016 SDValue Shift = In.getOperand(1); 1017 if (TLO.LegalTypes()) { 1018 uint64_t ShVal = ShAmt->getZExtValue(); 1019 Shift = TLO.DAG.getConstant(ShVal, dl, 1020 getShiftAmountTy(Op.getValueType(), DL)); 1021 } 1022 1023 APInt HighBits = APInt::getHighBitsSet(OperandBitWidth, 1024 OperandBitWidth - BitWidth); 1025 HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth); 1026 1027 if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) { 1028 // None of the shifted in bits are needed. Add a truncate of the 1029 // shift input, then shift it. 1030 SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl, 1031 Op.getValueType(), 1032 In.getOperand(0)); 1033 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, 1034 Op.getValueType(), 1035 NewTrunc, 1036 Shift)); 1037 } 1038 break; 1039 } 1040 } 1041 1042 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1043 break; 1044 } 1045 case ISD::AssertZext: { 1046 // AssertZext demands all of the high bits, plus any of the low bits 1047 // demanded by its users. 1048 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1049 APInt InMask = APInt::getLowBitsSet(BitWidth, 1050 VT.getSizeInBits()); 1051 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask, 1052 KnownZero, KnownOne, TLO, Depth+1)) 1053 return true; 1054 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1055 1056 KnownZero |= ~InMask & NewMask; 1057 break; 1058 } 1059 case ISD::BITCAST: 1060 // If this is an FP->Int bitcast and if the sign bit is the only 1061 // thing demanded, turn this into a FGETSIGN. 1062 if (!TLO.LegalOperations() && 1063 !Op.getValueType().isVector() && 1064 !Op.getOperand(0).getValueType().isVector() && 1065 NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) && 1066 Op.getOperand(0).getValueType().isFloatingPoint()) { 1067 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType()); 1068 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 1069 if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple() && 1070 Op.getOperand(0).getValueType() != MVT::f128) { 1071 // Cannot eliminate/lower SHL for f128 yet. 1072 EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32; 1073 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 1074 // place. We expect the SHL to be eliminated by other optimizations. 1075 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0)); 1076 unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits(); 1077 if (!OpVTLegal && OpVTSizeInBits > 32) 1078 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign); 1079 unsigned ShVal = Op.getValueType().getSizeInBits()-1; 1080 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, Op.getValueType()); 1081 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, 1082 Op.getValueType(), 1083 Sign, ShAmt)); 1084 } 1085 } 1086 break; 1087 case ISD::ADD: 1088 case ISD::MUL: 1089 case ISD::SUB: { 1090 // Add, Sub, and Mul don't demand any bits in positions beyond that 1091 // of the highest bit demanded of them. 1092 APInt LoMask = APInt::getLowBitsSet(BitWidth, 1093 BitWidth - NewMask.countLeadingZeros()); 1094 if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2, 1095 KnownOne2, TLO, Depth+1)) 1096 return true; 1097 if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2, 1098 KnownOne2, TLO, Depth+1)) 1099 return true; 1100 // See if the operation should be performed at a smaller bit width. 1101 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) 1102 return true; 1103 } 1104 // FALL THROUGH 1105 default: 1106 // Just use computeKnownBits to compute output bits. 1107 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth); 1108 break; 1109 } 1110 1111 // If we know the value of all of the demanded bits, return this as a 1112 // constant. 1113 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { 1114 // Avoid folding to a constant if any OpaqueConstant is involved. 1115 const SDNode *N = Op.getNode(); 1116 for (SDNodeIterator I = SDNodeIterator::begin(N), 1117 E = SDNodeIterator::end(N); I != E; ++I) { 1118 SDNode *Op = *I; 1119 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 1120 if (C->isOpaque()) 1121 return false; 1122 } 1123 return TLO.CombineTo(Op, 1124 TLO.DAG.getConstant(KnownOne, dl, Op.getValueType())); 1125 } 1126 1127 return false; 1128 } 1129 1130 /// Determine which of the bits specified in Mask are known to be either zero or 1131 /// one and return them in the KnownZero/KnownOne bitsets. 1132 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 1133 APInt &KnownZero, 1134 APInt &KnownOne, 1135 const SelectionDAG &DAG, 1136 unsigned Depth) const { 1137 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 1138 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1139 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 1140 Op.getOpcode() == ISD::INTRINSIC_VOID) && 1141 "Should use MaskedValueIsZero if you don't know whether Op" 1142 " is a target node!"); 1143 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0); 1144 } 1145 1146 /// This method can be implemented by targets that want to expose additional 1147 /// information about sign bits to the DAG Combiner. 1148 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 1149 const SelectionDAG &, 1150 unsigned Depth) const { 1151 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 1152 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1153 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 1154 Op.getOpcode() == ISD::INTRINSIC_VOID) && 1155 "Should use ComputeNumSignBits if you don't know whether Op" 1156 " is a target node!"); 1157 return 1; 1158 } 1159 1160 /// Test if the given value is known to have exactly one bit set. This differs 1161 /// from computeKnownBits in that it doesn't need to determine which bit is set. 1162 static bool ValueHasExactlyOneBitSet(SDValue Val, const SelectionDAG &DAG) { 1163 // A left-shift of a constant one will have exactly one bit set, because 1164 // shifting the bit off the end is undefined. 1165 if (Val.getOpcode() == ISD::SHL) 1166 if (ConstantSDNode *C = 1167 dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0))) 1168 if (C->getAPIntValue() == 1) 1169 return true; 1170 1171 // Similarly, a right-shift of a constant sign-bit will have exactly 1172 // one bit set. 1173 if (Val.getOpcode() == ISD::SRL) 1174 if (ConstantSDNode *C = 1175 dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0))) 1176 if (C->getAPIntValue().isSignBit()) 1177 return true; 1178 1179 // More could be done here, though the above checks are enough 1180 // to handle some common cases. 1181 1182 // Fall back to computeKnownBits to catch other known cases. 1183 EVT OpVT = Val.getValueType(); 1184 unsigned BitWidth = OpVT.getScalarType().getSizeInBits(); 1185 APInt KnownZero, KnownOne; 1186 DAG.computeKnownBits(Val, KnownZero, KnownOne); 1187 return (KnownZero.countPopulation() == BitWidth - 1) && 1188 (KnownOne.countPopulation() == 1); 1189 } 1190 1191 bool TargetLowering::isConstTrueVal(const SDNode *N) const { 1192 if (!N) 1193 return false; 1194 1195 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 1196 if (!CN) { 1197 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 1198 if (!BV) 1199 return false; 1200 1201 BitVector UndefElements; 1202 CN = BV->getConstantSplatNode(&UndefElements); 1203 // Only interested in constant splats, and we don't try to handle undef 1204 // elements in identifying boolean constants. 1205 if (!CN || UndefElements.none()) 1206 return false; 1207 } 1208 1209 switch (getBooleanContents(N->getValueType(0))) { 1210 case UndefinedBooleanContent: 1211 return CN->getAPIntValue()[0]; 1212 case ZeroOrOneBooleanContent: 1213 return CN->isOne(); 1214 case ZeroOrNegativeOneBooleanContent: 1215 return CN->isAllOnesValue(); 1216 } 1217 1218 llvm_unreachable("Invalid boolean contents"); 1219 } 1220 1221 bool TargetLowering::isConstFalseVal(const SDNode *N) const { 1222 if (!N) 1223 return false; 1224 1225 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 1226 if (!CN) { 1227 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 1228 if (!BV) 1229 return false; 1230 1231 BitVector UndefElements; 1232 CN = BV->getConstantSplatNode(&UndefElements); 1233 // Only interested in constant splats, and we don't try to handle undef 1234 // elements in identifying boolean constants. 1235 if (!CN || UndefElements.none()) 1236 return false; 1237 } 1238 1239 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 1240 return !CN->getAPIntValue()[0]; 1241 1242 return CN->isNullValue(); 1243 } 1244 1245 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 1246 bool SExt) const { 1247 if (VT == MVT::i1) 1248 return N->isOne(); 1249 1250 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 1251 switch (Cnt) { 1252 case TargetLowering::ZeroOrOneBooleanContent: 1253 // An extended value of 1 is always true, unless its original type is i1, 1254 // in which case it will be sign extended to -1. 1255 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 1256 case TargetLowering::UndefinedBooleanContent: 1257 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1258 return N->isAllOnesValue() && SExt; 1259 } 1260 llvm_unreachable("Unexpected enumeration."); 1261 } 1262 1263 /// Try to simplify a setcc built with the specified operands and cc. If it is 1264 /// unable to simplify it, return a null SDValue. 1265 SDValue 1266 TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 1267 ISD::CondCode Cond, bool foldBooleans, 1268 DAGCombinerInfo &DCI, SDLoc dl) const { 1269 SelectionDAG &DAG = DCI.DAG; 1270 1271 // These setcc operations always fold. 1272 switch (Cond) { 1273 default: break; 1274 case ISD::SETFALSE: 1275 case ISD::SETFALSE2: return DAG.getConstant(0, dl, VT); 1276 case ISD::SETTRUE: 1277 case ISD::SETTRUE2: { 1278 TargetLowering::BooleanContent Cnt = 1279 getBooleanContents(N0->getValueType(0)); 1280 return DAG.getConstant( 1281 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl, 1282 VT); 1283 } 1284 } 1285 1286 // Ensure that the constant occurs on the RHS, and fold constant 1287 // comparisons. 1288 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 1289 if (isa<ConstantSDNode>(N0.getNode()) && 1290 (DCI.isBeforeLegalizeOps() || 1291 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 1292 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 1293 1294 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 1295 const APInt &C1 = N1C->getAPIntValue(); 1296 1297 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 1298 // equality comparison, then we're just comparing whether X itself is 1299 // zero. 1300 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) && 1301 N0.getOperand(0).getOpcode() == ISD::CTLZ && 1302 N0.getOperand(1).getOpcode() == ISD::Constant) { 1303 const APInt &ShAmt 1304 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 1305 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1306 ShAmt == Log2_32(N0.getValueType().getSizeInBits())) { 1307 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 1308 // (srl (ctlz x), 5) == 0 -> X != 0 1309 // (srl (ctlz x), 5) != 1 -> X != 0 1310 Cond = ISD::SETNE; 1311 } else { 1312 // (srl (ctlz x), 5) != 0 -> X == 0 1313 // (srl (ctlz x), 5) == 1 -> X == 0 1314 Cond = ISD::SETEQ; 1315 } 1316 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 1317 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), 1318 Zero, Cond); 1319 } 1320 } 1321 1322 SDValue CTPOP = N0; 1323 // Look through truncs that don't change the value of a ctpop. 1324 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE) 1325 CTPOP = N0.getOperand(0); 1326 1327 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP && 1328 (N0 == CTPOP || N0.getValueType().getSizeInBits() > 1329 Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) { 1330 EVT CTVT = CTPOP.getValueType(); 1331 SDValue CTOp = CTPOP.getOperand(0); 1332 1333 // (ctpop x) u< 2 -> (x & x-1) == 0 1334 // (ctpop x) u> 1 -> (x & x-1) != 0 1335 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){ 1336 SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp, 1337 DAG.getConstant(1, dl, CTVT)); 1338 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub); 1339 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 1340 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC); 1341 } 1342 1343 // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal. 1344 } 1345 1346 // (zext x) == C --> x == (trunc C) 1347 // (sext x) == C --> x == (trunc C) 1348 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1349 DCI.isBeforeLegalize() && N0->hasOneUse()) { 1350 unsigned MinBits = N0.getValueSizeInBits(); 1351 SDValue PreExt; 1352 bool Signed = false; 1353 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 1354 // ZExt 1355 MinBits = N0->getOperand(0).getValueSizeInBits(); 1356 PreExt = N0->getOperand(0); 1357 } else if (N0->getOpcode() == ISD::AND) { 1358 // DAGCombine turns costly ZExts into ANDs 1359 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 1360 if ((C->getAPIntValue()+1).isPowerOf2()) { 1361 MinBits = C->getAPIntValue().countTrailingOnes(); 1362 PreExt = N0->getOperand(0); 1363 } 1364 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 1365 // SExt 1366 MinBits = N0->getOperand(0).getValueSizeInBits(); 1367 PreExt = N0->getOperand(0); 1368 Signed = true; 1369 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 1370 // ZEXTLOAD / SEXTLOAD 1371 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 1372 MinBits = LN0->getMemoryVT().getSizeInBits(); 1373 PreExt = N0; 1374 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 1375 Signed = true; 1376 MinBits = LN0->getMemoryVT().getSizeInBits(); 1377 PreExt = N0; 1378 } 1379 } 1380 1381 // Figure out how many bits we need to preserve this constant. 1382 unsigned ReqdBits = Signed ? 1383 C1.getBitWidth() - C1.getNumSignBits() + 1 : 1384 C1.getActiveBits(); 1385 1386 // Make sure we're not losing bits from the constant. 1387 if (MinBits > 0 && 1388 MinBits < C1.getBitWidth() && 1389 MinBits >= ReqdBits) { 1390 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 1391 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 1392 // Will get folded away. 1393 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 1394 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 1395 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 1396 } 1397 1398 // If truncating the setcc operands is not desirable, we can still 1399 // simplify the expression in some cases: 1400 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 1401 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 1402 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 1403 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 1404 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 1405 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 1406 SDValue TopSetCC = N0->getOperand(0); 1407 unsigned N0Opc = N0->getOpcode(); 1408 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 1409 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 1410 TopSetCC.getOpcode() == ISD::SETCC && 1411 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 1412 (isConstFalseVal(N1C) || 1413 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 1414 1415 bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) || 1416 (!N1C->isNullValue() && Cond == ISD::SETNE); 1417 1418 if (!Inverse) 1419 return TopSetCC; 1420 1421 ISD::CondCode InvCond = ISD::getSetCCInverse( 1422 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 1423 TopSetCC.getOperand(0).getValueType().isInteger()); 1424 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 1425 TopSetCC.getOperand(1), 1426 InvCond); 1427 1428 } 1429 } 1430 } 1431 1432 // If the LHS is '(and load, const)', the RHS is 0, 1433 // the test is for equality or unsigned, and all 1 bits of the const are 1434 // in the same partial word, see if we can shorten the load. 1435 if (DCI.isBeforeLegalize() && 1436 !ISD::isSignedIntSetCC(Cond) && 1437 N0.getOpcode() == ISD::AND && C1 == 0 && 1438 N0.getNode()->hasOneUse() && 1439 isa<LoadSDNode>(N0.getOperand(0)) && 1440 N0.getOperand(0).getNode()->hasOneUse() && 1441 isa<ConstantSDNode>(N0.getOperand(1))) { 1442 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 1443 APInt bestMask; 1444 unsigned bestWidth = 0, bestOffset = 0; 1445 if (!Lod->isVolatile() && Lod->isUnindexed()) { 1446 unsigned origWidth = N0.getValueType().getSizeInBits(); 1447 unsigned maskWidth = origWidth; 1448 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 1449 // 8 bits, but have to be careful... 1450 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 1451 origWidth = Lod->getMemoryVT().getSizeInBits(); 1452 const APInt &Mask = 1453 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 1454 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 1455 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 1456 for (unsigned offset=0; offset<origWidth/width; offset++) { 1457 if ((newMask & Mask) == Mask) { 1458 if (!DAG.getDataLayout().isLittleEndian()) 1459 bestOffset = (origWidth/width - offset - 1) * (width/8); 1460 else 1461 bestOffset = (uint64_t)offset * (width/8); 1462 bestMask = Mask.lshr(offset * (width/8) * 8); 1463 bestWidth = width; 1464 break; 1465 } 1466 newMask = newMask << width; 1467 } 1468 } 1469 } 1470 if (bestWidth) { 1471 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 1472 if (newVT.isRound()) { 1473 EVT PtrType = Lod->getOperand(1).getValueType(); 1474 SDValue Ptr = Lod->getBasePtr(); 1475 if (bestOffset != 0) 1476 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(), 1477 DAG.getConstant(bestOffset, dl, PtrType)); 1478 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset); 1479 SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr, 1480 Lod->getPointerInfo().getWithOffset(bestOffset), 1481 false, false, false, NewAlign); 1482 return DAG.getSetCC(dl, VT, 1483 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 1484 DAG.getConstant(bestMask.trunc(bestWidth), 1485 dl, newVT)), 1486 DAG.getConstant(0LL, dl, newVT), Cond); 1487 } 1488 } 1489 } 1490 1491 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 1492 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 1493 unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits(); 1494 1495 // If the comparison constant has bits in the upper part, the 1496 // zero-extended value could never match. 1497 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 1498 C1.getBitWidth() - InSize))) { 1499 switch (Cond) { 1500 case ISD::SETUGT: 1501 case ISD::SETUGE: 1502 case ISD::SETEQ: return DAG.getConstant(0, dl, VT); 1503 case ISD::SETULT: 1504 case ISD::SETULE: 1505 case ISD::SETNE: return DAG.getConstant(1, dl, VT); 1506 case ISD::SETGT: 1507 case ISD::SETGE: 1508 // True if the sign bit of C1 is set. 1509 return DAG.getConstant(C1.isNegative(), dl, VT); 1510 case ISD::SETLT: 1511 case ISD::SETLE: 1512 // True if the sign bit of C1 isn't set. 1513 return DAG.getConstant(C1.isNonNegative(), dl, VT); 1514 default: 1515 break; 1516 } 1517 } 1518 1519 // Otherwise, we can perform the comparison with the low bits. 1520 switch (Cond) { 1521 case ISD::SETEQ: 1522 case ISD::SETNE: 1523 case ISD::SETUGT: 1524 case ISD::SETUGE: 1525 case ISD::SETULT: 1526 case ISD::SETULE: { 1527 EVT newVT = N0.getOperand(0).getValueType(); 1528 if (DCI.isBeforeLegalizeOps() || 1529 (isOperationLegal(ISD::SETCC, newVT) && 1530 getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) { 1531 EVT NewSetCCVT = 1532 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT); 1533 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 1534 1535 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 1536 NewConst, Cond); 1537 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 1538 } 1539 break; 1540 } 1541 default: 1542 break; // todo, be more careful with signed comparisons 1543 } 1544 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 1545 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 1546 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 1547 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 1548 EVT ExtDstTy = N0.getValueType(); 1549 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 1550 1551 // If the constant doesn't fit into the number of bits for the source of 1552 // the sign extension, it is impossible for both sides to be equal. 1553 if (C1.getMinSignedBits() > ExtSrcTyBits) 1554 return DAG.getConstant(Cond == ISD::SETNE, dl, VT); 1555 1556 SDValue ZextOp; 1557 EVT Op0Ty = N0.getOperand(0).getValueType(); 1558 if (Op0Ty == ExtSrcTy) { 1559 ZextOp = N0.getOperand(0); 1560 } else { 1561 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 1562 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0), 1563 DAG.getConstant(Imm, dl, Op0Ty)); 1564 } 1565 if (!DCI.isCalledByLegalizer()) 1566 DCI.AddToWorklist(ZextOp.getNode()); 1567 // Otherwise, make this a use of a zext. 1568 return DAG.getSetCC(dl, VT, ZextOp, 1569 DAG.getConstant(C1 & APInt::getLowBitsSet( 1570 ExtDstTyBits, 1571 ExtSrcTyBits), 1572 dl, ExtDstTy), 1573 Cond); 1574 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) && 1575 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 1576 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 1577 if (N0.getOpcode() == ISD::SETCC && 1578 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) { 1579 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1); 1580 if (TrueWhenTrue) 1581 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 1582 // Invert the condition. 1583 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 1584 CC = ISD::getSetCCInverse(CC, 1585 N0.getOperand(0).getValueType().isInteger()); 1586 if (DCI.isBeforeLegalizeOps() || 1587 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 1588 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 1589 } 1590 1591 if ((N0.getOpcode() == ISD::XOR || 1592 (N0.getOpcode() == ISD::AND && 1593 N0.getOperand(0).getOpcode() == ISD::XOR && 1594 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 1595 isa<ConstantSDNode>(N0.getOperand(1)) && 1596 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) { 1597 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 1598 // can only do this if the top bits are known zero. 1599 unsigned BitWidth = N0.getValueSizeInBits(); 1600 if (DAG.MaskedValueIsZero(N0, 1601 APInt::getHighBitsSet(BitWidth, 1602 BitWidth-1))) { 1603 // Okay, get the un-inverted input value. 1604 SDValue Val; 1605 if (N0.getOpcode() == ISD::XOR) 1606 Val = N0.getOperand(0); 1607 else { 1608 assert(N0.getOpcode() == ISD::AND && 1609 N0.getOperand(0).getOpcode() == ISD::XOR); 1610 // ((X^1)&1)^1 -> X & 1 1611 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 1612 N0.getOperand(0).getOperand(0), 1613 N0.getOperand(1)); 1614 } 1615 1616 return DAG.getSetCC(dl, VT, Val, N1, 1617 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1618 } 1619 } else if (N1C->getAPIntValue() == 1 && 1620 (VT == MVT::i1 || 1621 getBooleanContents(N0->getValueType(0)) == 1622 ZeroOrOneBooleanContent)) { 1623 SDValue Op0 = N0; 1624 if (Op0.getOpcode() == ISD::TRUNCATE) 1625 Op0 = Op0.getOperand(0); 1626 1627 if ((Op0.getOpcode() == ISD::XOR) && 1628 Op0.getOperand(0).getOpcode() == ISD::SETCC && 1629 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 1630 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 1631 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 1632 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1), 1633 Cond); 1634 } 1635 if (Op0.getOpcode() == ISD::AND && 1636 isa<ConstantSDNode>(Op0.getOperand(1)) && 1637 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) { 1638 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 1639 if (Op0.getValueType().bitsGT(VT)) 1640 Op0 = DAG.getNode(ISD::AND, dl, VT, 1641 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 1642 DAG.getConstant(1, dl, VT)); 1643 else if (Op0.getValueType().bitsLT(VT)) 1644 Op0 = DAG.getNode(ISD::AND, dl, VT, 1645 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 1646 DAG.getConstant(1, dl, VT)); 1647 1648 return DAG.getSetCC(dl, VT, Op0, 1649 DAG.getConstant(0, dl, Op0.getValueType()), 1650 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1651 } 1652 if (Op0.getOpcode() == ISD::AssertZext && 1653 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 1654 return DAG.getSetCC(dl, VT, Op0, 1655 DAG.getConstant(0, dl, Op0.getValueType()), 1656 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1657 } 1658 } 1659 1660 APInt MinVal, MaxVal; 1661 unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits(); 1662 if (ISD::isSignedIntSetCC(Cond)) { 1663 MinVal = APInt::getSignedMinValue(OperandBitSize); 1664 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 1665 } else { 1666 MinVal = APInt::getMinValue(OperandBitSize); 1667 MaxVal = APInt::getMaxValue(OperandBitSize); 1668 } 1669 1670 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 1671 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 1672 if (C1 == MinVal) return DAG.getConstant(1, dl, VT); // X >= MIN --> true 1673 // X >= C0 --> X > (C0 - 1) 1674 APInt C = C1 - 1; 1675 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 1676 if ((DCI.isBeforeLegalizeOps() || 1677 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 1678 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 && 1679 isLegalICmpImmediate(C.getSExtValue())))) { 1680 return DAG.getSetCC(dl, VT, N0, 1681 DAG.getConstant(C, dl, N1.getValueType()), 1682 NewCC); 1683 } 1684 } 1685 1686 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 1687 if (C1 == MaxVal) return DAG.getConstant(1, dl, VT); // X <= MAX --> true 1688 // X <= C0 --> X < (C0 + 1) 1689 APInt C = C1 + 1; 1690 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 1691 if ((DCI.isBeforeLegalizeOps() || 1692 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 1693 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 && 1694 isLegalICmpImmediate(C.getSExtValue())))) { 1695 return DAG.getSetCC(dl, VT, N0, 1696 DAG.getConstant(C, dl, N1.getValueType()), 1697 NewCC); 1698 } 1699 } 1700 1701 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal) 1702 return DAG.getConstant(0, dl, VT); // X < MIN --> false 1703 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal) 1704 return DAG.getConstant(1, dl, VT); // X >= MIN --> true 1705 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal) 1706 return DAG.getConstant(0, dl, VT); // X > MAX --> false 1707 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal) 1708 return DAG.getConstant(1, dl, VT); // X <= MAX --> true 1709 1710 // Canonicalize setgt X, Min --> setne X, Min 1711 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal) 1712 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 1713 // Canonicalize setlt X, Max --> setne X, Max 1714 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal) 1715 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 1716 1717 // If we have setult X, 1, turn it into seteq X, 0 1718 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1) 1719 return DAG.getSetCC(dl, VT, N0, 1720 DAG.getConstant(MinVal, dl, N0.getValueType()), 1721 ISD::SETEQ); 1722 // If we have setugt X, Max-1, turn it into seteq X, Max 1723 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1) 1724 return DAG.getSetCC(dl, VT, N0, 1725 DAG.getConstant(MaxVal, dl, N0.getValueType()), 1726 ISD::SETEQ); 1727 1728 // If we have "setcc X, C0", check to see if we can shrink the immediate 1729 // by changing cc. 1730 1731 // SETUGT X, SINTMAX -> SETLT X, 0 1732 if (Cond == ISD::SETUGT && 1733 C1 == APInt::getSignedMaxValue(OperandBitSize)) 1734 return DAG.getSetCC(dl, VT, N0, 1735 DAG.getConstant(0, dl, N1.getValueType()), 1736 ISD::SETLT); 1737 1738 // SETULT X, SINTMIN -> SETGT X, -1 1739 if (Cond == ISD::SETULT && 1740 C1 == APInt::getSignedMinValue(OperandBitSize)) { 1741 SDValue ConstMinusOne = 1742 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl, 1743 N1.getValueType()); 1744 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT); 1745 } 1746 1747 // Fold bit comparisons when we can. 1748 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1749 (VT == N0.getValueType() || 1750 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) && 1751 N0.getOpcode() == ISD::AND) { 1752 auto &DL = DAG.getDataLayout(); 1753 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 1754 EVT ShiftTy = DCI.isBeforeLegalize() 1755 ? getPointerTy(DL) 1756 : getShiftAmountTy(N0.getValueType(), DL); 1757 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 1758 // Perform the xform if the AND RHS is a single bit. 1759 if (AndRHS->getAPIntValue().isPowerOf2()) { 1760 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1761 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0, 1762 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl, 1763 ShiftTy))); 1764 } 1765 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 1766 // (X & 8) == 8 --> (X & 8) >> 3 1767 // Perform the xform if C1 is a single bit. 1768 if (C1.isPowerOf2()) { 1769 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1770 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0, 1771 DAG.getConstant(C1.logBase2(), dl, 1772 ShiftTy))); 1773 } 1774 } 1775 } 1776 } 1777 1778 if (C1.getMinSignedBits() <= 64 && 1779 !isLegalICmpImmediate(C1.getSExtValue())) { 1780 // (X & -256) == 256 -> (X >> 8) == 1 1781 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1782 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 1783 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 1784 const APInt &AndRHSC = AndRHS->getAPIntValue(); 1785 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) { 1786 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 1787 auto &DL = DAG.getDataLayout(); 1788 EVT ShiftTy = DCI.isBeforeLegalize() 1789 ? getPointerTy(DL) 1790 : getShiftAmountTy(N0.getValueType(), DL); 1791 EVT CmpTy = N0.getValueType(); 1792 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0), 1793 DAG.getConstant(ShiftBits, dl, 1794 ShiftTy)); 1795 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy); 1796 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 1797 } 1798 } 1799 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 1800 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 1801 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 1802 // X < 0x100000000 -> (X >> 32) < 1 1803 // X >= 0x100000000 -> (X >> 32) >= 1 1804 // X <= 0x0ffffffff -> (X >> 32) < 1 1805 // X > 0x0ffffffff -> (X >> 32) >= 1 1806 unsigned ShiftBits; 1807 APInt NewC = C1; 1808 ISD::CondCode NewCond = Cond; 1809 if (AdjOne) { 1810 ShiftBits = C1.countTrailingOnes(); 1811 NewC = NewC + 1; 1812 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 1813 } else { 1814 ShiftBits = C1.countTrailingZeros(); 1815 } 1816 NewC = NewC.lshr(ShiftBits); 1817 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 1818 isLegalICmpImmediate(NewC.getSExtValue())) { 1819 auto &DL = DAG.getDataLayout(); 1820 EVT ShiftTy = DCI.isBeforeLegalize() 1821 ? getPointerTy(DL) 1822 : getShiftAmountTy(N0.getValueType(), DL); 1823 EVT CmpTy = N0.getValueType(); 1824 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0, 1825 DAG.getConstant(ShiftBits, dl, ShiftTy)); 1826 SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy); 1827 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 1828 } 1829 } 1830 } 1831 } 1832 1833 if (isa<ConstantFPSDNode>(N0.getNode())) { 1834 // Constant fold or commute setcc. 1835 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl); 1836 if (O.getNode()) return O; 1837 } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) { 1838 // If the RHS of an FP comparison is a constant, simplify it away in 1839 // some cases. 1840 if (CFP->getValueAPF().isNaN()) { 1841 // If an operand is known to be a nan, we can fold it. 1842 switch (ISD::getUnorderedFlavor(Cond)) { 1843 default: llvm_unreachable("Unknown flavor!"); 1844 case 0: // Known false. 1845 return DAG.getConstant(0, dl, VT); 1846 case 1: // Known true. 1847 return DAG.getConstant(1, dl, VT); 1848 case 2: // Undefined. 1849 return DAG.getUNDEF(VT); 1850 } 1851 } 1852 1853 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 1854 // constant if knowing that the operand is non-nan is enough. We prefer to 1855 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 1856 // materialize 0.0. 1857 if (Cond == ISD::SETO || Cond == ISD::SETUO) 1858 return DAG.getSetCC(dl, VT, N0, N0, Cond); 1859 1860 // If the condition is not legal, see if we can find an equivalent one 1861 // which is legal. 1862 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 1863 // If the comparison was an awkward floating-point == or != and one of 1864 // the comparison operands is infinity or negative infinity, convert the 1865 // condition to a less-awkward <= or >=. 1866 if (CFP->getValueAPF().isInfinity()) { 1867 if (CFP->getValueAPF().isNegative()) { 1868 if (Cond == ISD::SETOEQ && 1869 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType())) 1870 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE); 1871 if (Cond == ISD::SETUEQ && 1872 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType())) 1873 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE); 1874 if (Cond == ISD::SETUNE && 1875 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType())) 1876 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT); 1877 if (Cond == ISD::SETONE && 1878 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType())) 1879 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT); 1880 } else { 1881 if (Cond == ISD::SETOEQ && 1882 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType())) 1883 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE); 1884 if (Cond == ISD::SETUEQ && 1885 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType())) 1886 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE); 1887 if (Cond == ISD::SETUNE && 1888 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType())) 1889 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT); 1890 if (Cond == ISD::SETONE && 1891 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType())) 1892 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT); 1893 } 1894 } 1895 } 1896 } 1897 1898 if (N0 == N1) { 1899 // The sext(setcc()) => setcc() optimization relies on the appropriate 1900 // constant being emitted. 1901 uint64_t EqVal = 0; 1902 switch (getBooleanContents(N0.getValueType())) { 1903 case UndefinedBooleanContent: 1904 case ZeroOrOneBooleanContent: 1905 EqVal = ISD::isTrueWhenEqual(Cond); 1906 break; 1907 case ZeroOrNegativeOneBooleanContent: 1908 EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0; 1909 break; 1910 } 1911 1912 // We can always fold X == X for integer setcc's. 1913 if (N0.getValueType().isInteger()) { 1914 return DAG.getConstant(EqVal, dl, VT); 1915 } 1916 unsigned UOF = ISD::getUnorderedFlavor(Cond); 1917 if (UOF == 2) // FP operators that are undefined on NaNs. 1918 return DAG.getConstant(EqVal, dl, VT); 1919 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond))) 1920 return DAG.getConstant(EqVal, dl, VT); 1921 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 1922 // if it is not already. 1923 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 1924 if (NewCond != Cond && (DCI.isBeforeLegalizeOps() || 1925 getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal)) 1926 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 1927 } 1928 1929 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1930 N0.getValueType().isInteger()) { 1931 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 1932 N0.getOpcode() == ISD::XOR) { 1933 // Simplify (X+Y) == (X+Z) --> Y == Z 1934 if (N0.getOpcode() == N1.getOpcode()) { 1935 if (N0.getOperand(0) == N1.getOperand(0)) 1936 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 1937 if (N0.getOperand(1) == N1.getOperand(1)) 1938 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 1939 if (DAG.isCommutativeBinOp(N0.getOpcode())) { 1940 // If X op Y == Y op X, try other combinations. 1941 if (N0.getOperand(0) == N1.getOperand(1)) 1942 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 1943 Cond); 1944 if (N0.getOperand(1) == N1.getOperand(0)) 1945 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 1946 Cond); 1947 } 1948 } 1949 1950 // If RHS is a legal immediate value for a compare instruction, we need 1951 // to be careful about increasing register pressure needlessly. 1952 bool LegalRHSImm = false; 1953 1954 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 1955 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 1956 // Turn (X+C1) == C2 --> X == C2-C1 1957 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) { 1958 return DAG.getSetCC(dl, VT, N0.getOperand(0), 1959 DAG.getConstant(RHSC->getAPIntValue()- 1960 LHSR->getAPIntValue(), 1961 dl, N0.getValueType()), Cond); 1962 } 1963 1964 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0. 1965 if (N0.getOpcode() == ISD::XOR) 1966 // If we know that all of the inverted bits are zero, don't bother 1967 // performing the inversion. 1968 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue())) 1969 return 1970 DAG.getSetCC(dl, VT, N0.getOperand(0), 1971 DAG.getConstant(LHSR->getAPIntValue() ^ 1972 RHSC->getAPIntValue(), 1973 dl, N0.getValueType()), 1974 Cond); 1975 } 1976 1977 // Turn (C1-X) == C2 --> X == C1-C2 1978 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) { 1979 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) { 1980 return 1981 DAG.getSetCC(dl, VT, N0.getOperand(1), 1982 DAG.getConstant(SUBC->getAPIntValue() - 1983 RHSC->getAPIntValue(), 1984 dl, N0.getValueType()), 1985 Cond); 1986 } 1987 } 1988 1989 // Could RHSC fold directly into a compare? 1990 if (RHSC->getValueType(0).getSizeInBits() <= 64) 1991 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 1992 } 1993 1994 // Simplify (X+Z) == X --> Z == 0 1995 // Don't do this if X is an immediate that can fold into a cmp 1996 // instruction and X+Z has other uses. It could be an induction variable 1997 // chain, and the transform would increase register pressure. 1998 if (!LegalRHSImm || N0.getNode()->hasOneUse()) { 1999 if (N0.getOperand(0) == N1) 2000 return DAG.getSetCC(dl, VT, N0.getOperand(1), 2001 DAG.getConstant(0, dl, N0.getValueType()), Cond); 2002 if (N0.getOperand(1) == N1) { 2003 if (DAG.isCommutativeBinOp(N0.getOpcode())) 2004 return DAG.getSetCC(dl, VT, N0.getOperand(0), 2005 DAG.getConstant(0, dl, N0.getValueType()), 2006 Cond); 2007 if (N0.getNode()->hasOneUse()) { 2008 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!"); 2009 auto &DL = DAG.getDataLayout(); 2010 // (Z-X) == X --> Z == X<<1 2011 SDValue SH = DAG.getNode( 2012 ISD::SHL, dl, N1.getValueType(), N1, 2013 DAG.getConstant(1, dl, 2014 getShiftAmountTy(N1.getValueType(), DL))); 2015 if (!DCI.isCalledByLegalizer()) 2016 DCI.AddToWorklist(SH.getNode()); 2017 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond); 2018 } 2019 } 2020 } 2021 } 2022 2023 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 2024 N1.getOpcode() == ISD::XOR) { 2025 // Simplify X == (X+Z) --> Z == 0 2026 if (N1.getOperand(0) == N0) 2027 return DAG.getSetCC(dl, VT, N1.getOperand(1), 2028 DAG.getConstant(0, dl, N1.getValueType()), Cond); 2029 if (N1.getOperand(1) == N0) { 2030 if (DAG.isCommutativeBinOp(N1.getOpcode())) 2031 return DAG.getSetCC(dl, VT, N1.getOperand(0), 2032 DAG.getConstant(0, dl, N1.getValueType()), Cond); 2033 if (N1.getNode()->hasOneUse()) { 2034 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!"); 2035 auto &DL = DAG.getDataLayout(); 2036 // X == (Z-X) --> X<<1 == Z 2037 SDValue SH = DAG.getNode( 2038 ISD::SHL, dl, N1.getValueType(), N0, 2039 DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL))); 2040 if (!DCI.isCalledByLegalizer()) 2041 DCI.AddToWorklist(SH.getNode()); 2042 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond); 2043 } 2044 } 2045 } 2046 2047 // Simplify x&y == y to x&y != 0 if y has exactly one bit set. 2048 // Note that where y is variable and is known to have at most 2049 // one bit set (for example, if it is z&1) we cannot do this; 2050 // the expressions are not equivalent when y==0. 2051 if (N0.getOpcode() == ISD::AND) 2052 if (N0.getOperand(0) == N1 || N0.getOperand(1) == N1) { 2053 if (ValueHasExactlyOneBitSet(N1, DAG)) { 2054 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true); 2055 if (DCI.isBeforeLegalizeOps() || 2056 isCondCodeLegal(Cond, N0.getSimpleValueType())) { 2057 SDValue Zero = DAG.getConstant(0, dl, N1.getValueType()); 2058 return DAG.getSetCC(dl, VT, N0, Zero, Cond); 2059 } 2060 } 2061 } 2062 if (N1.getOpcode() == ISD::AND) 2063 if (N1.getOperand(0) == N0 || N1.getOperand(1) == N0) { 2064 if (ValueHasExactlyOneBitSet(N0, DAG)) { 2065 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true); 2066 if (DCI.isBeforeLegalizeOps() || 2067 isCondCodeLegal(Cond, N1.getSimpleValueType())) { 2068 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 2069 return DAG.getSetCC(dl, VT, N1, Zero, Cond); 2070 } 2071 } 2072 } 2073 } 2074 2075 // Fold away ALL boolean setcc's. 2076 SDValue Temp; 2077 if (N0.getValueType() == MVT::i1 && foldBooleans) { 2078 switch (Cond) { 2079 default: llvm_unreachable("Unknown integer setcc!"); 2080 case ISD::SETEQ: // X == Y -> ~(X^Y) 2081 Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1); 2082 N0 = DAG.getNOT(dl, Temp, MVT::i1); 2083 if (!DCI.isCalledByLegalizer()) 2084 DCI.AddToWorklist(Temp.getNode()); 2085 break; 2086 case ISD::SETNE: // X != Y --> (X^Y) 2087 N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1); 2088 break; 2089 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 2090 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 2091 Temp = DAG.getNOT(dl, N0, MVT::i1); 2092 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp); 2093 if (!DCI.isCalledByLegalizer()) 2094 DCI.AddToWorklist(Temp.getNode()); 2095 break; 2096 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 2097 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 2098 Temp = DAG.getNOT(dl, N1, MVT::i1); 2099 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp); 2100 if (!DCI.isCalledByLegalizer()) 2101 DCI.AddToWorklist(Temp.getNode()); 2102 break; 2103 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 2104 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 2105 Temp = DAG.getNOT(dl, N0, MVT::i1); 2106 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp); 2107 if (!DCI.isCalledByLegalizer()) 2108 DCI.AddToWorklist(Temp.getNode()); 2109 break; 2110 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 2111 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 2112 Temp = DAG.getNOT(dl, N1, MVT::i1); 2113 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp); 2114 break; 2115 } 2116 if (VT != MVT::i1) { 2117 if (!DCI.isCalledByLegalizer()) 2118 DCI.AddToWorklist(N0.getNode()); 2119 // FIXME: If running after legalize, we probably can't do this. 2120 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0); 2121 } 2122 return N0; 2123 } 2124 2125 // Could not fold it. 2126 return SDValue(); 2127 } 2128 2129 /// Returns true (and the GlobalValue and the offset) if the node is a 2130 /// GlobalAddress + offset. 2131 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA, 2132 int64_t &Offset) const { 2133 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 2134 GA = GASD->getGlobal(); 2135 Offset += GASD->getOffset(); 2136 return true; 2137 } 2138 2139 if (N->getOpcode() == ISD::ADD) { 2140 SDValue N1 = N->getOperand(0); 2141 SDValue N2 = N->getOperand(1); 2142 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 2143 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 2144 Offset += V->getSExtValue(); 2145 return true; 2146 } 2147 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 2148 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 2149 Offset += V->getSExtValue(); 2150 return true; 2151 } 2152 } 2153 } 2154 2155 return false; 2156 } 2157 2158 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 2159 DAGCombinerInfo &DCI) const { 2160 // Default implementation: no optimization. 2161 return SDValue(); 2162 } 2163 2164 //===----------------------------------------------------------------------===// 2165 // Inline Assembler Implementation Methods 2166 //===----------------------------------------------------------------------===// 2167 2168 TargetLowering::ConstraintType 2169 TargetLowering::getConstraintType(StringRef Constraint) const { 2170 unsigned S = Constraint.size(); 2171 2172 if (S == 1) { 2173 switch (Constraint[0]) { 2174 default: break; 2175 case 'r': return C_RegisterClass; 2176 case 'm': // memory 2177 case 'o': // offsetable 2178 case 'V': // not offsetable 2179 return C_Memory; 2180 case 'i': // Simple Integer or Relocatable Constant 2181 case 'n': // Simple Integer 2182 case 'E': // Floating Point Constant 2183 case 'F': // Floating Point Constant 2184 case 's': // Relocatable Constant 2185 case 'p': // Address. 2186 case 'X': // Allow ANY value. 2187 case 'I': // Target registers. 2188 case 'J': 2189 case 'K': 2190 case 'L': 2191 case 'M': 2192 case 'N': 2193 case 'O': 2194 case 'P': 2195 case '<': 2196 case '>': 2197 return C_Other; 2198 } 2199 } 2200 2201 if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') { 2202 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 2203 return C_Memory; 2204 return C_Register; 2205 } 2206 return C_Unknown; 2207 } 2208 2209 /// Try to replace an X constraint, which matches anything, with another that 2210 /// has more specific requirements based on the type of the corresponding 2211 /// operand. 2212 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{ 2213 if (ConstraintVT.isInteger()) 2214 return "r"; 2215 if (ConstraintVT.isFloatingPoint()) 2216 return "f"; // works for many targets 2217 return nullptr; 2218 } 2219 2220 /// Lower the specified operand into the Ops vector. 2221 /// If it is invalid, don't add anything to Ops. 2222 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 2223 std::string &Constraint, 2224 std::vector<SDValue> &Ops, 2225 SelectionDAG &DAG) const { 2226 2227 if (Constraint.length() > 1) return; 2228 2229 char ConstraintLetter = Constraint[0]; 2230 switch (ConstraintLetter) { 2231 default: break; 2232 case 'X': // Allows any operand; labels (basic block) use this. 2233 if (Op.getOpcode() == ISD::BasicBlock) { 2234 Ops.push_back(Op); 2235 return; 2236 } 2237 // fall through 2238 case 'i': // Simple Integer or Relocatable Constant 2239 case 'n': // Simple Integer 2240 case 's': { // Relocatable Constant 2241 // These operands are interested in values of the form (GV+C), where C may 2242 // be folded in as an offset of GV, or it may be explicitly added. Also, it 2243 // is possible and fine if either GV or C are missing. 2244 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 2245 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op); 2246 2247 // If we have "(add GV, C)", pull out GV/C 2248 if (Op.getOpcode() == ISD::ADD) { 2249 C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 2250 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0)); 2251 if (!C || !GA) { 2252 C = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 2253 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1)); 2254 } 2255 if (!C || !GA) 2256 C = nullptr, GA = nullptr; 2257 } 2258 2259 // If we find a valid operand, map to the TargetXXX version so that the 2260 // value itself doesn't get selected. 2261 if (GA) { // Either &GV or &GV+C 2262 if (ConstraintLetter != 'n') { 2263 int64_t Offs = GA->getOffset(); 2264 if (C) Offs += C->getZExtValue(); 2265 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), 2266 C ? SDLoc(C) : SDLoc(), 2267 Op.getValueType(), Offs)); 2268 } 2269 return; 2270 } 2271 if (C) { // just C, no GV. 2272 // Simple constants are not allowed for 's'. 2273 if (ConstraintLetter != 's') { 2274 // gcc prints these as sign extended. Sign extend value to 64 bits 2275 // now; without this it would get ZExt'd later in 2276 // ScheduleDAGSDNodes::EmitNode, which is very generic. 2277 Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(), 2278 SDLoc(C), MVT::i64)); 2279 } 2280 return; 2281 } 2282 break; 2283 } 2284 } 2285 } 2286 2287 std::pair<unsigned, const TargetRegisterClass *> 2288 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 2289 StringRef Constraint, 2290 MVT VT) const { 2291 if (Constraint.empty() || Constraint[0] != '{') 2292 return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr)); 2293 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?"); 2294 2295 // Remove the braces from around the name. 2296 StringRef RegName(Constraint.data()+1, Constraint.size()-2); 2297 2298 std::pair<unsigned, const TargetRegisterClass*> R = 2299 std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr)); 2300 2301 // Figure out which register class contains this reg. 2302 for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(), 2303 E = RI->regclass_end(); RCI != E; ++RCI) { 2304 const TargetRegisterClass *RC = *RCI; 2305 2306 // If none of the value types for this register class are valid, we 2307 // can't use it. For example, 64-bit reg classes on 32-bit targets. 2308 if (!isLegalRC(RC)) 2309 continue; 2310 2311 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); 2312 I != E; ++I) { 2313 if (RegName.equals_lower(RI->getName(*I))) { 2314 std::pair<unsigned, const TargetRegisterClass*> S = 2315 std::make_pair(*I, RC); 2316 2317 // If this register class has the requested value type, return it, 2318 // otherwise keep searching and return the first class found 2319 // if no other is found which explicitly has the requested type. 2320 if (RC->hasType(VT)) 2321 return S; 2322 else if (!R.second) 2323 R = S; 2324 } 2325 } 2326 } 2327 2328 return R; 2329 } 2330 2331 //===----------------------------------------------------------------------===// 2332 // Constraint Selection. 2333 2334 /// Return true of this is an input operand that is a matching constraint like 2335 /// "4". 2336 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 2337 assert(!ConstraintCode.empty() && "No known constraint!"); 2338 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 2339 } 2340 2341 /// If this is an input matching constraint, this method returns the output 2342 /// operand it matches. 2343 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 2344 assert(!ConstraintCode.empty() && "No known constraint!"); 2345 return atoi(ConstraintCode.c_str()); 2346 } 2347 2348 /// Split up the constraint string from the inline assembly value into the 2349 /// specific constraints and their prefixes, and also tie in the associated 2350 /// operand values. 2351 /// If this returns an empty vector, and if the constraint string itself 2352 /// isn't empty, there was an error parsing. 2353 TargetLowering::AsmOperandInfoVector 2354 TargetLowering::ParseConstraints(const DataLayout &DL, 2355 const TargetRegisterInfo *TRI, 2356 ImmutableCallSite CS) const { 2357 /// Information about all of the constraints. 2358 AsmOperandInfoVector ConstraintOperands; 2359 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 2360 unsigned maCount = 0; // Largest number of multiple alternative constraints. 2361 2362 // Do a prepass over the constraints, canonicalizing them, and building up the 2363 // ConstraintOperands list. 2364 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 2365 unsigned ResNo = 0; // ResNo - The result number of the next output. 2366 2367 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 2368 ConstraintOperands.emplace_back(std::move(CI)); 2369 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 2370 2371 // Update multiple alternative constraint count. 2372 if (OpInfo.multipleAlternatives.size() > maCount) 2373 maCount = OpInfo.multipleAlternatives.size(); 2374 2375 OpInfo.ConstraintVT = MVT::Other; 2376 2377 // Compute the value type for each operand. 2378 switch (OpInfo.Type) { 2379 case InlineAsm::isOutput: 2380 // Indirect outputs just consume an argument. 2381 if (OpInfo.isIndirect) { 2382 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 2383 break; 2384 } 2385 2386 // The return value of the call is this value. As such, there is no 2387 // corresponding argument. 2388 assert(!CS.getType()->isVoidTy() && 2389 "Bad inline asm!"); 2390 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 2391 OpInfo.ConstraintVT = 2392 getSimpleValueType(DL, STy->getElementType(ResNo)); 2393 } else { 2394 assert(ResNo == 0 && "Asm only has one result!"); 2395 OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType()); 2396 } 2397 ++ResNo; 2398 break; 2399 case InlineAsm::isInput: 2400 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 2401 break; 2402 case InlineAsm::isClobber: 2403 // Nothing to do. 2404 break; 2405 } 2406 2407 if (OpInfo.CallOperandVal) { 2408 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 2409 if (OpInfo.isIndirect) { 2410 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 2411 if (!PtrTy) 2412 report_fatal_error("Indirect operand for inline asm not a pointer!"); 2413 OpTy = PtrTy->getElementType(); 2414 } 2415 2416 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 2417 if (StructType *STy = dyn_cast<StructType>(OpTy)) 2418 if (STy->getNumElements() == 1) 2419 OpTy = STy->getElementType(0); 2420 2421 // If OpTy is not a single value, it may be a struct/union that we 2422 // can tile with integers. 2423 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 2424 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 2425 switch (BitSize) { 2426 default: break; 2427 case 1: 2428 case 8: 2429 case 16: 2430 case 32: 2431 case 64: 2432 case 128: 2433 OpInfo.ConstraintVT = 2434 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true); 2435 break; 2436 } 2437 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) { 2438 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace()); 2439 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize); 2440 } else { 2441 OpInfo.ConstraintVT = MVT::getVT(OpTy, true); 2442 } 2443 } 2444 } 2445 2446 // If we have multiple alternative constraints, select the best alternative. 2447 if (!ConstraintOperands.empty()) { 2448 if (maCount) { 2449 unsigned bestMAIndex = 0; 2450 int bestWeight = -1; 2451 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 2452 int weight = -1; 2453 unsigned maIndex; 2454 // Compute the sums of the weights for each alternative, keeping track 2455 // of the best (highest weight) one so far. 2456 for (maIndex = 0; maIndex < maCount; ++maIndex) { 2457 int weightSum = 0; 2458 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2459 cIndex != eIndex; ++cIndex) { 2460 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex]; 2461 if (OpInfo.Type == InlineAsm::isClobber) 2462 continue; 2463 2464 // If this is an output operand with a matching input operand, 2465 // look up the matching input. If their types mismatch, e.g. one 2466 // is an integer, the other is floating point, or their sizes are 2467 // different, flag it as an maCantMatch. 2468 if (OpInfo.hasMatchingInput()) { 2469 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 2470 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 2471 if ((OpInfo.ConstraintVT.isInteger() != 2472 Input.ConstraintVT.isInteger()) || 2473 (OpInfo.ConstraintVT.getSizeInBits() != 2474 Input.ConstraintVT.getSizeInBits())) { 2475 weightSum = -1; // Can't match. 2476 break; 2477 } 2478 } 2479 } 2480 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 2481 if (weight == -1) { 2482 weightSum = -1; 2483 break; 2484 } 2485 weightSum += weight; 2486 } 2487 // Update best. 2488 if (weightSum > bestWeight) { 2489 bestWeight = weightSum; 2490 bestMAIndex = maIndex; 2491 } 2492 } 2493 2494 // Now select chosen alternative in each constraint. 2495 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2496 cIndex != eIndex; ++cIndex) { 2497 AsmOperandInfo& cInfo = ConstraintOperands[cIndex]; 2498 if (cInfo.Type == InlineAsm::isClobber) 2499 continue; 2500 cInfo.selectAlternative(bestMAIndex); 2501 } 2502 } 2503 } 2504 2505 // Check and hook up tied operands, choose constraint code to use. 2506 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2507 cIndex != eIndex; ++cIndex) { 2508 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex]; 2509 2510 // If this is an output operand with a matching input operand, look up the 2511 // matching input. If their types mismatch, e.g. one is an integer, the 2512 // other is floating point, or their sizes are different, flag it as an 2513 // error. 2514 if (OpInfo.hasMatchingInput()) { 2515 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 2516 2517 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 2518 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 2519 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 2520 OpInfo.ConstraintVT); 2521 std::pair<unsigned, const TargetRegisterClass *> InputRC = 2522 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 2523 Input.ConstraintVT); 2524 if ((OpInfo.ConstraintVT.isInteger() != 2525 Input.ConstraintVT.isInteger()) || 2526 (MatchRC.second != InputRC.second)) { 2527 report_fatal_error("Unsupported asm: input constraint" 2528 " with a matching output constraint of" 2529 " incompatible type!"); 2530 } 2531 } 2532 } 2533 } 2534 2535 return ConstraintOperands; 2536 } 2537 2538 /// Return an integer indicating how general CT is. 2539 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 2540 switch (CT) { 2541 case TargetLowering::C_Other: 2542 case TargetLowering::C_Unknown: 2543 return 0; 2544 case TargetLowering::C_Register: 2545 return 1; 2546 case TargetLowering::C_RegisterClass: 2547 return 2; 2548 case TargetLowering::C_Memory: 2549 return 3; 2550 } 2551 llvm_unreachable("Invalid constraint type"); 2552 } 2553 2554 /// Examine constraint type and operand type and determine a weight value. 2555 /// This object must already have been set up with the operand type 2556 /// and the current alternative constraint selected. 2557 TargetLowering::ConstraintWeight 2558 TargetLowering::getMultipleConstraintMatchWeight( 2559 AsmOperandInfo &info, int maIndex) const { 2560 InlineAsm::ConstraintCodeVector *rCodes; 2561 if (maIndex >= (int)info.multipleAlternatives.size()) 2562 rCodes = &info.Codes; 2563 else 2564 rCodes = &info.multipleAlternatives[maIndex].Codes; 2565 ConstraintWeight BestWeight = CW_Invalid; 2566 2567 // Loop over the options, keeping track of the most general one. 2568 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) { 2569 ConstraintWeight weight = 2570 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str()); 2571 if (weight > BestWeight) 2572 BestWeight = weight; 2573 } 2574 2575 return BestWeight; 2576 } 2577 2578 /// Examine constraint type and operand type and determine a weight value. 2579 /// This object must already have been set up with the operand type 2580 /// and the current alternative constraint selected. 2581 TargetLowering::ConstraintWeight 2582 TargetLowering::getSingleConstraintMatchWeight( 2583 AsmOperandInfo &info, const char *constraint) const { 2584 ConstraintWeight weight = CW_Invalid; 2585 Value *CallOperandVal = info.CallOperandVal; 2586 // If we don't have a value, we can't do a match, 2587 // but allow it at the lowest weight. 2588 if (!CallOperandVal) 2589 return CW_Default; 2590 // Look at the constraint type. 2591 switch (*constraint) { 2592 case 'i': // immediate integer. 2593 case 'n': // immediate integer with a known value. 2594 if (isa<ConstantInt>(CallOperandVal)) 2595 weight = CW_Constant; 2596 break; 2597 case 's': // non-explicit intregal immediate. 2598 if (isa<GlobalValue>(CallOperandVal)) 2599 weight = CW_Constant; 2600 break; 2601 case 'E': // immediate float if host format. 2602 case 'F': // immediate float. 2603 if (isa<ConstantFP>(CallOperandVal)) 2604 weight = CW_Constant; 2605 break; 2606 case '<': // memory operand with autodecrement. 2607 case '>': // memory operand with autoincrement. 2608 case 'm': // memory operand. 2609 case 'o': // offsettable memory operand 2610 case 'V': // non-offsettable memory operand 2611 weight = CW_Memory; 2612 break; 2613 case 'r': // general register. 2614 case 'g': // general register, memory operand or immediate integer. 2615 // note: Clang converts "g" to "imr". 2616 if (CallOperandVal->getType()->isIntegerTy()) 2617 weight = CW_Register; 2618 break; 2619 case 'X': // any operand. 2620 default: 2621 weight = CW_Default; 2622 break; 2623 } 2624 return weight; 2625 } 2626 2627 /// If there are multiple different constraints that we could pick for this 2628 /// operand (e.g. "imr") try to pick the 'best' one. 2629 /// This is somewhat tricky: constraints fall into four classes: 2630 /// Other -> immediates and magic values 2631 /// Register -> one specific register 2632 /// RegisterClass -> a group of regs 2633 /// Memory -> memory 2634 /// Ideally, we would pick the most specific constraint possible: if we have 2635 /// something that fits into a register, we would pick it. The problem here 2636 /// is that if we have something that could either be in a register or in 2637 /// memory that use of the register could cause selection of *other* 2638 /// operands to fail: they might only succeed if we pick memory. Because of 2639 /// this the heuristic we use is: 2640 /// 2641 /// 1) If there is an 'other' constraint, and if the operand is valid for 2642 /// that constraint, use it. This makes us take advantage of 'i' 2643 /// constraints when available. 2644 /// 2) Otherwise, pick the most general constraint present. This prefers 2645 /// 'm' over 'r', for example. 2646 /// 2647 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 2648 const TargetLowering &TLI, 2649 SDValue Op, SelectionDAG *DAG) { 2650 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 2651 unsigned BestIdx = 0; 2652 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 2653 int BestGenerality = -1; 2654 2655 // Loop over the options, keeping track of the most general one. 2656 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 2657 TargetLowering::ConstraintType CType = 2658 TLI.getConstraintType(OpInfo.Codes[i]); 2659 2660 // If this is an 'other' constraint, see if the operand is valid for it. 2661 // For example, on X86 we might have an 'rI' constraint. If the operand 2662 // is an integer in the range [0..31] we want to use I (saving a load 2663 // of a register), otherwise we must use 'r'. 2664 if (CType == TargetLowering::C_Other && Op.getNode()) { 2665 assert(OpInfo.Codes[i].size() == 1 && 2666 "Unhandled multi-letter 'other' constraint"); 2667 std::vector<SDValue> ResultOps; 2668 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 2669 ResultOps, *DAG); 2670 if (!ResultOps.empty()) { 2671 BestType = CType; 2672 BestIdx = i; 2673 break; 2674 } 2675 } 2676 2677 // Things with matching constraints can only be registers, per gcc 2678 // documentation. This mainly affects "g" constraints. 2679 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 2680 continue; 2681 2682 // This constraint letter is more general than the previous one, use it. 2683 int Generality = getConstraintGenerality(CType); 2684 if (Generality > BestGenerality) { 2685 BestType = CType; 2686 BestIdx = i; 2687 BestGenerality = Generality; 2688 } 2689 } 2690 2691 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 2692 OpInfo.ConstraintType = BestType; 2693 } 2694 2695 /// Determines the constraint code and constraint type to use for the specific 2696 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 2697 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 2698 SDValue Op, 2699 SelectionDAG *DAG) const { 2700 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 2701 2702 // Single-letter constraints ('r') are very common. 2703 if (OpInfo.Codes.size() == 1) { 2704 OpInfo.ConstraintCode = OpInfo.Codes[0]; 2705 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 2706 } else { 2707 ChooseConstraint(OpInfo, *this, Op, DAG); 2708 } 2709 2710 // 'X' matches anything. 2711 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 2712 // Labels and constants are handled elsewhere ('X' is the only thing 2713 // that matches labels). For Functions, the type here is the type of 2714 // the result, which is not what we want to look at; leave them alone. 2715 Value *v = OpInfo.CallOperandVal; 2716 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) { 2717 OpInfo.CallOperandVal = v; 2718 return; 2719 } 2720 2721 // Otherwise, try to resolve it to something we know about by looking at 2722 // the actual operand type. 2723 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 2724 OpInfo.ConstraintCode = Repl; 2725 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 2726 } 2727 } 2728 } 2729 2730 /// \brief Given an exact SDIV by a constant, create a multiplication 2731 /// with the multiplicative inverse of the constant. 2732 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d, 2733 SDLoc dl, SelectionDAG &DAG, 2734 std::vector<SDNode *> &Created) { 2735 assert(d != 0 && "Division by zero!"); 2736 2737 // Shift the value upfront if it is even, so the LSB is one. 2738 unsigned ShAmt = d.countTrailingZeros(); 2739 if (ShAmt) { 2740 // TODO: For UDIV use SRL instead of SRA. 2741 SDValue Amt = 2742 DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(), 2743 DAG.getDataLayout())); 2744 SDNodeFlags Flags; 2745 Flags.setExact(true); 2746 Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, &Flags); 2747 Created.push_back(Op1.getNode()); 2748 d = d.ashr(ShAmt); 2749 } 2750 2751 // Calculate the multiplicative inverse, using Newton's method. 2752 APInt t, xn = d; 2753 while ((t = d*xn) != 1) 2754 xn *= APInt(d.getBitWidth(), 2) - t; 2755 2756 SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType()); 2757 SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2); 2758 Created.push_back(Mul.getNode()); 2759 return Mul; 2760 } 2761 2762 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 2763 SelectionDAG &DAG, 2764 std::vector<SDNode *> *Created) const { 2765 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2766 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2767 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 2768 return SDValue(N,0); // Lower SDIV as SDIV 2769 return SDValue(); 2770 } 2771 2772 /// \brief Given an ISD::SDIV node expressing a divide by constant, 2773 /// return a DAG expression to select that will generate the same value by 2774 /// multiplying by a magic number. 2775 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 2776 SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor, 2777 SelectionDAG &DAG, bool IsAfterLegalization, 2778 std::vector<SDNode *> *Created) const { 2779 assert(Created && "No vector to hold sdiv ops."); 2780 2781 EVT VT = N->getValueType(0); 2782 SDLoc dl(N); 2783 2784 // Check to see if we can do this. 2785 // FIXME: We should be more aggressive here. 2786 if (!isTypeLegal(VT)) 2787 return SDValue(); 2788 2789 // If the sdiv has an 'exact' bit we can use a simpler lowering. 2790 if (cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact()) 2791 return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created); 2792 2793 APInt::ms magics = Divisor.magic(); 2794 2795 // Multiply the numerator (operand 0) by the magic value 2796 // FIXME: We should support doing a MUL in a wider type 2797 SDValue Q; 2798 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) : 2799 isOperationLegalOrCustom(ISD::MULHS, VT)) 2800 Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0), 2801 DAG.getConstant(magics.m, dl, VT)); 2802 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) : 2803 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT)) 2804 Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), 2805 N->getOperand(0), 2806 DAG.getConstant(magics.m, dl, VT)).getNode(), 1); 2807 else 2808 return SDValue(); // No mulhs or equvialent 2809 // If d > 0 and m < 0, add the numerator 2810 if (Divisor.isStrictlyPositive() && magics.m.isNegative()) { 2811 Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0)); 2812 Created->push_back(Q.getNode()); 2813 } 2814 // If d < 0 and m > 0, subtract the numerator. 2815 if (Divisor.isNegative() && magics.m.isStrictlyPositive()) { 2816 Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0)); 2817 Created->push_back(Q.getNode()); 2818 } 2819 auto &DL = DAG.getDataLayout(); 2820 // Shift right algebraic if shift value is nonzero 2821 if (magics.s > 0) { 2822 Q = DAG.getNode( 2823 ISD::SRA, dl, VT, Q, 2824 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL))); 2825 Created->push_back(Q.getNode()); 2826 } 2827 // Extract the sign bit and add it to the quotient 2828 SDValue T = 2829 DAG.getNode(ISD::SRL, dl, VT, Q, 2830 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, 2831 getShiftAmountTy(Q.getValueType(), DL))); 2832 Created->push_back(T.getNode()); 2833 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 2834 } 2835 2836 /// \brief Given an ISD::UDIV node expressing a divide by constant, 2837 /// return a DAG expression to select that will generate the same value by 2838 /// multiplying by a magic number. 2839 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 2840 SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor, 2841 SelectionDAG &DAG, bool IsAfterLegalization, 2842 std::vector<SDNode *> *Created) const { 2843 assert(Created && "No vector to hold udiv ops."); 2844 2845 EVT VT = N->getValueType(0); 2846 SDLoc dl(N); 2847 auto &DL = DAG.getDataLayout(); 2848 2849 // Check to see if we can do this. 2850 // FIXME: We should be more aggressive here. 2851 if (!isTypeLegal(VT)) 2852 return SDValue(); 2853 2854 // FIXME: We should use a narrower constant when the upper 2855 // bits are known to be zero. 2856 APInt::mu magics = Divisor.magicu(); 2857 2858 SDValue Q = N->getOperand(0); 2859 2860 // If the divisor is even, we can avoid using the expensive fixup by shifting 2861 // the divided value upfront. 2862 if (magics.a != 0 && !Divisor[0]) { 2863 unsigned Shift = Divisor.countTrailingZeros(); 2864 Q = DAG.getNode( 2865 ISD::SRL, dl, VT, Q, 2866 DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL))); 2867 Created->push_back(Q.getNode()); 2868 2869 // Get magic number for the shifted divisor. 2870 magics = Divisor.lshr(Shift).magicu(Shift); 2871 assert(magics.a == 0 && "Should use cheap fixup now"); 2872 } 2873 2874 // Multiply the numerator (operand 0) by the magic value 2875 // FIXME: We should support doing a MUL in a wider type 2876 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) : 2877 isOperationLegalOrCustom(ISD::MULHU, VT)) 2878 Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT)); 2879 else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) : 2880 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT)) 2881 Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q, 2882 DAG.getConstant(magics.m, dl, VT)).getNode(), 1); 2883 else 2884 return SDValue(); // No mulhu or equvialent 2885 2886 Created->push_back(Q.getNode()); 2887 2888 if (magics.a == 0) { 2889 assert(magics.s < Divisor.getBitWidth() && 2890 "We shouldn't generate an undefined shift!"); 2891 return DAG.getNode( 2892 ISD::SRL, dl, VT, Q, 2893 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL))); 2894 } else { 2895 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q); 2896 Created->push_back(NPQ.getNode()); 2897 NPQ = DAG.getNode( 2898 ISD::SRL, dl, VT, NPQ, 2899 DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL))); 2900 Created->push_back(NPQ.getNode()); 2901 NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 2902 Created->push_back(NPQ.getNode()); 2903 return DAG.getNode( 2904 ISD::SRL, dl, VT, NPQ, 2905 DAG.getConstant(magics.s - 1, dl, 2906 getShiftAmountTy(NPQ.getValueType(), DL))); 2907 } 2908 } 2909 2910 bool TargetLowering:: 2911 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 2912 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 2913 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 2914 "be a constant integer"); 2915 return true; 2916 } 2917 2918 return false; 2919 } 2920 2921 //===----------------------------------------------------------------------===// 2922 // Legalization Utilities 2923 //===----------------------------------------------------------------------===// 2924 2925 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 2926 SelectionDAG &DAG, SDValue LL, SDValue LH, 2927 SDValue RL, SDValue RH) const { 2928 EVT VT = N->getValueType(0); 2929 SDLoc dl(N); 2930 2931 bool HasMULHS = isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 2932 bool HasMULHU = isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 2933 bool HasSMUL_LOHI = isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 2934 bool HasUMUL_LOHI = isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 2935 if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) { 2936 unsigned OuterBitSize = VT.getSizeInBits(); 2937 unsigned InnerBitSize = HiLoVT.getSizeInBits(); 2938 unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0)); 2939 unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1)); 2940 2941 // LL, LH, RL, and RH must be either all NULL or all set to a value. 2942 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 2943 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 2944 2945 if (!LL.getNode() && !RL.getNode() && 2946 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 2947 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(0)); 2948 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(1)); 2949 } 2950 2951 if (!LL.getNode()) 2952 return false; 2953 2954 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 2955 if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) && 2956 DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) { 2957 // The inputs are both zero-extended. 2958 if (HasUMUL_LOHI) { 2959 // We can emit a umul_lohi. 2960 Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL, 2961 RL); 2962 Hi = SDValue(Lo.getNode(), 1); 2963 return true; 2964 } 2965 if (HasMULHU) { 2966 // We can emit a mulhu+mul. 2967 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL); 2968 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL); 2969 return true; 2970 } 2971 } 2972 if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) { 2973 // The input values are both sign-extended. 2974 if (HasSMUL_LOHI) { 2975 // We can emit a smul_lohi. 2976 Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL, 2977 RL); 2978 Hi = SDValue(Lo.getNode(), 1); 2979 return true; 2980 } 2981 if (HasMULHS) { 2982 // We can emit a mulhs+mul. 2983 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL); 2984 Hi = DAG.getNode(ISD::MULHS, dl, HiLoVT, LL, RL); 2985 return true; 2986 } 2987 } 2988 2989 if (!LH.getNode() && !RH.getNode() && 2990 isOperationLegalOrCustom(ISD::SRL, VT) && 2991 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 2992 auto &DL = DAG.getDataLayout(); 2993 unsigned ShiftAmt = VT.getSizeInBits() - HiLoVT.getSizeInBits(); 2994 SDValue Shift = DAG.getConstant(ShiftAmt, dl, getShiftAmountTy(VT, DL)); 2995 LH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(0), Shift); 2996 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 2997 RH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(1), Shift); 2998 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 2999 } 3000 3001 if (!LH.getNode()) 3002 return false; 3003 3004 if (HasUMUL_LOHI) { 3005 // Lo,Hi = umul LHS, RHS. 3006 SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl, 3007 DAG.getVTList(HiLoVT, HiLoVT), LL, RL); 3008 Lo = UMulLOHI; 3009 Hi = UMulLOHI.getValue(1); 3010 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 3011 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 3012 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 3013 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 3014 return true; 3015 } 3016 if (HasMULHU) { 3017 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL); 3018 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL); 3019 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 3020 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 3021 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 3022 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 3023 return true; 3024 } 3025 } 3026 return false; 3027 } 3028 3029 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 3030 SelectionDAG &DAG) const { 3031 EVT VT = Node->getOperand(0).getValueType(); 3032 EVT NVT = Node->getValueType(0); 3033 SDLoc dl(SDValue(Node, 0)); 3034 3035 // FIXME: Only f32 to i64 conversions are supported. 3036 if (VT != MVT::f32 || NVT != MVT::i64) 3037 return false; 3038 3039 // Expand f32 -> i64 conversion 3040 // This algorithm comes from compiler-rt's implementation of fixsfdi: 3041 // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c 3042 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), 3043 VT.getSizeInBits()); 3044 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 3045 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 3046 SDValue Bias = DAG.getConstant(127, dl, IntVT); 3047 SDValue SignMask = DAG.getConstant(APInt::getSignBit(VT.getSizeInBits()), dl, 3048 IntVT); 3049 SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT); 3050 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 3051 3052 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0)); 3053 3054 auto &DL = DAG.getDataLayout(); 3055 SDValue ExponentBits = DAG.getNode( 3056 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 3057 DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL))); 3058 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 3059 3060 SDValue Sign = DAG.getNode( 3061 ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 3062 DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL))); 3063 Sign = DAG.getSExtOrTrunc(Sign, dl, NVT); 3064 3065 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 3066 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 3067 DAG.getConstant(0x00800000, dl, IntVT)); 3068 3069 R = DAG.getZExtOrTrunc(R, dl, NVT); 3070 3071 R = DAG.getSelectCC( 3072 dl, Exponent, ExponentLoBit, 3073 DAG.getNode(ISD::SHL, dl, NVT, R, 3074 DAG.getZExtOrTrunc( 3075 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 3076 dl, getShiftAmountTy(IntVT, DL))), 3077 DAG.getNode(ISD::SRL, dl, NVT, R, 3078 DAG.getZExtOrTrunc( 3079 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 3080 dl, getShiftAmountTy(IntVT, DL))), 3081 ISD::SETGT); 3082 3083 SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT, 3084 DAG.getNode(ISD::XOR, dl, NVT, R, Sign), 3085 Sign); 3086 3087 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 3088 DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT); 3089 return true; 3090 } 3091 3092 //===----------------------------------------------------------------------===// 3093 // Implementation of Emulated TLS Model 3094 //===----------------------------------------------------------------------===// 3095 3096 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 3097 SelectionDAG &DAG) const { 3098 // Access to address of TLS varialbe xyz is lowered to a function call: 3099 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 3100 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3101 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 3102 SDLoc dl(GA); 3103 3104 ArgListTy Args; 3105 ArgListEntry Entry; 3106 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 3107 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 3108 StringRef EmuTlsVarName(NameString); 3109 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 3110 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 3111 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 3112 Entry.Ty = VoidPtrType; 3113 Args.push_back(Entry); 3114 3115 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 3116 3117 TargetLowering::CallLoweringInfo CLI(DAG); 3118 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 3119 CLI.setCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args), 0); 3120 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3121 3122 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 3123 // At last for X86 targets, maybe good for other targets too? 3124 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 3125 MFI->setAdjustsStack(true); // Is this only for X86 target? 3126 MFI->setHasCalls(true); 3127 3128 assert((GA->getOffset() == 0) && 3129 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 3130 return CallResult.first; 3131 } 3132