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