1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the TargetLowering class.
12 //===----------------------------------------------------------------------===//
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/CallingConv.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/MathExtras.h"
28 /// InitLibcallNames - Set default libcall names.
30 static void InitLibcallNames(const char **Names) {
31 Names[RTLIB::SHL_I32] = "__ashlsi3";
32 Names[RTLIB::SHL_I64] = "__ashldi3";
33 Names[RTLIB::SRL_I32] = "__lshrsi3";
34 Names[RTLIB::SRL_I64] = "__lshrdi3";
35 Names[RTLIB::SRA_I32] = "__ashrsi3";
36 Names[RTLIB::SRA_I64] = "__ashrdi3";
37 Names[RTLIB::MUL_I32] = "__mulsi3";
38 Names[RTLIB::MUL_I64] = "__muldi3";
39 Names[RTLIB::SDIV_I32] = "__divsi3";
40 Names[RTLIB::SDIV_I64] = "__divdi3";
41 Names[RTLIB::UDIV_I32] = "__udivsi3";
42 Names[RTLIB::UDIV_I64] = "__udivdi3";
43 Names[RTLIB::SREM_I32] = "__modsi3";
44 Names[RTLIB::SREM_I64] = "__moddi3";
45 Names[RTLIB::UREM_I32] = "__umodsi3";
46 Names[RTLIB::UREM_I64] = "__umoddi3";
47 Names[RTLIB::NEG_I32] = "__negsi2";
48 Names[RTLIB::NEG_I64] = "__negdi2";
49 Names[RTLIB::ADD_F32] = "__addsf3";
50 Names[RTLIB::ADD_F64] = "__adddf3";
51 Names[RTLIB::ADD_F80] = "__addxf3";
52 Names[RTLIB::ADD_PPCF128] = "__gcc_qadd";
53 Names[RTLIB::SUB_F32] = "__subsf3";
54 Names[RTLIB::SUB_F64] = "__subdf3";
55 Names[RTLIB::SUB_F80] = "__subxf3";
56 Names[RTLIB::SUB_PPCF128] = "__gcc_qsub";
57 Names[RTLIB::MUL_F32] = "__mulsf3";
58 Names[RTLIB::MUL_F64] = "__muldf3";
59 Names[RTLIB::MUL_F80] = "__mulxf3";
60 Names[RTLIB::MUL_PPCF128] = "__gcc_qmul";
61 Names[RTLIB::DIV_F32] = "__divsf3";
62 Names[RTLIB::DIV_F64] = "__divdf3";
63 Names[RTLIB::DIV_F80] = "__divxf3";
64 Names[RTLIB::DIV_PPCF128] = "__gcc_qdiv";
65 Names[RTLIB::REM_F32] = "fmodf";
66 Names[RTLIB::REM_F64] = "fmod";
67 Names[RTLIB::REM_F80] = "fmodl";
68 Names[RTLIB::REM_PPCF128] = "fmodl";
69 Names[RTLIB::POWI_F32] = "__powisf2";
70 Names[RTLIB::POWI_F64] = "__powidf2";
71 Names[RTLIB::POWI_F80] = "__powixf2";
72 Names[RTLIB::POWI_PPCF128] = "__powitf2";
73 Names[RTLIB::SQRT_F32] = "sqrtf";
74 Names[RTLIB::SQRT_F64] = "sqrt";
75 Names[RTLIB::SQRT_F80] = "sqrtl";
76 Names[RTLIB::SQRT_PPCF128] = "sqrtl";
77 Names[RTLIB::SIN_F32] = "sinf";
78 Names[RTLIB::SIN_F64] = "sin";
79 Names[RTLIB::SIN_F80] = "sinl";
80 Names[RTLIB::SIN_PPCF128] = "sinl";
81 Names[RTLIB::COS_F32] = "cosf";
82 Names[RTLIB::COS_F64] = "cos";
83 Names[RTLIB::COS_F80] = "cosl";
84 Names[RTLIB::COS_PPCF128] = "cosl";
85 Names[RTLIB::POW_F32] = "powf";
86 Names[RTLIB::POW_F64] = "pow";
87 Names[RTLIB::POW_F80] = "powl";
88 Names[RTLIB::POW_PPCF128] = "powl";
89 Names[RTLIB::FPEXT_F32_F64] = "__extendsfdf2";
90 Names[RTLIB::FPROUND_F64_F32] = "__truncdfsf2";
91 Names[RTLIB::FPTOSINT_F32_I32] = "__fixsfsi";
92 Names[RTLIB::FPTOSINT_F32_I64] = "__fixsfdi";
93 Names[RTLIB::FPTOSINT_F64_I32] = "__fixdfsi";
94 Names[RTLIB::FPTOSINT_F64_I64] = "__fixdfdi";
95 Names[RTLIB::FPTOSINT_F80_I64] = "__fixxfdi";
96 Names[RTLIB::FPTOSINT_PPCF128_I64] = "__fixtfdi";
97 Names[RTLIB::FPTOUINT_F32_I32] = "__fixunssfsi";
98 Names[RTLIB::FPTOUINT_F32_I64] = "__fixunssfdi";
99 Names[RTLIB::FPTOUINT_F64_I32] = "__fixunsdfsi";
100 Names[RTLIB::FPTOUINT_F64_I64] = "__fixunsdfdi";
101 Names[RTLIB::FPTOUINT_F80_I32] = "__fixunsxfsi";
102 Names[RTLIB::FPTOUINT_F80_I64] = "__fixunsxfdi";
103 Names[RTLIB::FPTOUINT_PPCF128_I64] = "__fixunstfdi";
104 Names[RTLIB::SINTTOFP_I32_F32] = "__floatsisf";
105 Names[RTLIB::SINTTOFP_I32_F64] = "__floatsidf";
106 Names[RTLIB::SINTTOFP_I64_F32] = "__floatdisf";
107 Names[RTLIB::SINTTOFP_I64_F64] = "__floatdidf";
108 Names[RTLIB::SINTTOFP_I64_F80] = "__floatdixf";
109 Names[RTLIB::SINTTOFP_I64_PPCF128] = "__floatditf";
110 Names[RTLIB::SINTTOFP_I128_F32] = "__floattisf";
111 Names[RTLIB::SINTTOFP_I128_F64] = "__floattidf";
112 Names[RTLIB::SINTTOFP_I128_F80] = "__floattixf";
113 Names[RTLIB::SINTTOFP_I128_PPCF128] = "__floattitf";
114 Names[RTLIB::UINTTOFP_I32_F32] = "__floatunsisf";
115 Names[RTLIB::UINTTOFP_I32_F64] = "__floatunsidf";
116 Names[RTLIB::UINTTOFP_I64_F32] = "__floatundisf";
117 Names[RTLIB::UINTTOFP_I64_F64] = "__floatundidf";
118 Names[RTLIB::OEQ_F32] = "__eqsf2";
119 Names[RTLIB::OEQ_F64] = "__eqdf2";
120 Names[RTLIB::UNE_F32] = "__nesf2";
121 Names[RTLIB::UNE_F64] = "__nedf2";
122 Names[RTLIB::OGE_F32] = "__gesf2";
123 Names[RTLIB::OGE_F64] = "__gedf2";
124 Names[RTLIB::OLT_F32] = "__ltsf2";
125 Names[RTLIB::OLT_F64] = "__ltdf2";
126 Names[RTLIB::OLE_F32] = "__lesf2";
127 Names[RTLIB::OLE_F64] = "__ledf2";
128 Names[RTLIB::OGT_F32] = "__gtsf2";
129 Names[RTLIB::OGT_F64] = "__gtdf2";
130 Names[RTLIB::UO_F32] = "__unordsf2";
131 Names[RTLIB::UO_F64] = "__unorddf2";
132 Names[RTLIB::O_F32] = "__unordsf2";
133 Names[RTLIB::O_F64] = "__unorddf2";
136 /// InitCmpLibcallCCs - Set default comparison libcall CC.
138 static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
139 memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL);
140 CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
141 CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
142 CCs[RTLIB::UNE_F32] = ISD::SETNE;
143 CCs[RTLIB::UNE_F64] = ISD::SETNE;
144 CCs[RTLIB::OGE_F32] = ISD::SETGE;
145 CCs[RTLIB::OGE_F64] = ISD::SETGE;
146 CCs[RTLIB::OLT_F32] = ISD::SETLT;
147 CCs[RTLIB::OLT_F64] = ISD::SETLT;
148 CCs[RTLIB::OLE_F32] = ISD::SETLE;
149 CCs[RTLIB::OLE_F64] = ISD::SETLE;
150 CCs[RTLIB::OGT_F32] = ISD::SETGT;
151 CCs[RTLIB::OGT_F64] = ISD::SETGT;
152 CCs[RTLIB::UO_F32] = ISD::SETNE;
153 CCs[RTLIB::UO_F64] = ISD::SETNE;
154 CCs[RTLIB::O_F32] = ISD::SETEQ;
155 CCs[RTLIB::O_F64] = ISD::SETEQ;
158 TargetLowering::TargetLowering(TargetMachine &tm)
159 : TM(tm), TD(TM.getTargetData()) {
160 assert(ISD::BUILTIN_OP_END <= 156 &&
161 "Fixed size array in TargetLowering is not large enough!");
162 // All operations default to being supported.
163 memset(OpActions, 0, sizeof(OpActions));
164 memset(LoadXActions, 0, sizeof(LoadXActions));
165 memset(TruncStoreActions, 0, sizeof(TruncStoreActions));
166 memset(IndexedModeActions, 0, sizeof(IndexedModeActions));
167 memset(ConvertActions, 0, sizeof(ConvertActions));
169 // Set default actions for various operations.
170 for (unsigned VT = 0; VT != (unsigned)MVT::LAST_VALUETYPE; ++VT) {
171 // Default all indexed load / store to expand.
172 for (unsigned IM = (unsigned)ISD::PRE_INC;
173 IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
174 setIndexedLoadAction(IM, (MVT::ValueType)VT, Expand);
175 setIndexedStoreAction(IM, (MVT::ValueType)VT, Expand);
178 // These operations default to expand.
179 setOperationAction(ISD::FGETSIGN, (MVT::ValueType)VT, Expand);
182 // Most targets ignore the @llvm.prefetch intrinsic.
183 setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
185 // ConstantFP nodes default to expand. Targets can either change this to
186 // Legal, in which case all fp constants are legal, or use addLegalFPImmediate
187 // to optimize expansions for certain constants.
188 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
189 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
190 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
192 // Default ISD::TRAP to expand (which turns it into abort).
193 setOperationAction(ISD::TRAP, MVT::Other, Expand);
195 IsLittleEndian = TD->isLittleEndian();
196 UsesGlobalOffsetTable = false;
197 ShiftAmountTy = PointerTy = getValueType(TD->getIntPtrType());
198 ShiftAmtHandling = Undefined;
199 memset(RegClassForVT, 0,MVT::LAST_VALUETYPE*sizeof(TargetRegisterClass*));
200 memset(TargetDAGCombineArray, 0, array_lengthof(TargetDAGCombineArray));
201 maxStoresPerMemset = maxStoresPerMemcpy = maxStoresPerMemmove = 8;
202 allowUnalignedMemoryAccesses = false;
203 UseUnderscoreSetJmp = false;
204 UseUnderscoreLongJmp = false;
205 SelectIsExpensive = false;
206 IntDivIsCheap = false;
207 Pow2DivIsCheap = false;
208 StackPointerRegisterToSaveRestore = 0;
209 ExceptionPointerRegister = 0;
210 ExceptionSelectorRegister = 0;
211 SetCCResultContents = UndefinedSetCCResult;
212 SchedPreferenceInfo = SchedulingForLatency;
214 JumpBufAlignment = 0;
215 IfCvtBlockSizeLimit = 2;
216 IfCvtDupBlockSizeLimit = 0;
217 PrefLoopAlignment = 0;
219 InitLibcallNames(LibcallRoutineNames);
220 InitCmpLibcallCCs(CmpLibcallCCs);
222 // Tell Legalize whether the assembler supports DEBUG_LOC.
223 if (!TM.getTargetAsmInfo()->hasDotLocAndDotFile())
224 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
227 TargetLowering::~TargetLowering() {}
230 SDOperand TargetLowering::LowerMEMCPY(SDOperand Op, SelectionDAG &DAG) {
231 assert(getSubtarget() && "Subtarget not defined");
232 SDOperand ChainOp = Op.getOperand(0);
233 SDOperand DestOp = Op.getOperand(1);
234 SDOperand SourceOp = Op.getOperand(2);
235 SDOperand CountOp = Op.getOperand(3);
236 SDOperand AlignOp = Op.getOperand(4);
237 SDOperand AlwaysInlineOp = Op.getOperand(5);
239 bool AlwaysInline = (bool)cast<ConstantSDNode>(AlwaysInlineOp)->getValue();
240 unsigned Align = (unsigned)cast<ConstantSDNode>(AlignOp)->getValue();
241 if (Align == 0) Align = 1;
243 // If size is unknown, call memcpy.
244 ConstantSDNode *I = dyn_cast<ConstantSDNode>(CountOp);
246 assert(!AlwaysInline && "Cannot inline copy of unknown size");
247 return LowerMEMCPYCall(ChainOp, DestOp, SourceOp, CountOp, DAG);
250 // If not DWORD aligned or if size is more than threshold, then call memcpy.
251 // The libc version is likely to be faster for the following cases. It can
252 // use the address value and run time information about the CPU.
253 // With glibc 2.6.1 on a core 2, coping an array of 100M longs was 30% faster
254 unsigned Size = I->getValue();
256 (Size <= getSubtarget()->getMaxInlineSizeThreshold() &&
258 return LowerMEMCPYInline(ChainOp, DestOp, SourceOp, Size, Align, DAG);
259 return LowerMEMCPYCall(ChainOp, DestOp, SourceOp, CountOp, DAG);
263 SDOperand TargetLowering::LowerMEMCPYCall(SDOperand Chain,
268 MVT::ValueType IntPtr = getPointerTy();
269 TargetLowering::ArgListTy Args;
270 TargetLowering::ArgListEntry Entry;
271 Entry.Ty = getTargetData()->getIntPtrType();
272 Entry.Node = Dest; Args.push_back(Entry);
273 Entry.Node = Source; Args.push_back(Entry);
274 Entry.Node = Count; Args.push_back(Entry);
275 std::pair<SDOperand,SDOperand> CallResult =
276 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
277 false, DAG.getExternalSymbol("memcpy", IntPtr), Args, DAG);
278 return CallResult.second;
282 /// computeRegisterProperties - Once all of the register classes are added,
283 /// this allows us to compute derived properties we expose.
284 void TargetLowering::computeRegisterProperties() {
285 assert(MVT::LAST_VALUETYPE <= 32 &&
286 "Too many value types for ValueTypeActions to hold!");
288 // Everything defaults to needing one register.
289 for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
290 NumRegistersForVT[i] = 1;
291 RegisterTypeForVT[i] = TransformToType[i] = i;
293 // ...except isVoid, which doesn't need any registers.
294 NumRegistersForVT[MVT::isVoid] = 0;
296 // Find the largest integer register class.
297 unsigned LargestIntReg = MVT::i128;
298 for (; RegClassForVT[LargestIntReg] == 0; --LargestIntReg)
299 assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
301 // Every integer value type larger than this largest register takes twice as
302 // many registers to represent as the previous ValueType.
303 for (MVT::ValueType ExpandedReg = LargestIntReg + 1;
304 MVT::isInteger(ExpandedReg); ++ExpandedReg) {
305 NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
306 RegisterTypeForVT[ExpandedReg] = LargestIntReg;
307 TransformToType[ExpandedReg] = ExpandedReg - 1;
308 ValueTypeActions.setTypeAction(ExpandedReg, Expand);
311 // Inspect all of the ValueType's smaller than the largest integer
312 // register to see which ones need promotion.
313 MVT::ValueType LegalIntReg = LargestIntReg;
314 for (MVT::ValueType IntReg = LargestIntReg - 1;
315 IntReg >= MVT::i1; --IntReg) {
316 if (isTypeLegal(IntReg)) {
317 LegalIntReg = IntReg;
319 RegisterTypeForVT[IntReg] = TransformToType[IntReg] = LegalIntReg;
320 ValueTypeActions.setTypeAction(IntReg, Promote);
324 // ppcf128 type is really two f64's.
325 if (!isTypeLegal(MVT::ppcf128)) {
326 NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
327 RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
328 TransformToType[MVT::ppcf128] = MVT::f64;
329 ValueTypeActions.setTypeAction(MVT::ppcf128, Expand);
332 // Decide how to handle f64. If the target does not have native f64 support,
333 // expand it to i64 and we will be generating soft float library calls.
334 if (!isTypeLegal(MVT::f64)) {
335 NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
336 RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
337 TransformToType[MVT::f64] = MVT::i64;
338 ValueTypeActions.setTypeAction(MVT::f64, Expand);
341 // Decide how to handle f32. If the target does not have native support for
342 // f32, promote it to f64 if it is legal. Otherwise, expand it to i32.
343 if (!isTypeLegal(MVT::f32)) {
344 if (isTypeLegal(MVT::f64)) {
345 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::f64];
346 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::f64];
347 TransformToType[MVT::f32] = MVT::f64;
348 ValueTypeActions.setTypeAction(MVT::f32, Promote);
350 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
351 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
352 TransformToType[MVT::f32] = MVT::i32;
353 ValueTypeActions.setTypeAction(MVT::f32, Expand);
357 // Loop over all of the vector value types to see which need transformations.
358 for (MVT::ValueType i = MVT::FIRST_VECTOR_VALUETYPE;
359 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
360 if (!isTypeLegal(i)) {
361 MVT::ValueType IntermediateVT, RegisterVT;
362 unsigned NumIntermediates;
363 NumRegistersForVT[i] =
364 getVectorTypeBreakdown(i,
365 IntermediateVT, NumIntermediates,
367 RegisterTypeForVT[i] = RegisterVT;
368 TransformToType[i] = MVT::Other; // this isn't actually used
369 ValueTypeActions.setTypeAction(i, Expand);
374 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
380 TargetLowering::getSetCCResultType(const SDOperand &) const {
381 return getValueType(TD->getIntPtrType());
385 /// getVectorTypeBreakdown - Vector types are broken down into some number of
386 /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32
387 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
388 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
390 /// This method returns the number of registers needed, and the VT for each
391 /// register. It also returns the VT and quantity of the intermediate values
392 /// before they are promoted/expanded.
394 unsigned TargetLowering::getVectorTypeBreakdown(MVT::ValueType VT,
395 MVT::ValueType &IntermediateVT,
396 unsigned &NumIntermediates,
397 MVT::ValueType &RegisterVT) const {
398 // Figure out the right, legal destination reg to copy into.
399 unsigned NumElts = MVT::getVectorNumElements(VT);
400 MVT::ValueType EltTy = MVT::getVectorElementType(VT);
402 unsigned NumVectorRegs = 1;
404 // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we
405 // could break down into LHS/RHS like LegalizeDAG does.
406 if (!isPowerOf2_32(NumElts)) {
407 NumVectorRegs = NumElts;
411 // Divide the input until we get to a supported size. This will always
412 // end with a scalar if the target doesn't support vectors.
413 while (NumElts > 1 &&
414 !isTypeLegal(MVT::getVectorType(EltTy, NumElts))) {
419 NumIntermediates = NumVectorRegs;
421 MVT::ValueType NewVT = MVT::getVectorType(EltTy, NumElts);
422 if (!isTypeLegal(NewVT))
424 IntermediateVT = NewVT;
426 MVT::ValueType DestVT = getTypeToTransformTo(NewVT);
428 if (DestVT < NewVT) {
429 // Value is expanded, e.g. i64 -> i16.
430 return NumVectorRegs*(MVT::getSizeInBits(NewVT)/MVT::getSizeInBits(DestVT));
432 // Otherwise, promotion or legal types use the same number of registers as
433 // the vector decimated to the appropriate level.
434 return NumVectorRegs;
440 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
441 /// function arguments in the caller parameter area. This is the actual
442 /// alignment, not its logarithm.
443 unsigned TargetLowering::getByValTypeAlignment(const Type *Ty) const {
444 return TD->getCallFrameTypeAlignment(Ty);
447 SDOperand TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
448 SelectionDAG &DAG) const {
449 if (usesGlobalOffsetTable())
450 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
454 //===----------------------------------------------------------------------===//
455 // Optimization Methods
456 //===----------------------------------------------------------------------===//
458 /// ShrinkDemandedConstant - Check to see if the specified operand of the
459 /// specified instruction is a constant integer. If so, check to see if there
460 /// are any bits set in the constant that are not demanded. If so, shrink the
461 /// constant and return true.
462 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDOperand Op,
463 const APInt &Demanded) {
464 // FIXME: ISD::SELECT, ISD::SELECT_CC
465 switch(Op.getOpcode()) {
470 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
471 if (C->getAPIntValue().intersects(~Demanded)) {
472 MVT::ValueType VT = Op.getValueType();
473 SDOperand New = DAG.getNode(Op.getOpcode(), VT, Op.getOperand(0),
474 DAG.getConstant(Demanded &
477 return CombineTo(Op, New);
484 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
485 /// DemandedMask bits of the result of Op are ever used downstream. If we can
486 /// use this information to simplify Op, create a new simplified DAG node and
487 /// return true, returning the original and new nodes in Old and New. Otherwise,
488 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
489 /// the expression (used to simplify the caller). The KnownZero/One bits may
490 /// only be accurate for those bits in the DemandedMask.
491 bool TargetLowering::SimplifyDemandedBits(SDOperand Op,
492 const APInt &DemandedMask,
495 TargetLoweringOpt &TLO,
496 unsigned Depth) const {
497 unsigned BitWidth = DemandedMask.getBitWidth();
498 assert(Op.getValueSizeInBits() == BitWidth &&
499 "Mask size mismatches value type size!");
500 APInt NewMask = DemandedMask;
502 // Don't know anything.
503 KnownZero = KnownOne = APInt(BitWidth, 0);
505 // Other users may use these bits.
506 if (!Op.Val->hasOneUse()) {
508 // If not at the root, Just compute the KnownZero/KnownOne bits to
509 // simplify things downstream.
510 TLO.DAG.ComputeMaskedBits(Op, DemandedMask, KnownZero, KnownOne, Depth);
513 // If this is the root being simplified, allow it to have multiple uses,
514 // just set the NewMask to all bits.
515 NewMask = APInt::getAllOnesValue(BitWidth);
516 } else if (DemandedMask == 0) {
517 // Not demanding any bits from Op.
518 if (Op.getOpcode() != ISD::UNDEF)
519 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::UNDEF, Op.getValueType()));
521 } else if (Depth == 6) { // Limit search depth.
525 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
526 switch (Op.getOpcode()) {
528 // We know all of the bits for a constant!
529 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & NewMask;
530 KnownZero = ~KnownOne & NewMask;
531 return false; // Don't fall through, will infinitely loop.
533 // If the RHS is a constant, check to see if the LHS would be zero without
534 // using the bits from the RHS. Below, we use knowledge about the RHS to
535 // simplify the LHS, here we're using information from the LHS to simplify
537 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
538 APInt LHSZero, LHSOne;
539 TLO.DAG.ComputeMaskedBits(Op.getOperand(0), NewMask,
540 LHSZero, LHSOne, Depth+1);
541 // If the LHS already has zeros where RHSC does, this and is dead.
542 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
543 return TLO.CombineTo(Op, Op.getOperand(0));
544 // If any of the set bits in the RHS are known zero on the LHS, shrink
546 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
550 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
551 KnownOne, TLO, Depth+1))
553 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
554 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
555 KnownZero2, KnownOne2, TLO, Depth+1))
557 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
559 // If all of the demanded bits are known one on one side, return the other.
560 // These bits cannot contribute to the result of the 'and'.
561 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
562 return TLO.CombineTo(Op, Op.getOperand(0));
563 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
564 return TLO.CombineTo(Op, Op.getOperand(1));
565 // If all of the demanded bits in the inputs are known zeros, return zero.
566 if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
567 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType()));
568 // If the RHS is a constant, see if we can simplify it.
569 if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
572 // Output known-1 bits are only known if set in both the LHS & RHS.
573 KnownOne &= KnownOne2;
574 // Output known-0 are known to be clear if zero in either the LHS | RHS.
575 KnownZero |= KnownZero2;
578 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
579 KnownOne, TLO, Depth+1))
581 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
582 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
583 KnownZero2, KnownOne2, TLO, Depth+1))
585 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
587 // If all of the demanded bits are known zero on one side, return the other.
588 // These bits cannot contribute to the result of the 'or'.
589 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
590 return TLO.CombineTo(Op, Op.getOperand(0));
591 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
592 return TLO.CombineTo(Op, Op.getOperand(1));
593 // If all of the potentially set bits on one side are known to be set on
594 // the other side, just use the 'other' side.
595 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
596 return TLO.CombineTo(Op, Op.getOperand(0));
597 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
598 return TLO.CombineTo(Op, Op.getOperand(1));
599 // If the RHS is a constant, see if we can simplify it.
600 if (TLO.ShrinkDemandedConstant(Op, NewMask))
603 // Output known-0 bits are only known if clear in both the LHS & RHS.
604 KnownZero &= KnownZero2;
605 // Output known-1 are known to be set if set in either the LHS | RHS.
606 KnownOne |= KnownOne2;
609 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
610 KnownOne, TLO, Depth+1))
612 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
613 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
614 KnownOne2, TLO, Depth+1))
616 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
618 // If all of the demanded bits are known zero on one side, return the other.
619 // These bits cannot contribute to the result of the 'xor'.
620 if ((KnownZero & NewMask) == NewMask)
621 return TLO.CombineTo(Op, Op.getOperand(0));
622 if ((KnownZero2 & NewMask) == NewMask)
623 return TLO.CombineTo(Op, Op.getOperand(1));
625 // If all of the unknown bits are known to be zero on one side or the other
626 // (but not both) turn this into an *inclusive* or.
627 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
628 if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
629 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, Op.getValueType(),
633 // Output known-0 bits are known if clear or set in both the LHS & RHS.
634 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
635 // Output known-1 are known to be set if set in only one of the LHS, RHS.
636 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
638 // If all of the demanded bits on one side are known, and all of the set
639 // bits on that side are also known to be set on the other side, turn this
640 // into an AND, as we know the bits will be cleared.
641 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
642 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known
643 if ((KnownOne & KnownOne2) == KnownOne) {
644 MVT::ValueType VT = Op.getValueType();
645 SDOperand ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, VT);
646 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, VT, Op.getOperand(0),
651 // If the RHS is a constant, see if we can simplify it.
652 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
653 if (TLO.ShrinkDemandedConstant(Op, NewMask))
656 KnownZero = KnownZeroOut;
657 KnownOne = KnownOneOut;
660 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
661 KnownOne, TLO, Depth+1))
663 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
664 KnownOne2, TLO, Depth+1))
666 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
667 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
669 // If the operands are constants, see if we can simplify them.
670 if (TLO.ShrinkDemandedConstant(Op, NewMask))
673 // Only known if known in both the LHS and RHS.
674 KnownOne &= KnownOne2;
675 KnownZero &= KnownZero2;
678 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
679 KnownOne, TLO, Depth+1))
681 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
682 KnownOne2, TLO, Depth+1))
684 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
685 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
687 // If the operands are constants, see if we can simplify them.
688 if (TLO.ShrinkDemandedConstant(Op, NewMask))
691 // Only known if known in both the LHS and RHS.
692 KnownOne &= KnownOne2;
693 KnownZero &= KnownZero2;
696 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
697 unsigned ShAmt = SA->getValue();
698 SDOperand InOp = Op.getOperand(0);
700 // If the shift count is an invalid immediate, don't do anything.
701 if (ShAmt >= BitWidth)
704 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
705 // single shift. We can do this if the bottom bits (which are shifted
706 // out) are never demanded.
707 if (InOp.getOpcode() == ISD::SRL &&
708 isa<ConstantSDNode>(InOp.getOperand(1))) {
709 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
710 unsigned C1 = cast<ConstantSDNode>(InOp.getOperand(1))->getValue();
711 unsigned Opc = ISD::SHL;
719 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
720 MVT::ValueType VT = Op.getValueType();
721 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, VT,
722 InOp.getOperand(0), NewSA));
726 if (SimplifyDemandedBits(Op.getOperand(0), NewMask.lshr(ShAmt),
727 KnownZero, KnownOne, TLO, Depth+1))
729 KnownZero <<= SA->getValue();
730 KnownOne <<= SA->getValue();
731 // low bits known zero.
732 KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getValue());
736 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
737 MVT::ValueType VT = Op.getValueType();
738 unsigned ShAmt = SA->getValue();
739 unsigned VTSize = MVT::getSizeInBits(VT);
740 SDOperand InOp = Op.getOperand(0);
742 // If the shift count is an invalid immediate, don't do anything.
743 if (ShAmt >= BitWidth)
746 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
747 // single shift. We can do this if the top bits (which are shifted out)
748 // are never demanded.
749 if (InOp.getOpcode() == ISD::SHL &&
750 isa<ConstantSDNode>(InOp.getOperand(1))) {
751 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
752 unsigned C1 = cast<ConstantSDNode>(InOp.getOperand(1))->getValue();
753 unsigned Opc = ISD::SRL;
761 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
762 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, VT,
763 InOp.getOperand(0), NewSA));
767 // Compute the new bits that are at the top now.
768 if (SimplifyDemandedBits(InOp, (NewMask << ShAmt),
769 KnownZero, KnownOne, TLO, Depth+1))
771 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
772 KnownZero = KnownZero.lshr(ShAmt);
773 KnownOne = KnownOne.lshr(ShAmt);
775 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
776 KnownZero |= HighBits; // High bits known zero.
780 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
781 MVT::ValueType VT = Op.getValueType();
782 unsigned ShAmt = SA->getValue();
784 // If the shift count is an invalid immediate, don't do anything.
785 if (ShAmt >= BitWidth)
788 APInt InDemandedMask = (NewMask << ShAmt);
790 // If any of the demanded bits are produced by the sign extension, we also
791 // demand the input sign bit.
792 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
793 if (HighBits.intersects(NewMask))
794 InDemandedMask |= APInt::getSignBit(MVT::getSizeInBits(VT));
796 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
797 KnownZero, KnownOne, TLO, Depth+1))
799 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
800 KnownZero = KnownZero.lshr(ShAmt);
801 KnownOne = KnownOne.lshr(ShAmt);
803 // Handle the sign bit, adjusted to where it is now in the mask.
804 APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
806 // If the input sign bit is known to be zero, or if none of the top bits
807 // are demanded, turn this into an unsigned shift right.
808 if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
809 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, VT, Op.getOperand(0),
811 } else if (KnownOne.intersects(SignBit)) { // New bits are known one.
812 KnownOne |= HighBits;
816 case ISD::SIGN_EXTEND_INREG: {
817 MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
819 // Sign extension. Compute the demanded bits in the result that are not
820 // present in the input.
821 APInt NewBits = APInt::getHighBitsSet(BitWidth,
822 BitWidth - MVT::getSizeInBits(EVT)) &
825 // If none of the extended bits are demanded, eliminate the sextinreg.
827 return TLO.CombineTo(Op, Op.getOperand(0));
829 APInt InSignBit = APInt::getSignBit(MVT::getSizeInBits(EVT));
830 InSignBit.zext(BitWidth);
831 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth,
832 MVT::getSizeInBits(EVT)) &
835 // Since the sign extended bits are demanded, we know that the sign
837 InputDemandedBits |= InSignBit;
839 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
840 KnownZero, KnownOne, TLO, Depth+1))
842 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
844 // If the sign bit of the input is known set or clear, then we know the
845 // top bits of the result.
847 // If the input sign bit is known zero, convert this into a zero extension.
848 if (KnownZero.intersects(InSignBit))
849 return TLO.CombineTo(Op,
850 TLO.DAG.getZeroExtendInReg(Op.getOperand(0), EVT));
852 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
854 KnownZero &= ~NewBits;
855 } else { // Input sign bit unknown
856 KnownZero &= ~NewBits;
857 KnownOne &= ~NewBits;
861 case ISD::ZERO_EXTEND: {
862 unsigned OperandBitWidth = Op.getOperand(0).getValueSizeInBits();
863 APInt InMask = NewMask;
864 InMask.trunc(OperandBitWidth);
866 // If none of the top bits are demanded, convert this into an any_extend.
868 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
869 if (!NewBits.intersects(NewMask))
870 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND,
874 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
875 KnownZero, KnownOne, TLO, Depth+1))
877 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
878 KnownZero.zext(BitWidth);
879 KnownOne.zext(BitWidth);
880 KnownZero |= NewBits;
883 case ISD::SIGN_EXTEND: {
884 MVT::ValueType InVT = Op.getOperand(0).getValueType();
885 unsigned InBits = MVT::getSizeInBits(InVT);
886 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits);
887 APInt InSignBit = APInt::getLowBitsSet(BitWidth, InBits);
888 APInt NewBits = ~InMask & NewMask;
890 // If none of the top bits are demanded, convert this into an any_extend.
892 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND,Op.getValueType(),
895 // Since some of the sign extended bits are demanded, we know that the sign
897 APInt InDemandedBits = InMask & NewMask;
898 InDemandedBits |= InSignBit;
899 InDemandedBits.trunc(InBits);
901 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
902 KnownOne, TLO, Depth+1))
904 KnownZero.zext(BitWidth);
905 KnownOne.zext(BitWidth);
907 // If the sign bit is known zero, convert this to a zero extend.
908 if (KnownZero.intersects(InSignBit))
909 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND,
913 // If the sign bit is known one, the top bits match.
914 if (KnownOne.intersects(InSignBit)) {
916 KnownZero &= ~NewBits;
917 } else { // Otherwise, top bits aren't known.
918 KnownOne &= ~NewBits;
919 KnownZero &= ~NewBits;
923 case ISD::ANY_EXTEND: {
924 unsigned OperandBitWidth = Op.getOperand(0).getValueSizeInBits();
925 APInt InMask = NewMask;
926 InMask.trunc(OperandBitWidth);
927 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
928 KnownZero, KnownOne, TLO, Depth+1))
930 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
931 KnownZero.zext(BitWidth);
932 KnownOne.zext(BitWidth);
935 case ISD::TRUNCATE: {
936 // Simplify the input, using demanded bit information, and compute the known
937 // zero/one bits live out.
938 APInt TruncMask = NewMask;
939 TruncMask.zext(Op.getOperand(0).getValueSizeInBits());
940 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
941 KnownZero, KnownOne, TLO, Depth+1))
943 KnownZero.trunc(BitWidth);
944 KnownOne.trunc(BitWidth);
946 // If the input is only used by this truncate, see if we can shrink it based
947 // on the known demanded bits.
948 if (Op.getOperand(0).Val->hasOneUse()) {
949 SDOperand In = Op.getOperand(0);
950 unsigned InBitWidth = In.getValueSizeInBits();
951 switch (In.getOpcode()) {
954 // Shrink SRL by a constant if none of the high bits shifted in are
956 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1))){
957 APInt HighBits = APInt::getHighBitsSet(InBitWidth,
958 InBitWidth - BitWidth);
959 HighBits = HighBits.lshr(ShAmt->getValue());
960 HighBits.trunc(BitWidth);
962 if (ShAmt->getValue() < BitWidth && !(HighBits & NewMask)) {
963 // None of the shifted in bits are needed. Add a truncate of the
964 // shift input, then shift it.
965 SDOperand NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE,
968 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL,Op.getValueType(),
969 NewTrunc, In.getOperand(1)));
976 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
979 case ISD::AssertZext: {
980 MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
981 APInt InMask = APInt::getLowBitsSet(BitWidth,
982 MVT::getSizeInBits(VT));
983 if (SimplifyDemandedBits(Op.getOperand(0), InMask & NewMask,
984 KnownZero, KnownOne, TLO, Depth+1))
986 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
987 KnownZero |= ~InMask & NewMask;
990 case ISD::BIT_CONVERT:
992 // If this is an FP->Int bitcast and if the sign bit is the only thing that
993 // is demanded, turn this into a FGETSIGN.
994 if (NewMask == MVT::getIntVTSignBit(Op.getValueType()) &&
995 MVT::isFloatingPoint(Op.getOperand(0).getValueType()) &&
996 !MVT::isVector(Op.getOperand(0).getValueType())) {
997 // Only do this xform if FGETSIGN is valid or if before legalize.
998 if (!TLO.AfterLegalize ||
999 isOperationLegal(ISD::FGETSIGN, Op.getValueType())) {
1000 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1001 // place. We expect the SHL to be eliminated by other optimizations.
1002 SDOperand Sign = TLO.DAG.getNode(ISD::FGETSIGN, Op.getValueType(),
1004 unsigned ShVal = MVT::getSizeInBits(Op.getValueType())-1;
1005 SDOperand ShAmt = TLO.DAG.getConstant(ShVal, getShiftAmountTy());
1006 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, Op.getValueType(),
1014 case ISD::INTRINSIC_WO_CHAIN:
1015 case ISD::INTRINSIC_W_CHAIN:
1016 case ISD::INTRINSIC_VOID:
1023 // Just use ComputeMaskedBits to compute output bits.
1024 TLO.DAG.ComputeMaskedBits(Op, NewMask, KnownZero, KnownOne, Depth);
1028 // If we know the value of all of the demanded bits, return this as a
1030 if ((NewMask & (KnownZero|KnownOne)) == NewMask)
1031 return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
1036 /// computeMaskedBitsForTargetNode - Determine which of the bits specified
1037 /// in Mask are known to be either zero or one and return them in the
1038 /// KnownZero/KnownOne bitsets.
1039 void TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
1043 const SelectionDAG &DAG,
1044 unsigned Depth) const {
1045 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1046 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1047 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1048 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1049 "Should use MaskedValueIsZero if you don't know whether Op"
1050 " is a target node!");
1051 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
1054 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
1055 /// targets that want to expose additional information about sign bits to the
1057 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDOperand Op,
1058 unsigned Depth) const {
1059 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1060 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1061 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1062 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1063 "Should use ComputeNumSignBits if you don't know whether Op"
1064 " is a target node!");
1069 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
1070 /// and cc. If it is unable to simplify it, return a null SDOperand.
1072 TargetLowering::SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
1073 ISD::CondCode Cond, bool foldBooleans,
1074 DAGCombinerInfo &DCI) const {
1075 SelectionDAG &DAG = DCI.DAG;
1077 // These setcc operations always fold.
1081 case ISD::SETFALSE2: return DAG.getConstant(0, VT);
1083 case ISD::SETTRUE2: return DAG.getConstant(1, VT);
1086 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1087 const APInt &C1 = N1C->getAPIntValue();
1088 if (isa<ConstantSDNode>(N0.Val)) {
1089 return DAG.FoldSetCC(VT, N0, N1, Cond);
1091 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1092 // equality comparison, then we're just comparing whether X itself is
1094 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1095 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1096 N0.getOperand(1).getOpcode() == ISD::Constant) {
1097 unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1098 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1099 ShAmt == Log2_32(MVT::getSizeInBits(N0.getValueType()))) {
1100 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1101 // (srl (ctlz x), 5) == 0 -> X != 0
1102 // (srl (ctlz x), 5) != 1 -> X != 0
1105 // (srl (ctlz x), 5) != 0 -> X == 0
1106 // (srl (ctlz x), 5) == 1 -> X == 0
1109 SDOperand Zero = DAG.getConstant(0, N0.getValueType());
1110 return DAG.getSetCC(VT, N0.getOperand(0).getOperand(0),
1115 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1116 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1117 unsigned InSize = MVT::getSizeInBits(N0.getOperand(0).getValueType());
1119 // If the comparison constant has bits in the upper part, the
1120 // zero-extended value could never match.
1121 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1122 C1.getBitWidth() - InSize))) {
1126 case ISD::SETEQ: return DAG.getConstant(0, VT);
1129 case ISD::SETNE: return DAG.getConstant(1, VT);
1132 // True if the sign bit of C1 is set.
1133 return DAG.getConstant(C1.isNegative(), VT);
1136 // True if the sign bit of C1 isn't set.
1137 return DAG.getConstant(C1.isNonNegative(), VT);
1143 // Otherwise, we can perform the comparison with the low bits.
1151 return DAG.getSetCC(VT, N0.getOperand(0),
1152 DAG.getConstant(APInt(C1).trunc(InSize),
1153 N0.getOperand(0).getValueType()),
1156 break; // todo, be more careful with signed comparisons
1158 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1159 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1160 MVT::ValueType ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
1161 unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
1162 MVT::ValueType ExtDstTy = N0.getValueType();
1163 unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
1165 // If the extended part has any inconsistent bits, it cannot ever
1166 // compare equal. In other words, they have to be all ones or all
1169 APInt::getHighBitsSet(ExtDstTyBits, ExtDstTyBits - ExtSrcTyBits);
1170 if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits)
1171 return DAG.getConstant(Cond == ISD::SETNE, VT);
1174 MVT::ValueType Op0Ty = N0.getOperand(0).getValueType();
1175 if (Op0Ty == ExtSrcTy) {
1176 ZextOp = N0.getOperand(0);
1178 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1179 ZextOp = DAG.getNode(ISD::AND, Op0Ty, N0.getOperand(0),
1180 DAG.getConstant(Imm, Op0Ty));
1182 if (!DCI.isCalledByLegalizer())
1183 DCI.AddToWorklist(ZextOp.Val);
1184 // Otherwise, make this a use of a zext.
1185 return DAG.getSetCC(VT, ZextOp,
1186 DAG.getConstant(C1 & APInt::getLowBitsSet(
1191 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1192 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1194 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
1195 if (N0.getOpcode() == ISD::SETCC) {
1196 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getValue() != 1);
1200 // Invert the condition.
1201 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1202 CC = ISD::getSetCCInverse(CC,
1203 MVT::isInteger(N0.getOperand(0).getValueType()));
1204 return DAG.getSetCC(VT, N0.getOperand(0), N0.getOperand(1), CC);
1207 if ((N0.getOpcode() == ISD::XOR ||
1208 (N0.getOpcode() == ISD::AND &&
1209 N0.getOperand(0).getOpcode() == ISD::XOR &&
1210 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1211 isa<ConstantSDNode>(N0.getOperand(1)) &&
1212 cast<ConstantSDNode>(N0.getOperand(1))->getValue() == 1) {
1213 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
1214 // can only do this if the top bits are known zero.
1215 unsigned BitWidth = N0.getValueSizeInBits();
1216 if (DAG.MaskedValueIsZero(N0,
1217 APInt::getHighBitsSet(BitWidth,
1219 // Okay, get the un-inverted input value.
1221 if (N0.getOpcode() == ISD::XOR)
1222 Val = N0.getOperand(0);
1224 assert(N0.getOpcode() == ISD::AND &&
1225 N0.getOperand(0).getOpcode() == ISD::XOR);
1226 // ((X^1)&1)^1 -> X & 1
1227 Val = DAG.getNode(ISD::AND, N0.getValueType(),
1228 N0.getOperand(0).getOperand(0),
1231 return DAG.getSetCC(VT, Val, N1,
1232 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1237 APInt MinVal, MaxVal;
1238 unsigned OperandBitSize = MVT::getSizeInBits(N1C->getValueType(0));
1239 if (ISD::isSignedIntSetCC(Cond)) {
1240 MinVal = APInt::getSignedMinValue(OperandBitSize);
1241 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1243 MinVal = APInt::getMinValue(OperandBitSize);
1244 MaxVal = APInt::getMaxValue(OperandBitSize);
1247 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1248 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1249 if (C1 == MinVal) return DAG.getConstant(1, VT); // X >= MIN --> true
1250 // X >= C0 --> X > (C0-1)
1251 return DAG.getSetCC(VT, N0, DAG.getConstant(C1-1, N1.getValueType()),
1252 (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
1255 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1256 if (C1 == MaxVal) return DAG.getConstant(1, VT); // X <= MAX --> true
1257 // X <= C0 --> X < (C0+1)
1258 return DAG.getSetCC(VT, N0, DAG.getConstant(C1+1, N1.getValueType()),
1259 (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
1262 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1263 return DAG.getConstant(0, VT); // X < MIN --> false
1264 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1265 return DAG.getConstant(1, VT); // X >= MIN --> true
1266 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1267 return DAG.getConstant(0, VT); // X > MAX --> false
1268 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1269 return DAG.getConstant(1, VT); // X <= MAX --> true
1271 // Canonicalize setgt X, Min --> setne X, Min
1272 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1273 return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
1274 // Canonicalize setlt X, Max --> setne X, Max
1275 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1276 return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
1278 // If we have setult X, 1, turn it into seteq X, 0
1279 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1280 return DAG.getSetCC(VT, N0, DAG.getConstant(MinVal, N0.getValueType()),
1282 // If we have setugt X, Max-1, turn it into seteq X, Max
1283 else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1284 return DAG.getSetCC(VT, N0, DAG.getConstant(MaxVal, N0.getValueType()),
1287 // If we have "setcc X, C0", check to see if we can shrink the immediate
1290 // SETUGT X, SINTMAX -> SETLT X, 0
1291 if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
1292 C1 == (~0ULL >> (65-OperandBitSize)))
1293 return DAG.getSetCC(VT, N0, DAG.getConstant(0, N1.getValueType()),
1296 // FIXME: Implement the rest of these.
1298 // Fold bit comparisons when we can.
1299 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1300 VT == N0.getValueType() && N0.getOpcode() == ISD::AND)
1301 if (ConstantSDNode *AndRHS =
1302 dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1303 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
1304 // Perform the xform if the AND RHS is a single bit.
1305 if (isPowerOf2_64(AndRHS->getValue())) {
1306 return DAG.getNode(ISD::SRL, VT, N0,
1307 DAG.getConstant(Log2_64(AndRHS->getValue()),
1308 getShiftAmountTy()));
1310 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getValue()) {
1311 // (X & 8) == 8 --> (X & 8) >> 3
1312 // Perform the xform if C1 is a single bit.
1313 if (C1.isPowerOf2()) {
1314 return DAG.getNode(ISD::SRL, VT, N0,
1315 DAG.getConstant(C1.logBase2(), getShiftAmountTy()));
1320 } else if (isa<ConstantSDNode>(N0.Val)) {
1321 // Ensure that the constant occurs on the RHS.
1322 return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
1325 if (isa<ConstantFPSDNode>(N0.Val)) {
1326 // Constant fold or commute setcc.
1327 SDOperand O = DAG.FoldSetCC(VT, N0, N1, Cond);
1328 if (O.Val) return O;
1329 } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1330 // If the RHS of an FP comparison is a constant, simplify it away in
1332 if (CFP->getValueAPF().isNaN()) {
1333 // If an operand is known to be a nan, we can fold it.
1334 switch (ISD::getUnorderedFlavor(Cond)) {
1335 default: assert(0 && "Unknown flavor!");
1336 case 0: // Known false.
1337 return DAG.getConstant(0, VT);
1338 case 1: // Known true.
1339 return DAG.getConstant(1, VT);
1340 case 2: // Undefined.
1341 return DAG.getNode(ISD::UNDEF, VT);
1345 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
1346 // constant if knowing that the operand is non-nan is enough. We prefer to
1347 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
1349 if (Cond == ISD::SETO || Cond == ISD::SETUO)
1350 return DAG.getSetCC(VT, N0, N0, Cond);
1354 // We can always fold X == X for integer setcc's.
1355 if (MVT::isInteger(N0.getValueType()))
1356 return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
1357 unsigned UOF = ISD::getUnorderedFlavor(Cond);
1358 if (UOF == 2) // FP operators that are undefined on NaNs.
1359 return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
1360 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
1361 return DAG.getConstant(UOF, VT);
1362 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
1363 // if it is not already.
1364 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
1365 if (NewCond != Cond)
1366 return DAG.getSetCC(VT, N0, N1, NewCond);
1369 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1370 MVT::isInteger(N0.getValueType())) {
1371 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
1372 N0.getOpcode() == ISD::XOR) {
1373 // Simplify (X+Y) == (X+Z) --> Y == Z
1374 if (N0.getOpcode() == N1.getOpcode()) {
1375 if (N0.getOperand(0) == N1.getOperand(0))
1376 return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(1), Cond);
1377 if (N0.getOperand(1) == N1.getOperand(1))
1378 return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(0), Cond);
1379 if (DAG.isCommutativeBinOp(N0.getOpcode())) {
1380 // If X op Y == Y op X, try other combinations.
1381 if (N0.getOperand(0) == N1.getOperand(1))
1382 return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(0), Cond);
1383 if (N0.getOperand(1) == N1.getOperand(0))
1384 return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(1), Cond);
1388 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
1389 if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1390 // Turn (X+C1) == C2 --> X == C2-C1
1391 if (N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse()) {
1392 return DAG.getSetCC(VT, N0.getOperand(0),
1393 DAG.getConstant(RHSC->getValue()-LHSR->getValue(),
1394 N0.getValueType()), Cond);
1397 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
1398 if (N0.getOpcode() == ISD::XOR)
1399 // If we know that all of the inverted bits are zero, don't bother
1400 // performing the inversion.
1401 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
1403 DAG.getSetCC(VT, N0.getOperand(0),
1404 DAG.getConstant(LHSR->getAPIntValue() ^
1405 RHSC->getAPIntValue(),
1410 // Turn (C1-X) == C2 --> X == C1-C2
1411 if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1412 if (N0.getOpcode() == ISD::SUB && N0.Val->hasOneUse()) {
1414 DAG.getSetCC(VT, N0.getOperand(1),
1415 DAG.getConstant(SUBC->getAPIntValue() -
1416 RHSC->getAPIntValue(),
1423 // Simplify (X+Z) == X --> Z == 0
1424 if (N0.getOperand(0) == N1)
1425 return DAG.getSetCC(VT, N0.getOperand(1),
1426 DAG.getConstant(0, N0.getValueType()), Cond);
1427 if (N0.getOperand(1) == N1) {
1428 if (DAG.isCommutativeBinOp(N0.getOpcode()))
1429 return DAG.getSetCC(VT, N0.getOperand(0),
1430 DAG.getConstant(0, N0.getValueType()), Cond);
1431 else if (N0.Val->hasOneUse()) {
1432 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
1433 // (Z-X) == X --> Z == X<<1
1434 SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(),
1436 DAG.getConstant(1, getShiftAmountTy()));
1437 if (!DCI.isCalledByLegalizer())
1438 DCI.AddToWorklist(SH.Val);
1439 return DAG.getSetCC(VT, N0.getOperand(0), SH, Cond);
1444 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
1445 N1.getOpcode() == ISD::XOR) {
1446 // Simplify X == (X+Z) --> Z == 0
1447 if (N1.getOperand(0) == N0) {
1448 return DAG.getSetCC(VT, N1.getOperand(1),
1449 DAG.getConstant(0, N1.getValueType()), Cond);
1450 } else if (N1.getOperand(1) == N0) {
1451 if (DAG.isCommutativeBinOp(N1.getOpcode())) {
1452 return DAG.getSetCC(VT, N1.getOperand(0),
1453 DAG.getConstant(0, N1.getValueType()), Cond);
1454 } else if (N1.Val->hasOneUse()) {
1455 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
1456 // X == (Z-X) --> X<<1 == Z
1457 SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(), N0,
1458 DAG.getConstant(1, getShiftAmountTy()));
1459 if (!DCI.isCalledByLegalizer())
1460 DCI.AddToWorklist(SH.Val);
1461 return DAG.getSetCC(VT, SH, N1.getOperand(0), Cond);
1467 // Fold away ALL boolean setcc's.
1469 if (N0.getValueType() == MVT::i1 && foldBooleans) {
1471 default: assert(0 && "Unknown integer setcc!");
1472 case ISD::SETEQ: // X == Y -> (X^Y)^1
1473 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
1474 N0 = DAG.getNode(ISD::XOR, MVT::i1, Temp, DAG.getConstant(1, MVT::i1));
1475 if (!DCI.isCalledByLegalizer())
1476 DCI.AddToWorklist(Temp.Val);
1478 case ISD::SETNE: // X != Y --> (X^Y)
1479 N0 = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
1481 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> X^1 & Y
1482 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> X^1 & Y
1483 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
1484 N0 = DAG.getNode(ISD::AND, MVT::i1, N1, Temp);
1485 if (!DCI.isCalledByLegalizer())
1486 DCI.AddToWorklist(Temp.Val);
1488 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> Y^1 & X
1489 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> Y^1 & X
1490 Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
1491 N0 = DAG.getNode(ISD::AND, MVT::i1, N0, Temp);
1492 if (!DCI.isCalledByLegalizer())
1493 DCI.AddToWorklist(Temp.Val);
1495 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> X^1 | Y
1496 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> X^1 | Y
1497 Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
1498 N0 = DAG.getNode(ISD::OR, MVT::i1, N1, Temp);
1499 if (!DCI.isCalledByLegalizer())
1500 DCI.AddToWorklist(Temp.Val);
1502 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> Y^1 | X
1503 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> Y^1 | X
1504 Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
1505 N0 = DAG.getNode(ISD::OR, MVT::i1, N0, Temp);
1508 if (VT != MVT::i1) {
1509 if (!DCI.isCalledByLegalizer())
1510 DCI.AddToWorklist(N0.Val);
1511 // FIXME: If running after legalize, we probably can't do this.
1512 N0 = DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
1517 // Could not fold it.
1521 SDOperand TargetLowering::
1522 PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1523 // Default implementation: no optimization.
1527 //===----------------------------------------------------------------------===//
1528 // Inline Assembler Implementation Methods
1529 //===----------------------------------------------------------------------===//
1531 TargetLowering::ConstraintType
1532 TargetLowering::getConstraintType(const std::string &Constraint) const {
1533 // FIXME: lots more standard ones to handle.
1534 if (Constraint.size() == 1) {
1535 switch (Constraint[0]) {
1537 case 'r': return C_RegisterClass;
1539 case 'o': // offsetable
1540 case 'V': // not offsetable
1542 case 'i': // Simple Integer or Relocatable Constant
1543 case 'n': // Simple Integer
1544 case 's': // Relocatable Constant
1545 case 'X': // Allow ANY value.
1546 case 'I': // Target registers.
1558 if (Constraint.size() > 1 && Constraint[0] == '{' &&
1559 Constraint[Constraint.size()-1] == '}')
1564 /// LowerXConstraint - try to replace an X constraint, which matches anything,
1565 /// with another that has more specific requirements based on the type of the
1566 /// corresponding operand.
1567 void TargetLowering::lowerXConstraint(MVT::ValueType ConstraintVT,
1568 std::string& s) const {
1569 if (MVT::isInteger(ConstraintVT))
1571 else if (MVT::isFloatingPoint(ConstraintVT))
1572 s = "f"; // works for many targets
1577 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1578 /// vector. If it is invalid, don't add anything to Ops.
1579 void TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
1580 char ConstraintLetter,
1581 std::vector<SDOperand> &Ops,
1582 SelectionDAG &DAG) {
1583 switch (ConstraintLetter) {
1585 case 'X': // Allows any operand; labels (basic block) use this.
1586 if (Op.getOpcode() == ISD::BasicBlock) {
1591 case 'i': // Simple Integer or Relocatable Constant
1592 case 'n': // Simple Integer
1593 case 's': { // Relocatable Constant
1594 // These operands are interested in values of the form (GV+C), where C may
1595 // be folded in as an offset of GV, or it may be explicitly added. Also, it
1596 // is possible and fine if either GV or C are missing.
1597 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
1598 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1600 // If we have "(add GV, C)", pull out GV/C
1601 if (Op.getOpcode() == ISD::ADD) {
1602 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1603 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
1604 if (C == 0 || GA == 0) {
1605 C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1606 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
1608 if (C == 0 || GA == 0)
1612 // If we find a valid operand, map to the TargetXXX version so that the
1613 // value itself doesn't get selected.
1614 if (GA) { // Either &GV or &GV+C
1615 if (ConstraintLetter != 'n') {
1616 int64_t Offs = GA->getOffset();
1617 if (C) Offs += C->getValue();
1618 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
1619 Op.getValueType(), Offs));
1623 if (C) { // just C, no GV.
1624 // Simple constants are not allowed for 's'.
1625 if (ConstraintLetter != 's') {
1626 Ops.push_back(DAG.getTargetConstant(C->getValue(), Op.getValueType()));
1635 std::vector<unsigned> TargetLowering::
1636 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1637 MVT::ValueType VT) const {
1638 return std::vector<unsigned>();
1642 std::pair<unsigned, const TargetRegisterClass*> TargetLowering::
1643 getRegForInlineAsmConstraint(const std::string &Constraint,
1644 MVT::ValueType VT) const {
1645 if (Constraint[0] != '{')
1646 return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
1647 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
1649 // Remove the braces from around the name.
1650 std::string RegName(Constraint.begin()+1, Constraint.end()-1);
1652 // Figure out which register class contains this reg.
1653 const TargetRegisterInfo *RI = TM.getRegisterInfo();
1654 for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
1655 E = RI->regclass_end(); RCI != E; ++RCI) {
1656 const TargetRegisterClass *RC = *RCI;
1658 // If none of the the value types for this register class are valid, we
1659 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1660 bool isLegal = false;
1661 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1663 if (isTypeLegal(*I)) {
1669 if (!isLegal) continue;
1671 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
1673 if (StringsEqualNoCase(RegName, RI->get(*I).AsmName))
1674 return std::make_pair(*I, RC);
1678 return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
1681 //===----------------------------------------------------------------------===//
1682 // Loop Strength Reduction hooks
1683 //===----------------------------------------------------------------------===//
1685 /// isLegalAddressingMode - Return true if the addressing mode represented
1686 /// by AM is legal for this target, for a load/store of the specified type.
1687 bool TargetLowering::isLegalAddressingMode(const AddrMode &AM,
1688 const Type *Ty) const {
1689 // The default implementation of this implements a conservative RISCy, r+r and
1692 // Allows a sign-extended 16-bit immediate field.
1693 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
1696 // No global is ever allowed as a base.
1700 // Only support r+r,
1702 case 0: // "r+i" or just "i", depending on HasBaseReg.
1705 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
1707 // Otherwise we have r+r or r+i.
1710 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
1712 // Allow 2*r as r+r.
1719 // Magic for divide replacement
1722 int64_t m; // magic number
1723 int64_t s; // shift amount
1727 uint64_t m; // magic number
1728 int64_t a; // add indicator
1729 int64_t s; // shift amount
1732 /// magic - calculate the magic numbers required to codegen an integer sdiv as
1733 /// a sequence of multiply and shifts. Requires that the divisor not be 0, 1,
1735 static ms magic32(int32_t d) {
1737 uint32_t ad, anc, delta, q1, r1, q2, r2, t;
1738 const uint32_t two31 = 0x80000000U;
1742 t = two31 + ((uint32_t)d >> 31);
1743 anc = t - 1 - t%ad; // absolute value of nc
1744 p = 31; // initialize p
1745 q1 = two31/anc; // initialize q1 = 2p/abs(nc)
1746 r1 = two31 - q1*anc; // initialize r1 = rem(2p,abs(nc))
1747 q2 = two31/ad; // initialize q2 = 2p/abs(d)
1748 r2 = two31 - q2*ad; // initialize r2 = rem(2p,abs(d))
1751 q1 = 2*q1; // update q1 = 2p/abs(nc)
1752 r1 = 2*r1; // update r1 = rem(2p/abs(nc))
1753 if (r1 >= anc) { // must be unsigned comparison
1757 q2 = 2*q2; // update q2 = 2p/abs(d)
1758 r2 = 2*r2; // update r2 = rem(2p/abs(d))
1759 if (r2 >= ad) { // must be unsigned comparison
1764 } while (q1 < delta || (q1 == delta && r1 == 0));
1766 mag.m = (int32_t)(q2 + 1); // make sure to sign extend
1767 if (d < 0) mag.m = -mag.m; // resulting magic number
1768 mag.s = p - 32; // resulting shift
1772 /// magicu - calculate the magic numbers required to codegen an integer udiv as
1773 /// a sequence of multiply, add and shifts. Requires that the divisor not be 0.
1774 static mu magicu32(uint32_t d) {
1776 uint32_t nc, delta, q1, r1, q2, r2;
1778 magu.a = 0; // initialize "add" indicator
1780 p = 31; // initialize p
1781 q1 = 0x80000000/nc; // initialize q1 = 2p/nc
1782 r1 = 0x80000000 - q1*nc; // initialize r1 = rem(2p,nc)
1783 q2 = 0x7FFFFFFF/d; // initialize q2 = (2p-1)/d
1784 r2 = 0x7FFFFFFF - q2*d; // initialize r2 = rem((2p-1),d)
1787 if (r1 >= nc - r1 ) {
1788 q1 = 2*q1 + 1; // update q1
1789 r1 = 2*r1 - nc; // update r1
1792 q1 = 2*q1; // update q1
1793 r1 = 2*r1; // update r1
1795 if (r2 + 1 >= d - r2) {
1796 if (q2 >= 0x7FFFFFFF) magu.a = 1;
1797 q2 = 2*q2 + 1; // update q2
1798 r2 = 2*r2 + 1 - d; // update r2
1801 if (q2 >= 0x80000000) magu.a = 1;
1802 q2 = 2*q2; // update q2
1803 r2 = 2*r2 + 1; // update r2
1806 } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
1807 magu.m = q2 + 1; // resulting magic number
1808 magu.s = p - 32; // resulting shift
1812 /// magic - calculate the magic numbers required to codegen an integer sdiv as
1813 /// a sequence of multiply and shifts. Requires that the divisor not be 0, 1,
1815 static ms magic64(int64_t d) {
1817 uint64_t ad, anc, delta, q1, r1, q2, r2, t;
1818 const uint64_t two63 = 9223372036854775808ULL; // 2^63
1821 ad = d >= 0 ? d : -d;
1822 t = two63 + ((uint64_t)d >> 63);
1823 anc = t - 1 - t%ad; // absolute value of nc
1824 p = 63; // initialize p
1825 q1 = two63/anc; // initialize q1 = 2p/abs(nc)
1826 r1 = two63 - q1*anc; // initialize r1 = rem(2p,abs(nc))
1827 q2 = two63/ad; // initialize q2 = 2p/abs(d)
1828 r2 = two63 - q2*ad; // initialize r2 = rem(2p,abs(d))
1831 q1 = 2*q1; // update q1 = 2p/abs(nc)
1832 r1 = 2*r1; // update r1 = rem(2p/abs(nc))
1833 if (r1 >= anc) { // must be unsigned comparison
1837 q2 = 2*q2; // update q2 = 2p/abs(d)
1838 r2 = 2*r2; // update r2 = rem(2p/abs(d))
1839 if (r2 >= ad) { // must be unsigned comparison
1844 } while (q1 < delta || (q1 == delta && r1 == 0));
1847 if (d < 0) mag.m = -mag.m; // resulting magic number
1848 mag.s = p - 64; // resulting shift
1852 /// magicu - calculate the magic numbers required to codegen an integer udiv as
1853 /// a sequence of multiply, add and shifts. Requires that the divisor not be 0.
1854 static mu magicu64(uint64_t d)
1857 uint64_t nc, delta, q1, r1, q2, r2;
1859 magu.a = 0; // initialize "add" indicator
1861 p = 63; // initialize p
1862 q1 = 0x8000000000000000ull/nc; // initialize q1 = 2p/nc
1863 r1 = 0x8000000000000000ull - q1*nc; // initialize r1 = rem(2p,nc)
1864 q2 = 0x7FFFFFFFFFFFFFFFull/d; // initialize q2 = (2p-1)/d
1865 r2 = 0x7FFFFFFFFFFFFFFFull - q2*d; // initialize r2 = rem((2p-1),d)
1868 if (r1 >= nc - r1 ) {
1869 q1 = 2*q1 + 1; // update q1
1870 r1 = 2*r1 - nc; // update r1
1873 q1 = 2*q1; // update q1
1874 r1 = 2*r1; // update r1
1876 if (r2 + 1 >= d - r2) {
1877 if (q2 >= 0x7FFFFFFFFFFFFFFFull) magu.a = 1;
1878 q2 = 2*q2 + 1; // update q2
1879 r2 = 2*r2 + 1 - d; // update r2
1882 if (q2 >= 0x8000000000000000ull) magu.a = 1;
1883 q2 = 2*q2; // update q2
1884 r2 = 2*r2 + 1; // update r2
1887 } while (p < 128 && (q1 < delta || (q1 == delta && r1 == 0)));
1888 magu.m = q2 + 1; // resulting magic number
1889 magu.s = p - 64; // resulting shift
1893 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
1894 /// return a DAG expression to select that will generate the same value by
1895 /// multiplying by a magic number. See:
1896 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
1897 SDOperand TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
1898 std::vector<SDNode*>* Created) const {
1899 MVT::ValueType VT = N->getValueType(0);
1901 // Check to see if we can do this.
1902 if (!isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
1903 return SDOperand(); // BuildSDIV only operates on i32 or i64
1905 int64_t d = cast<ConstantSDNode>(N->getOperand(1))->getSignExtended();
1906 ms magics = (VT == MVT::i32) ? magic32(d) : magic64(d);
1908 // Multiply the numerator (operand 0) by the magic value
1910 if (isOperationLegal(ISD::MULHS, VT))
1911 Q = DAG.getNode(ISD::MULHS, VT, N->getOperand(0),
1912 DAG.getConstant(magics.m, VT));
1913 else if (isOperationLegal(ISD::SMUL_LOHI, VT))
1914 Q = SDOperand(DAG.getNode(ISD::SMUL_LOHI, DAG.getVTList(VT, VT),
1916 DAG.getConstant(magics.m, VT)).Val, 1);
1918 return SDOperand(); // No mulhs or equvialent
1919 // If d > 0 and m < 0, add the numerator
1920 if (d > 0 && magics.m < 0) {
1921 Q = DAG.getNode(ISD::ADD, VT, Q, N->getOperand(0));
1923 Created->push_back(Q.Val);
1925 // If d < 0 and m > 0, subtract the numerator.
1926 if (d < 0 && magics.m > 0) {
1927 Q = DAG.getNode(ISD::SUB, VT, Q, N->getOperand(0));
1929 Created->push_back(Q.Val);
1931 // Shift right algebraic if shift value is nonzero
1933 Q = DAG.getNode(ISD::SRA, VT, Q,
1934 DAG.getConstant(magics.s, getShiftAmountTy()));
1936 Created->push_back(Q.Val);
1938 // Extract the sign bit and add it to the quotient
1940 DAG.getNode(ISD::SRL, VT, Q, DAG.getConstant(MVT::getSizeInBits(VT)-1,
1941 getShiftAmountTy()));
1943 Created->push_back(T.Val);
1944 return DAG.getNode(ISD::ADD, VT, Q, T);
1947 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
1948 /// return a DAG expression to select that will generate the same value by
1949 /// multiplying by a magic number. See:
1950 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
1951 SDOperand TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
1952 std::vector<SDNode*>* Created) const {
1953 MVT::ValueType VT = N->getValueType(0);
1955 // Check to see if we can do this.
1956 if (!isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
1957 return SDOperand(); // BuildUDIV only operates on i32 or i64
1959 uint64_t d = cast<ConstantSDNode>(N->getOperand(1))->getValue();
1960 mu magics = (VT == MVT::i32) ? magicu32(d) : magicu64(d);
1962 // Multiply the numerator (operand 0) by the magic value
1964 if (isOperationLegal(ISD::MULHU, VT))
1965 Q = DAG.getNode(ISD::MULHU, VT, N->getOperand(0),
1966 DAG.getConstant(magics.m, VT));
1967 else if (isOperationLegal(ISD::UMUL_LOHI, VT))
1968 Q = SDOperand(DAG.getNode(ISD::UMUL_LOHI, DAG.getVTList(VT, VT),
1970 DAG.getConstant(magics.m, VT)).Val, 1);
1972 return SDOperand(); // No mulhu or equvialent
1974 Created->push_back(Q.Val);
1976 if (magics.a == 0) {
1977 return DAG.getNode(ISD::SRL, VT, Q,
1978 DAG.getConstant(magics.s, getShiftAmountTy()));
1980 SDOperand NPQ = DAG.getNode(ISD::SUB, VT, N->getOperand(0), Q);
1982 Created->push_back(NPQ.Val);
1983 NPQ = DAG.getNode(ISD::SRL, VT, NPQ,
1984 DAG.getConstant(1, getShiftAmountTy()));
1986 Created->push_back(NPQ.Val);
1987 NPQ = DAG.getNode(ISD::ADD, VT, NPQ, Q);
1989 Created->push_back(NPQ.Val);
1990 return DAG.getNode(ISD::SRL, VT, NPQ,
1991 DAG.getConstant(magics.s-1, getShiftAmountTy()));