TargetLowering.cpp revision ad4196b44ae714a6b95e238d9d96303df74b0429
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/TargetAsmInfo.h" 15#include "llvm/Target/TargetLowering.h" 16#include "llvm/Target/TargetSubtarget.h" 17#include "llvm/Target/TargetData.h" 18#include "llvm/Target/TargetMachine.h" 19#include "llvm/Target/TargetRegisterInfo.h" 20#include "llvm/GlobalVariable.h" 21#include "llvm/DerivedTypes.h" 22#include "llvm/CodeGen/MachineFrameInfo.h" 23#include "llvm/CodeGen/SelectionDAG.h" 24#include "llvm/ADT/StringExtras.h" 25#include "llvm/ADT/STLExtras.h" 26#include "llvm/Support/MathExtras.h" 27using namespace llvm; 28 29/// InitLibcallNames - Set default libcall names. 30/// 31static void InitLibcallNames(const char **Names) { 32 Names[RTLIB::SHL_I32] = "__ashlsi3"; 33 Names[RTLIB::SHL_I64] = "__ashldi3"; 34 Names[RTLIB::SRL_I32] = "__lshrsi3"; 35 Names[RTLIB::SRL_I64] = "__lshrdi3"; 36 Names[RTLIB::SRA_I32] = "__ashrsi3"; 37 Names[RTLIB::SRA_I64] = "__ashrdi3"; 38 Names[RTLIB::MUL_I32] = "__mulsi3"; 39 Names[RTLIB::MUL_I64] = "__muldi3"; 40 Names[RTLIB::SDIV_I32] = "__divsi3"; 41 Names[RTLIB::SDIV_I64] = "__divdi3"; 42 Names[RTLIB::UDIV_I32] = "__udivsi3"; 43 Names[RTLIB::UDIV_I64] = "__udivdi3"; 44 Names[RTLIB::SREM_I32] = "__modsi3"; 45 Names[RTLIB::SREM_I64] = "__moddi3"; 46 Names[RTLIB::UREM_I32] = "__umodsi3"; 47 Names[RTLIB::UREM_I64] = "__umoddi3"; 48 Names[RTLIB::NEG_I32] = "__negsi2"; 49 Names[RTLIB::NEG_I64] = "__negdi2"; 50 Names[RTLIB::ADD_F32] = "__addsf3"; 51 Names[RTLIB::ADD_F64] = "__adddf3"; 52 Names[RTLIB::ADD_F80] = "__addxf3"; 53 Names[RTLIB::ADD_PPCF128] = "__gcc_qadd"; 54 Names[RTLIB::SUB_F32] = "__subsf3"; 55 Names[RTLIB::SUB_F64] = "__subdf3"; 56 Names[RTLIB::SUB_F80] = "__subxf3"; 57 Names[RTLIB::SUB_PPCF128] = "__gcc_qsub"; 58 Names[RTLIB::MUL_F32] = "__mulsf3"; 59 Names[RTLIB::MUL_F64] = "__muldf3"; 60 Names[RTLIB::MUL_F80] = "__mulxf3"; 61 Names[RTLIB::MUL_PPCF128] = "__gcc_qmul"; 62 Names[RTLIB::DIV_F32] = "__divsf3"; 63 Names[RTLIB::DIV_F64] = "__divdf3"; 64 Names[RTLIB::DIV_F80] = "__divxf3"; 65 Names[RTLIB::DIV_PPCF128] = "__gcc_qdiv"; 66 Names[RTLIB::REM_F32] = "fmodf"; 67 Names[RTLIB::REM_F64] = "fmod"; 68 Names[RTLIB::REM_F80] = "fmodl"; 69 Names[RTLIB::REM_PPCF128] = "fmodl"; 70 Names[RTLIB::POWI_F32] = "__powisf2"; 71 Names[RTLIB::POWI_F64] = "__powidf2"; 72 Names[RTLIB::POWI_F80] = "__powixf2"; 73 Names[RTLIB::POWI_PPCF128] = "__powitf2"; 74 Names[RTLIB::SQRT_F32] = "sqrtf"; 75 Names[RTLIB::SQRT_F64] = "sqrt"; 76 Names[RTLIB::SQRT_F80] = "sqrtl"; 77 Names[RTLIB::SQRT_PPCF128] = "sqrtl"; 78 Names[RTLIB::SIN_F32] = "sinf"; 79 Names[RTLIB::SIN_F64] = "sin"; 80 Names[RTLIB::SIN_F80] = "sinl"; 81 Names[RTLIB::SIN_PPCF128] = "sinl"; 82 Names[RTLIB::COS_F32] = "cosf"; 83 Names[RTLIB::COS_F64] = "cos"; 84 Names[RTLIB::COS_F80] = "cosl"; 85 Names[RTLIB::COS_PPCF128] = "cosl"; 86 Names[RTLIB::POW_F32] = "powf"; 87 Names[RTLIB::POW_F64] = "pow"; 88 Names[RTLIB::POW_F80] = "powl"; 89 Names[RTLIB::POW_PPCF128] = "powl"; 90 Names[RTLIB::FPEXT_F32_F64] = "__extendsfdf2"; 91 Names[RTLIB::FPROUND_F64_F32] = "__truncdfsf2"; 92 Names[RTLIB::FPTOSINT_F32_I32] = "__fixsfsi"; 93 Names[RTLIB::FPTOSINT_F32_I64] = "__fixsfdi"; 94 Names[RTLIB::FPTOSINT_F32_I128] = "__fixsfti"; 95 Names[RTLIB::FPTOSINT_F64_I32] = "__fixdfsi"; 96 Names[RTLIB::FPTOSINT_F64_I64] = "__fixdfdi"; 97 Names[RTLIB::FPTOSINT_F64_I128] = "__fixdfti"; 98 Names[RTLIB::FPTOSINT_F80_I64] = "__fixxfdi"; 99 Names[RTLIB::FPTOSINT_F80_I128] = "__fixxfti"; 100 Names[RTLIB::FPTOSINT_PPCF128_I64] = "__fixtfdi"; 101 Names[RTLIB::FPTOSINT_PPCF128_I128] = "__fixtfti"; 102 Names[RTLIB::FPTOUINT_F32_I32] = "__fixunssfsi"; 103 Names[RTLIB::FPTOUINT_F32_I64] = "__fixunssfdi"; 104 Names[RTLIB::FPTOUINT_F32_I128] = "__fixunssfti"; 105 Names[RTLIB::FPTOUINT_F64_I32] = "__fixunsdfsi"; 106 Names[RTLIB::FPTOUINT_F64_I64] = "__fixunsdfdi"; 107 Names[RTLIB::FPTOUINT_F64_I128] = "__fixunsdfti"; 108 Names[RTLIB::FPTOUINT_F80_I32] = "__fixunsxfsi"; 109 Names[RTLIB::FPTOUINT_F80_I64] = "__fixunsxfdi"; 110 Names[RTLIB::FPTOUINT_F80_I128] = "__fixunsxfti"; 111 Names[RTLIB::FPTOUINT_PPCF128_I64] = "__fixunstfdi"; 112 Names[RTLIB::FPTOUINT_PPCF128_I128] = "__fixunstfti"; 113 Names[RTLIB::SINTTOFP_I32_F32] = "__floatsisf"; 114 Names[RTLIB::SINTTOFP_I32_F64] = "__floatsidf"; 115 Names[RTLIB::SINTTOFP_I64_F32] = "__floatdisf"; 116 Names[RTLIB::SINTTOFP_I64_F64] = "__floatdidf"; 117 Names[RTLIB::SINTTOFP_I64_F80] = "__floatdixf"; 118 Names[RTLIB::SINTTOFP_I64_PPCF128] = "__floatditf"; 119 Names[RTLIB::SINTTOFP_I128_F32] = "__floattisf"; 120 Names[RTLIB::SINTTOFP_I128_F64] = "__floattidf"; 121 Names[RTLIB::SINTTOFP_I128_F80] = "__floattixf"; 122 Names[RTLIB::SINTTOFP_I128_PPCF128] = "__floattitf"; 123 Names[RTLIB::UINTTOFP_I32_F32] = "__floatunsisf"; 124 Names[RTLIB::UINTTOFP_I32_F64] = "__floatunsidf"; 125 Names[RTLIB::UINTTOFP_I64_F32] = "__floatundisf"; 126 Names[RTLIB::UINTTOFP_I64_F64] = "__floatundidf"; 127 Names[RTLIB::OEQ_F32] = "__eqsf2"; 128 Names[RTLIB::OEQ_F64] = "__eqdf2"; 129 Names[RTLIB::UNE_F32] = "__nesf2"; 130 Names[RTLIB::UNE_F64] = "__nedf2"; 131 Names[RTLIB::OGE_F32] = "__gesf2"; 132 Names[RTLIB::OGE_F64] = "__gedf2"; 133 Names[RTLIB::OLT_F32] = "__ltsf2"; 134 Names[RTLIB::OLT_F64] = "__ltdf2"; 135 Names[RTLIB::OLE_F32] = "__lesf2"; 136 Names[RTLIB::OLE_F64] = "__ledf2"; 137 Names[RTLIB::OGT_F32] = "__gtsf2"; 138 Names[RTLIB::OGT_F64] = "__gtdf2"; 139 Names[RTLIB::UO_F32] = "__unordsf2"; 140 Names[RTLIB::UO_F64] = "__unorddf2"; 141 Names[RTLIB::O_F32] = "__unordsf2"; 142 Names[RTLIB::O_F64] = "__unorddf2"; 143} 144 145/// InitCmpLibcallCCs - Set default comparison libcall CC. 146/// 147static void InitCmpLibcallCCs(ISD::CondCode *CCs) { 148 memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL); 149 CCs[RTLIB::OEQ_F32] = ISD::SETEQ; 150 CCs[RTLIB::OEQ_F64] = ISD::SETEQ; 151 CCs[RTLIB::UNE_F32] = ISD::SETNE; 152 CCs[RTLIB::UNE_F64] = ISD::SETNE; 153 CCs[RTLIB::OGE_F32] = ISD::SETGE; 154 CCs[RTLIB::OGE_F64] = ISD::SETGE; 155 CCs[RTLIB::OLT_F32] = ISD::SETLT; 156 CCs[RTLIB::OLT_F64] = ISD::SETLT; 157 CCs[RTLIB::OLE_F32] = ISD::SETLE; 158 CCs[RTLIB::OLE_F64] = ISD::SETLE; 159 CCs[RTLIB::OGT_F32] = ISD::SETGT; 160 CCs[RTLIB::OGT_F64] = ISD::SETGT; 161 CCs[RTLIB::UO_F32] = ISD::SETNE; 162 CCs[RTLIB::UO_F64] = ISD::SETNE; 163 CCs[RTLIB::O_F32] = ISD::SETEQ; 164 CCs[RTLIB::O_F64] = ISD::SETEQ; 165} 166 167TargetLowering::TargetLowering(TargetMachine &tm) 168 : TM(tm), TD(TM.getTargetData()) { 169 assert(ISD::BUILTIN_OP_END <= OpActionsCapacity && 170 "Fixed size array in TargetLowering is not large enough!"); 171 // All operations default to being supported. 172 memset(OpActions, 0, sizeof(OpActions)); 173 memset(LoadXActions, 0, sizeof(LoadXActions)); 174 memset(TruncStoreActions, 0, sizeof(TruncStoreActions)); 175 memset(IndexedModeActions, 0, sizeof(IndexedModeActions)); 176 memset(ConvertActions, 0, sizeof(ConvertActions)); 177 178 // Set default actions for various operations. 179 for (unsigned VT = 0; VT != (unsigned)MVT::LAST_VALUETYPE; ++VT) { 180 // Default all indexed load / store to expand. 181 for (unsigned IM = (unsigned)ISD::PRE_INC; 182 IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) { 183 setIndexedLoadAction(IM, (MVT::ValueType)VT, Expand); 184 setIndexedStoreAction(IM, (MVT::ValueType)VT, Expand); 185 } 186 187 // These operations default to expand. 188 setOperationAction(ISD::FGETSIGN, (MVT::ValueType)VT, Expand); 189 } 190 191 // Most targets ignore the @llvm.prefetch intrinsic. 192 setOperationAction(ISD::PREFETCH, MVT::Other, Expand); 193 194 // ConstantFP nodes default to expand. Targets can either change this to 195 // Legal, in which case all fp constants are legal, or use addLegalFPImmediate 196 // to optimize expansions for certain constants. 197 setOperationAction(ISD::ConstantFP, MVT::f32, Expand); 198 setOperationAction(ISD::ConstantFP, MVT::f64, Expand); 199 setOperationAction(ISD::ConstantFP, MVT::f80, Expand); 200 201 // Default ISD::TRAP to expand (which turns it into abort). 202 setOperationAction(ISD::TRAP, MVT::Other, Expand); 203 204 IsLittleEndian = TD->isLittleEndian(); 205 UsesGlobalOffsetTable = false; 206 ShiftAmountTy = PointerTy = getValueType(TD->getIntPtrType()); 207 ShiftAmtHandling = Undefined; 208 memset(RegClassForVT, 0,MVT::LAST_VALUETYPE*sizeof(TargetRegisterClass*)); 209 memset(TargetDAGCombineArray, 0, array_lengthof(TargetDAGCombineArray)); 210 maxStoresPerMemset = maxStoresPerMemcpy = maxStoresPerMemmove = 8; 211 allowUnalignedMemoryAccesses = false; 212 UseUnderscoreSetJmp = false; 213 UseUnderscoreLongJmp = false; 214 SelectIsExpensive = false; 215 IntDivIsCheap = false; 216 Pow2DivIsCheap = false; 217 StackPointerRegisterToSaveRestore = 0; 218 ExceptionPointerRegister = 0; 219 ExceptionSelectorRegister = 0; 220 SetCCResultContents = UndefinedSetCCResult; 221 SchedPreferenceInfo = SchedulingForLatency; 222 JumpBufSize = 0; 223 JumpBufAlignment = 0; 224 IfCvtBlockSizeLimit = 2; 225 IfCvtDupBlockSizeLimit = 0; 226 PrefLoopAlignment = 0; 227 228 InitLibcallNames(LibcallRoutineNames); 229 InitCmpLibcallCCs(CmpLibcallCCs); 230 231 // Tell Legalize whether the assembler supports DEBUG_LOC. 232 if (!TM.getTargetAsmInfo()->hasDotLocAndDotFile()) 233 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand); 234} 235 236TargetLowering::~TargetLowering() {} 237 238/// computeRegisterProperties - Once all of the register classes are added, 239/// this allows us to compute derived properties we expose. 240void TargetLowering::computeRegisterProperties() { 241 assert(MVT::LAST_VALUETYPE <= 32 && 242 "Too many value types for ValueTypeActions to hold!"); 243 244 // Everything defaults to needing one register. 245 for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) { 246 NumRegistersForVT[i] = 1; 247 RegisterTypeForVT[i] = TransformToType[i] = i; 248 } 249 // ...except isVoid, which doesn't need any registers. 250 NumRegistersForVT[MVT::isVoid] = 0; 251 252 // Find the largest integer register class. 253 unsigned LargestIntReg = MVT::i128; 254 for (; RegClassForVT[LargestIntReg] == 0; --LargestIntReg) 255 assert(LargestIntReg != MVT::i1 && "No integer registers defined!"); 256 257 // Every integer value type larger than this largest register takes twice as 258 // many registers to represent as the previous ValueType. 259 for (MVT::ValueType ExpandedReg = LargestIntReg + 1; 260 MVT::isInteger(ExpandedReg); ++ExpandedReg) { 261 NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1]; 262 RegisterTypeForVT[ExpandedReg] = LargestIntReg; 263 TransformToType[ExpandedReg] = ExpandedReg - 1; 264 ValueTypeActions.setTypeAction(ExpandedReg, Expand); 265 } 266 267 // Inspect all of the ValueType's smaller than the largest integer 268 // register to see which ones need promotion. 269 MVT::ValueType LegalIntReg = LargestIntReg; 270 for (MVT::ValueType IntReg = LargestIntReg - 1; 271 IntReg >= MVT::i1; --IntReg) { 272 if (isTypeLegal(IntReg)) { 273 LegalIntReg = IntReg; 274 } else { 275 RegisterTypeForVT[IntReg] = TransformToType[IntReg] = LegalIntReg; 276 ValueTypeActions.setTypeAction(IntReg, Promote); 277 } 278 } 279 280 // ppcf128 type is really two f64's. 281 if (!isTypeLegal(MVT::ppcf128)) { 282 NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64]; 283 RegisterTypeForVT[MVT::ppcf128] = MVT::f64; 284 TransformToType[MVT::ppcf128] = MVT::f64; 285 ValueTypeActions.setTypeAction(MVT::ppcf128, Expand); 286 } 287 288 // Decide how to handle f64. If the target does not have native f64 support, 289 // expand it to i64 and we will be generating soft float library calls. 290 if (!isTypeLegal(MVT::f64)) { 291 NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64]; 292 RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64]; 293 TransformToType[MVT::f64] = MVT::i64; 294 ValueTypeActions.setTypeAction(MVT::f64, Expand); 295 } 296 297 // Decide how to handle f32. If the target does not have native support for 298 // f32, promote it to f64 if it is legal. Otherwise, expand it to i32. 299 if (!isTypeLegal(MVT::f32)) { 300 if (isTypeLegal(MVT::f64)) { 301 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::f64]; 302 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::f64]; 303 TransformToType[MVT::f32] = MVT::f64; 304 ValueTypeActions.setTypeAction(MVT::f32, Promote); 305 } else { 306 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32]; 307 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32]; 308 TransformToType[MVT::f32] = MVT::i32; 309 ValueTypeActions.setTypeAction(MVT::f32, Expand); 310 } 311 } 312 313 // Loop over all of the vector value types to see which need transformations. 314 for (MVT::ValueType i = MVT::FIRST_VECTOR_VALUETYPE; 315 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) { 316 if (!isTypeLegal(i)) { 317 MVT::ValueType IntermediateVT, RegisterVT; 318 unsigned NumIntermediates; 319 NumRegistersForVT[i] = 320 getVectorTypeBreakdown(i, 321 IntermediateVT, NumIntermediates, 322 RegisterVT); 323 RegisterTypeForVT[i] = RegisterVT; 324 TransformToType[i] = MVT::Other; // this isn't actually used 325 ValueTypeActions.setTypeAction(i, Expand); 326 } 327 } 328} 329 330const char *TargetLowering::getTargetNodeName(unsigned Opcode) const { 331 return NULL; 332} 333 334 335MVT::ValueType 336TargetLowering::getSetCCResultType(const SDOperand &) const { 337 return getValueType(TD->getIntPtrType()); 338} 339 340 341/// getVectorTypeBreakdown - Vector types are broken down into some number of 342/// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32 343/// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack. 344/// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86. 345/// 346/// This method returns the number of registers needed, and the VT for each 347/// register. It also returns the VT and quantity of the intermediate values 348/// before they are promoted/expanded. 349/// 350unsigned TargetLowering::getVectorTypeBreakdown(MVT::ValueType VT, 351 MVT::ValueType &IntermediateVT, 352 unsigned &NumIntermediates, 353 MVT::ValueType &RegisterVT) const { 354 // Figure out the right, legal destination reg to copy into. 355 unsigned NumElts = MVT::getVectorNumElements(VT); 356 MVT::ValueType EltTy = MVT::getVectorElementType(VT); 357 358 unsigned NumVectorRegs = 1; 359 360 // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we 361 // could break down into LHS/RHS like LegalizeDAG does. 362 if (!isPowerOf2_32(NumElts)) { 363 NumVectorRegs = NumElts; 364 NumElts = 1; 365 } 366 367 // Divide the input until we get to a supported size. This will always 368 // end with a scalar if the target doesn't support vectors. 369 while (NumElts > 1 && 370 !isTypeLegal(MVT::getVectorType(EltTy, NumElts))) { 371 NumElts >>= 1; 372 NumVectorRegs <<= 1; 373 } 374 375 NumIntermediates = NumVectorRegs; 376 377 MVT::ValueType NewVT = MVT::getVectorType(EltTy, NumElts); 378 if (!isTypeLegal(NewVT)) 379 NewVT = EltTy; 380 IntermediateVT = NewVT; 381 382 MVT::ValueType DestVT = getTypeToTransformTo(NewVT); 383 RegisterVT = DestVT; 384 if (DestVT < NewVT) { 385 // Value is expanded, e.g. i64 -> i16. 386 return NumVectorRegs*(MVT::getSizeInBits(NewVT)/MVT::getSizeInBits(DestVT)); 387 } else { 388 // Otherwise, promotion or legal types use the same number of registers as 389 // the vector decimated to the appropriate level. 390 return NumVectorRegs; 391 } 392 393 return 1; 394} 395 396/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 397/// function arguments in the caller parameter area. This is the actual 398/// alignment, not its logarithm. 399unsigned TargetLowering::getByValTypeAlignment(const Type *Ty) const { 400 return TD->getCallFrameTypeAlignment(Ty); 401} 402 403SDOperand TargetLowering::getPICJumpTableRelocBase(SDOperand Table, 404 SelectionDAG &DAG) const { 405 if (usesGlobalOffsetTable()) 406 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy()); 407 return Table; 408} 409 410//===----------------------------------------------------------------------===// 411// Optimization Methods 412//===----------------------------------------------------------------------===// 413 414/// ShrinkDemandedConstant - Check to see if the specified operand of the 415/// specified instruction is a constant integer. If so, check to see if there 416/// are any bits set in the constant that are not demanded. If so, shrink the 417/// constant and return true. 418bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDOperand Op, 419 const APInt &Demanded) { 420 // FIXME: ISD::SELECT, ISD::SELECT_CC 421 switch(Op.getOpcode()) { 422 default: break; 423 case ISD::AND: 424 case ISD::OR: 425 case ISD::XOR: 426 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 427 if (C->getAPIntValue().intersects(~Demanded)) { 428 MVT::ValueType VT = Op.getValueType(); 429 SDOperand New = DAG.getNode(Op.getOpcode(), VT, Op.getOperand(0), 430 DAG.getConstant(Demanded & 431 C->getAPIntValue(), 432 VT)); 433 return CombineTo(Op, New); 434 } 435 break; 436 } 437 return false; 438} 439 440/// SimplifyDemandedBits - Look at Op. At this point, we know that only the 441/// DemandedMask bits of the result of Op are ever used downstream. If we can 442/// use this information to simplify Op, create a new simplified DAG node and 443/// return true, returning the original and new nodes in Old and New. Otherwise, 444/// analyze the expression and return a mask of KnownOne and KnownZero bits for 445/// the expression (used to simplify the caller). The KnownZero/One bits may 446/// only be accurate for those bits in the DemandedMask. 447bool TargetLowering::SimplifyDemandedBits(SDOperand Op, 448 const APInt &DemandedMask, 449 APInt &KnownZero, 450 APInt &KnownOne, 451 TargetLoweringOpt &TLO, 452 unsigned Depth) const { 453 unsigned BitWidth = DemandedMask.getBitWidth(); 454 assert(Op.getValueSizeInBits() == BitWidth && 455 "Mask size mismatches value type size!"); 456 APInt NewMask = DemandedMask; 457 458 // Don't know anything. 459 KnownZero = KnownOne = APInt(BitWidth, 0); 460 461 // Other users may use these bits. 462 if (!Op.Val->hasOneUse()) { 463 if (Depth != 0) { 464 // If not at the root, Just compute the KnownZero/KnownOne bits to 465 // simplify things downstream. 466 TLO.DAG.ComputeMaskedBits(Op, DemandedMask, KnownZero, KnownOne, Depth); 467 return false; 468 } 469 // If this is the root being simplified, allow it to have multiple uses, 470 // just set the NewMask to all bits. 471 NewMask = APInt::getAllOnesValue(BitWidth); 472 } else if (DemandedMask == 0) { 473 // Not demanding any bits from Op. 474 if (Op.getOpcode() != ISD::UNDEF) 475 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::UNDEF, Op.getValueType())); 476 return false; 477 } else if (Depth == 6) { // Limit search depth. 478 return false; 479 } 480 481 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut; 482 switch (Op.getOpcode()) { 483 case ISD::Constant: 484 // We know all of the bits for a constant! 485 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & NewMask; 486 KnownZero = ~KnownOne & NewMask; 487 return false; // Don't fall through, will infinitely loop. 488 case ISD::AND: 489 // If the RHS is a constant, check to see if the LHS would be zero without 490 // using the bits from the RHS. Below, we use knowledge about the RHS to 491 // simplify the LHS, here we're using information from the LHS to simplify 492 // the RHS. 493 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 494 APInt LHSZero, LHSOne; 495 TLO.DAG.ComputeMaskedBits(Op.getOperand(0), NewMask, 496 LHSZero, LHSOne, Depth+1); 497 // If the LHS already has zeros where RHSC does, this and is dead. 498 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask)) 499 return TLO.CombineTo(Op, Op.getOperand(0)); 500 // If any of the set bits in the RHS are known zero on the LHS, shrink 501 // the constant. 502 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask)) 503 return true; 504 } 505 506 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero, 507 KnownOne, TLO, Depth+1)) 508 return true; 509 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 510 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask, 511 KnownZero2, KnownOne2, TLO, Depth+1)) 512 return true; 513 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 514 515 // If all of the demanded bits are known one on one side, return the other. 516 // These bits cannot contribute to the result of the 'and'. 517 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask)) 518 return TLO.CombineTo(Op, Op.getOperand(0)); 519 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask)) 520 return TLO.CombineTo(Op, Op.getOperand(1)); 521 // If all of the demanded bits in the inputs are known zeros, return zero. 522 if ((NewMask & (KnownZero|KnownZero2)) == NewMask) 523 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType())); 524 // If the RHS is a constant, see if we can simplify it. 525 if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask)) 526 return true; 527 528 // Output known-1 bits are only known if set in both the LHS & RHS. 529 KnownOne &= KnownOne2; 530 // Output known-0 are known to be clear if zero in either the LHS | RHS. 531 KnownZero |= KnownZero2; 532 break; 533 case ISD::OR: 534 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero, 535 KnownOne, TLO, Depth+1)) 536 return true; 537 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 538 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask, 539 KnownZero2, KnownOne2, TLO, Depth+1)) 540 return true; 541 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 542 543 // If all of the demanded bits are known zero on one side, return the other. 544 // These bits cannot contribute to the result of the 'or'. 545 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask)) 546 return TLO.CombineTo(Op, Op.getOperand(0)); 547 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask)) 548 return TLO.CombineTo(Op, Op.getOperand(1)); 549 // If all of the potentially set bits on one side are known to be set on 550 // the other side, just use the 'other' side. 551 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask)) 552 return TLO.CombineTo(Op, Op.getOperand(0)); 553 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask)) 554 return TLO.CombineTo(Op, Op.getOperand(1)); 555 // If the RHS is a constant, see if we can simplify it. 556 if (TLO.ShrinkDemandedConstant(Op, NewMask)) 557 return true; 558 559 // Output known-0 bits are only known if clear in both the LHS & RHS. 560 KnownZero &= KnownZero2; 561 // Output known-1 are known to be set if set in either the LHS | RHS. 562 KnownOne |= KnownOne2; 563 break; 564 case ISD::XOR: 565 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero, 566 KnownOne, TLO, Depth+1)) 567 return true; 568 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 569 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2, 570 KnownOne2, TLO, Depth+1)) 571 return true; 572 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 573 574 // If all of the demanded bits are known zero on one side, return the other. 575 // These bits cannot contribute to the result of the 'xor'. 576 if ((KnownZero & NewMask) == NewMask) 577 return TLO.CombineTo(Op, Op.getOperand(0)); 578 if ((KnownZero2 & NewMask) == NewMask) 579 return TLO.CombineTo(Op, Op.getOperand(1)); 580 581 // If all of the unknown bits are known to be zero on one side or the other 582 // (but not both) turn this into an *inclusive* or. 583 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 584 if ((NewMask & ~KnownZero & ~KnownZero2) == 0) 585 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, Op.getValueType(), 586 Op.getOperand(0), 587 Op.getOperand(1))); 588 589 // Output known-0 bits are known if clear or set in both the LHS & RHS. 590 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2); 591 // Output known-1 are known to be set if set in only one of the LHS, RHS. 592 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2); 593 594 // If all of the demanded bits on one side are known, and all of the set 595 // bits on that side are also known to be set on the other side, turn this 596 // into an AND, as we know the bits will be cleared. 597 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 598 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known 599 if ((KnownOne & KnownOne2) == KnownOne) { 600 MVT::ValueType VT = Op.getValueType(); 601 SDOperand ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, VT); 602 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, VT, Op.getOperand(0), 603 ANDC)); 604 } 605 } 606 607 // If the RHS is a constant, see if we can simplify it. 608 // for XOR, we prefer to force bits to 1 if they will make a -1. 609 // if we can't force bits, try to shrink constant 610 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 611 APInt Expanded = C->getAPIntValue() | (~NewMask); 612 // if we can expand it to have all bits set, do it 613 if (Expanded.isAllOnesValue()) { 614 if (Expanded != C->getAPIntValue()) { 615 MVT::ValueType VT = Op.getValueType(); 616 SDOperand New = TLO.DAG.getNode(Op.getOpcode(), VT, Op.getOperand(0), 617 TLO.DAG.getConstant(Expanded, VT)); 618 return TLO.CombineTo(Op, New); 619 } 620 // if it already has all the bits set, nothing to change 621 // but don't shrink either! 622 } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) { 623 return true; 624 } 625 } 626 627 KnownZero = KnownZeroOut; 628 KnownOne = KnownOneOut; 629 break; 630 case ISD::SELECT: 631 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero, 632 KnownOne, TLO, Depth+1)) 633 return true; 634 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2, 635 KnownOne2, TLO, Depth+1)) 636 return true; 637 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 638 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 639 640 // If the operands are constants, see if we can simplify them. 641 if (TLO.ShrinkDemandedConstant(Op, NewMask)) 642 return true; 643 644 // Only known if known in both the LHS and RHS. 645 KnownOne &= KnownOne2; 646 KnownZero &= KnownZero2; 647 break; 648 case ISD::SELECT_CC: 649 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero, 650 KnownOne, TLO, Depth+1)) 651 return true; 652 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2, 653 KnownOne2, TLO, Depth+1)) 654 return true; 655 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 656 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 657 658 // If the operands are constants, see if we can simplify them. 659 if (TLO.ShrinkDemandedConstant(Op, NewMask)) 660 return true; 661 662 // Only known if known in both the LHS and RHS. 663 KnownOne &= KnownOne2; 664 KnownZero &= KnownZero2; 665 break; 666 case ISD::SHL: 667 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 668 unsigned ShAmt = SA->getValue(); 669 SDOperand InOp = Op.getOperand(0); 670 671 // If the shift count is an invalid immediate, don't do anything. 672 if (ShAmt >= BitWidth) 673 break; 674 675 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 676 // single shift. We can do this if the bottom bits (which are shifted 677 // out) are never demanded. 678 if (InOp.getOpcode() == ISD::SRL && 679 isa<ConstantSDNode>(InOp.getOperand(1))) { 680 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) { 681 unsigned C1 = cast<ConstantSDNode>(InOp.getOperand(1))->getValue(); 682 unsigned Opc = ISD::SHL; 683 int Diff = ShAmt-C1; 684 if (Diff < 0) { 685 Diff = -Diff; 686 Opc = ISD::SRL; 687 } 688 689 SDOperand NewSA = 690 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType()); 691 MVT::ValueType VT = Op.getValueType(); 692 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, VT, 693 InOp.getOperand(0), NewSA)); 694 } 695 } 696 697 if (SimplifyDemandedBits(Op.getOperand(0), NewMask.lshr(ShAmt), 698 KnownZero, KnownOne, TLO, Depth+1)) 699 return true; 700 KnownZero <<= SA->getValue(); 701 KnownOne <<= SA->getValue(); 702 // low bits known zero. 703 KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getValue()); 704 } 705 break; 706 case ISD::SRL: 707 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 708 MVT::ValueType VT = Op.getValueType(); 709 unsigned ShAmt = SA->getValue(); 710 unsigned VTSize = MVT::getSizeInBits(VT); 711 SDOperand InOp = Op.getOperand(0); 712 713 // If the shift count is an invalid immediate, don't do anything. 714 if (ShAmt >= BitWidth) 715 break; 716 717 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 718 // single shift. We can do this if the top bits (which are shifted out) 719 // are never demanded. 720 if (InOp.getOpcode() == ISD::SHL && 721 isa<ConstantSDNode>(InOp.getOperand(1))) { 722 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) { 723 unsigned C1 = cast<ConstantSDNode>(InOp.getOperand(1))->getValue(); 724 unsigned Opc = ISD::SRL; 725 int Diff = ShAmt-C1; 726 if (Diff < 0) { 727 Diff = -Diff; 728 Opc = ISD::SHL; 729 } 730 731 SDOperand NewSA = 732 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType()); 733 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, VT, 734 InOp.getOperand(0), NewSA)); 735 } 736 } 737 738 // Compute the new bits that are at the top now. 739 if (SimplifyDemandedBits(InOp, (NewMask << ShAmt), 740 KnownZero, KnownOne, TLO, Depth+1)) 741 return true; 742 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 743 KnownZero = KnownZero.lshr(ShAmt); 744 KnownOne = KnownOne.lshr(ShAmt); 745 746 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 747 KnownZero |= HighBits; // High bits known zero. 748 } 749 break; 750 case ISD::SRA: 751 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 752 MVT::ValueType VT = Op.getValueType(); 753 unsigned ShAmt = SA->getValue(); 754 755 // If the shift count is an invalid immediate, don't do anything. 756 if (ShAmt >= BitWidth) 757 break; 758 759 APInt InDemandedMask = (NewMask << ShAmt); 760 761 // If any of the demanded bits are produced by the sign extension, we also 762 // demand the input sign bit. 763 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 764 if (HighBits.intersects(NewMask)) 765 InDemandedMask |= APInt::getSignBit(MVT::getSizeInBits(VT)); 766 767 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask, 768 KnownZero, KnownOne, TLO, Depth+1)) 769 return true; 770 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 771 KnownZero = KnownZero.lshr(ShAmt); 772 KnownOne = KnownOne.lshr(ShAmt); 773 774 // Handle the sign bit, adjusted to where it is now in the mask. 775 APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt); 776 777 // If the input sign bit is known to be zero, or if none of the top bits 778 // are demanded, turn this into an unsigned shift right. 779 if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) { 780 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, VT, Op.getOperand(0), 781 Op.getOperand(1))); 782 } else if (KnownOne.intersects(SignBit)) { // New bits are known one. 783 KnownOne |= HighBits; 784 } 785 } 786 break; 787 case ISD::SIGN_EXTEND_INREG: { 788 MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 789 790 // Sign extension. Compute the demanded bits in the result that are not 791 // present in the input. 792 APInt NewBits = APInt::getHighBitsSet(BitWidth, 793 BitWidth - MVT::getSizeInBits(EVT)) & 794 NewMask; 795 796 // If none of the extended bits are demanded, eliminate the sextinreg. 797 if (NewBits == 0) 798 return TLO.CombineTo(Op, Op.getOperand(0)); 799 800 APInt InSignBit = APInt::getSignBit(MVT::getSizeInBits(EVT)); 801 InSignBit.zext(BitWidth); 802 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, 803 MVT::getSizeInBits(EVT)) & 804 NewMask; 805 806 // Since the sign extended bits are demanded, we know that the sign 807 // bit is demanded. 808 InputDemandedBits |= InSignBit; 809 810 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits, 811 KnownZero, KnownOne, TLO, Depth+1)) 812 return true; 813 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 814 815 // If the sign bit of the input is known set or clear, then we know the 816 // top bits of the result. 817 818 // If the input sign bit is known zero, convert this into a zero extension. 819 if (KnownZero.intersects(InSignBit)) 820 return TLO.CombineTo(Op, 821 TLO.DAG.getZeroExtendInReg(Op.getOperand(0), EVT)); 822 823 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set 824 KnownOne |= NewBits; 825 KnownZero &= ~NewBits; 826 } else { // Input sign bit unknown 827 KnownZero &= ~NewBits; 828 KnownOne &= ~NewBits; 829 } 830 break; 831 } 832 case ISD::ZERO_EXTEND: { 833 unsigned OperandBitWidth = Op.getOperand(0).getValueSizeInBits(); 834 APInt InMask = NewMask; 835 InMask.trunc(OperandBitWidth); 836 837 // If none of the top bits are demanded, convert this into an any_extend. 838 APInt NewBits = 839 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask; 840 if (!NewBits.intersects(NewMask)) 841 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, 842 Op.getValueType(), 843 Op.getOperand(0))); 844 845 if (SimplifyDemandedBits(Op.getOperand(0), InMask, 846 KnownZero, KnownOne, TLO, Depth+1)) 847 return true; 848 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 849 KnownZero.zext(BitWidth); 850 KnownOne.zext(BitWidth); 851 KnownZero |= NewBits; 852 break; 853 } 854 case ISD::SIGN_EXTEND: { 855 MVT::ValueType InVT = Op.getOperand(0).getValueType(); 856 unsigned InBits = MVT::getSizeInBits(InVT); 857 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits); 858 APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits); 859 APInt NewBits = ~InMask & NewMask; 860 861 // If none of the top bits are demanded, convert this into an any_extend. 862 if (NewBits == 0) 863 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND,Op.getValueType(), 864 Op.getOperand(0))); 865 866 // Since some of the sign extended bits are demanded, we know that the sign 867 // bit is demanded. 868 APInt InDemandedBits = InMask & NewMask; 869 InDemandedBits |= InSignBit; 870 InDemandedBits.trunc(InBits); 871 872 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero, 873 KnownOne, TLO, Depth+1)) 874 return true; 875 KnownZero.zext(BitWidth); 876 KnownOne.zext(BitWidth); 877 878 // If the sign bit is known zero, convert this to a zero extend. 879 if (KnownZero.intersects(InSignBit)) 880 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, 881 Op.getValueType(), 882 Op.getOperand(0))); 883 884 // If the sign bit is known one, the top bits match. 885 if (KnownOne.intersects(InSignBit)) { 886 KnownOne |= NewBits; 887 KnownZero &= ~NewBits; 888 } else { // Otherwise, top bits aren't known. 889 KnownOne &= ~NewBits; 890 KnownZero &= ~NewBits; 891 } 892 break; 893 } 894 case ISD::ANY_EXTEND: { 895 unsigned OperandBitWidth = Op.getOperand(0).getValueSizeInBits(); 896 APInt InMask = NewMask; 897 InMask.trunc(OperandBitWidth); 898 if (SimplifyDemandedBits(Op.getOperand(0), InMask, 899 KnownZero, KnownOne, TLO, Depth+1)) 900 return true; 901 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 902 KnownZero.zext(BitWidth); 903 KnownOne.zext(BitWidth); 904 break; 905 } 906 case ISD::TRUNCATE: { 907 // Simplify the input, using demanded bit information, and compute the known 908 // zero/one bits live out. 909 APInt TruncMask = NewMask; 910 TruncMask.zext(Op.getOperand(0).getValueSizeInBits()); 911 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask, 912 KnownZero, KnownOne, TLO, Depth+1)) 913 return true; 914 KnownZero.trunc(BitWidth); 915 KnownOne.trunc(BitWidth); 916 917 // If the input is only used by this truncate, see if we can shrink it based 918 // on the known demanded bits. 919 if (Op.getOperand(0).Val->hasOneUse()) { 920 SDOperand In = Op.getOperand(0); 921 unsigned InBitWidth = In.getValueSizeInBits(); 922 switch (In.getOpcode()) { 923 default: break; 924 case ISD::SRL: 925 // Shrink SRL by a constant if none of the high bits shifted in are 926 // demanded. 927 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1))){ 928 APInt HighBits = APInt::getHighBitsSet(InBitWidth, 929 InBitWidth - BitWidth); 930 HighBits = HighBits.lshr(ShAmt->getValue()); 931 HighBits.trunc(BitWidth); 932 933 if (ShAmt->getValue() < BitWidth && !(HighBits & NewMask)) { 934 // None of the shifted in bits are needed. Add a truncate of the 935 // shift input, then shift it. 936 SDOperand NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, 937 Op.getValueType(), 938 In.getOperand(0)); 939 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL,Op.getValueType(), 940 NewTrunc, In.getOperand(1))); 941 } 942 } 943 break; 944 } 945 } 946 947 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 948 break; 949 } 950 case ISD::AssertZext: { 951 MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 952 APInt InMask = APInt::getLowBitsSet(BitWidth, 953 MVT::getSizeInBits(VT)); 954 if (SimplifyDemandedBits(Op.getOperand(0), InMask & NewMask, 955 KnownZero, KnownOne, TLO, Depth+1)) 956 return true; 957 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 958 KnownZero |= ~InMask & NewMask; 959 break; 960 } 961 case ISD::BIT_CONVERT: 962#if 0 963 // If this is an FP->Int bitcast and if the sign bit is the only thing that 964 // is demanded, turn this into a FGETSIGN. 965 if (NewMask == MVT::getIntVTSignBit(Op.getValueType()) && 966 MVT::isFloatingPoint(Op.getOperand(0).getValueType()) && 967 !MVT::isVector(Op.getOperand(0).getValueType())) { 968 // Only do this xform if FGETSIGN is valid or if before legalize. 969 if (!TLO.AfterLegalize || 970 isOperationLegal(ISD::FGETSIGN, Op.getValueType())) { 971 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 972 // place. We expect the SHL to be eliminated by other optimizations. 973 SDOperand Sign = TLO.DAG.getNode(ISD::FGETSIGN, Op.getValueType(), 974 Op.getOperand(0)); 975 unsigned ShVal = MVT::getSizeInBits(Op.getValueType())-1; 976 SDOperand ShAmt = TLO.DAG.getConstant(ShVal, getShiftAmountTy()); 977 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, Op.getValueType(), 978 Sign, ShAmt)); 979 } 980 } 981#endif 982 break; 983 default: 984 // Just use ComputeMaskedBits to compute output bits. 985 TLO.DAG.ComputeMaskedBits(Op, NewMask, KnownZero, KnownOne, Depth); 986 break; 987 } 988 989 // If we know the value of all of the demanded bits, return this as a 990 // constant. 991 if ((NewMask & (KnownZero|KnownOne)) == NewMask) 992 return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType())); 993 994 return false; 995} 996 997/// computeMaskedBitsForTargetNode - Determine which of the bits specified 998/// in Mask are known to be either zero or one and return them in the 999/// KnownZero/KnownOne bitsets. 1000void TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op, 1001 const APInt &Mask, 1002 APInt &KnownZero, 1003 APInt &KnownOne, 1004 const SelectionDAG &DAG, 1005 unsigned Depth) const { 1006 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 1007 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1008 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 1009 Op.getOpcode() == ISD::INTRINSIC_VOID) && 1010 "Should use MaskedValueIsZero if you don't know whether Op" 1011 " is a target node!"); 1012 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); 1013} 1014 1015/// ComputeNumSignBitsForTargetNode - This method can be implemented by 1016/// targets that want to expose additional information about sign bits to the 1017/// DAG Combiner. 1018unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDOperand Op, 1019 unsigned Depth) const { 1020 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 1021 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1022 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 1023 Op.getOpcode() == ISD::INTRINSIC_VOID) && 1024 "Should use ComputeNumSignBits if you don't know whether Op" 1025 " is a target node!"); 1026 return 1; 1027} 1028 1029 1030/// SimplifySetCC - Try to simplify a setcc built with the specified operands 1031/// and cc. If it is unable to simplify it, return a null SDOperand. 1032SDOperand 1033TargetLowering::SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1, 1034 ISD::CondCode Cond, bool foldBooleans, 1035 DAGCombinerInfo &DCI) const { 1036 SelectionDAG &DAG = DCI.DAG; 1037 1038 // These setcc operations always fold. 1039 switch (Cond) { 1040 default: break; 1041 case ISD::SETFALSE: 1042 case ISD::SETFALSE2: return DAG.getConstant(0, VT); 1043 case ISD::SETTRUE: 1044 case ISD::SETTRUE2: return DAG.getConstant(1, VT); 1045 } 1046 1047 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) { 1048 const APInt &C1 = N1C->getAPIntValue(); 1049 if (isa<ConstantSDNode>(N0.Val)) { 1050 return DAG.FoldSetCC(VT, N0, N1, Cond); 1051 } else { 1052 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 1053 // equality comparison, then we're just comparing whether X itself is 1054 // zero. 1055 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) && 1056 N0.getOperand(0).getOpcode() == ISD::CTLZ && 1057 N0.getOperand(1).getOpcode() == ISD::Constant) { 1058 unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getValue(); 1059 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1060 ShAmt == Log2_32(MVT::getSizeInBits(N0.getValueType()))) { 1061 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 1062 // (srl (ctlz x), 5) == 0 -> X != 0 1063 // (srl (ctlz x), 5) != 1 -> X != 0 1064 Cond = ISD::SETNE; 1065 } else { 1066 // (srl (ctlz x), 5) != 0 -> X == 0 1067 // (srl (ctlz x), 5) == 1 -> X == 0 1068 Cond = ISD::SETEQ; 1069 } 1070 SDOperand Zero = DAG.getConstant(0, N0.getValueType()); 1071 return DAG.getSetCC(VT, N0.getOperand(0).getOperand(0), 1072 Zero, Cond); 1073 } 1074 } 1075 1076 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 1077 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 1078 unsigned InSize = MVT::getSizeInBits(N0.getOperand(0).getValueType()); 1079 1080 // If the comparison constant has bits in the upper part, the 1081 // zero-extended value could never match. 1082 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 1083 C1.getBitWidth() - InSize))) { 1084 switch (Cond) { 1085 case ISD::SETUGT: 1086 case ISD::SETUGE: 1087 case ISD::SETEQ: return DAG.getConstant(0, VT); 1088 case ISD::SETULT: 1089 case ISD::SETULE: 1090 case ISD::SETNE: return DAG.getConstant(1, VT); 1091 case ISD::SETGT: 1092 case ISD::SETGE: 1093 // True if the sign bit of C1 is set. 1094 return DAG.getConstant(C1.isNegative(), VT); 1095 case ISD::SETLT: 1096 case ISD::SETLE: 1097 // True if the sign bit of C1 isn't set. 1098 return DAG.getConstant(C1.isNonNegative(), VT); 1099 default: 1100 break; 1101 } 1102 } 1103 1104 // Otherwise, we can perform the comparison with the low bits. 1105 switch (Cond) { 1106 case ISD::SETEQ: 1107 case ISD::SETNE: 1108 case ISD::SETUGT: 1109 case ISD::SETUGE: 1110 case ISD::SETULT: 1111 case ISD::SETULE: 1112 return DAG.getSetCC(VT, N0.getOperand(0), 1113 DAG.getConstant(APInt(C1).trunc(InSize), 1114 N0.getOperand(0).getValueType()), 1115 Cond); 1116 default: 1117 break; // todo, be more careful with signed comparisons 1118 } 1119 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 1120 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 1121 MVT::ValueType ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 1122 unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy); 1123 MVT::ValueType ExtDstTy = N0.getValueType(); 1124 unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy); 1125 1126 // If the extended part has any inconsistent bits, it cannot ever 1127 // compare equal. In other words, they have to be all ones or all 1128 // zeros. 1129 APInt ExtBits = 1130 APInt::getHighBitsSet(ExtDstTyBits, ExtDstTyBits - ExtSrcTyBits); 1131 if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits) 1132 return DAG.getConstant(Cond == ISD::SETNE, VT); 1133 1134 SDOperand ZextOp; 1135 MVT::ValueType Op0Ty = N0.getOperand(0).getValueType(); 1136 if (Op0Ty == ExtSrcTy) { 1137 ZextOp = N0.getOperand(0); 1138 } else { 1139 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 1140 ZextOp = DAG.getNode(ISD::AND, Op0Ty, N0.getOperand(0), 1141 DAG.getConstant(Imm, Op0Ty)); 1142 } 1143 if (!DCI.isCalledByLegalizer()) 1144 DCI.AddToWorklist(ZextOp.Val); 1145 // Otherwise, make this a use of a zext. 1146 return DAG.getSetCC(VT, ZextOp, 1147 DAG.getConstant(C1 & APInt::getLowBitsSet( 1148 ExtDstTyBits, 1149 ExtSrcTyBits), 1150 ExtDstTy), 1151 Cond); 1152 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) && 1153 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 1154 1155 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 1156 if (N0.getOpcode() == ISD::SETCC) { 1157 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getValue() != 1); 1158 if (TrueWhenTrue) 1159 return N0; 1160 1161 // Invert the condition. 1162 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 1163 CC = ISD::getSetCCInverse(CC, 1164 MVT::isInteger(N0.getOperand(0).getValueType())); 1165 return DAG.getSetCC(VT, N0.getOperand(0), N0.getOperand(1), CC); 1166 } 1167 1168 if ((N0.getOpcode() == ISD::XOR || 1169 (N0.getOpcode() == ISD::AND && 1170 N0.getOperand(0).getOpcode() == ISD::XOR && 1171 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 1172 isa<ConstantSDNode>(N0.getOperand(1)) && 1173 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) { 1174 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 1175 // can only do this if the top bits are known zero. 1176 unsigned BitWidth = N0.getValueSizeInBits(); 1177 if (DAG.MaskedValueIsZero(N0, 1178 APInt::getHighBitsSet(BitWidth, 1179 BitWidth-1))) { 1180 // Okay, get the un-inverted input value. 1181 SDOperand Val; 1182 if (N0.getOpcode() == ISD::XOR) 1183 Val = N0.getOperand(0); 1184 else { 1185 assert(N0.getOpcode() == ISD::AND && 1186 N0.getOperand(0).getOpcode() == ISD::XOR); 1187 // ((X^1)&1)^1 -> X & 1 1188 Val = DAG.getNode(ISD::AND, N0.getValueType(), 1189 N0.getOperand(0).getOperand(0), 1190 N0.getOperand(1)); 1191 } 1192 return DAG.getSetCC(VT, Val, N1, 1193 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1194 } 1195 } 1196 } 1197 1198 APInt MinVal, MaxVal; 1199 unsigned OperandBitSize = MVT::getSizeInBits(N1C->getValueType(0)); 1200 if (ISD::isSignedIntSetCC(Cond)) { 1201 MinVal = APInt::getSignedMinValue(OperandBitSize); 1202 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 1203 } else { 1204 MinVal = APInt::getMinValue(OperandBitSize); 1205 MaxVal = APInt::getMaxValue(OperandBitSize); 1206 } 1207 1208 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 1209 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 1210 if (C1 == MinVal) return DAG.getConstant(1, VT); // X >= MIN --> true 1211 // X >= C0 --> X > (C0-1) 1212 return DAG.getSetCC(VT, N0, DAG.getConstant(C1-1, N1.getValueType()), 1213 (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT); 1214 } 1215 1216 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 1217 if (C1 == MaxVal) return DAG.getConstant(1, VT); // X <= MAX --> true 1218 // X <= C0 --> X < (C0+1) 1219 return DAG.getSetCC(VT, N0, DAG.getConstant(C1+1, N1.getValueType()), 1220 (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT); 1221 } 1222 1223 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal) 1224 return DAG.getConstant(0, VT); // X < MIN --> false 1225 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal) 1226 return DAG.getConstant(1, VT); // X >= MIN --> true 1227 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal) 1228 return DAG.getConstant(0, VT); // X > MAX --> false 1229 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal) 1230 return DAG.getConstant(1, VT); // X <= MAX --> true 1231 1232 // Canonicalize setgt X, Min --> setne X, Min 1233 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal) 1234 return DAG.getSetCC(VT, N0, N1, ISD::SETNE); 1235 // Canonicalize setlt X, Max --> setne X, Max 1236 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal) 1237 return DAG.getSetCC(VT, N0, N1, ISD::SETNE); 1238 1239 // If we have setult X, 1, turn it into seteq X, 0 1240 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1) 1241 return DAG.getSetCC(VT, N0, DAG.getConstant(MinVal, N0.getValueType()), 1242 ISD::SETEQ); 1243 // If we have setugt X, Max-1, turn it into seteq X, Max 1244 else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1) 1245 return DAG.getSetCC(VT, N0, DAG.getConstant(MaxVal, N0.getValueType()), 1246 ISD::SETEQ); 1247 1248 // If we have "setcc X, C0", check to see if we can shrink the immediate 1249 // by changing cc. 1250 1251 // SETUGT X, SINTMAX -> SETLT X, 0 1252 if (Cond == ISD::SETUGT && OperandBitSize != 1 && 1253 C1 == (~0ULL >> (65-OperandBitSize))) 1254 return DAG.getSetCC(VT, N0, DAG.getConstant(0, N1.getValueType()), 1255 ISD::SETLT); 1256 1257 // FIXME: Implement the rest of these. 1258 1259 // Fold bit comparisons when we can. 1260 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1261 VT == N0.getValueType() && N0.getOpcode() == ISD::AND) 1262 if (ConstantSDNode *AndRHS = 1263 dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 1264 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 1265 // Perform the xform if the AND RHS is a single bit. 1266 if (isPowerOf2_64(AndRHS->getValue())) { 1267 return DAG.getNode(ISD::SRL, VT, N0, 1268 DAG.getConstant(Log2_64(AndRHS->getValue()), 1269 getShiftAmountTy())); 1270 } 1271 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getValue()) { 1272 // (X & 8) == 8 --> (X & 8) >> 3 1273 // Perform the xform if C1 is a single bit. 1274 if (C1.isPowerOf2()) { 1275 return DAG.getNode(ISD::SRL, VT, N0, 1276 DAG.getConstant(C1.logBase2(), getShiftAmountTy())); 1277 } 1278 } 1279 } 1280 } 1281 } else if (isa<ConstantSDNode>(N0.Val)) { 1282 // Ensure that the constant occurs on the RHS. 1283 return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond)); 1284 } 1285 1286 if (isa<ConstantFPSDNode>(N0.Val)) { 1287 // Constant fold or commute setcc. 1288 SDOperand O = DAG.FoldSetCC(VT, N0, N1, Cond); 1289 if (O.Val) return O; 1290 } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.Val)) { 1291 // If the RHS of an FP comparison is a constant, simplify it away in 1292 // some cases. 1293 if (CFP->getValueAPF().isNaN()) { 1294 // If an operand is known to be a nan, we can fold it. 1295 switch (ISD::getUnorderedFlavor(Cond)) { 1296 default: assert(0 && "Unknown flavor!"); 1297 case 0: // Known false. 1298 return DAG.getConstant(0, VT); 1299 case 1: // Known true. 1300 return DAG.getConstant(1, VT); 1301 case 2: // Undefined. 1302 return DAG.getNode(ISD::UNDEF, VT); 1303 } 1304 } 1305 1306 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 1307 // constant if knowing that the operand is non-nan is enough. We prefer to 1308 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 1309 // materialize 0.0. 1310 if (Cond == ISD::SETO || Cond == ISD::SETUO) 1311 return DAG.getSetCC(VT, N0, N0, Cond); 1312 } 1313 1314 if (N0 == N1) { 1315 // We can always fold X == X for integer setcc's. 1316 if (MVT::isInteger(N0.getValueType())) 1317 return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT); 1318 unsigned UOF = ISD::getUnorderedFlavor(Cond); 1319 if (UOF == 2) // FP operators that are undefined on NaNs. 1320 return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT); 1321 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond))) 1322 return DAG.getConstant(UOF, VT); 1323 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 1324 // if it is not already. 1325 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 1326 if (NewCond != Cond) 1327 return DAG.getSetCC(VT, N0, N1, NewCond); 1328 } 1329 1330 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1331 MVT::isInteger(N0.getValueType())) { 1332 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 1333 N0.getOpcode() == ISD::XOR) { 1334 // Simplify (X+Y) == (X+Z) --> Y == Z 1335 if (N0.getOpcode() == N1.getOpcode()) { 1336 if (N0.getOperand(0) == N1.getOperand(0)) 1337 return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(1), Cond); 1338 if (N0.getOperand(1) == N1.getOperand(1)) 1339 return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(0), Cond); 1340 if (DAG.isCommutativeBinOp(N0.getOpcode())) { 1341 // If X op Y == Y op X, try other combinations. 1342 if (N0.getOperand(0) == N1.getOperand(1)) 1343 return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(0), Cond); 1344 if (N0.getOperand(1) == N1.getOperand(0)) 1345 return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(1), Cond); 1346 } 1347 } 1348 1349 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) { 1350 if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 1351 // Turn (X+C1) == C2 --> X == C2-C1 1352 if (N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse()) { 1353 return DAG.getSetCC(VT, N0.getOperand(0), 1354 DAG.getConstant(RHSC->getValue()-LHSR->getValue(), 1355 N0.getValueType()), Cond); 1356 } 1357 1358 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0. 1359 if (N0.getOpcode() == ISD::XOR) 1360 // If we know that all of the inverted bits are zero, don't bother 1361 // performing the inversion. 1362 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue())) 1363 return 1364 DAG.getSetCC(VT, N0.getOperand(0), 1365 DAG.getConstant(LHSR->getAPIntValue() ^ 1366 RHSC->getAPIntValue(), 1367 N0.getValueType()), 1368 Cond); 1369 } 1370 1371 // Turn (C1-X) == C2 --> X == C1-C2 1372 if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) { 1373 if (N0.getOpcode() == ISD::SUB && N0.Val->hasOneUse()) { 1374 return 1375 DAG.getSetCC(VT, N0.getOperand(1), 1376 DAG.getConstant(SUBC->getAPIntValue() - 1377 RHSC->getAPIntValue(), 1378 N0.getValueType()), 1379 Cond); 1380 } 1381 } 1382 } 1383 1384 // Simplify (X+Z) == X --> Z == 0 1385 if (N0.getOperand(0) == N1) 1386 return DAG.getSetCC(VT, N0.getOperand(1), 1387 DAG.getConstant(0, N0.getValueType()), Cond); 1388 if (N0.getOperand(1) == N1) { 1389 if (DAG.isCommutativeBinOp(N0.getOpcode())) 1390 return DAG.getSetCC(VT, N0.getOperand(0), 1391 DAG.getConstant(0, N0.getValueType()), Cond); 1392 else if (N0.Val->hasOneUse()) { 1393 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!"); 1394 // (Z-X) == X --> Z == X<<1 1395 SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(), 1396 N1, 1397 DAG.getConstant(1, getShiftAmountTy())); 1398 if (!DCI.isCalledByLegalizer()) 1399 DCI.AddToWorklist(SH.Val); 1400 return DAG.getSetCC(VT, N0.getOperand(0), SH, Cond); 1401 } 1402 } 1403 } 1404 1405 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 1406 N1.getOpcode() == ISD::XOR) { 1407 // Simplify X == (X+Z) --> Z == 0 1408 if (N1.getOperand(0) == N0) { 1409 return DAG.getSetCC(VT, N1.getOperand(1), 1410 DAG.getConstant(0, N1.getValueType()), Cond); 1411 } else if (N1.getOperand(1) == N0) { 1412 if (DAG.isCommutativeBinOp(N1.getOpcode())) { 1413 return DAG.getSetCC(VT, N1.getOperand(0), 1414 DAG.getConstant(0, N1.getValueType()), Cond); 1415 } else if (N1.Val->hasOneUse()) { 1416 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!"); 1417 // X == (Z-X) --> X<<1 == Z 1418 SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(), N0, 1419 DAG.getConstant(1, getShiftAmountTy())); 1420 if (!DCI.isCalledByLegalizer()) 1421 DCI.AddToWorklist(SH.Val); 1422 return DAG.getSetCC(VT, SH, N1.getOperand(0), Cond); 1423 } 1424 } 1425 } 1426 } 1427 1428 // Fold away ALL boolean setcc's. 1429 SDOperand Temp; 1430 if (N0.getValueType() == MVT::i1 && foldBooleans) { 1431 switch (Cond) { 1432 default: assert(0 && "Unknown integer setcc!"); 1433 case ISD::SETEQ: // X == Y -> (X^Y)^1 1434 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, N1); 1435 N0 = DAG.getNode(ISD::XOR, MVT::i1, Temp, DAG.getConstant(1, MVT::i1)); 1436 if (!DCI.isCalledByLegalizer()) 1437 DCI.AddToWorklist(Temp.Val); 1438 break; 1439 case ISD::SETNE: // X != Y --> (X^Y) 1440 N0 = DAG.getNode(ISD::XOR, MVT::i1, N0, N1); 1441 break; 1442 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> X^1 & Y 1443 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> X^1 & Y 1444 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1)); 1445 N0 = DAG.getNode(ISD::AND, MVT::i1, N1, Temp); 1446 if (!DCI.isCalledByLegalizer()) 1447 DCI.AddToWorklist(Temp.Val); 1448 break; 1449 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> Y^1 & X 1450 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> Y^1 & X 1451 Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1)); 1452 N0 = DAG.getNode(ISD::AND, MVT::i1, N0, Temp); 1453 if (!DCI.isCalledByLegalizer()) 1454 DCI.AddToWorklist(Temp.Val); 1455 break; 1456 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> X^1 | Y 1457 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> X^1 | Y 1458 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1)); 1459 N0 = DAG.getNode(ISD::OR, MVT::i1, N1, Temp); 1460 if (!DCI.isCalledByLegalizer()) 1461 DCI.AddToWorklist(Temp.Val); 1462 break; 1463 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> Y^1 | X 1464 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> Y^1 | X 1465 Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1)); 1466 N0 = DAG.getNode(ISD::OR, MVT::i1, N0, Temp); 1467 break; 1468 } 1469 if (VT != MVT::i1) { 1470 if (!DCI.isCalledByLegalizer()) 1471 DCI.AddToWorklist(N0.Val); 1472 // FIXME: If running after legalize, we probably can't do this. 1473 N0 = DAG.getNode(ISD::ZERO_EXTEND, VT, N0); 1474 } 1475 return N0; 1476 } 1477 1478 // Could not fold it. 1479 return SDOperand(); 1480} 1481 1482/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the 1483/// node is a GlobalAddress + offset. 1484bool TargetLowering::isGAPlusOffset(SDNode *N, GlobalValue* &GA, 1485 int64_t &Offset) const { 1486 if (isa<GlobalAddressSDNode>(N)) { 1487 GA = cast<GlobalAddressSDNode>(N)->getGlobal(); 1488 return true; 1489 } 1490 1491 if (N->getOpcode() == ISD::ADD) { 1492 SDOperand N1 = N->getOperand(0); 1493 SDOperand N2 = N->getOperand(1); 1494 if (isGAPlusOffset(N1.Val, GA, Offset)) { 1495 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2); 1496 if (V) { 1497 Offset += V->getSignExtended(); 1498 return true; 1499 } 1500 } else if (isGAPlusOffset(N2.Val, GA, Offset)) { 1501 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1); 1502 if (V) { 1503 Offset += V->getSignExtended(); 1504 return true; 1505 } 1506 } 1507 } 1508 return false; 1509} 1510 1511 1512/// isConsecutiveLoad - Return true if LD (which must be a LoadSDNode) is 1513/// loading 'Bytes' bytes from a location that is 'Dist' units away from the 1514/// location that the 'Base' load is loading from. 1515bool TargetLowering::isConsecutiveLoad(SDNode *LD, SDNode *Base, 1516 unsigned Bytes, int Dist, 1517 MachineFrameInfo *MFI) const { 1518 if (LD->getOperand(0).Val != Base->getOperand(0).Val) 1519 return false; 1520 MVT::ValueType VT = LD->getValueType(0); 1521 if (MVT::getSizeInBits(VT) / 8 != Bytes) 1522 return false; 1523 1524 SDOperand Loc = LD->getOperand(1); 1525 SDOperand BaseLoc = Base->getOperand(1); 1526 if (Loc.getOpcode() == ISD::FrameIndex) { 1527 if (BaseLoc.getOpcode() != ISD::FrameIndex) 1528 return false; 1529 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 1530 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 1531 int FS = MFI->getObjectSize(FI); 1532 int BFS = MFI->getObjectSize(BFI); 1533 if (FS != BFS || FS != (int)Bytes) return false; 1534 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes); 1535 } 1536 1537 GlobalValue *GV1 = NULL; 1538 GlobalValue *GV2 = NULL; 1539 int64_t Offset1 = 0; 1540 int64_t Offset2 = 0; 1541 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1); 1542 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2); 1543 if (isGA1 && isGA2 && GV1 == GV2) 1544 return Offset1 == (Offset2 + Dist*Bytes); 1545 return false; 1546} 1547 1548 1549SDOperand TargetLowering:: 1550PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const { 1551 // Default implementation: no optimization. 1552 return SDOperand(); 1553} 1554 1555//===----------------------------------------------------------------------===// 1556// Inline Assembler Implementation Methods 1557//===----------------------------------------------------------------------===// 1558 1559 1560TargetLowering::ConstraintType 1561TargetLowering::getConstraintType(const std::string &Constraint) const { 1562 // FIXME: lots more standard ones to handle. 1563 if (Constraint.size() == 1) { 1564 switch (Constraint[0]) { 1565 default: break; 1566 case 'r': return C_RegisterClass; 1567 case 'm': // memory 1568 case 'o': // offsetable 1569 case 'V': // not offsetable 1570 return C_Memory; 1571 case 'i': // Simple Integer or Relocatable Constant 1572 case 'n': // Simple Integer 1573 case 's': // Relocatable Constant 1574 case 'X': // Allow ANY value. 1575 case 'I': // Target registers. 1576 case 'J': 1577 case 'K': 1578 case 'L': 1579 case 'M': 1580 case 'N': 1581 case 'O': 1582 case 'P': 1583 return C_Other; 1584 } 1585 } 1586 1587 if (Constraint.size() > 1 && Constraint[0] == '{' && 1588 Constraint[Constraint.size()-1] == '}') 1589 return C_Register; 1590 return C_Unknown; 1591} 1592 1593/// LowerXConstraint - try to replace an X constraint, which matches anything, 1594/// with another that has more specific requirements based on the type of the 1595/// corresponding operand. 1596const char *TargetLowering::LowerXConstraint(MVT::ValueType ConstraintVT) const{ 1597 if (MVT::isInteger(ConstraintVT)) 1598 return "r"; 1599 if (MVT::isFloatingPoint(ConstraintVT)) 1600 return "f"; // works for many targets 1601 return 0; 1602} 1603 1604/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 1605/// vector. If it is invalid, don't add anything to Ops. 1606void TargetLowering::LowerAsmOperandForConstraint(SDOperand Op, 1607 char ConstraintLetter, 1608 std::vector<SDOperand> &Ops, 1609 SelectionDAG &DAG) const { 1610 switch (ConstraintLetter) { 1611 default: break; 1612 case 'X': // Allows any operand; labels (basic block) use this. 1613 if (Op.getOpcode() == ISD::BasicBlock) { 1614 Ops.push_back(Op); 1615 return; 1616 } 1617 // fall through 1618 case 'i': // Simple Integer or Relocatable Constant 1619 case 'n': // Simple Integer 1620 case 's': { // Relocatable Constant 1621 // These operands are interested in values of the form (GV+C), where C may 1622 // be folded in as an offset of GV, or it may be explicitly added. Also, it 1623 // is possible and fine if either GV or C are missing. 1624 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 1625 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op); 1626 1627 // If we have "(add GV, C)", pull out GV/C 1628 if (Op.getOpcode() == ISD::ADD) { 1629 C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 1630 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0)); 1631 if (C == 0 || GA == 0) { 1632 C = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 1633 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1)); 1634 } 1635 if (C == 0 || GA == 0) 1636 C = 0, GA = 0; 1637 } 1638 1639 // If we find a valid operand, map to the TargetXXX version so that the 1640 // value itself doesn't get selected. 1641 if (GA) { // Either &GV or &GV+C 1642 if (ConstraintLetter != 'n') { 1643 int64_t Offs = GA->getOffset(); 1644 if (C) Offs += C->getValue(); 1645 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), 1646 Op.getValueType(), Offs)); 1647 return; 1648 } 1649 } 1650 if (C) { // just C, no GV. 1651 // Simple constants are not allowed for 's'. 1652 if (ConstraintLetter != 's') { 1653 Ops.push_back(DAG.getTargetConstant(C->getValue(), Op.getValueType())); 1654 return; 1655 } 1656 } 1657 break; 1658 } 1659 } 1660} 1661 1662std::vector<unsigned> TargetLowering:: 1663getRegClassForInlineAsmConstraint(const std::string &Constraint, 1664 MVT::ValueType VT) const { 1665 return std::vector<unsigned>(); 1666} 1667 1668 1669std::pair<unsigned, const TargetRegisterClass*> TargetLowering:: 1670getRegForInlineAsmConstraint(const std::string &Constraint, 1671 MVT::ValueType VT) const { 1672 if (Constraint[0] != '{') 1673 return std::pair<unsigned, const TargetRegisterClass*>(0, 0); 1674 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?"); 1675 1676 // Remove the braces from around the name. 1677 std::string RegName(Constraint.begin()+1, Constraint.end()-1); 1678 1679 // Figure out which register class contains this reg. 1680 const TargetRegisterInfo *RI = TM.getRegisterInfo(); 1681 for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(), 1682 E = RI->regclass_end(); RCI != E; ++RCI) { 1683 const TargetRegisterClass *RC = *RCI; 1684 1685 // If none of the the value types for this register class are valid, we 1686 // can't use it. For example, 64-bit reg classes on 32-bit targets. 1687 bool isLegal = false; 1688 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end(); 1689 I != E; ++I) { 1690 if (isTypeLegal(*I)) { 1691 isLegal = true; 1692 break; 1693 } 1694 } 1695 1696 if (!isLegal) continue; 1697 1698 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); 1699 I != E; ++I) { 1700 if (StringsEqualNoCase(RegName, RI->get(*I).AsmName)) 1701 return std::make_pair(*I, RC); 1702 } 1703 } 1704 1705 return std::pair<unsigned, const TargetRegisterClass*>(0, 0); 1706} 1707 1708//===----------------------------------------------------------------------===// 1709// Constraint Selection. 1710 1711/// getConstraintGenerality - Return an integer indicating how general CT 1712/// is. 1713static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 1714 switch (CT) { 1715 default: assert(0 && "Unknown constraint type!"); 1716 case TargetLowering::C_Other: 1717 case TargetLowering::C_Unknown: 1718 return 0; 1719 case TargetLowering::C_Register: 1720 return 1; 1721 case TargetLowering::C_RegisterClass: 1722 return 2; 1723 case TargetLowering::C_Memory: 1724 return 3; 1725 } 1726} 1727 1728/// ChooseConstraint - If there are multiple different constraints that we 1729/// could pick for this operand (e.g. "imr") try to pick the 'best' one. 1730/// This is somewhat tricky: constraints fall into four classes: 1731/// Other -> immediates and magic values 1732/// Register -> one specific register 1733/// RegisterClass -> a group of regs 1734/// Memory -> memory 1735/// Ideally, we would pick the most specific constraint possible: if we have 1736/// something that fits into a register, we would pick it. The problem here 1737/// is that if we have something that could either be in a register or in 1738/// memory that use of the register could cause selection of *other* 1739/// operands to fail: they might only succeed if we pick memory. Because of 1740/// this the heuristic we use is: 1741/// 1742/// 1) If there is an 'other' constraint, and if the operand is valid for 1743/// that constraint, use it. This makes us take advantage of 'i' 1744/// constraints when available. 1745/// 2) Otherwise, pick the most general constraint present. This prefers 1746/// 'm' over 'r', for example. 1747/// 1748static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 1749 const TargetLowering &TLI, 1750 SDOperand Op, SelectionDAG *DAG) { 1751 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 1752 unsigned BestIdx = 0; 1753 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 1754 int BestGenerality = -1; 1755 1756 // Loop over the options, keeping track of the most general one. 1757 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 1758 TargetLowering::ConstraintType CType = 1759 TLI.getConstraintType(OpInfo.Codes[i]); 1760 1761 // If this is an 'other' constraint, see if the operand is valid for it. 1762 // For example, on X86 we might have an 'rI' constraint. If the operand 1763 // is an integer in the range [0..31] we want to use I (saving a load 1764 // of a register), otherwise we must use 'r'. 1765 if (CType == TargetLowering::C_Other && Op.Val) { 1766 assert(OpInfo.Codes[i].size() == 1 && 1767 "Unhandled multi-letter 'other' constraint"); 1768 std::vector<SDOperand> ResultOps; 1769 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i][0], 1770 ResultOps, *DAG); 1771 if (!ResultOps.empty()) { 1772 BestType = CType; 1773 BestIdx = i; 1774 break; 1775 } 1776 } 1777 1778 // This constraint letter is more general than the previous one, use it. 1779 int Generality = getConstraintGenerality(CType); 1780 if (Generality > BestGenerality) { 1781 BestType = CType; 1782 BestIdx = i; 1783 BestGenerality = Generality; 1784 } 1785 } 1786 1787 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 1788 OpInfo.ConstraintType = BestType; 1789} 1790 1791/// ComputeConstraintToUse - Determines the constraint code and constraint 1792/// type to use for the specific AsmOperandInfo, setting 1793/// OpInfo.ConstraintCode and OpInfo.ConstraintType. 1794void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 1795 SDOperand Op, 1796 SelectionDAG *DAG) const { 1797 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 1798 1799 // Single-letter constraints ('r') are very common. 1800 if (OpInfo.Codes.size() == 1) { 1801 OpInfo.ConstraintCode = OpInfo.Codes[0]; 1802 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 1803 } else { 1804 ChooseConstraint(OpInfo, *this, Op, DAG); 1805 } 1806 1807 // 'X' matches anything. 1808 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 1809 // Labels and constants are handled elsewhere ('X' is the only thing 1810 // that matches labels). 1811 if (isa<BasicBlock>(OpInfo.CallOperandVal) || 1812 isa<ConstantInt>(OpInfo.CallOperandVal)) 1813 return; 1814 1815 // Otherwise, try to resolve it to something we know about by looking at 1816 // the actual operand type. 1817 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 1818 OpInfo.ConstraintCode = Repl; 1819 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 1820 } 1821 } 1822} 1823 1824//===----------------------------------------------------------------------===// 1825// Loop Strength Reduction hooks 1826//===----------------------------------------------------------------------===// 1827 1828/// isLegalAddressingMode - Return true if the addressing mode represented 1829/// by AM is legal for this target, for a load/store of the specified type. 1830bool TargetLowering::isLegalAddressingMode(const AddrMode &AM, 1831 const Type *Ty) const { 1832 // The default implementation of this implements a conservative RISCy, r+r and 1833 // r+i addr mode. 1834 1835 // Allows a sign-extended 16-bit immediate field. 1836 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 1837 return false; 1838 1839 // No global is ever allowed as a base. 1840 if (AM.BaseGV) 1841 return false; 1842 1843 // Only support r+r, 1844 switch (AM.Scale) { 1845 case 0: // "r+i" or just "i", depending on HasBaseReg. 1846 break; 1847 case 1: 1848 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 1849 return false; 1850 // Otherwise we have r+r or r+i. 1851 break; 1852 case 2: 1853 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 1854 return false; 1855 // Allow 2*r as r+r. 1856 break; 1857 } 1858 1859 return true; 1860} 1861 1862// Magic for divide replacement 1863 1864struct ms { 1865 int64_t m; // magic number 1866 int64_t s; // shift amount 1867}; 1868 1869struct mu { 1870 uint64_t m; // magic number 1871 int64_t a; // add indicator 1872 int64_t s; // shift amount 1873}; 1874 1875/// magic - calculate the magic numbers required to codegen an integer sdiv as 1876/// a sequence of multiply and shifts. Requires that the divisor not be 0, 1, 1877/// or -1. 1878static ms magic32(int32_t d) { 1879 int32_t p; 1880 uint32_t ad, anc, delta, q1, r1, q2, r2, t; 1881 const uint32_t two31 = 0x80000000U; 1882 struct ms mag; 1883 1884 ad = abs(d); 1885 t = two31 + ((uint32_t)d >> 31); 1886 anc = t - 1 - t%ad; // absolute value of nc 1887 p = 31; // initialize p 1888 q1 = two31/anc; // initialize q1 = 2p/abs(nc) 1889 r1 = two31 - q1*anc; // initialize r1 = rem(2p,abs(nc)) 1890 q2 = two31/ad; // initialize q2 = 2p/abs(d) 1891 r2 = two31 - q2*ad; // initialize r2 = rem(2p,abs(d)) 1892 do { 1893 p = p + 1; 1894 q1 = 2*q1; // update q1 = 2p/abs(nc) 1895 r1 = 2*r1; // update r1 = rem(2p/abs(nc)) 1896 if (r1 >= anc) { // must be unsigned comparison 1897 q1 = q1 + 1; 1898 r1 = r1 - anc; 1899 } 1900 q2 = 2*q2; // update q2 = 2p/abs(d) 1901 r2 = 2*r2; // update r2 = rem(2p/abs(d)) 1902 if (r2 >= ad) { // must be unsigned comparison 1903 q2 = q2 + 1; 1904 r2 = r2 - ad; 1905 } 1906 delta = ad - r2; 1907 } while (q1 < delta || (q1 == delta && r1 == 0)); 1908 1909 mag.m = (int32_t)(q2 + 1); // make sure to sign extend 1910 if (d < 0) mag.m = -mag.m; // resulting magic number 1911 mag.s = p - 32; // resulting shift 1912 return mag; 1913} 1914 1915/// magicu - calculate the magic numbers required to codegen an integer udiv as 1916/// a sequence of multiply, add and shifts. Requires that the divisor not be 0. 1917static mu magicu32(uint32_t d) { 1918 int32_t p; 1919 uint32_t nc, delta, q1, r1, q2, r2; 1920 struct mu magu; 1921 magu.a = 0; // initialize "add" indicator 1922 nc = - 1 - (-d)%d; 1923 p = 31; // initialize p 1924 q1 = 0x80000000/nc; // initialize q1 = 2p/nc 1925 r1 = 0x80000000 - q1*nc; // initialize r1 = rem(2p,nc) 1926 q2 = 0x7FFFFFFF/d; // initialize q2 = (2p-1)/d 1927 r2 = 0x7FFFFFFF - q2*d; // initialize r2 = rem((2p-1),d) 1928 do { 1929 p = p + 1; 1930 if (r1 >= nc - r1 ) { 1931 q1 = 2*q1 + 1; // update q1 1932 r1 = 2*r1 - nc; // update r1 1933 } 1934 else { 1935 q1 = 2*q1; // update q1 1936 r1 = 2*r1; // update r1 1937 } 1938 if (r2 + 1 >= d - r2) { 1939 if (q2 >= 0x7FFFFFFF) magu.a = 1; 1940 q2 = 2*q2 + 1; // update q2 1941 r2 = 2*r2 + 1 - d; // update r2 1942 } 1943 else { 1944 if (q2 >= 0x80000000) magu.a = 1; 1945 q2 = 2*q2; // update q2 1946 r2 = 2*r2 + 1; // update r2 1947 } 1948 delta = d - 1 - r2; 1949 } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0))); 1950 magu.m = q2 + 1; // resulting magic number 1951 magu.s = p - 32; // resulting shift 1952 return magu; 1953} 1954 1955/// magic - calculate the magic numbers required to codegen an integer sdiv as 1956/// a sequence of multiply and shifts. Requires that the divisor not be 0, 1, 1957/// or -1. 1958static ms magic64(int64_t d) { 1959 int64_t p; 1960 uint64_t ad, anc, delta, q1, r1, q2, r2, t; 1961 const uint64_t two63 = 9223372036854775808ULL; // 2^63 1962 struct ms mag; 1963 1964 ad = d >= 0 ? d : -d; 1965 t = two63 + ((uint64_t)d >> 63); 1966 anc = t - 1 - t%ad; // absolute value of nc 1967 p = 63; // initialize p 1968 q1 = two63/anc; // initialize q1 = 2p/abs(nc) 1969 r1 = two63 - q1*anc; // initialize r1 = rem(2p,abs(nc)) 1970 q2 = two63/ad; // initialize q2 = 2p/abs(d) 1971 r2 = two63 - q2*ad; // initialize r2 = rem(2p,abs(d)) 1972 do { 1973 p = p + 1; 1974 q1 = 2*q1; // update q1 = 2p/abs(nc) 1975 r1 = 2*r1; // update r1 = rem(2p/abs(nc)) 1976 if (r1 >= anc) { // must be unsigned comparison 1977 q1 = q1 + 1; 1978 r1 = r1 - anc; 1979 } 1980 q2 = 2*q2; // update q2 = 2p/abs(d) 1981 r2 = 2*r2; // update r2 = rem(2p/abs(d)) 1982 if (r2 >= ad) { // must be unsigned comparison 1983 q2 = q2 + 1; 1984 r2 = r2 - ad; 1985 } 1986 delta = ad - r2; 1987 } while (q1 < delta || (q1 == delta && r1 == 0)); 1988 1989 mag.m = q2 + 1; 1990 if (d < 0) mag.m = -mag.m; // resulting magic number 1991 mag.s = p - 64; // resulting shift 1992 return mag; 1993} 1994 1995/// magicu - calculate the magic numbers required to codegen an integer udiv as 1996/// a sequence of multiply, add and shifts. Requires that the divisor not be 0. 1997static mu magicu64(uint64_t d) 1998{ 1999 int64_t p; 2000 uint64_t nc, delta, q1, r1, q2, r2; 2001 struct mu magu; 2002 magu.a = 0; // initialize "add" indicator 2003 nc = - 1 - (-d)%d; 2004 p = 63; // initialize p 2005 q1 = 0x8000000000000000ull/nc; // initialize q1 = 2p/nc 2006 r1 = 0x8000000000000000ull - q1*nc; // initialize r1 = rem(2p,nc) 2007 q2 = 0x7FFFFFFFFFFFFFFFull/d; // initialize q2 = (2p-1)/d 2008 r2 = 0x7FFFFFFFFFFFFFFFull - q2*d; // initialize r2 = rem((2p-1),d) 2009 do { 2010 p = p + 1; 2011 if (r1 >= nc - r1 ) { 2012 q1 = 2*q1 + 1; // update q1 2013 r1 = 2*r1 - nc; // update r1 2014 } 2015 else { 2016 q1 = 2*q1; // update q1 2017 r1 = 2*r1; // update r1 2018 } 2019 if (r2 + 1 >= d - r2) { 2020 if (q2 >= 0x7FFFFFFFFFFFFFFFull) magu.a = 1; 2021 q2 = 2*q2 + 1; // update q2 2022 r2 = 2*r2 + 1 - d; // update r2 2023 } 2024 else { 2025 if (q2 >= 0x8000000000000000ull) magu.a = 1; 2026 q2 = 2*q2; // update q2 2027 r2 = 2*r2 + 1; // update r2 2028 } 2029 delta = d - 1 - r2; 2030 } while (p < 128 && (q1 < delta || (q1 == delta && r1 == 0))); 2031 magu.m = q2 + 1; // resulting magic number 2032 magu.s = p - 64; // resulting shift 2033 return magu; 2034} 2035 2036/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant, 2037/// return a DAG expression to select that will generate the same value by 2038/// multiplying by a magic number. See: 2039/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 2040SDOperand TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 2041 std::vector<SDNode*>* Created) const { 2042 MVT::ValueType VT = N->getValueType(0); 2043 2044 // Check to see if we can do this. 2045 if (!isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64)) 2046 return SDOperand(); // BuildSDIV only operates on i32 or i64 2047 2048 int64_t d = cast<ConstantSDNode>(N->getOperand(1))->getSignExtended(); 2049 ms magics = (VT == MVT::i32) ? magic32(d) : magic64(d); 2050 2051 // Multiply the numerator (operand 0) by the magic value 2052 SDOperand Q; 2053 if (isOperationLegal(ISD::MULHS, VT)) 2054 Q = DAG.getNode(ISD::MULHS, VT, N->getOperand(0), 2055 DAG.getConstant(magics.m, VT)); 2056 else if (isOperationLegal(ISD::SMUL_LOHI, VT)) 2057 Q = SDOperand(DAG.getNode(ISD::SMUL_LOHI, DAG.getVTList(VT, VT), 2058 N->getOperand(0), 2059 DAG.getConstant(magics.m, VT)).Val, 1); 2060 else 2061 return SDOperand(); // No mulhs or equvialent 2062 // If d > 0 and m < 0, add the numerator 2063 if (d > 0 && magics.m < 0) { 2064 Q = DAG.getNode(ISD::ADD, VT, Q, N->getOperand(0)); 2065 if (Created) 2066 Created->push_back(Q.Val); 2067 } 2068 // If d < 0 and m > 0, subtract the numerator. 2069 if (d < 0 && magics.m > 0) { 2070 Q = DAG.getNode(ISD::SUB, VT, Q, N->getOperand(0)); 2071 if (Created) 2072 Created->push_back(Q.Val); 2073 } 2074 // Shift right algebraic if shift value is nonzero 2075 if (magics.s > 0) { 2076 Q = DAG.getNode(ISD::SRA, VT, Q, 2077 DAG.getConstant(magics.s, getShiftAmountTy())); 2078 if (Created) 2079 Created->push_back(Q.Val); 2080 } 2081 // Extract the sign bit and add it to the quotient 2082 SDOperand T = 2083 DAG.getNode(ISD::SRL, VT, Q, DAG.getConstant(MVT::getSizeInBits(VT)-1, 2084 getShiftAmountTy())); 2085 if (Created) 2086 Created->push_back(T.Val); 2087 return DAG.getNode(ISD::ADD, VT, Q, T); 2088} 2089 2090/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant, 2091/// return a DAG expression to select that will generate the same value by 2092/// multiplying by a magic number. See: 2093/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 2094SDOperand TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG, 2095 std::vector<SDNode*>* Created) const { 2096 MVT::ValueType VT = N->getValueType(0); 2097 2098 // Check to see if we can do this. 2099 if (!isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64)) 2100 return SDOperand(); // BuildUDIV only operates on i32 or i64 2101 2102 uint64_t d = cast<ConstantSDNode>(N->getOperand(1))->getValue(); 2103 mu magics = (VT == MVT::i32) ? magicu32(d) : magicu64(d); 2104 2105 // Multiply the numerator (operand 0) by the magic value 2106 SDOperand Q; 2107 if (isOperationLegal(ISD::MULHU, VT)) 2108 Q = DAG.getNode(ISD::MULHU, VT, N->getOperand(0), 2109 DAG.getConstant(magics.m, VT)); 2110 else if (isOperationLegal(ISD::UMUL_LOHI, VT)) 2111 Q = SDOperand(DAG.getNode(ISD::UMUL_LOHI, DAG.getVTList(VT, VT), 2112 N->getOperand(0), 2113 DAG.getConstant(magics.m, VT)).Val, 1); 2114 else 2115 return SDOperand(); // No mulhu or equvialent 2116 if (Created) 2117 Created->push_back(Q.Val); 2118 2119 if (magics.a == 0) { 2120 return DAG.getNode(ISD::SRL, VT, Q, 2121 DAG.getConstant(magics.s, getShiftAmountTy())); 2122 } else { 2123 SDOperand NPQ = DAG.getNode(ISD::SUB, VT, N->getOperand(0), Q); 2124 if (Created) 2125 Created->push_back(NPQ.Val); 2126 NPQ = DAG.getNode(ISD::SRL, VT, NPQ, 2127 DAG.getConstant(1, getShiftAmountTy())); 2128 if (Created) 2129 Created->push_back(NPQ.Val); 2130 NPQ = DAG.getNode(ISD::ADD, VT, NPQ, Q); 2131 if (Created) 2132 Created->push_back(NPQ.Val); 2133 return DAG.getNode(ISD::SRL, VT, NPQ, 2134 DAG.getConstant(magics.s-1, getShiftAmountTy())); 2135 } 2136} 2137