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 /// Try to simplify a setcc built with the specified operands and cc. If it is 1246 /// unable to simplify it, return a null SDValue. 1247 SDValue 1248 TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 1249 ISD::CondCode Cond, bool foldBooleans, 1250 DAGCombinerInfo &DCI, SDLoc dl) const { 1251 SelectionDAG &DAG = DCI.DAG; 1252 1253 // These setcc operations always fold. 1254 switch (Cond) { 1255 default: break; 1256 case ISD::SETFALSE: 1257 case ISD::SETFALSE2: return DAG.getConstant(0, dl, VT); 1258 case ISD::SETTRUE: 1259 case ISD::SETTRUE2: { 1260 TargetLowering::BooleanContent Cnt = 1261 getBooleanContents(N0->getValueType(0)); 1262 return DAG.getConstant( 1263 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl, 1264 VT); 1265 } 1266 } 1267 1268 // Ensure that the constant occurs on the RHS, and fold constant 1269 // comparisons. 1270 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 1271 if (isa<ConstantSDNode>(N0.getNode()) && 1272 (DCI.isBeforeLegalizeOps() || 1273 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 1274 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 1275 1276 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 1277 const APInt &C1 = N1C->getAPIntValue(); 1278 1279 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 1280 // equality comparison, then we're just comparing whether X itself is 1281 // zero. 1282 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) && 1283 N0.getOperand(0).getOpcode() == ISD::CTLZ && 1284 N0.getOperand(1).getOpcode() == ISD::Constant) { 1285 const APInt &ShAmt 1286 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 1287 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1288 ShAmt == Log2_32(N0.getValueType().getSizeInBits())) { 1289 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 1290 // (srl (ctlz x), 5) == 0 -> X != 0 1291 // (srl (ctlz x), 5) != 1 -> X != 0 1292 Cond = ISD::SETNE; 1293 } else { 1294 // (srl (ctlz x), 5) != 0 -> X == 0 1295 // (srl (ctlz x), 5) == 1 -> X == 0 1296 Cond = ISD::SETEQ; 1297 } 1298 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 1299 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), 1300 Zero, Cond); 1301 } 1302 } 1303 1304 SDValue CTPOP = N0; 1305 // Look through truncs that don't change the value of a ctpop. 1306 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE) 1307 CTPOP = N0.getOperand(0); 1308 1309 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP && 1310 (N0 == CTPOP || N0.getValueType().getSizeInBits() > 1311 Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) { 1312 EVT CTVT = CTPOP.getValueType(); 1313 SDValue CTOp = CTPOP.getOperand(0); 1314 1315 // (ctpop x) u< 2 -> (x & x-1) == 0 1316 // (ctpop x) u> 1 -> (x & x-1) != 0 1317 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){ 1318 SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp, 1319 DAG.getConstant(1, dl, CTVT)); 1320 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub); 1321 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 1322 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC); 1323 } 1324 1325 // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal. 1326 } 1327 1328 // (zext x) == C --> x == (trunc C) 1329 // (sext x) == C --> x == (trunc C) 1330 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1331 DCI.isBeforeLegalize() && N0->hasOneUse()) { 1332 unsigned MinBits = N0.getValueSizeInBits(); 1333 SDValue PreExt; 1334 bool Signed = false; 1335 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 1336 // ZExt 1337 MinBits = N0->getOperand(0).getValueSizeInBits(); 1338 PreExt = N0->getOperand(0); 1339 } else if (N0->getOpcode() == ISD::AND) { 1340 // DAGCombine turns costly ZExts into ANDs 1341 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 1342 if ((C->getAPIntValue()+1).isPowerOf2()) { 1343 MinBits = C->getAPIntValue().countTrailingOnes(); 1344 PreExt = N0->getOperand(0); 1345 } 1346 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 1347 // SExt 1348 MinBits = N0->getOperand(0).getValueSizeInBits(); 1349 PreExt = N0->getOperand(0); 1350 Signed = true; 1351 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 1352 // ZEXTLOAD / SEXTLOAD 1353 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 1354 MinBits = LN0->getMemoryVT().getSizeInBits(); 1355 PreExt = N0; 1356 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 1357 Signed = true; 1358 MinBits = LN0->getMemoryVT().getSizeInBits(); 1359 PreExt = N0; 1360 } 1361 } 1362 1363 // Figure out how many bits we need to preserve this constant. 1364 unsigned ReqdBits = Signed ? 1365 C1.getBitWidth() - C1.getNumSignBits() + 1 : 1366 C1.getActiveBits(); 1367 1368 // Make sure we're not losing bits from the constant. 1369 if (MinBits > 0 && 1370 MinBits < C1.getBitWidth() && 1371 MinBits >= ReqdBits) { 1372 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 1373 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 1374 // Will get folded away. 1375 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 1376 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 1377 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 1378 } 1379 } 1380 } 1381 1382 // If the LHS is '(and load, const)', the RHS is 0, 1383 // the test is for equality or unsigned, and all 1 bits of the const are 1384 // in the same partial word, see if we can shorten the load. 1385 if (DCI.isBeforeLegalize() && 1386 !ISD::isSignedIntSetCC(Cond) && 1387 N0.getOpcode() == ISD::AND && C1 == 0 && 1388 N0.getNode()->hasOneUse() && 1389 isa<LoadSDNode>(N0.getOperand(0)) && 1390 N0.getOperand(0).getNode()->hasOneUse() && 1391 isa<ConstantSDNode>(N0.getOperand(1))) { 1392 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 1393 APInt bestMask; 1394 unsigned bestWidth = 0, bestOffset = 0; 1395 if (!Lod->isVolatile() && Lod->isUnindexed()) { 1396 unsigned origWidth = N0.getValueType().getSizeInBits(); 1397 unsigned maskWidth = origWidth; 1398 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 1399 // 8 bits, but have to be careful... 1400 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 1401 origWidth = Lod->getMemoryVT().getSizeInBits(); 1402 const APInt &Mask = 1403 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 1404 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 1405 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 1406 for (unsigned offset=0; offset<origWidth/width; offset++) { 1407 if ((newMask & Mask) == Mask) { 1408 if (!DAG.getDataLayout().isLittleEndian()) 1409 bestOffset = (origWidth/width - offset - 1) * (width/8); 1410 else 1411 bestOffset = (uint64_t)offset * (width/8); 1412 bestMask = Mask.lshr(offset * (width/8) * 8); 1413 bestWidth = width; 1414 break; 1415 } 1416 newMask = newMask << width; 1417 } 1418 } 1419 } 1420 if (bestWidth) { 1421 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 1422 if (newVT.isRound()) { 1423 EVT PtrType = Lod->getOperand(1).getValueType(); 1424 SDValue Ptr = Lod->getBasePtr(); 1425 if (bestOffset != 0) 1426 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(), 1427 DAG.getConstant(bestOffset, dl, PtrType)); 1428 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset); 1429 SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr, 1430 Lod->getPointerInfo().getWithOffset(bestOffset), 1431 false, false, false, NewAlign); 1432 return DAG.getSetCC(dl, VT, 1433 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 1434 DAG.getConstant(bestMask.trunc(bestWidth), 1435 dl, newVT)), 1436 DAG.getConstant(0LL, dl, newVT), Cond); 1437 } 1438 } 1439 } 1440 1441 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 1442 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 1443 unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits(); 1444 1445 // If the comparison constant has bits in the upper part, the 1446 // zero-extended value could never match. 1447 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 1448 C1.getBitWidth() - InSize))) { 1449 switch (Cond) { 1450 case ISD::SETUGT: 1451 case ISD::SETUGE: 1452 case ISD::SETEQ: return DAG.getConstant(0, dl, VT); 1453 case ISD::SETULT: 1454 case ISD::SETULE: 1455 case ISD::SETNE: return DAG.getConstant(1, dl, VT); 1456 case ISD::SETGT: 1457 case ISD::SETGE: 1458 // True if the sign bit of C1 is set. 1459 return DAG.getConstant(C1.isNegative(), dl, VT); 1460 case ISD::SETLT: 1461 case ISD::SETLE: 1462 // True if the sign bit of C1 isn't set. 1463 return DAG.getConstant(C1.isNonNegative(), dl, VT); 1464 default: 1465 break; 1466 } 1467 } 1468 1469 // Otherwise, we can perform the comparison with the low bits. 1470 switch (Cond) { 1471 case ISD::SETEQ: 1472 case ISD::SETNE: 1473 case ISD::SETUGT: 1474 case ISD::SETUGE: 1475 case ISD::SETULT: 1476 case ISD::SETULE: { 1477 EVT newVT = N0.getOperand(0).getValueType(); 1478 if (DCI.isBeforeLegalizeOps() || 1479 (isOperationLegal(ISD::SETCC, newVT) && 1480 getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) { 1481 EVT NewSetCCVT = 1482 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT); 1483 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 1484 1485 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 1486 NewConst, Cond); 1487 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 1488 } 1489 break; 1490 } 1491 default: 1492 break; // todo, be more careful with signed comparisons 1493 } 1494 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 1495 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 1496 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 1497 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 1498 EVT ExtDstTy = N0.getValueType(); 1499 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 1500 1501 // If the constant doesn't fit into the number of bits for the source of 1502 // the sign extension, it is impossible for both sides to be equal. 1503 if (C1.getMinSignedBits() > ExtSrcTyBits) 1504 return DAG.getConstant(Cond == ISD::SETNE, dl, VT); 1505 1506 SDValue ZextOp; 1507 EVT Op0Ty = N0.getOperand(0).getValueType(); 1508 if (Op0Ty == ExtSrcTy) { 1509 ZextOp = N0.getOperand(0); 1510 } else { 1511 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 1512 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0), 1513 DAG.getConstant(Imm, dl, Op0Ty)); 1514 } 1515 if (!DCI.isCalledByLegalizer()) 1516 DCI.AddToWorklist(ZextOp.getNode()); 1517 // Otherwise, make this a use of a zext. 1518 return DAG.getSetCC(dl, VT, ZextOp, 1519 DAG.getConstant(C1 & APInt::getLowBitsSet( 1520 ExtDstTyBits, 1521 ExtSrcTyBits), 1522 dl, ExtDstTy), 1523 Cond); 1524 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) && 1525 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 1526 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 1527 if (N0.getOpcode() == ISD::SETCC && 1528 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) { 1529 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1); 1530 if (TrueWhenTrue) 1531 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 1532 // Invert the condition. 1533 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 1534 CC = ISD::getSetCCInverse(CC, 1535 N0.getOperand(0).getValueType().isInteger()); 1536 if (DCI.isBeforeLegalizeOps() || 1537 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 1538 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 1539 } 1540 1541 if ((N0.getOpcode() == ISD::XOR || 1542 (N0.getOpcode() == ISD::AND && 1543 N0.getOperand(0).getOpcode() == ISD::XOR && 1544 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 1545 isa<ConstantSDNode>(N0.getOperand(1)) && 1546 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) { 1547 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 1548 // can only do this if the top bits are known zero. 1549 unsigned BitWidth = N0.getValueSizeInBits(); 1550 if (DAG.MaskedValueIsZero(N0, 1551 APInt::getHighBitsSet(BitWidth, 1552 BitWidth-1))) { 1553 // Okay, get the un-inverted input value. 1554 SDValue Val; 1555 if (N0.getOpcode() == ISD::XOR) 1556 Val = N0.getOperand(0); 1557 else { 1558 assert(N0.getOpcode() == ISD::AND && 1559 N0.getOperand(0).getOpcode() == ISD::XOR); 1560 // ((X^1)&1)^1 -> X & 1 1561 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 1562 N0.getOperand(0).getOperand(0), 1563 N0.getOperand(1)); 1564 } 1565 1566 return DAG.getSetCC(dl, VT, Val, N1, 1567 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1568 } 1569 } else if (N1C->getAPIntValue() == 1 && 1570 (VT == MVT::i1 || 1571 getBooleanContents(N0->getValueType(0)) == 1572 ZeroOrOneBooleanContent)) { 1573 SDValue Op0 = N0; 1574 if (Op0.getOpcode() == ISD::TRUNCATE) 1575 Op0 = Op0.getOperand(0); 1576 1577 if ((Op0.getOpcode() == ISD::XOR) && 1578 Op0.getOperand(0).getOpcode() == ISD::SETCC && 1579 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 1580 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 1581 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 1582 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1), 1583 Cond); 1584 } 1585 if (Op0.getOpcode() == ISD::AND && 1586 isa<ConstantSDNode>(Op0.getOperand(1)) && 1587 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) { 1588 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 1589 if (Op0.getValueType().bitsGT(VT)) 1590 Op0 = DAG.getNode(ISD::AND, dl, VT, 1591 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 1592 DAG.getConstant(1, dl, VT)); 1593 else if (Op0.getValueType().bitsLT(VT)) 1594 Op0 = DAG.getNode(ISD::AND, dl, VT, 1595 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 1596 DAG.getConstant(1, dl, VT)); 1597 1598 return DAG.getSetCC(dl, VT, Op0, 1599 DAG.getConstant(0, dl, Op0.getValueType()), 1600 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1601 } 1602 if (Op0.getOpcode() == ISD::AssertZext && 1603 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 1604 return DAG.getSetCC(dl, VT, Op0, 1605 DAG.getConstant(0, dl, Op0.getValueType()), 1606 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1607 } 1608 } 1609 1610 APInt MinVal, MaxVal; 1611 unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits(); 1612 if (ISD::isSignedIntSetCC(Cond)) { 1613 MinVal = APInt::getSignedMinValue(OperandBitSize); 1614 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 1615 } else { 1616 MinVal = APInt::getMinValue(OperandBitSize); 1617 MaxVal = APInt::getMaxValue(OperandBitSize); 1618 } 1619 1620 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 1621 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 1622 if (C1 == MinVal) return DAG.getConstant(1, dl, VT); // X >= MIN --> true 1623 // X >= C0 --> X > (C0 - 1) 1624 APInt C = C1 - 1; 1625 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 1626 if ((DCI.isBeforeLegalizeOps() || 1627 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 1628 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 && 1629 isLegalICmpImmediate(C.getSExtValue())))) { 1630 return DAG.getSetCC(dl, VT, N0, 1631 DAG.getConstant(C, dl, N1.getValueType()), 1632 NewCC); 1633 } 1634 } 1635 1636 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 1637 if (C1 == MaxVal) return DAG.getConstant(1, dl, VT); // X <= MAX --> true 1638 // X <= C0 --> X < (C0 + 1) 1639 APInt C = C1 + 1; 1640 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 1641 if ((DCI.isBeforeLegalizeOps() || 1642 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 1643 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 && 1644 isLegalICmpImmediate(C.getSExtValue())))) { 1645 return DAG.getSetCC(dl, VT, N0, 1646 DAG.getConstant(C, dl, N1.getValueType()), 1647 NewCC); 1648 } 1649 } 1650 1651 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal) 1652 return DAG.getConstant(0, dl, VT); // X < MIN --> false 1653 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal) 1654 return DAG.getConstant(1, dl, VT); // X >= MIN --> true 1655 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal) 1656 return DAG.getConstant(0, dl, VT); // X > MAX --> false 1657 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal) 1658 return DAG.getConstant(1, dl, VT); // X <= MAX --> true 1659 1660 // Canonicalize setgt X, Min --> setne X, Min 1661 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal) 1662 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 1663 // Canonicalize setlt X, Max --> setne X, Max 1664 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal) 1665 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 1666 1667 // If we have setult X, 1, turn it into seteq X, 0 1668 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1) 1669 return DAG.getSetCC(dl, VT, N0, 1670 DAG.getConstant(MinVal, dl, N0.getValueType()), 1671 ISD::SETEQ); 1672 // If we have setugt X, Max-1, turn it into seteq X, Max 1673 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1) 1674 return DAG.getSetCC(dl, VT, N0, 1675 DAG.getConstant(MaxVal, dl, N0.getValueType()), 1676 ISD::SETEQ); 1677 1678 // If we have "setcc X, C0", check to see if we can shrink the immediate 1679 // by changing cc. 1680 1681 // SETUGT X, SINTMAX -> SETLT X, 0 1682 if (Cond == ISD::SETUGT && 1683 C1 == APInt::getSignedMaxValue(OperandBitSize)) 1684 return DAG.getSetCC(dl, VT, N0, 1685 DAG.getConstant(0, dl, N1.getValueType()), 1686 ISD::SETLT); 1687 1688 // SETULT X, SINTMIN -> SETGT X, -1 1689 if (Cond == ISD::SETULT && 1690 C1 == APInt::getSignedMinValue(OperandBitSize)) { 1691 SDValue ConstMinusOne = 1692 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl, 1693 N1.getValueType()); 1694 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT); 1695 } 1696 1697 // Fold bit comparisons when we can. 1698 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1699 (VT == N0.getValueType() || 1700 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) && 1701 N0.getOpcode() == ISD::AND) { 1702 auto &DL = DAG.getDataLayout(); 1703 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 1704 EVT ShiftTy = DCI.isBeforeLegalize() 1705 ? getPointerTy(DL) 1706 : getShiftAmountTy(N0.getValueType(), DL); 1707 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 1708 // Perform the xform if the AND RHS is a single bit. 1709 if (AndRHS->getAPIntValue().isPowerOf2()) { 1710 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1711 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0, 1712 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl, 1713 ShiftTy))); 1714 } 1715 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 1716 // (X & 8) == 8 --> (X & 8) >> 3 1717 // Perform the xform if C1 is a single bit. 1718 if (C1.isPowerOf2()) { 1719 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1720 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0, 1721 DAG.getConstant(C1.logBase2(), dl, 1722 ShiftTy))); 1723 } 1724 } 1725 } 1726 } 1727 1728 if (C1.getMinSignedBits() <= 64 && 1729 !isLegalICmpImmediate(C1.getSExtValue())) { 1730 // (X & -256) == 256 -> (X >> 8) == 1 1731 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1732 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 1733 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 1734 const APInt &AndRHSC = AndRHS->getAPIntValue(); 1735 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) { 1736 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 1737 auto &DL = DAG.getDataLayout(); 1738 EVT ShiftTy = DCI.isBeforeLegalize() 1739 ? getPointerTy(DL) 1740 : getShiftAmountTy(N0.getValueType(), DL); 1741 EVT CmpTy = N0.getValueType(); 1742 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0), 1743 DAG.getConstant(ShiftBits, dl, 1744 ShiftTy)); 1745 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy); 1746 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 1747 } 1748 } 1749 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 1750 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 1751 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 1752 // X < 0x100000000 -> (X >> 32) < 1 1753 // X >= 0x100000000 -> (X >> 32) >= 1 1754 // X <= 0x0ffffffff -> (X >> 32) < 1 1755 // X > 0x0ffffffff -> (X >> 32) >= 1 1756 unsigned ShiftBits; 1757 APInt NewC = C1; 1758 ISD::CondCode NewCond = Cond; 1759 if (AdjOne) { 1760 ShiftBits = C1.countTrailingOnes(); 1761 NewC = NewC + 1; 1762 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 1763 } else { 1764 ShiftBits = C1.countTrailingZeros(); 1765 } 1766 NewC = NewC.lshr(ShiftBits); 1767 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 1768 isLegalICmpImmediate(NewC.getSExtValue())) { 1769 auto &DL = DAG.getDataLayout(); 1770 EVT ShiftTy = DCI.isBeforeLegalize() 1771 ? getPointerTy(DL) 1772 : getShiftAmountTy(N0.getValueType(), DL); 1773 EVT CmpTy = N0.getValueType(); 1774 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0, 1775 DAG.getConstant(ShiftBits, dl, ShiftTy)); 1776 SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy); 1777 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 1778 } 1779 } 1780 } 1781 } 1782 1783 if (isa<ConstantFPSDNode>(N0.getNode())) { 1784 // Constant fold or commute setcc. 1785 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl); 1786 if (O.getNode()) return O; 1787 } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) { 1788 // If the RHS of an FP comparison is a constant, simplify it away in 1789 // some cases. 1790 if (CFP->getValueAPF().isNaN()) { 1791 // If an operand is known to be a nan, we can fold it. 1792 switch (ISD::getUnorderedFlavor(Cond)) { 1793 default: llvm_unreachable("Unknown flavor!"); 1794 case 0: // Known false. 1795 return DAG.getConstant(0, dl, VT); 1796 case 1: // Known true. 1797 return DAG.getConstant(1, dl, VT); 1798 case 2: // Undefined. 1799 return DAG.getUNDEF(VT); 1800 } 1801 } 1802 1803 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 1804 // constant if knowing that the operand is non-nan is enough. We prefer to 1805 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 1806 // materialize 0.0. 1807 if (Cond == ISD::SETO || Cond == ISD::SETUO) 1808 return DAG.getSetCC(dl, VT, N0, N0, Cond); 1809 1810 // If the condition is not legal, see if we can find an equivalent one 1811 // which is legal. 1812 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 1813 // If the comparison was an awkward floating-point == or != and one of 1814 // the comparison operands is infinity or negative infinity, convert the 1815 // condition to a less-awkward <= or >=. 1816 if (CFP->getValueAPF().isInfinity()) { 1817 if (CFP->getValueAPF().isNegative()) { 1818 if (Cond == ISD::SETOEQ && 1819 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType())) 1820 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE); 1821 if (Cond == ISD::SETUEQ && 1822 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType())) 1823 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE); 1824 if (Cond == ISD::SETUNE && 1825 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType())) 1826 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT); 1827 if (Cond == ISD::SETONE && 1828 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType())) 1829 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT); 1830 } else { 1831 if (Cond == ISD::SETOEQ && 1832 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType())) 1833 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE); 1834 if (Cond == ISD::SETUEQ && 1835 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType())) 1836 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE); 1837 if (Cond == ISD::SETUNE && 1838 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType())) 1839 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT); 1840 if (Cond == ISD::SETONE && 1841 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType())) 1842 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT); 1843 } 1844 } 1845 } 1846 } 1847 1848 if (N0 == N1) { 1849 // The sext(setcc()) => setcc() optimization relies on the appropriate 1850 // constant being emitted. 1851 uint64_t EqVal = 0; 1852 switch (getBooleanContents(N0.getValueType())) { 1853 case UndefinedBooleanContent: 1854 case ZeroOrOneBooleanContent: 1855 EqVal = ISD::isTrueWhenEqual(Cond); 1856 break; 1857 case ZeroOrNegativeOneBooleanContent: 1858 EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0; 1859 break; 1860 } 1861 1862 // We can always fold X == X for integer setcc's. 1863 if (N0.getValueType().isInteger()) { 1864 return DAG.getConstant(EqVal, dl, VT); 1865 } 1866 unsigned UOF = ISD::getUnorderedFlavor(Cond); 1867 if (UOF == 2) // FP operators that are undefined on NaNs. 1868 return DAG.getConstant(EqVal, dl, VT); 1869 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond))) 1870 return DAG.getConstant(EqVal, dl, VT); 1871 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 1872 // if it is not already. 1873 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 1874 if (NewCond != Cond && (DCI.isBeforeLegalizeOps() || 1875 getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal)) 1876 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 1877 } 1878 1879 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1880 N0.getValueType().isInteger()) { 1881 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 1882 N0.getOpcode() == ISD::XOR) { 1883 // Simplify (X+Y) == (X+Z) --> Y == Z 1884 if (N0.getOpcode() == N1.getOpcode()) { 1885 if (N0.getOperand(0) == N1.getOperand(0)) 1886 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 1887 if (N0.getOperand(1) == N1.getOperand(1)) 1888 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 1889 if (DAG.isCommutativeBinOp(N0.getOpcode())) { 1890 // If X op Y == Y op X, try other combinations. 1891 if (N0.getOperand(0) == N1.getOperand(1)) 1892 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 1893 Cond); 1894 if (N0.getOperand(1) == N1.getOperand(0)) 1895 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 1896 Cond); 1897 } 1898 } 1899 1900 // If RHS is a legal immediate value for a compare instruction, we need 1901 // to be careful about increasing register pressure needlessly. 1902 bool LegalRHSImm = false; 1903 1904 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 1905 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 1906 // Turn (X+C1) == C2 --> X == C2-C1 1907 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) { 1908 return DAG.getSetCC(dl, VT, N0.getOperand(0), 1909 DAG.getConstant(RHSC->getAPIntValue()- 1910 LHSR->getAPIntValue(), 1911 dl, N0.getValueType()), Cond); 1912 } 1913 1914 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0. 1915 if (N0.getOpcode() == ISD::XOR) 1916 // If we know that all of the inverted bits are zero, don't bother 1917 // performing the inversion. 1918 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue())) 1919 return 1920 DAG.getSetCC(dl, VT, N0.getOperand(0), 1921 DAG.getConstant(LHSR->getAPIntValue() ^ 1922 RHSC->getAPIntValue(), 1923 dl, N0.getValueType()), 1924 Cond); 1925 } 1926 1927 // Turn (C1-X) == C2 --> X == C1-C2 1928 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) { 1929 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) { 1930 return 1931 DAG.getSetCC(dl, VT, N0.getOperand(1), 1932 DAG.getConstant(SUBC->getAPIntValue() - 1933 RHSC->getAPIntValue(), 1934 dl, N0.getValueType()), 1935 Cond); 1936 } 1937 } 1938 1939 // Could RHSC fold directly into a compare? 1940 if (RHSC->getValueType(0).getSizeInBits() <= 64) 1941 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 1942 } 1943 1944 // Simplify (X+Z) == X --> Z == 0 1945 // Don't do this if X is an immediate that can fold into a cmp 1946 // instruction and X+Z has other uses. It could be an induction variable 1947 // chain, and the transform would increase register pressure. 1948 if (!LegalRHSImm || N0.getNode()->hasOneUse()) { 1949 if (N0.getOperand(0) == N1) 1950 return DAG.getSetCC(dl, VT, N0.getOperand(1), 1951 DAG.getConstant(0, dl, N0.getValueType()), Cond); 1952 if (N0.getOperand(1) == N1) { 1953 if (DAG.isCommutativeBinOp(N0.getOpcode())) 1954 return DAG.getSetCC(dl, VT, N0.getOperand(0), 1955 DAG.getConstant(0, dl, N0.getValueType()), 1956 Cond); 1957 if (N0.getNode()->hasOneUse()) { 1958 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!"); 1959 auto &DL = DAG.getDataLayout(); 1960 // (Z-X) == X --> Z == X<<1 1961 SDValue SH = DAG.getNode( 1962 ISD::SHL, dl, N1.getValueType(), N1, 1963 DAG.getConstant(1, dl, 1964 getShiftAmountTy(N1.getValueType(), DL))); 1965 if (!DCI.isCalledByLegalizer()) 1966 DCI.AddToWorklist(SH.getNode()); 1967 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond); 1968 } 1969 } 1970 } 1971 } 1972 1973 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 1974 N1.getOpcode() == ISD::XOR) { 1975 // Simplify X == (X+Z) --> Z == 0 1976 if (N1.getOperand(0) == N0) 1977 return DAG.getSetCC(dl, VT, N1.getOperand(1), 1978 DAG.getConstant(0, dl, N1.getValueType()), Cond); 1979 if (N1.getOperand(1) == N0) { 1980 if (DAG.isCommutativeBinOp(N1.getOpcode())) 1981 return DAG.getSetCC(dl, VT, N1.getOperand(0), 1982 DAG.getConstant(0, dl, N1.getValueType()), Cond); 1983 if (N1.getNode()->hasOneUse()) { 1984 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!"); 1985 auto &DL = DAG.getDataLayout(); 1986 // X == (Z-X) --> X<<1 == Z 1987 SDValue SH = DAG.getNode( 1988 ISD::SHL, dl, N1.getValueType(), N0, 1989 DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL))); 1990 if (!DCI.isCalledByLegalizer()) 1991 DCI.AddToWorklist(SH.getNode()); 1992 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond); 1993 } 1994 } 1995 } 1996 1997 // Simplify x&y == y to x&y != 0 if y has exactly one bit set. 1998 // Note that where y is variable and is known to have at most 1999 // one bit set (for example, if it is z&1) we cannot do this; 2000 // the expressions are not equivalent when y==0. 2001 if (N0.getOpcode() == ISD::AND) 2002 if (N0.getOperand(0) == N1 || N0.getOperand(1) == N1) { 2003 if (ValueHasExactlyOneBitSet(N1, DAG)) { 2004 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true); 2005 if (DCI.isBeforeLegalizeOps() || 2006 isCondCodeLegal(Cond, N0.getSimpleValueType())) { 2007 SDValue Zero = DAG.getConstant(0, dl, N1.getValueType()); 2008 return DAG.getSetCC(dl, VT, N0, Zero, Cond); 2009 } 2010 } 2011 } 2012 if (N1.getOpcode() == ISD::AND) 2013 if (N1.getOperand(0) == N0 || N1.getOperand(1) == N0) { 2014 if (ValueHasExactlyOneBitSet(N0, DAG)) { 2015 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true); 2016 if (DCI.isBeforeLegalizeOps() || 2017 isCondCodeLegal(Cond, N1.getSimpleValueType())) { 2018 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 2019 return DAG.getSetCC(dl, VT, N1, Zero, Cond); 2020 } 2021 } 2022 } 2023 } 2024 2025 // Fold away ALL boolean setcc's. 2026 SDValue Temp; 2027 if (N0.getValueType() == MVT::i1 && foldBooleans) { 2028 switch (Cond) { 2029 default: llvm_unreachable("Unknown integer setcc!"); 2030 case ISD::SETEQ: // X == Y -> ~(X^Y) 2031 Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1); 2032 N0 = DAG.getNOT(dl, Temp, MVT::i1); 2033 if (!DCI.isCalledByLegalizer()) 2034 DCI.AddToWorklist(Temp.getNode()); 2035 break; 2036 case ISD::SETNE: // X != Y --> (X^Y) 2037 N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1); 2038 break; 2039 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 2040 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 2041 Temp = DAG.getNOT(dl, N0, MVT::i1); 2042 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp); 2043 if (!DCI.isCalledByLegalizer()) 2044 DCI.AddToWorklist(Temp.getNode()); 2045 break; 2046 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 2047 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 2048 Temp = DAG.getNOT(dl, N1, MVT::i1); 2049 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp); 2050 if (!DCI.isCalledByLegalizer()) 2051 DCI.AddToWorklist(Temp.getNode()); 2052 break; 2053 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 2054 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 2055 Temp = DAG.getNOT(dl, N0, MVT::i1); 2056 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp); 2057 if (!DCI.isCalledByLegalizer()) 2058 DCI.AddToWorklist(Temp.getNode()); 2059 break; 2060 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 2061 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 2062 Temp = DAG.getNOT(dl, N1, MVT::i1); 2063 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp); 2064 break; 2065 } 2066 if (VT != MVT::i1) { 2067 if (!DCI.isCalledByLegalizer()) 2068 DCI.AddToWorklist(N0.getNode()); 2069 // FIXME: If running after legalize, we probably can't do this. 2070 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0); 2071 } 2072 return N0; 2073 } 2074 2075 // Could not fold it. 2076 return SDValue(); 2077 } 2078 2079 /// Returns true (and the GlobalValue and the offset) if the node is a 2080 /// GlobalAddress + offset. 2081 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA, 2082 int64_t &Offset) const { 2083 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 2084 GA = GASD->getGlobal(); 2085 Offset += GASD->getOffset(); 2086 return true; 2087 } 2088 2089 if (N->getOpcode() == ISD::ADD) { 2090 SDValue N1 = N->getOperand(0); 2091 SDValue N2 = N->getOperand(1); 2092 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 2093 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 2094 Offset += V->getSExtValue(); 2095 return true; 2096 } 2097 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 2098 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 2099 Offset += V->getSExtValue(); 2100 return true; 2101 } 2102 } 2103 } 2104 2105 return false; 2106 } 2107 2108 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 2109 DAGCombinerInfo &DCI) const { 2110 // Default implementation: no optimization. 2111 return SDValue(); 2112 } 2113 2114 //===----------------------------------------------------------------------===// 2115 // Inline Assembler Implementation Methods 2116 //===----------------------------------------------------------------------===// 2117 2118 TargetLowering::ConstraintType 2119 TargetLowering::getConstraintType(StringRef Constraint) const { 2120 unsigned S = Constraint.size(); 2121 2122 if (S == 1) { 2123 switch (Constraint[0]) { 2124 default: break; 2125 case 'r': return C_RegisterClass; 2126 case 'm': // memory 2127 case 'o': // offsetable 2128 case 'V': // not offsetable 2129 return C_Memory; 2130 case 'i': // Simple Integer or Relocatable Constant 2131 case 'n': // Simple Integer 2132 case 'E': // Floating Point Constant 2133 case 'F': // Floating Point Constant 2134 case 's': // Relocatable Constant 2135 case 'p': // Address. 2136 case 'X': // Allow ANY value. 2137 case 'I': // Target registers. 2138 case 'J': 2139 case 'K': 2140 case 'L': 2141 case 'M': 2142 case 'N': 2143 case 'O': 2144 case 'P': 2145 case '<': 2146 case '>': 2147 return C_Other; 2148 } 2149 } 2150 2151 if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') { 2152 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 2153 return C_Memory; 2154 return C_Register; 2155 } 2156 return C_Unknown; 2157 } 2158 2159 /// Try to replace an X constraint, which matches anything, with another that 2160 /// has more specific requirements based on the type of the corresponding 2161 /// operand. 2162 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{ 2163 if (ConstraintVT.isInteger()) 2164 return "r"; 2165 if (ConstraintVT.isFloatingPoint()) 2166 return "f"; // works for many targets 2167 return nullptr; 2168 } 2169 2170 /// Lower the specified operand into the Ops vector. 2171 /// If it is invalid, don't add anything to Ops. 2172 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 2173 std::string &Constraint, 2174 std::vector<SDValue> &Ops, 2175 SelectionDAG &DAG) const { 2176 2177 if (Constraint.length() > 1) return; 2178 2179 char ConstraintLetter = Constraint[0]; 2180 switch (ConstraintLetter) { 2181 default: break; 2182 case 'X': // Allows any operand; labels (basic block) use this. 2183 if (Op.getOpcode() == ISD::BasicBlock) { 2184 Ops.push_back(Op); 2185 return; 2186 } 2187 // fall through 2188 case 'i': // Simple Integer or Relocatable Constant 2189 case 'n': // Simple Integer 2190 case 's': { // Relocatable Constant 2191 // These operands are interested in values of the form (GV+C), where C may 2192 // be folded in as an offset of GV, or it may be explicitly added. Also, it 2193 // is possible and fine if either GV or C are missing. 2194 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 2195 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op); 2196 2197 // If we have "(add GV, C)", pull out GV/C 2198 if (Op.getOpcode() == ISD::ADD) { 2199 C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 2200 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0)); 2201 if (!C || !GA) { 2202 C = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 2203 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1)); 2204 } 2205 if (!C || !GA) 2206 C = nullptr, GA = nullptr; 2207 } 2208 2209 // If we find a valid operand, map to the TargetXXX version so that the 2210 // value itself doesn't get selected. 2211 if (GA) { // Either &GV or &GV+C 2212 if (ConstraintLetter != 'n') { 2213 int64_t Offs = GA->getOffset(); 2214 if (C) Offs += C->getZExtValue(); 2215 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), 2216 C ? SDLoc(C) : SDLoc(), 2217 Op.getValueType(), Offs)); 2218 } 2219 return; 2220 } 2221 if (C) { // just C, no GV. 2222 // Simple constants are not allowed for 's'. 2223 if (ConstraintLetter != 's') { 2224 // gcc prints these as sign extended. Sign extend value to 64 bits 2225 // now; without this it would get ZExt'd later in 2226 // ScheduleDAGSDNodes::EmitNode, which is very generic. 2227 Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(), 2228 SDLoc(C), MVT::i64)); 2229 } 2230 return; 2231 } 2232 break; 2233 } 2234 } 2235 } 2236 2237 std::pair<unsigned, const TargetRegisterClass *> 2238 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 2239 StringRef Constraint, 2240 MVT VT) const { 2241 if (Constraint.empty() || Constraint[0] != '{') 2242 return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr)); 2243 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?"); 2244 2245 // Remove the braces from around the name. 2246 StringRef RegName(Constraint.data()+1, Constraint.size()-2); 2247 2248 std::pair<unsigned, const TargetRegisterClass*> R = 2249 std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr)); 2250 2251 // Figure out which register class contains this reg. 2252 for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(), 2253 E = RI->regclass_end(); RCI != E; ++RCI) { 2254 const TargetRegisterClass *RC = *RCI; 2255 2256 // If none of the value types for this register class are valid, we 2257 // can't use it. For example, 64-bit reg classes on 32-bit targets. 2258 if (!isLegalRC(RC)) 2259 continue; 2260 2261 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); 2262 I != E; ++I) { 2263 if (RegName.equals_lower(RI->getName(*I))) { 2264 std::pair<unsigned, const TargetRegisterClass*> S = 2265 std::make_pair(*I, RC); 2266 2267 // If this register class has the requested value type, return it, 2268 // otherwise keep searching and return the first class found 2269 // if no other is found which explicitly has the requested type. 2270 if (RC->hasType(VT)) 2271 return S; 2272 else if (!R.second) 2273 R = S; 2274 } 2275 } 2276 } 2277 2278 return R; 2279 } 2280 2281 //===----------------------------------------------------------------------===// 2282 // Constraint Selection. 2283 2284 /// Return true of this is an input operand that is a matching constraint like 2285 /// "4". 2286 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 2287 assert(!ConstraintCode.empty() && "No known constraint!"); 2288 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 2289 } 2290 2291 /// If this is an input matching constraint, this method returns the output 2292 /// operand it matches. 2293 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 2294 assert(!ConstraintCode.empty() && "No known constraint!"); 2295 return atoi(ConstraintCode.c_str()); 2296 } 2297 2298 /// Split up the constraint string from the inline assembly value into the 2299 /// specific constraints and their prefixes, and also tie in the associated 2300 /// operand values. 2301 /// If this returns an empty vector, and if the constraint string itself 2302 /// isn't empty, there was an error parsing. 2303 TargetLowering::AsmOperandInfoVector 2304 TargetLowering::ParseConstraints(const DataLayout &DL, 2305 const TargetRegisterInfo *TRI, 2306 ImmutableCallSite CS) const { 2307 /// Information about all of the constraints. 2308 AsmOperandInfoVector ConstraintOperands; 2309 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 2310 unsigned maCount = 0; // Largest number of multiple alternative constraints. 2311 2312 // Do a prepass over the constraints, canonicalizing them, and building up the 2313 // ConstraintOperands list. 2314 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 2315 unsigned ResNo = 0; // ResNo - The result number of the next output. 2316 2317 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 2318 ConstraintOperands.emplace_back(std::move(CI)); 2319 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 2320 2321 // Update multiple alternative constraint count. 2322 if (OpInfo.multipleAlternatives.size() > maCount) 2323 maCount = OpInfo.multipleAlternatives.size(); 2324 2325 OpInfo.ConstraintVT = MVT::Other; 2326 2327 // Compute the value type for each operand. 2328 switch (OpInfo.Type) { 2329 case InlineAsm::isOutput: 2330 // Indirect outputs just consume an argument. 2331 if (OpInfo.isIndirect) { 2332 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 2333 break; 2334 } 2335 2336 // The return value of the call is this value. As such, there is no 2337 // corresponding argument. 2338 assert(!CS.getType()->isVoidTy() && 2339 "Bad inline asm!"); 2340 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 2341 OpInfo.ConstraintVT = 2342 getSimpleValueType(DL, STy->getElementType(ResNo)); 2343 } else { 2344 assert(ResNo == 0 && "Asm only has one result!"); 2345 OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType()); 2346 } 2347 ++ResNo; 2348 break; 2349 case InlineAsm::isInput: 2350 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 2351 break; 2352 case InlineAsm::isClobber: 2353 // Nothing to do. 2354 break; 2355 } 2356 2357 if (OpInfo.CallOperandVal) { 2358 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 2359 if (OpInfo.isIndirect) { 2360 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 2361 if (!PtrTy) 2362 report_fatal_error("Indirect operand for inline asm not a pointer!"); 2363 OpTy = PtrTy->getElementType(); 2364 } 2365 2366 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 2367 if (StructType *STy = dyn_cast<StructType>(OpTy)) 2368 if (STy->getNumElements() == 1) 2369 OpTy = STy->getElementType(0); 2370 2371 // If OpTy is not a single value, it may be a struct/union that we 2372 // can tile with integers. 2373 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 2374 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 2375 switch (BitSize) { 2376 default: break; 2377 case 1: 2378 case 8: 2379 case 16: 2380 case 32: 2381 case 64: 2382 case 128: 2383 OpInfo.ConstraintVT = 2384 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true); 2385 break; 2386 } 2387 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) { 2388 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace()); 2389 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize); 2390 } else { 2391 OpInfo.ConstraintVT = MVT::getVT(OpTy, true); 2392 } 2393 } 2394 } 2395 2396 // If we have multiple alternative constraints, select the best alternative. 2397 if (!ConstraintOperands.empty()) { 2398 if (maCount) { 2399 unsigned bestMAIndex = 0; 2400 int bestWeight = -1; 2401 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 2402 int weight = -1; 2403 unsigned maIndex; 2404 // Compute the sums of the weights for each alternative, keeping track 2405 // of the best (highest weight) one so far. 2406 for (maIndex = 0; maIndex < maCount; ++maIndex) { 2407 int weightSum = 0; 2408 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2409 cIndex != eIndex; ++cIndex) { 2410 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex]; 2411 if (OpInfo.Type == InlineAsm::isClobber) 2412 continue; 2413 2414 // If this is an output operand with a matching input operand, 2415 // look up the matching input. If their types mismatch, e.g. one 2416 // is an integer, the other is floating point, or their sizes are 2417 // different, flag it as an maCantMatch. 2418 if (OpInfo.hasMatchingInput()) { 2419 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 2420 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 2421 if ((OpInfo.ConstraintVT.isInteger() != 2422 Input.ConstraintVT.isInteger()) || 2423 (OpInfo.ConstraintVT.getSizeInBits() != 2424 Input.ConstraintVT.getSizeInBits())) { 2425 weightSum = -1; // Can't match. 2426 break; 2427 } 2428 } 2429 } 2430 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 2431 if (weight == -1) { 2432 weightSum = -1; 2433 break; 2434 } 2435 weightSum += weight; 2436 } 2437 // Update best. 2438 if (weightSum > bestWeight) { 2439 bestWeight = weightSum; 2440 bestMAIndex = maIndex; 2441 } 2442 } 2443 2444 // Now select chosen alternative in each constraint. 2445 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2446 cIndex != eIndex; ++cIndex) { 2447 AsmOperandInfo& cInfo = ConstraintOperands[cIndex]; 2448 if (cInfo.Type == InlineAsm::isClobber) 2449 continue; 2450 cInfo.selectAlternative(bestMAIndex); 2451 } 2452 } 2453 } 2454 2455 // Check and hook up tied operands, choose constraint code to use. 2456 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2457 cIndex != eIndex; ++cIndex) { 2458 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex]; 2459 2460 // If this is an output operand with a matching input operand, look up the 2461 // matching input. If their types mismatch, e.g. one is an integer, the 2462 // other is floating point, or their sizes are different, flag it as an 2463 // error. 2464 if (OpInfo.hasMatchingInput()) { 2465 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 2466 2467 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 2468 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 2469 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 2470 OpInfo.ConstraintVT); 2471 std::pair<unsigned, const TargetRegisterClass *> InputRC = 2472 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 2473 Input.ConstraintVT); 2474 if ((OpInfo.ConstraintVT.isInteger() != 2475 Input.ConstraintVT.isInteger()) || 2476 (MatchRC.second != InputRC.second)) { 2477 report_fatal_error("Unsupported asm: input constraint" 2478 " with a matching output constraint of" 2479 " incompatible type!"); 2480 } 2481 } 2482 } 2483 } 2484 2485 return ConstraintOperands; 2486 } 2487 2488 /// Return an integer indicating how general CT is. 2489 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 2490 switch (CT) { 2491 case TargetLowering::C_Other: 2492 case TargetLowering::C_Unknown: 2493 return 0; 2494 case TargetLowering::C_Register: 2495 return 1; 2496 case TargetLowering::C_RegisterClass: 2497 return 2; 2498 case TargetLowering::C_Memory: 2499 return 3; 2500 } 2501 llvm_unreachable("Invalid constraint type"); 2502 } 2503 2504 /// Examine constraint type and operand type and determine a weight value. 2505 /// This object must already have been set up with the operand type 2506 /// and the current alternative constraint selected. 2507 TargetLowering::ConstraintWeight 2508 TargetLowering::getMultipleConstraintMatchWeight( 2509 AsmOperandInfo &info, int maIndex) const { 2510 InlineAsm::ConstraintCodeVector *rCodes; 2511 if (maIndex >= (int)info.multipleAlternatives.size()) 2512 rCodes = &info.Codes; 2513 else 2514 rCodes = &info.multipleAlternatives[maIndex].Codes; 2515 ConstraintWeight BestWeight = CW_Invalid; 2516 2517 // Loop over the options, keeping track of the most general one. 2518 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) { 2519 ConstraintWeight weight = 2520 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str()); 2521 if (weight > BestWeight) 2522 BestWeight = weight; 2523 } 2524 2525 return BestWeight; 2526 } 2527 2528 /// Examine constraint type and operand type and determine a weight value. 2529 /// This object must already have been set up with the operand type 2530 /// and the current alternative constraint selected. 2531 TargetLowering::ConstraintWeight 2532 TargetLowering::getSingleConstraintMatchWeight( 2533 AsmOperandInfo &info, const char *constraint) const { 2534 ConstraintWeight weight = CW_Invalid; 2535 Value *CallOperandVal = info.CallOperandVal; 2536 // If we don't have a value, we can't do a match, 2537 // but allow it at the lowest weight. 2538 if (!CallOperandVal) 2539 return CW_Default; 2540 // Look at the constraint type. 2541 switch (*constraint) { 2542 case 'i': // immediate integer. 2543 case 'n': // immediate integer with a known value. 2544 if (isa<ConstantInt>(CallOperandVal)) 2545 weight = CW_Constant; 2546 break; 2547 case 's': // non-explicit intregal immediate. 2548 if (isa<GlobalValue>(CallOperandVal)) 2549 weight = CW_Constant; 2550 break; 2551 case 'E': // immediate float if host format. 2552 case 'F': // immediate float. 2553 if (isa<ConstantFP>(CallOperandVal)) 2554 weight = CW_Constant; 2555 break; 2556 case '<': // memory operand with autodecrement. 2557 case '>': // memory operand with autoincrement. 2558 case 'm': // memory operand. 2559 case 'o': // offsettable memory operand 2560 case 'V': // non-offsettable memory operand 2561 weight = CW_Memory; 2562 break; 2563 case 'r': // general register. 2564 case 'g': // general register, memory operand or immediate integer. 2565 // note: Clang converts "g" to "imr". 2566 if (CallOperandVal->getType()->isIntegerTy()) 2567 weight = CW_Register; 2568 break; 2569 case 'X': // any operand. 2570 default: 2571 weight = CW_Default; 2572 break; 2573 } 2574 return weight; 2575 } 2576 2577 /// If there are multiple different constraints that we could pick for this 2578 /// operand (e.g. "imr") try to pick the 'best' one. 2579 /// This is somewhat tricky: constraints fall into four classes: 2580 /// Other -> immediates and magic values 2581 /// Register -> one specific register 2582 /// RegisterClass -> a group of regs 2583 /// Memory -> memory 2584 /// Ideally, we would pick the most specific constraint possible: if we have 2585 /// something that fits into a register, we would pick it. The problem here 2586 /// is that if we have something that could either be in a register or in 2587 /// memory that use of the register could cause selection of *other* 2588 /// operands to fail: they might only succeed if we pick memory. Because of 2589 /// this the heuristic we use is: 2590 /// 2591 /// 1) If there is an 'other' constraint, and if the operand is valid for 2592 /// that constraint, use it. This makes us take advantage of 'i' 2593 /// constraints when available. 2594 /// 2) Otherwise, pick the most general constraint present. This prefers 2595 /// 'm' over 'r', for example. 2596 /// 2597 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 2598 const TargetLowering &TLI, 2599 SDValue Op, SelectionDAG *DAG) { 2600 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 2601 unsigned BestIdx = 0; 2602 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 2603 int BestGenerality = -1; 2604 2605 // Loop over the options, keeping track of the most general one. 2606 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 2607 TargetLowering::ConstraintType CType = 2608 TLI.getConstraintType(OpInfo.Codes[i]); 2609 2610 // If this is an 'other' constraint, see if the operand is valid for it. 2611 // For example, on X86 we might have an 'rI' constraint. If the operand 2612 // is an integer in the range [0..31] we want to use I (saving a load 2613 // of a register), otherwise we must use 'r'. 2614 if (CType == TargetLowering::C_Other && Op.getNode()) { 2615 assert(OpInfo.Codes[i].size() == 1 && 2616 "Unhandled multi-letter 'other' constraint"); 2617 std::vector<SDValue> ResultOps; 2618 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 2619 ResultOps, *DAG); 2620 if (!ResultOps.empty()) { 2621 BestType = CType; 2622 BestIdx = i; 2623 break; 2624 } 2625 } 2626 2627 // Things with matching constraints can only be registers, per gcc 2628 // documentation. This mainly affects "g" constraints. 2629 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 2630 continue; 2631 2632 // This constraint letter is more general than the previous one, use it. 2633 int Generality = getConstraintGenerality(CType); 2634 if (Generality > BestGenerality) { 2635 BestType = CType; 2636 BestIdx = i; 2637 BestGenerality = Generality; 2638 } 2639 } 2640 2641 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 2642 OpInfo.ConstraintType = BestType; 2643 } 2644 2645 /// Determines the constraint code and constraint type to use for the specific 2646 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 2647 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 2648 SDValue Op, 2649 SelectionDAG *DAG) const { 2650 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 2651 2652 // Single-letter constraints ('r') are very common. 2653 if (OpInfo.Codes.size() == 1) { 2654 OpInfo.ConstraintCode = OpInfo.Codes[0]; 2655 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 2656 } else { 2657 ChooseConstraint(OpInfo, *this, Op, DAG); 2658 } 2659 2660 // 'X' matches anything. 2661 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 2662 // Labels and constants are handled elsewhere ('X' is the only thing 2663 // that matches labels). For Functions, the type here is the type of 2664 // the result, which is not what we want to look at; leave them alone. 2665 Value *v = OpInfo.CallOperandVal; 2666 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) { 2667 OpInfo.CallOperandVal = v; 2668 return; 2669 } 2670 2671 // Otherwise, try to resolve it to something we know about by looking at 2672 // the actual operand type. 2673 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 2674 OpInfo.ConstraintCode = Repl; 2675 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 2676 } 2677 } 2678 } 2679 2680 /// \brief Given an exact SDIV by a constant, create a multiplication 2681 /// with the multiplicative inverse of the constant. 2682 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d, 2683 SDLoc dl, SelectionDAG &DAG, 2684 std::vector<SDNode *> &Created) { 2685 assert(d != 0 && "Division by zero!"); 2686 2687 // Shift the value upfront if it is even, so the LSB is one. 2688 unsigned ShAmt = d.countTrailingZeros(); 2689 if (ShAmt) { 2690 // TODO: For UDIV use SRL instead of SRA. 2691 SDValue Amt = 2692 DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(), 2693 DAG.getDataLayout())); 2694 SDNodeFlags Flags; 2695 Flags.setExact(true); 2696 Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, &Flags); 2697 Created.push_back(Op1.getNode()); 2698 d = d.ashr(ShAmt); 2699 } 2700 2701 // Calculate the multiplicative inverse, using Newton's method. 2702 APInt t, xn = d; 2703 while ((t = d*xn) != 1) 2704 xn *= APInt(d.getBitWidth(), 2) - t; 2705 2706 SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType()); 2707 SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2); 2708 Created.push_back(Mul.getNode()); 2709 return Mul; 2710 } 2711 2712 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 2713 SelectionDAG &DAG, 2714 std::vector<SDNode *> *Created) const { 2715 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2716 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2717 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 2718 return SDValue(N,0); // Lower SDIV as SDIV 2719 return SDValue(); 2720 } 2721 2722 /// \brief Given an ISD::SDIV node expressing a divide by constant, 2723 /// return a DAG expression to select that will generate the same value by 2724 /// multiplying by a magic number. 2725 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 2726 SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor, 2727 SelectionDAG &DAG, bool IsAfterLegalization, 2728 std::vector<SDNode *> *Created) const { 2729 assert(Created && "No vector to hold sdiv ops."); 2730 2731 EVT VT = N->getValueType(0); 2732 SDLoc dl(N); 2733 2734 // Check to see if we can do this. 2735 // FIXME: We should be more aggressive here. 2736 if (!isTypeLegal(VT)) 2737 return SDValue(); 2738 2739 // If the sdiv has an 'exact' bit we can use a simpler lowering. 2740 if (cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact()) 2741 return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created); 2742 2743 APInt::ms magics = Divisor.magic(); 2744 2745 // Multiply the numerator (operand 0) by the magic value 2746 // FIXME: We should support doing a MUL in a wider type 2747 SDValue Q; 2748 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) : 2749 isOperationLegalOrCustom(ISD::MULHS, VT)) 2750 Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0), 2751 DAG.getConstant(magics.m, dl, VT)); 2752 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) : 2753 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT)) 2754 Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), 2755 N->getOperand(0), 2756 DAG.getConstant(magics.m, dl, VT)).getNode(), 1); 2757 else 2758 return SDValue(); // No mulhs or equvialent 2759 // If d > 0 and m < 0, add the numerator 2760 if (Divisor.isStrictlyPositive() && magics.m.isNegative()) { 2761 Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0)); 2762 Created->push_back(Q.getNode()); 2763 } 2764 // If d < 0 and m > 0, subtract the numerator. 2765 if (Divisor.isNegative() && magics.m.isStrictlyPositive()) { 2766 Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0)); 2767 Created->push_back(Q.getNode()); 2768 } 2769 auto &DL = DAG.getDataLayout(); 2770 // Shift right algebraic if shift value is nonzero 2771 if (magics.s > 0) { 2772 Q = DAG.getNode( 2773 ISD::SRA, dl, VT, Q, 2774 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL))); 2775 Created->push_back(Q.getNode()); 2776 } 2777 // Extract the sign bit and add it to the quotient 2778 SDValue T = 2779 DAG.getNode(ISD::SRL, dl, VT, Q, 2780 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, 2781 getShiftAmountTy(Q.getValueType(), DL))); 2782 Created->push_back(T.getNode()); 2783 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 2784 } 2785 2786 /// \brief Given an ISD::UDIV node expressing a divide by constant, 2787 /// return a DAG expression to select that will generate the same value by 2788 /// multiplying by a magic number. 2789 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 2790 SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor, 2791 SelectionDAG &DAG, bool IsAfterLegalization, 2792 std::vector<SDNode *> *Created) const { 2793 assert(Created && "No vector to hold udiv ops."); 2794 2795 EVT VT = N->getValueType(0); 2796 SDLoc dl(N); 2797 auto &DL = DAG.getDataLayout(); 2798 2799 // Check to see if we can do this. 2800 // FIXME: We should be more aggressive here. 2801 if (!isTypeLegal(VT)) 2802 return SDValue(); 2803 2804 // FIXME: We should use a narrower constant when the upper 2805 // bits are known to be zero. 2806 APInt::mu magics = Divisor.magicu(); 2807 2808 SDValue Q = N->getOperand(0); 2809 2810 // If the divisor is even, we can avoid using the expensive fixup by shifting 2811 // the divided value upfront. 2812 if (magics.a != 0 && !Divisor[0]) { 2813 unsigned Shift = Divisor.countTrailingZeros(); 2814 Q = DAG.getNode( 2815 ISD::SRL, dl, VT, Q, 2816 DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL))); 2817 Created->push_back(Q.getNode()); 2818 2819 // Get magic number for the shifted divisor. 2820 magics = Divisor.lshr(Shift).magicu(Shift); 2821 assert(magics.a == 0 && "Should use cheap fixup now"); 2822 } 2823 2824 // Multiply the numerator (operand 0) by the magic value 2825 // FIXME: We should support doing a MUL in a wider type 2826 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) : 2827 isOperationLegalOrCustom(ISD::MULHU, VT)) 2828 Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT)); 2829 else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) : 2830 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT)) 2831 Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q, 2832 DAG.getConstant(magics.m, dl, VT)).getNode(), 1); 2833 else 2834 return SDValue(); // No mulhu or equvialent 2835 2836 Created->push_back(Q.getNode()); 2837 2838 if (magics.a == 0) { 2839 assert(magics.s < Divisor.getBitWidth() && 2840 "We shouldn't generate an undefined shift!"); 2841 return DAG.getNode( 2842 ISD::SRL, dl, VT, Q, 2843 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL))); 2844 } else { 2845 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q); 2846 Created->push_back(NPQ.getNode()); 2847 NPQ = DAG.getNode( 2848 ISD::SRL, dl, VT, NPQ, 2849 DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL))); 2850 Created->push_back(NPQ.getNode()); 2851 NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 2852 Created->push_back(NPQ.getNode()); 2853 return DAG.getNode( 2854 ISD::SRL, dl, VT, NPQ, 2855 DAG.getConstant(magics.s - 1, dl, 2856 getShiftAmountTy(NPQ.getValueType(), DL))); 2857 } 2858 } 2859 2860 bool TargetLowering:: 2861 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 2862 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 2863 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 2864 "be a constant integer"); 2865 return true; 2866 } 2867 2868 return false; 2869 } 2870 2871 //===----------------------------------------------------------------------===// 2872 // Legalization Utilities 2873 //===----------------------------------------------------------------------===// 2874 2875 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 2876 SelectionDAG &DAG, SDValue LL, SDValue LH, 2877 SDValue RL, SDValue RH) const { 2878 EVT VT = N->getValueType(0); 2879 SDLoc dl(N); 2880 2881 bool HasMULHS = isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 2882 bool HasMULHU = isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 2883 bool HasSMUL_LOHI = isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 2884 bool HasUMUL_LOHI = isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 2885 if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) { 2886 unsigned OuterBitSize = VT.getSizeInBits(); 2887 unsigned InnerBitSize = HiLoVT.getSizeInBits(); 2888 unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0)); 2889 unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1)); 2890 2891 // LL, LH, RL, and RH must be either all NULL or all set to a value. 2892 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 2893 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 2894 2895 if (!LL.getNode() && !RL.getNode() && 2896 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 2897 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(0)); 2898 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(1)); 2899 } 2900 2901 if (!LL.getNode()) 2902 return false; 2903 2904 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 2905 if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) && 2906 DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) { 2907 // The inputs are both zero-extended. 2908 if (HasUMUL_LOHI) { 2909 // We can emit a umul_lohi. 2910 Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL, 2911 RL); 2912 Hi = SDValue(Lo.getNode(), 1); 2913 return true; 2914 } 2915 if (HasMULHU) { 2916 // We can emit a mulhu+mul. 2917 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL); 2918 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL); 2919 return true; 2920 } 2921 } 2922 if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) { 2923 // The input values are both sign-extended. 2924 if (HasSMUL_LOHI) { 2925 // We can emit a smul_lohi. 2926 Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL, 2927 RL); 2928 Hi = SDValue(Lo.getNode(), 1); 2929 return true; 2930 } 2931 if (HasMULHS) { 2932 // We can emit a mulhs+mul. 2933 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL); 2934 Hi = DAG.getNode(ISD::MULHS, dl, HiLoVT, LL, RL); 2935 return true; 2936 } 2937 } 2938 2939 if (!LH.getNode() && !RH.getNode() && 2940 isOperationLegalOrCustom(ISD::SRL, VT) && 2941 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 2942 auto &DL = DAG.getDataLayout(); 2943 unsigned ShiftAmt = VT.getSizeInBits() - HiLoVT.getSizeInBits(); 2944 SDValue Shift = DAG.getConstant(ShiftAmt, dl, getShiftAmountTy(VT, DL)); 2945 LH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(0), Shift); 2946 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 2947 RH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(1), Shift); 2948 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 2949 } 2950 2951 if (!LH.getNode()) 2952 return false; 2953 2954 if (HasUMUL_LOHI) { 2955 // Lo,Hi = umul LHS, RHS. 2956 SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl, 2957 DAG.getVTList(HiLoVT, HiLoVT), LL, RL); 2958 Lo = UMulLOHI; 2959 Hi = UMulLOHI.getValue(1); 2960 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 2961 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 2962 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 2963 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 2964 return true; 2965 } 2966 if (HasMULHU) { 2967 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL); 2968 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL); 2969 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 2970 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 2971 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 2972 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 2973 return true; 2974 } 2975 } 2976 return false; 2977 } 2978 2979 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 2980 SelectionDAG &DAG) const { 2981 EVT VT = Node->getOperand(0).getValueType(); 2982 EVT NVT = Node->getValueType(0); 2983 SDLoc dl(SDValue(Node, 0)); 2984 2985 // FIXME: Only f32 to i64 conversions are supported. 2986 if (VT != MVT::f32 || NVT != MVT::i64) 2987 return false; 2988 2989 // Expand f32 -> i64 conversion 2990 // This algorithm comes from compiler-rt's implementation of fixsfdi: 2991 // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c 2992 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), 2993 VT.getSizeInBits()); 2994 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 2995 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 2996 SDValue Bias = DAG.getConstant(127, dl, IntVT); 2997 SDValue SignMask = DAG.getConstant(APInt::getSignBit(VT.getSizeInBits()), dl, 2998 IntVT); 2999 SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT); 3000 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 3001 3002 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0)); 3003 3004 auto &DL = DAG.getDataLayout(); 3005 SDValue ExponentBits = DAG.getNode( 3006 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 3007 DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL))); 3008 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 3009 3010 SDValue Sign = DAG.getNode( 3011 ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 3012 DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL))); 3013 Sign = DAG.getSExtOrTrunc(Sign, dl, NVT); 3014 3015 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 3016 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 3017 DAG.getConstant(0x00800000, dl, IntVT)); 3018 3019 R = DAG.getZExtOrTrunc(R, dl, NVT); 3020 3021 R = DAG.getSelectCC( 3022 dl, Exponent, ExponentLoBit, 3023 DAG.getNode(ISD::SHL, dl, NVT, R, 3024 DAG.getZExtOrTrunc( 3025 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 3026 dl, getShiftAmountTy(IntVT, DL))), 3027 DAG.getNode(ISD::SRL, dl, NVT, R, 3028 DAG.getZExtOrTrunc( 3029 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 3030 dl, getShiftAmountTy(IntVT, DL))), 3031 ISD::SETGT); 3032 3033 SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT, 3034 DAG.getNode(ISD::XOR, dl, NVT, R, Sign), 3035 Sign); 3036 3037 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 3038 DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT); 3039 return true; 3040 } 3041 3042 //===----------------------------------------------------------------------===// 3043 // Implementation of Emulated TLS Model 3044 //===----------------------------------------------------------------------===// 3045 3046 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 3047 SelectionDAG &DAG) const { 3048 // Access to address of TLS varialbe xyz is lowered to a function call: 3049 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 3050 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3051 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 3052 SDLoc dl(GA); 3053 3054 ArgListTy Args; 3055 ArgListEntry Entry; 3056 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 3057 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 3058 StringRef EmuTlsVarName(NameString); 3059 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 3060 if (!EmuTlsVar) 3061 EmuTlsVar = dyn_cast_or_null<GlobalVariable>( 3062 VariableModule->getOrInsertGlobal(EmuTlsVarName, VoidPtrType)); 3063 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 3064 Entry.Ty = VoidPtrType; 3065 Args.push_back(Entry); 3066 3067 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 3068 3069 TargetLowering::CallLoweringInfo CLI(DAG); 3070 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 3071 CLI.setCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args), 0); 3072 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3073 3074 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 3075 // At last for X86 targets, maybe good for other targets too? 3076 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 3077 MFI->setAdjustsStack(true); // Is this only for X86 target? 3078 MFI->setHasCalls(true); 3079 3080 assert((GA->getOffset() == 0) && 3081 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 3082 return CallResult.first; 3083 } 3084