remove extraneous &'s.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / TargetLowering.cpp
1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Target/TargetLowering.h"
15 #include "llvm/Target/TargetSubtarget.h"
16 #include "llvm/Target/TargetData.h"
17 #include "llvm/Target/TargetMachine.h"
18 #include "llvm/Target/MRegisterInfo.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Target/TargetAsmInfo.h"
25 #include "llvm/CallingConv.h"
26 using namespace llvm;
27
28 /// InitLibcallNames - Set default libcall names.
29 ///
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::UINTTOFP_I32_F32] = "__floatunsisf";
111   Names[RTLIB::UINTTOFP_I32_F64] = "__floatunsidf";
112   Names[RTLIB::UINTTOFP_I64_F32] = "__floatundisf";
113   Names[RTLIB::UINTTOFP_I64_F64] = "__floatundidf";
114   Names[RTLIB::OEQ_F32] = "__eqsf2";
115   Names[RTLIB::OEQ_F64] = "__eqdf2";
116   Names[RTLIB::UNE_F32] = "__nesf2";
117   Names[RTLIB::UNE_F64] = "__nedf2";
118   Names[RTLIB::OGE_F32] = "__gesf2";
119   Names[RTLIB::OGE_F64] = "__gedf2";
120   Names[RTLIB::OLT_F32] = "__ltsf2";
121   Names[RTLIB::OLT_F64] = "__ltdf2";
122   Names[RTLIB::OLE_F32] = "__lesf2";
123   Names[RTLIB::OLE_F64] = "__ledf2";
124   Names[RTLIB::OGT_F32] = "__gtsf2";
125   Names[RTLIB::OGT_F64] = "__gtdf2";
126   Names[RTLIB::UO_F32] = "__unordsf2";
127   Names[RTLIB::UO_F64] = "__unorddf2";
128   Names[RTLIB::O_F32] = "__unordsf2";
129   Names[RTLIB::O_F64] = "__unorddf2";
130 }
131
132 /// InitCmpLibcallCCs - Set default comparison libcall CC.
133 ///
134 static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
135   memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL);
136   CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
137   CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
138   CCs[RTLIB::UNE_F32] = ISD::SETNE;
139   CCs[RTLIB::UNE_F64] = ISD::SETNE;
140   CCs[RTLIB::OGE_F32] = ISD::SETGE;
141   CCs[RTLIB::OGE_F64] = ISD::SETGE;
142   CCs[RTLIB::OLT_F32] = ISD::SETLT;
143   CCs[RTLIB::OLT_F64] = ISD::SETLT;
144   CCs[RTLIB::OLE_F32] = ISD::SETLE;
145   CCs[RTLIB::OLE_F64] = ISD::SETLE;
146   CCs[RTLIB::OGT_F32] = ISD::SETGT;
147   CCs[RTLIB::OGT_F64] = ISD::SETGT;
148   CCs[RTLIB::UO_F32] = ISD::SETNE;
149   CCs[RTLIB::UO_F64] = ISD::SETNE;
150   CCs[RTLIB::O_F32] = ISD::SETEQ;
151   CCs[RTLIB::O_F64] = ISD::SETEQ;
152 }
153
154 TargetLowering::TargetLowering(TargetMachine &tm)
155   : TM(tm), TD(TM.getTargetData()) {
156   assert(ISD::BUILTIN_OP_END <= 156 &&
157          "Fixed size array in TargetLowering is not large enough!");
158   // All operations default to being supported.
159   memset(OpActions, 0, sizeof(OpActions));
160   memset(LoadXActions, 0, sizeof(LoadXActions));
161   memset(TruncStoreActions, 0, sizeof(TruncStoreActions));
162   memset(IndexedModeActions, 0, sizeof(IndexedModeActions));
163   memset(ConvertActions, 0, sizeof(ConvertActions));
164
165   // Set default actions for various operations.
166   for (unsigned VT = 0; VT != (unsigned)MVT::LAST_VALUETYPE; ++VT) {
167     // Default all indexed load / store to expand.
168     for (unsigned IM = (unsigned)ISD::PRE_INC;
169          IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
170       setIndexedLoadAction(IM, (MVT::ValueType)VT, Expand);
171       setIndexedStoreAction(IM, (MVT::ValueType)VT, Expand);
172     }
173     
174     // These operations default to expand.
175     setOperationAction(ISD::FGETSIGN, (MVT::ValueType)VT, Expand);
176   }
177
178   // Default ISD::TRAP to expand (which turns it into abort).
179   setOperationAction(ISD::TRAP, MVT::Other, Expand);
180     
181   IsLittleEndian = TD->isLittleEndian();
182   UsesGlobalOffsetTable = false;
183   ShiftAmountTy = SetCCResultTy = PointerTy = getValueType(TD->getIntPtrType());
184   ShiftAmtHandling = Undefined;
185   memset(RegClassForVT, 0,MVT::LAST_VALUETYPE*sizeof(TargetRegisterClass*));
186   memset(TargetDAGCombineArray, 0, array_lengthof(TargetDAGCombineArray));
187   maxStoresPerMemset = maxStoresPerMemcpy = maxStoresPerMemmove = 8;
188   allowUnalignedMemoryAccesses = false;
189   UseUnderscoreSetJmp = false;
190   UseUnderscoreLongJmp = false;
191   SelectIsExpensive = false;
192   IntDivIsCheap = false;
193   Pow2DivIsCheap = false;
194   StackPointerRegisterToSaveRestore = 0;
195   ExceptionPointerRegister = 0;
196   ExceptionSelectorRegister = 0;
197   SetCCResultContents = UndefinedSetCCResult;
198   SchedPreferenceInfo = SchedulingForLatency;
199   JumpBufSize = 0;
200   JumpBufAlignment = 0;
201   IfCvtBlockSizeLimit = 2;
202
203   InitLibcallNames(LibcallRoutineNames);
204   InitCmpLibcallCCs(CmpLibcallCCs);
205
206   // Tell Legalize whether the assembler supports DEBUG_LOC.
207   if (!TM.getTargetAsmInfo()->hasDotLocAndDotFile())
208     setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
209 }
210
211 TargetLowering::~TargetLowering() {}
212
213
214 SDOperand TargetLowering::LowerMEMCPY(SDOperand Op, SelectionDAG &DAG) {
215   assert(getSubtarget() && "Subtarget not defined");
216   SDOperand ChainOp = Op.getOperand(0);
217   SDOperand DestOp = Op.getOperand(1);
218   SDOperand SourceOp = Op.getOperand(2);
219   SDOperand CountOp = Op.getOperand(3);
220   SDOperand AlignOp = Op.getOperand(4);
221   SDOperand AlwaysInlineOp = Op.getOperand(5);
222
223   bool AlwaysInline = (bool)cast<ConstantSDNode>(AlwaysInlineOp)->getValue();
224   unsigned Align = (unsigned)cast<ConstantSDNode>(AlignOp)->getValue();
225   if (Align == 0) Align = 1;
226
227   // If size is unknown, call memcpy.
228   ConstantSDNode *I = dyn_cast<ConstantSDNode>(CountOp);
229   if (!I) {
230     assert(!AlwaysInline && "Cannot inline copy of unknown size");
231     return LowerMEMCPYCall(ChainOp, DestOp, SourceOp, CountOp, DAG);
232   }
233
234   // If not DWORD aligned or if size is more than threshold, then call memcpy.
235   // The libc version is likely to be faster for the following cases. It can
236   // use the address value and run time information about the CPU.
237   // With glibc 2.6.1 on a core 2, coping an array of 100M longs was 30% faster
238   unsigned Size = I->getValue();
239   if (AlwaysInline ||
240       (Size <= getSubtarget()->getMaxInlineSizeThreshold() &&
241        (Align & 3) == 0))
242     return LowerMEMCPYInline(ChainOp, DestOp, SourceOp, Size, Align, DAG);
243   return LowerMEMCPYCall(ChainOp, DestOp, SourceOp, CountOp, DAG);
244 }
245
246
247 SDOperand TargetLowering::LowerMEMCPYCall(SDOperand Chain,
248                                           SDOperand Dest,
249                                           SDOperand Source,
250                                           SDOperand Count,
251                                           SelectionDAG &DAG) {
252   MVT::ValueType IntPtr = getPointerTy();
253   TargetLowering::ArgListTy Args;
254   TargetLowering::ArgListEntry Entry;
255   Entry.Ty = getTargetData()->getIntPtrType();
256   Entry.Node = Dest; Args.push_back(Entry);
257   Entry.Node = Source; Args.push_back(Entry);
258   Entry.Node = Count; Args.push_back(Entry);
259   std::pair<SDOperand,SDOperand> CallResult =
260       LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
261                   DAG.getExternalSymbol("memcpy", IntPtr), Args, DAG);
262   return CallResult.second;
263 }
264
265
266 /// computeRegisterProperties - Once all of the register classes are added,
267 /// this allows us to compute derived properties we expose.
268 void TargetLowering::computeRegisterProperties() {
269   assert(MVT::LAST_VALUETYPE <= 32 &&
270          "Too many value types for ValueTypeActions to hold!");
271
272   // Everything defaults to needing one register.
273   for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
274     NumRegistersForVT[i] = 1;
275     RegisterTypeForVT[i] = TransformToType[i] = i;
276   }
277   // ...except isVoid, which doesn't need any registers.
278   NumRegistersForVT[MVT::isVoid] = 0;
279
280   // Find the largest integer register class.
281   unsigned LargestIntReg = MVT::i128;
282   for (; RegClassForVT[LargestIntReg] == 0; --LargestIntReg)
283     assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
284
285   // Every integer value type larger than this largest register takes twice as
286   // many registers to represent as the previous ValueType.
287   for (MVT::ValueType ExpandedReg = LargestIntReg + 1;
288        MVT::isInteger(ExpandedReg); ++ExpandedReg) {
289     NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
290     RegisterTypeForVT[ExpandedReg] = LargestIntReg;
291     TransformToType[ExpandedReg] = ExpandedReg - 1;
292     ValueTypeActions.setTypeAction(ExpandedReg, Expand);
293   }
294
295   // Inspect all of the ValueType's smaller than the largest integer
296   // register to see which ones need promotion.
297   MVT::ValueType LegalIntReg = LargestIntReg;
298   for (MVT::ValueType IntReg = LargestIntReg - 1;
299        IntReg >= MVT::i1; --IntReg) {
300     if (isTypeLegal(IntReg)) {
301       LegalIntReg = IntReg;
302     } else {
303       RegisterTypeForVT[IntReg] = TransformToType[IntReg] = LegalIntReg;
304       ValueTypeActions.setTypeAction(IntReg, Promote);
305     }
306   }
307
308   // ppcf128 type is really two f64's.
309   if (!isTypeLegal(MVT::ppcf128)) {
310     NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
311     RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
312     TransformToType[MVT::ppcf128] = MVT::f64;
313     ValueTypeActions.setTypeAction(MVT::ppcf128, Expand);
314   }    
315
316   // Decide how to handle f64. If the target does not have native f64 support,
317   // expand it to i64 and we will be generating soft float library calls.
318   if (!isTypeLegal(MVT::f64)) {
319     NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
320     RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
321     TransformToType[MVT::f64] = MVT::i64;
322     ValueTypeActions.setTypeAction(MVT::f64, Expand);
323   }
324
325   // Decide how to handle f32. If the target does not have native support for
326   // f32, promote it to f64 if it is legal. Otherwise, expand it to i32.
327   if (!isTypeLegal(MVT::f32)) {
328     if (isTypeLegal(MVT::f64)) {
329       NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::f64];
330       RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::f64];
331       TransformToType[MVT::f32] = MVT::f64;
332       ValueTypeActions.setTypeAction(MVT::f32, Promote);
333     } else {
334       NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
335       RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
336       TransformToType[MVT::f32] = MVT::i32;
337       ValueTypeActions.setTypeAction(MVT::f32, Expand);
338     }
339   }
340   
341   // Loop over all of the vector value types to see which need transformations.
342   for (MVT::ValueType i = MVT::FIRST_VECTOR_VALUETYPE;
343        i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
344     if (!isTypeLegal(i)) {
345       MVT::ValueType IntermediateVT, RegisterVT;
346       unsigned NumIntermediates;
347       NumRegistersForVT[i] =
348         getVectorTypeBreakdown(i,
349                                IntermediateVT, NumIntermediates,
350                                RegisterVT);
351       RegisterTypeForVT[i] = RegisterVT;
352       TransformToType[i] = MVT::Other; // this isn't actually used
353       ValueTypeActions.setTypeAction(i, Expand);
354     }
355   }
356 }
357
358 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
359   return NULL;
360 }
361
362 /// getVectorTypeBreakdown - Vector types are broken down into some number of
363 /// legal first class types.  For example, MVT::v8f32 maps to 2 MVT::v4f32
364 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
365 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
366 ///
367 /// This method returns the number of registers needed, and the VT for each
368 /// register.  It also returns the VT and quantity of the intermediate values
369 /// before they are promoted/expanded.
370 ///
371 unsigned TargetLowering::getVectorTypeBreakdown(MVT::ValueType VT, 
372                                                 MVT::ValueType &IntermediateVT,
373                                                 unsigned &NumIntermediates,
374                                       MVT::ValueType &RegisterVT) const {
375   // Figure out the right, legal destination reg to copy into.
376   unsigned NumElts = MVT::getVectorNumElements(VT);
377   MVT::ValueType EltTy = MVT::getVectorElementType(VT);
378   
379   unsigned NumVectorRegs = 1;
380   
381   // FIXME: We don't support non-power-of-2-sized vectors for now.  Ideally we 
382   // could break down into LHS/RHS like LegalizeDAG does.
383   if (!isPowerOf2_32(NumElts)) {
384     NumVectorRegs = NumElts;
385     NumElts = 1;
386   }
387   
388   // Divide the input until we get to a supported size.  This will always
389   // end with a scalar if the target doesn't support vectors.
390   while (NumElts > 1 &&
391          !isTypeLegal(MVT::getVectorType(EltTy, NumElts))) {
392     NumElts >>= 1;
393     NumVectorRegs <<= 1;
394   }
395
396   NumIntermediates = NumVectorRegs;
397   
398   MVT::ValueType NewVT = MVT::getVectorType(EltTy, NumElts);
399   if (!isTypeLegal(NewVT))
400     NewVT = EltTy;
401   IntermediateVT = NewVT;
402
403   MVT::ValueType DestVT = getTypeToTransformTo(NewVT);
404   RegisterVT = DestVT;
405   if (DestVT < NewVT) {
406     // Value is expanded, e.g. i64 -> i16.
407     return NumVectorRegs*(MVT::getSizeInBits(NewVT)/MVT::getSizeInBits(DestVT));
408   } else {
409     // Otherwise, promotion or legal types use the same number of registers as
410     // the vector decimated to the appropriate level.
411     return NumVectorRegs;
412   }
413   
414   return 1;
415 }
416
417 SDOperand TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
418                                                    SelectionDAG &DAG) const {
419   if (usesGlobalOffsetTable())
420     return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
421   return Table;
422 }
423
424 //===----------------------------------------------------------------------===//
425 //  Optimization Methods
426 //===----------------------------------------------------------------------===//
427
428 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
429 /// specified instruction is a constant integer.  If so, check to see if there
430 /// are any bits set in the constant that are not demanded.  If so, shrink the
431 /// constant and return true.
432 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDOperand Op, 
433                                                             uint64_t Demanded) {
434   // FIXME: ISD::SELECT, ISD::SELECT_CC
435   switch(Op.getOpcode()) {
436   default: break;
437   case ISD::AND:
438   case ISD::OR:
439   case ISD::XOR:
440     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
441       if ((~Demanded & C->getValue()) != 0) {
442         MVT::ValueType VT = Op.getValueType();
443         SDOperand New = DAG.getNode(Op.getOpcode(), VT, Op.getOperand(0),
444                                     DAG.getConstant(Demanded & C->getValue(), 
445                                                     VT));
446         return CombineTo(Op, New);
447       }
448     break;
449   }
450   return false;
451 }
452
453 /// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
454 /// DemandedMask bits of the result of Op are ever used downstream.  If we can
455 /// use this information to simplify Op, create a new simplified DAG node and
456 /// return true, returning the original and new nodes in Old and New. Otherwise,
457 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
458 /// the expression (used to simplify the caller).  The KnownZero/One bits may
459 /// only be accurate for those bits in the DemandedMask.
460 bool TargetLowering::SimplifyDemandedBits(SDOperand Op, uint64_t DemandedMask, 
461                                           uint64_t &KnownZero,
462                                           uint64_t &KnownOne,
463                                           TargetLoweringOpt &TLO,
464                                           unsigned Depth) const {
465   KnownZero = KnownOne = 0;   // Don't know anything.
466
467   // The masks are not wide enough to represent this type!  Should use APInt.
468   if (Op.getValueType() == MVT::i128)
469     return false;
470   
471   // Other users may use these bits.
472   if (!Op.Val->hasOneUse()) { 
473     if (Depth != 0) {
474       // If not at the root, Just compute the KnownZero/KnownOne bits to 
475       // simplify things downstream.
476       TLO.DAG.ComputeMaskedBits(Op, DemandedMask, KnownZero, KnownOne, Depth);
477       return false;
478     }
479     // If this is the root being simplified, allow it to have multiple uses,
480     // just set the DemandedMask to all bits.
481     DemandedMask = MVT::getIntVTBitMask(Op.getValueType());
482   } else if (DemandedMask == 0) {   
483     // Not demanding any bits from Op.
484     if (Op.getOpcode() != ISD::UNDEF)
485       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::UNDEF, Op.getValueType()));
486     return false;
487   } else if (Depth == 6) {        // Limit search depth.
488     return false;
489   }
490
491   uint64_t KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
492   switch (Op.getOpcode()) {
493   case ISD::Constant:
494     // We know all of the bits for a constant!
495     KnownOne = cast<ConstantSDNode>(Op)->getValue() & DemandedMask;
496     KnownZero = ~KnownOne & DemandedMask;
497     return false;   // Don't fall through, will infinitely loop.
498   case ISD::AND:
499     // If the RHS is a constant, check to see if the LHS would be zero without
500     // using the bits from the RHS.  Below, we use knowledge about the RHS to
501     // simplify the LHS, here we're using information from the LHS to simplify
502     // the RHS.
503     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
504       uint64_t LHSZero, LHSOne;
505       TLO.DAG.ComputeMaskedBits(Op.getOperand(0), DemandedMask,
506                                 LHSZero, LHSOne, Depth+1);
507       // If the LHS already has zeros where RHSC does, this and is dead.
508       if ((LHSZero & DemandedMask) == (~RHSC->getValue() & DemandedMask))
509         return TLO.CombineTo(Op, Op.getOperand(0));
510       // If any of the set bits in the RHS are known zero on the LHS, shrink
511       // the constant.
512       if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & DemandedMask))
513         return true;
514     }
515     
516     if (SimplifyDemandedBits(Op.getOperand(1), DemandedMask, KnownZero,
517                              KnownOne, TLO, Depth+1))
518       return true;
519     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
520     if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & ~KnownZero,
521                              KnownZero2, KnownOne2, TLO, Depth+1))
522       return true;
523     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
524       
525     // If all of the demanded bits are known one on one side, return the other.
526     // These bits cannot contribute to the result of the 'and'.
527     if ((DemandedMask & ~KnownZero2 & KnownOne)==(DemandedMask & ~KnownZero2))
528       return TLO.CombineTo(Op, Op.getOperand(0));
529     if ((DemandedMask & ~KnownZero & KnownOne2)==(DemandedMask & ~KnownZero))
530       return TLO.CombineTo(Op, Op.getOperand(1));
531     // If all of the demanded bits in the inputs are known zeros, return zero.
532     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
533       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType()));
534     // If the RHS is a constant, see if we can simplify it.
535     if (TLO.ShrinkDemandedConstant(Op, DemandedMask & ~KnownZero2))
536       return true;
537       
538     // Output known-1 bits are only known if set in both the LHS & RHS.
539     KnownOne &= KnownOne2;
540     // Output known-0 are known to be clear if zero in either the LHS | RHS.
541     KnownZero |= KnownZero2;
542     break;
543   case ISD::OR:
544     if (SimplifyDemandedBits(Op.getOperand(1), DemandedMask, KnownZero, 
545                              KnownOne, TLO, Depth+1))
546       return true;
547     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
548     if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & ~KnownOne, 
549                              KnownZero2, KnownOne2, TLO, Depth+1))
550       return true;
551     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
552     
553     // If all of the demanded bits are known zero on one side, return the other.
554     // These bits cannot contribute to the result of the 'or'.
555     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
556       return TLO.CombineTo(Op, Op.getOperand(0));
557     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
558       return TLO.CombineTo(Op, Op.getOperand(1));
559     // If all of the potentially set bits on one side are known to be set on
560     // the other side, just use the 'other' side.
561     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
562         (DemandedMask & (~KnownZero)))
563       return TLO.CombineTo(Op, Op.getOperand(0));
564     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
565         (DemandedMask & (~KnownZero2)))
566       return TLO.CombineTo(Op, Op.getOperand(1));
567     // If the RHS is a constant, see if we can simplify it.
568     if (TLO.ShrinkDemandedConstant(Op, DemandedMask))
569       return true;
570           
571     // Output known-0 bits are only known if clear in both the LHS & RHS.
572     KnownZero &= KnownZero2;
573     // Output known-1 are known to be set if set in either the LHS | RHS.
574     KnownOne |= KnownOne2;
575     break;
576   case ISD::XOR:
577     if (SimplifyDemandedBits(Op.getOperand(1), DemandedMask, KnownZero, 
578                              KnownOne, TLO, Depth+1))
579       return true;
580     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
581     if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask, KnownZero2,
582                              KnownOne2, TLO, Depth+1))
583       return true;
584     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
585     
586     // If all of the demanded bits are known zero on one side, return the other.
587     // These bits cannot contribute to the result of the 'xor'.
588     if ((DemandedMask & KnownZero) == DemandedMask)
589       return TLO.CombineTo(Op, Op.getOperand(0));
590     if ((DemandedMask & KnownZero2) == DemandedMask)
591       return TLO.CombineTo(Op, Op.getOperand(1));
592       
593     // If all of the unknown bits are known to be zero on one side or the other
594     // (but not both) turn this into an *inclusive* or.
595     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
596     if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0)
597       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, Op.getValueType(),
598                                                Op.getOperand(0),
599                                                Op.getOperand(1)));
600     
601     // Output known-0 bits are known if clear or set in both the LHS & RHS.
602     KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
603     // Output known-1 are known to be set if set in only one of the LHS, RHS.
604     KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
605     
606     // If all of the demanded bits on one side are known, and all of the set
607     // bits on that side are also known to be set on the other side, turn this
608     // into an AND, as we know the bits will be cleared.
609     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
610     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
611       if ((KnownOne & KnownOne2) == KnownOne) {
612         MVT::ValueType VT = Op.getValueType();
613         SDOperand ANDC = TLO.DAG.getConstant(~KnownOne & DemandedMask, VT);
614         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, VT, Op.getOperand(0),
615                                                  ANDC));
616       }
617     }
618     
619     // If the RHS is a constant, see if we can simplify it.
620     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
621     if (TLO.ShrinkDemandedConstant(Op, DemandedMask))
622       return true;
623     
624     KnownZero = KnownZeroOut;
625     KnownOne  = KnownOneOut;
626     break;
627   case ISD::SETCC:
628     // If we know the result of a setcc has the top bits zero, use this info.
629     if (getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult)
630       KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
631     break;
632   case ISD::SELECT:
633     if (SimplifyDemandedBits(Op.getOperand(2), DemandedMask, KnownZero, 
634                              KnownOne, TLO, Depth+1))
635       return true;
636     if (SimplifyDemandedBits(Op.getOperand(1), DemandedMask, KnownZero2,
637                              KnownOne2, TLO, Depth+1))
638       return true;
639     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
640     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
641     
642     // If the operands are constants, see if we can simplify them.
643     if (TLO.ShrinkDemandedConstant(Op, DemandedMask))
644       return true;
645     
646     // Only known if known in both the LHS and RHS.
647     KnownOne &= KnownOne2;
648     KnownZero &= KnownZero2;
649     break;
650   case ISD::SELECT_CC:
651     if (SimplifyDemandedBits(Op.getOperand(3), DemandedMask, KnownZero, 
652                              KnownOne, TLO, Depth+1))
653       return true;
654     if (SimplifyDemandedBits(Op.getOperand(2), DemandedMask, KnownZero2,
655                              KnownOne2, TLO, Depth+1))
656       return true;
657     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
658     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
659     
660     // If the operands are constants, see if we can simplify them.
661     if (TLO.ShrinkDemandedConstant(Op, DemandedMask))
662       return true;
663       
664     // Only known if known in both the LHS and RHS.
665     KnownOne &= KnownOne2;
666     KnownZero &= KnownZero2;
667     break;
668   case ISD::SHL:
669     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
670       unsigned ShAmt = SA->getValue();
671       SDOperand InOp = Op.getOperand(0);
672
673       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
674       // single shift.  We can do this if the bottom bits (which are shifted
675       // out) are never demanded.
676       if (InOp.getOpcode() == ISD::SRL &&
677           isa<ConstantSDNode>(InOp.getOperand(1))) {
678         if (ShAmt && (DemandedMask & ((1ULL << ShAmt)-1)) == 0) {
679           unsigned C1 = cast<ConstantSDNode>(InOp.getOperand(1))->getValue();
680           unsigned Opc = ISD::SHL;
681           int Diff = ShAmt-C1;
682           if (Diff < 0) {
683             Diff = -Diff;
684             Opc = ISD::SRL;
685           }          
686           
687           SDOperand NewSA = 
688             TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
689           MVT::ValueType VT = Op.getValueType();
690           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, VT,
691                                                    InOp.getOperand(0), NewSA));
692         }
693       }      
694       
695       if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask >> ShAmt,
696                                KnownZero, KnownOne, TLO, Depth+1))
697         return true;
698       KnownZero <<= SA->getValue();
699       KnownOne  <<= SA->getValue();
700       KnownZero |= (1ULL << SA->getValue())-1;  // low bits known zero.
701     }
702     break;
703   case ISD::SRL:
704     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
705       MVT::ValueType VT = Op.getValueType();
706       unsigned ShAmt = SA->getValue();
707       uint64_t TypeMask = MVT::getIntVTBitMask(VT);
708       unsigned VTSize = MVT::getSizeInBits(VT);
709       SDOperand InOp = Op.getOperand(0);
710       
711       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
712       // single shift.  We can do this if the top bits (which are shifted out)
713       // are never demanded.
714       if (InOp.getOpcode() == ISD::SHL &&
715           isa<ConstantSDNode>(InOp.getOperand(1))) {
716         if (ShAmt && (DemandedMask & (~0ULL << (VTSize-ShAmt))) == 0) {
717           unsigned C1 = cast<ConstantSDNode>(InOp.getOperand(1))->getValue();
718           unsigned Opc = ISD::SRL;
719           int Diff = ShAmt-C1;
720           if (Diff < 0) {
721             Diff = -Diff;
722             Opc = ISD::SHL;
723           }          
724           
725           SDOperand NewSA =
726             TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
727           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, VT,
728                                                    InOp.getOperand(0), NewSA));
729         }
730       }      
731       
732       // Compute the new bits that are at the top now.
733       if (SimplifyDemandedBits(InOp, (DemandedMask << ShAmt) & TypeMask,
734                                KnownZero, KnownOne, TLO, Depth+1))
735         return true;
736       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
737       KnownZero &= TypeMask;
738       KnownOne  &= TypeMask;
739       KnownZero >>= ShAmt;
740       KnownOne  >>= ShAmt;
741
742       uint64_t HighBits = (1ULL << ShAmt)-1;
743       HighBits <<= VTSize - ShAmt;
744       KnownZero |= HighBits;  // High bits known zero.
745     }
746     break;
747   case ISD::SRA:
748     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
749       MVT::ValueType VT = Op.getValueType();
750       unsigned ShAmt = SA->getValue();
751       
752       // Compute the new bits that are at the top now.
753       uint64_t TypeMask = MVT::getIntVTBitMask(VT);
754       
755       uint64_t InDemandedMask = (DemandedMask << ShAmt) & TypeMask;
756
757       // If any of the demanded bits are produced by the sign extension, we also
758       // demand the input sign bit.
759       uint64_t HighBits = (1ULL << ShAmt)-1;
760       HighBits <<= MVT::getSizeInBits(VT) - ShAmt;
761       if (HighBits & DemandedMask)
762         InDemandedMask |= MVT::getIntVTSignBit(VT);
763       
764       if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
765                                KnownZero, KnownOne, TLO, Depth+1))
766         return true;
767       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
768       KnownZero &= TypeMask;
769       KnownOne  &= TypeMask;
770       KnownZero >>= ShAmt;
771       KnownOne  >>= ShAmt;
772       
773       // Handle the sign bits.
774       uint64_t SignBit = MVT::getIntVTSignBit(VT);
775       SignBit >>= ShAmt;  // Adjust to where it is now in the mask.
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 & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
780         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, VT, Op.getOperand(0),
781                                                  Op.getOperand(1)));
782       } else if (KnownOne & 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     uint64_t NewBits = ~MVT::getIntVTBitMask(EVT) & DemandedMask;
793     
794     // If none of the extended bits are demanded, eliminate the sextinreg.
795     if (NewBits == 0)
796       return TLO.CombineTo(Op, Op.getOperand(0));
797
798     uint64_t InSignBit = MVT::getIntVTSignBit(EVT);
799     int64_t InputDemandedBits = DemandedMask & MVT::getIntVTBitMask(EVT);
800     
801     // Since the sign extended bits are demanded, we know that the sign
802     // bit is demanded.
803     InputDemandedBits |= InSignBit;
804
805     if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
806                              KnownZero, KnownOne, TLO, Depth+1))
807       return true;
808     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
809
810     // If the sign bit of the input is known set or clear, then we know the
811     // top bits of the result.
812     
813     // If the input sign bit is known zero, convert this into a zero extension.
814     if (KnownZero & InSignBit)
815       return TLO.CombineTo(Op, 
816                            TLO.DAG.getZeroExtendInReg(Op.getOperand(0), EVT));
817     
818     if (KnownOne & InSignBit) {    // Input sign bit known set
819       KnownOne |= NewBits;
820       KnownZero &= ~NewBits;
821     } else {                       // Input sign bit unknown
822       KnownZero &= ~NewBits;
823       KnownOne &= ~NewBits;
824     }
825     break;
826   }
827   case ISD::CTTZ:
828   case ISD::CTLZ:
829   case ISD::CTPOP: {
830     MVT::ValueType VT = Op.getValueType();
831     unsigned LowBits = Log2_32(MVT::getSizeInBits(VT))+1;
832     KnownZero = ~((1ULL << LowBits)-1) & MVT::getIntVTBitMask(VT);
833     KnownOne  = 0;
834     break;
835   }
836   case ISD::LOAD: {
837     if (ISD::isZEXTLoad(Op.Val)) {
838       LoadSDNode *LD = cast<LoadSDNode>(Op);
839       MVT::ValueType VT = LD->getLoadedVT();
840       KnownZero |= ~MVT::getIntVTBitMask(VT) & DemandedMask;
841     }
842     break;
843   }
844   case ISD::ZERO_EXTEND: {
845     uint64_t InMask = MVT::getIntVTBitMask(Op.getOperand(0).getValueType());
846     
847     // If none of the top bits are demanded, convert this into an any_extend.
848     uint64_t NewBits = (~InMask) & DemandedMask;
849     if (NewBits == 0)
850       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, 
851                                                Op.getValueType(), 
852                                                Op.getOperand(0)));
853     
854     if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & InMask,
855                              KnownZero, KnownOne, TLO, Depth+1))
856       return true;
857     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
858     KnownZero |= NewBits;
859     break;
860   }
861   case ISD::SIGN_EXTEND: {
862     MVT::ValueType InVT = Op.getOperand(0).getValueType();
863     uint64_t InMask    = MVT::getIntVTBitMask(InVT);
864     uint64_t InSignBit = MVT::getIntVTSignBit(InVT);
865     uint64_t NewBits   = (~InMask) & DemandedMask;
866     
867     // If none of the top bits are demanded, convert this into an any_extend.
868     if (NewBits == 0)
869       return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND,Op.getValueType(),
870                                            Op.getOperand(0)));
871     
872     // Since some of the sign extended bits are demanded, we know that the sign
873     // bit is demanded.
874     uint64_t InDemandedBits = DemandedMask & InMask;
875     InDemandedBits |= InSignBit;
876     
877     if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero, 
878                              KnownOne, TLO, Depth+1))
879       return true;
880     
881     // If the sign bit is known zero, convert this to a zero extend.
882     if (KnownZero & InSignBit)
883       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, 
884                                                Op.getValueType(), 
885                                                Op.getOperand(0)));
886     
887     // If the sign bit is known one, the top bits match.
888     if (KnownOne & InSignBit) {
889       KnownOne  |= NewBits;
890       KnownZero &= ~NewBits;
891     } else {   // Otherwise, top bits aren't known.
892       KnownOne  &= ~NewBits;
893       KnownZero &= ~NewBits;
894     }
895     break;
896   }
897   case ISD::ANY_EXTEND: {
898     uint64_t InMask = MVT::getIntVTBitMask(Op.getOperand(0).getValueType());
899     if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & InMask,
900                              KnownZero, KnownOne, TLO, Depth+1))
901       return true;
902     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
903     break;
904   }
905   case ISD::TRUNCATE: {
906     // Simplify the input, using demanded bit information, and compute the known
907     // zero/one bits live out.
908     if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask,
909                              KnownZero, KnownOne, TLO, Depth+1))
910       return true;
911     
912     // If the input is only used by this truncate, see if we can shrink it based
913     // on the known demanded bits.
914     if (Op.getOperand(0).Val->hasOneUse()) {
915       SDOperand In = Op.getOperand(0);
916       switch (In.getOpcode()) {
917       default: break;
918       case ISD::SRL:
919         // Shrink SRL by a constant if none of the high bits shifted in are
920         // demanded.
921         if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1))){
922           uint64_t HighBits = MVT::getIntVTBitMask(In.getValueType());
923           HighBits &= ~MVT::getIntVTBitMask(Op.getValueType());
924           HighBits >>= ShAmt->getValue();
925           
926           if (ShAmt->getValue() < MVT::getSizeInBits(Op.getValueType()) &&
927               (DemandedMask & HighBits) == 0) {
928             // None of the shifted in bits are needed.  Add a truncate of the
929             // shift input, then shift it.
930             SDOperand NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, 
931                                                  Op.getValueType(), 
932                                                  In.getOperand(0));
933             return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL,Op.getValueType(),
934                                                    NewTrunc, In.getOperand(1)));
935           }
936         }
937         break;
938       }
939     }
940     
941     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
942     uint64_t OutMask = MVT::getIntVTBitMask(Op.getValueType());
943     KnownZero &= OutMask;
944     KnownOne &= OutMask;
945     break;
946   }
947   case ISD::AssertZext: {
948     MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
949     uint64_t InMask = MVT::getIntVTBitMask(VT);
950     if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask & InMask,
951                              KnownZero, KnownOne, TLO, Depth+1))
952       return true;
953     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
954     KnownZero |= ~InMask & DemandedMask;
955     break;
956   }
957   case ISD::FGETSIGN:
958     // All bits are zero except the low bit.
959     KnownZero = MVT::getIntVTBitMask(Op.getValueType()) ^ 1;
960     break;
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 (DemandedMask == 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   case ISD::ADD:
984   case ISD::SUB:
985   case ISD::INTRINSIC_WO_CHAIN:
986   case ISD::INTRINSIC_W_CHAIN:
987   case ISD::INTRINSIC_VOID:
988     // Just use ComputeMaskedBits to compute output bits.
989     TLO.DAG.ComputeMaskedBits(Op, DemandedMask, KnownZero, KnownOne, Depth);
990     break;
991   }
992   
993   // If we know the value of all of the demanded bits, return this as a
994   // constant.
995   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
996     return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
997   
998   return false;
999 }
1000
1001 /// computeMaskedBitsForTargetNode - Determine which of the bits specified 
1002 /// in Mask are known to be either zero or one and return them in the 
1003 /// KnownZero/KnownOne bitsets.
1004 void TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op, 
1005                                                     uint64_t Mask,
1006                                                     uint64_t &KnownZero, 
1007                                                     uint64_t &KnownOne,
1008                                                     const SelectionDAG &DAG,
1009                                                     unsigned Depth) const {
1010   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1011           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1012           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1013           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1014          "Should use MaskedValueIsZero if you don't know whether Op"
1015          " is a target node!");
1016   KnownZero = 0;
1017   KnownOne = 0;
1018 }
1019
1020 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
1021 /// targets that want to expose additional information about sign bits to the
1022 /// DAG Combiner.
1023 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDOperand Op,
1024                                                          unsigned Depth) const {
1025   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1026           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1027           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1028           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1029          "Should use ComputeNumSignBits if you don't know whether Op"
1030          " is a target node!");
1031   return 1;
1032 }
1033
1034
1035 /// SimplifySetCC - Try to simplify a setcc built with the specified operands 
1036 /// and cc. If it is unable to simplify it, return a null SDOperand.
1037 SDOperand
1038 TargetLowering::SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
1039                               ISD::CondCode Cond, bool foldBooleans,
1040                               DAGCombinerInfo &DCI) const {
1041   SelectionDAG &DAG = DCI.DAG;
1042
1043   // These setcc operations always fold.
1044   switch (Cond) {
1045   default: break;
1046   case ISD::SETFALSE:
1047   case ISD::SETFALSE2: return DAG.getConstant(0, VT);
1048   case ISD::SETTRUE:
1049   case ISD::SETTRUE2:  return DAG.getConstant(1, VT);
1050   }
1051
1052   if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1053     uint64_t C1 = N1C->getValue();
1054     if (isa<ConstantSDNode>(N0.Val)) {
1055       return DAG.FoldSetCC(VT, N0, N1, Cond);
1056     } else {
1057       // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1058       // equality comparison, then we're just comparing whether X itself is
1059       // zero.
1060       if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1061           N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1062           N0.getOperand(1).getOpcode() == ISD::Constant) {
1063         unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1064         if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1065             ShAmt == Log2_32(MVT::getSizeInBits(N0.getValueType()))) {
1066           if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1067             // (srl (ctlz x), 5) == 0  -> X != 0
1068             // (srl (ctlz x), 5) != 1  -> X != 0
1069             Cond = ISD::SETNE;
1070           } else {
1071             // (srl (ctlz x), 5) != 0  -> X == 0
1072             // (srl (ctlz x), 5) == 1  -> X == 0
1073             Cond = ISD::SETEQ;
1074           }
1075           SDOperand Zero = DAG.getConstant(0, N0.getValueType());
1076           return DAG.getSetCC(VT, N0.getOperand(0).getOperand(0),
1077                               Zero, Cond);
1078         }
1079       }
1080       
1081       // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1082       if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1083         unsigned InSize = MVT::getSizeInBits(N0.getOperand(0).getValueType());
1084
1085         // If the comparison constant has bits in the upper part, the
1086         // zero-extended value could never match.
1087         if (C1 & (~0ULL << InSize)) {
1088           unsigned VSize = MVT::getSizeInBits(N0.getValueType());
1089           switch (Cond) {
1090           case ISD::SETUGT:
1091           case ISD::SETUGE:
1092           case ISD::SETEQ: return DAG.getConstant(0, VT);
1093           case ISD::SETULT:
1094           case ISD::SETULE:
1095           case ISD::SETNE: return DAG.getConstant(1, VT);
1096           case ISD::SETGT:
1097           case ISD::SETGE:
1098             // True if the sign bit of C1 is set.
1099             return DAG.getConstant((C1 & (1ULL << (VSize-1))) != 0, VT);
1100           case ISD::SETLT:
1101           case ISD::SETLE:
1102             // True if the sign bit of C1 isn't set.
1103             return DAG.getConstant((C1 & (1ULL << (VSize-1))) == 0, VT);
1104           default:
1105             break;
1106           }
1107         }
1108
1109         // Otherwise, we can perform the comparison with the low bits.
1110         switch (Cond) {
1111         case ISD::SETEQ:
1112         case ISD::SETNE:
1113         case ISD::SETUGT:
1114         case ISD::SETUGE:
1115         case ISD::SETULT:
1116         case ISD::SETULE:
1117           return DAG.getSetCC(VT, N0.getOperand(0),
1118                           DAG.getConstant(C1, N0.getOperand(0).getValueType()),
1119                           Cond);
1120         default:
1121           break;   // todo, be more careful with signed comparisons
1122         }
1123       } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1124                  (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1125         MVT::ValueType ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
1126         unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
1127         MVT::ValueType ExtDstTy = N0.getValueType();
1128         unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
1129
1130         // If the extended part has any inconsistent bits, it cannot ever
1131         // compare equal.  In other words, they have to be all ones or all
1132         // zeros.
1133         uint64_t ExtBits =
1134           (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
1135         if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits)
1136           return DAG.getConstant(Cond == ISD::SETNE, VT);
1137         
1138         SDOperand ZextOp;
1139         MVT::ValueType Op0Ty = N0.getOperand(0).getValueType();
1140         if (Op0Ty == ExtSrcTy) {
1141           ZextOp = N0.getOperand(0);
1142         } else {
1143           int64_t Imm = ~0ULL >> (64-ExtSrcTyBits);
1144           ZextOp = DAG.getNode(ISD::AND, Op0Ty, N0.getOperand(0),
1145                                DAG.getConstant(Imm, Op0Ty));
1146         }
1147         if (!DCI.isCalledByLegalizer())
1148           DCI.AddToWorklist(ZextOp.Val);
1149         // Otherwise, make this a use of a zext.
1150         return DAG.getSetCC(VT, ZextOp, 
1151                             DAG.getConstant(C1 & (~0ULL>>(64-ExtSrcTyBits)), 
1152                                             ExtDstTy),
1153                             Cond);
1154       } else if ((N1C->getValue() == 0 || N1C->getValue() == 1) &&
1155                  (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1156         
1157         // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
1158         if (N0.getOpcode() == ISD::SETCC) {
1159           bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getValue() != 1);
1160           if (TrueWhenTrue)
1161             return N0;
1162           
1163           // Invert the condition.
1164           ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1165           CC = ISD::getSetCCInverse(CC, 
1166                                MVT::isInteger(N0.getOperand(0).getValueType()));
1167           return DAG.getSetCC(VT, N0.getOperand(0), N0.getOperand(1), CC);
1168         }
1169         
1170         if ((N0.getOpcode() == ISD::XOR ||
1171              (N0.getOpcode() == ISD::AND && 
1172               N0.getOperand(0).getOpcode() == ISD::XOR &&
1173               N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1174             isa<ConstantSDNode>(N0.getOperand(1)) &&
1175             cast<ConstantSDNode>(N0.getOperand(1))->getValue() == 1) {
1176           // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
1177           // can only do this if the top bits are known zero.
1178           if (DAG.MaskedValueIsZero(N0,
1179                                     MVT::getIntVTBitMask(N0.getValueType())-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       uint64_t MinVal, MaxVal;
1199       unsigned OperandBitSize = MVT::getSizeInBits(N1C->getValueType(0));
1200       if (ISD::isSignedIntSetCC(Cond)) {
1201         MinVal = 1ULL << (OperandBitSize-1);
1202         if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
1203           MaxVal = ~0ULL >> (65-OperandBitSize);
1204         else
1205           MaxVal = 0;
1206       } else {
1207         MinVal = 0;
1208         MaxVal = ~0ULL >> (64-OperandBitSize);
1209       }
1210
1211       // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1212       if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1213         if (C1 == MinVal) return DAG.getConstant(1, VT);   // X >= MIN --> true
1214         --C1;                                          // X >= C0 --> X > (C0-1)
1215         return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
1216                         (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
1217       }
1218
1219       if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1220         if (C1 == MaxVal) return DAG.getConstant(1, VT);   // X <= MAX --> true
1221         ++C1;                                          // X <= C0 --> X < (C0+1)
1222         return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
1223                         (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
1224       }
1225
1226       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1227         return DAG.getConstant(0, VT);      // X < MIN --> false
1228       if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1229         return DAG.getConstant(1, VT);      // X >= MIN --> true
1230       if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1231         return DAG.getConstant(0, VT);      // X > MAX --> false
1232       if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1233         return DAG.getConstant(1, VT);      // X <= MAX --> true
1234
1235       // Canonicalize setgt X, Min --> setne X, Min
1236       if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1237         return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
1238       // Canonicalize setlt X, Max --> setne X, Max
1239       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1240         return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
1241
1242       // If we have setult X, 1, turn it into seteq X, 0
1243       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1244         return DAG.getSetCC(VT, N0, DAG.getConstant(MinVal, N0.getValueType()),
1245                         ISD::SETEQ);
1246       // If we have setugt X, Max-1, turn it into seteq X, Max
1247       else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1248         return DAG.getSetCC(VT, N0, DAG.getConstant(MaxVal, N0.getValueType()),
1249                         ISD::SETEQ);
1250
1251       // If we have "setcc X, C0", check to see if we can shrink the immediate
1252       // by changing cc.
1253
1254       // SETUGT X, SINTMAX  -> SETLT X, 0
1255       if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
1256           C1 == (~0ULL >> (65-OperandBitSize)))
1257         return DAG.getSetCC(VT, N0, DAG.getConstant(0, N1.getValueType()),
1258                             ISD::SETLT);
1259
1260       // FIXME: Implement the rest of these.
1261
1262       // Fold bit comparisons when we can.
1263       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1264           VT == N0.getValueType() && N0.getOpcode() == ISD::AND)
1265         if (ConstantSDNode *AndRHS =
1266                     dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1267           if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
1268             // Perform the xform if the AND RHS is a single bit.
1269             if (isPowerOf2_64(AndRHS->getValue())) {
1270               return DAG.getNode(ISD::SRL, VT, N0,
1271                              DAG.getConstant(Log2_64(AndRHS->getValue()),
1272                                              getShiftAmountTy()));
1273             }
1274           } else if (Cond == ISD::SETEQ && C1 == AndRHS->getValue()) {
1275             // (X & 8) == 8  -->  (X & 8) >> 3
1276             // Perform the xform if C1 is a single bit.
1277             if (isPowerOf2_64(C1)) {
1278               return DAG.getNode(ISD::SRL, VT, N0,
1279                           DAG.getConstant(Log2_64(C1), getShiftAmountTy()));
1280             }
1281           }
1282         }
1283     }
1284   } else if (isa<ConstantSDNode>(N0.Val)) {
1285       // Ensure that the constant occurs on the RHS.
1286     return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
1287   }
1288
1289   if (isa<ConstantFPSDNode>(N0.Val)) {
1290     // Constant fold or commute setcc.
1291     SDOperand O = DAG.FoldSetCC(VT, N0, N1, Cond);    
1292     if (O.Val) return O;
1293   } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1294     // If the RHS of an FP comparison is a constant, simplify it away in
1295     // some cases.
1296     if (CFP->getValueAPF().isNaN()) {
1297       // If an operand is known to be a nan, we can fold it.
1298       switch (ISD::getUnorderedFlavor(Cond)) {
1299       default: assert(0 && "Unknown flavor!");
1300       case 0:  // Known false.
1301         return DAG.getConstant(0, VT);
1302       case 1:  // Known true.
1303         return DAG.getConstant(1, VT);
1304       case 2:  // Undefined.
1305         return DAG.getNode(ISD::UNDEF, VT);
1306       }
1307     }
1308     
1309     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
1310     // constant if knowing that the operand is non-nan is enough.  We prefer to
1311     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
1312     // materialize 0.0.
1313     if (Cond == ISD::SETO || Cond == ISD::SETUO)
1314       return DAG.getSetCC(VT, N0, N0, Cond);
1315   }
1316
1317   if (N0 == N1) {
1318     // We can always fold X == X for integer setcc's.
1319     if (MVT::isInteger(N0.getValueType()))
1320       return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
1321     unsigned UOF = ISD::getUnorderedFlavor(Cond);
1322     if (UOF == 2)   // FP operators that are undefined on NaNs.
1323       return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
1324     if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
1325       return DAG.getConstant(UOF, VT);
1326     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
1327     // if it is not already.
1328     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
1329     if (NewCond != Cond)
1330       return DAG.getSetCC(VT, N0, N1, NewCond);
1331   }
1332
1333   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1334       MVT::isInteger(N0.getValueType())) {
1335     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
1336         N0.getOpcode() == ISD::XOR) {
1337       // Simplify (X+Y) == (X+Z) -->  Y == Z
1338       if (N0.getOpcode() == N1.getOpcode()) {
1339         if (N0.getOperand(0) == N1.getOperand(0))
1340           return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(1), Cond);
1341         if (N0.getOperand(1) == N1.getOperand(1))
1342           return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(0), Cond);
1343         if (DAG.isCommutativeBinOp(N0.getOpcode())) {
1344           // If X op Y == Y op X, try other combinations.
1345           if (N0.getOperand(0) == N1.getOperand(1))
1346             return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(0), Cond);
1347           if (N0.getOperand(1) == N1.getOperand(0))
1348             return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(1), Cond);
1349         }
1350       }
1351       
1352       if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
1353         if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1354           // Turn (X+C1) == C2 --> X == C2-C1
1355           if (N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse()) {
1356             return DAG.getSetCC(VT, N0.getOperand(0),
1357                               DAG.getConstant(RHSC->getValue()-LHSR->getValue(),
1358                                 N0.getValueType()), Cond);
1359           }
1360           
1361           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
1362           if (N0.getOpcode() == ISD::XOR)
1363             // If we know that all of the inverted bits are zero, don't bother
1364             // performing the inversion.
1365             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getValue()))
1366               return DAG.getSetCC(VT, N0.getOperand(0),
1367                               DAG.getConstant(LHSR->getValue()^RHSC->getValue(),
1368                                               N0.getValueType()), 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 DAG.getSetCC(VT, N0.getOperand(1),
1375                              DAG.getConstant(SUBC->getValue()-RHSC->getValue(),
1376                                              N0.getValueType()), Cond);
1377           }
1378         }          
1379       }
1380
1381       // Simplify (X+Z) == X -->  Z == 0
1382       if (N0.getOperand(0) == N1)
1383         return DAG.getSetCC(VT, N0.getOperand(1),
1384                         DAG.getConstant(0, N0.getValueType()), Cond);
1385       if (N0.getOperand(1) == N1) {
1386         if (DAG.isCommutativeBinOp(N0.getOpcode()))
1387           return DAG.getSetCC(VT, N0.getOperand(0),
1388                           DAG.getConstant(0, N0.getValueType()), Cond);
1389         else if (N0.Val->hasOneUse()) {
1390           assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
1391           // (Z-X) == X  --> Z == X<<1
1392           SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(),
1393                                      N1, 
1394                                      DAG.getConstant(1, getShiftAmountTy()));
1395           if (!DCI.isCalledByLegalizer())
1396             DCI.AddToWorklist(SH.Val);
1397           return DAG.getSetCC(VT, N0.getOperand(0), SH, Cond);
1398         }
1399       }
1400     }
1401
1402     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
1403         N1.getOpcode() == ISD::XOR) {
1404       // Simplify  X == (X+Z) -->  Z == 0
1405       if (N1.getOperand(0) == N0) {
1406         return DAG.getSetCC(VT, N1.getOperand(1),
1407                         DAG.getConstant(0, N1.getValueType()), Cond);
1408       } else if (N1.getOperand(1) == N0) {
1409         if (DAG.isCommutativeBinOp(N1.getOpcode())) {
1410           return DAG.getSetCC(VT, N1.getOperand(0),
1411                           DAG.getConstant(0, N1.getValueType()), Cond);
1412         } else if (N1.Val->hasOneUse()) {
1413           assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
1414           // X == (Z-X)  --> X<<1 == Z
1415           SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(), N0, 
1416                                      DAG.getConstant(1, getShiftAmountTy()));
1417           if (!DCI.isCalledByLegalizer())
1418             DCI.AddToWorklist(SH.Val);
1419           return DAG.getSetCC(VT, SH, N1.getOperand(0), Cond);
1420         }
1421       }
1422     }
1423   }
1424
1425   // Fold away ALL boolean setcc's.
1426   SDOperand Temp;
1427   if (N0.getValueType() == MVT::i1 && foldBooleans) {
1428     switch (Cond) {
1429     default: assert(0 && "Unknown integer setcc!");
1430     case ISD::SETEQ:  // X == Y  -> (X^Y)^1
1431       Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
1432       N0 = DAG.getNode(ISD::XOR, MVT::i1, Temp, DAG.getConstant(1, MVT::i1));
1433       if (!DCI.isCalledByLegalizer())
1434         DCI.AddToWorklist(Temp.Val);
1435       break;
1436     case ISD::SETNE:  // X != Y   -->  (X^Y)
1437       N0 = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
1438       break;
1439     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  X^1 & Y
1440     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  X^1 & Y
1441       Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
1442       N0 = DAG.getNode(ISD::AND, MVT::i1, N1, Temp);
1443       if (!DCI.isCalledByLegalizer())
1444         DCI.AddToWorklist(Temp.Val);
1445       break;
1446     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  Y^1 & X
1447     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  Y^1 & X
1448       Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
1449       N0 = DAG.getNode(ISD::AND, MVT::i1, N0, Temp);
1450       if (!DCI.isCalledByLegalizer())
1451         DCI.AddToWorklist(Temp.Val);
1452       break;
1453     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  X^1 | Y
1454     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  X^1 | Y
1455       Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
1456       N0 = DAG.getNode(ISD::OR, MVT::i1, N1, Temp);
1457       if (!DCI.isCalledByLegalizer())
1458         DCI.AddToWorklist(Temp.Val);
1459       break;
1460     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  Y^1 | X
1461     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  Y^1 | X
1462       Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
1463       N0 = DAG.getNode(ISD::OR, MVT::i1, N0, Temp);
1464       break;
1465     }
1466     if (VT != MVT::i1) {
1467       if (!DCI.isCalledByLegalizer())
1468         DCI.AddToWorklist(N0.Val);
1469       // FIXME: If running after legalize, we probably can't do this.
1470       N0 = DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
1471     }
1472     return N0;
1473   }
1474
1475   // Could not fold it.
1476   return SDOperand();
1477 }
1478
1479 SDOperand TargetLowering::
1480 PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1481   // Default implementation: no optimization.
1482   return SDOperand();
1483 }
1484
1485 //===----------------------------------------------------------------------===//
1486 //  Inline Assembler Implementation Methods
1487 //===----------------------------------------------------------------------===//
1488
1489 TargetLowering::ConstraintType
1490 TargetLowering::getConstraintType(const std::string &Constraint) const {
1491   // FIXME: lots more standard ones to handle.
1492   if (Constraint.size() == 1) {
1493     switch (Constraint[0]) {
1494     default: break;
1495     case 'r': return C_RegisterClass;
1496     case 'm':    // memory
1497     case 'o':    // offsetable
1498     case 'V':    // not offsetable
1499       return C_Memory;
1500     case 'i':    // Simple Integer or Relocatable Constant
1501     case 'n':    // Simple Integer
1502     case 's':    // Relocatable Constant
1503     case 'X':    // Allow ANY value.
1504     case 'I':    // Target registers.
1505     case 'J':
1506     case 'K':
1507     case 'L':
1508     case 'M':
1509     case 'N':
1510     case 'O':
1511     case 'P':
1512       return C_Other;
1513     }
1514   }
1515   
1516   if (Constraint.size() > 1 && Constraint[0] == '{' && 
1517       Constraint[Constraint.size()-1] == '}')
1518     return C_Register;
1519   return C_Unknown;
1520 }
1521
1522 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1523 /// vector.  If it is invalid, don't add anything to Ops.
1524 void TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
1525                                                   char ConstraintLetter,
1526                                                   std::vector<SDOperand> &Ops,
1527                                                   SelectionDAG &DAG) {
1528   switch (ConstraintLetter) {
1529   default: break;
1530   case 'X':     // Allows any operand; labels (basic block) use this.
1531     if (Op.getOpcode() == ISD::BasicBlock) {
1532       Ops.push_back(Op);
1533       return;
1534     }
1535     // fall through
1536   case 'i':    // Simple Integer or Relocatable Constant
1537   case 'n':    // Simple Integer
1538   case 's': {  // Relocatable Constant
1539     // These operands are interested in values of the form (GV+C), where C may
1540     // be folded in as an offset of GV, or it may be explicitly added.  Also, it
1541     // is possible and fine if either GV or C are missing.
1542     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
1543     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1544     
1545     // If we have "(add GV, C)", pull out GV/C
1546     if (Op.getOpcode() == ISD::ADD) {
1547       C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1548       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
1549       if (C == 0 || GA == 0) {
1550         C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1551         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
1552       }
1553       if (C == 0 || GA == 0)
1554         C = 0, GA = 0;
1555     }
1556     
1557     // If we find a valid operand, map to the TargetXXX version so that the
1558     // value itself doesn't get selected.
1559     if (GA) {   // Either &GV   or   &GV+C
1560       if (ConstraintLetter != 'n') {
1561         int64_t Offs = GA->getOffset();
1562         if (C) Offs += C->getValue();
1563         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
1564                                                  Op.getValueType(), Offs));
1565         return;
1566       }
1567     }
1568     if (C) {   // just C, no GV.
1569       // Simple constants are not allowed for 's'.
1570       if (ConstraintLetter != 's') {
1571         Ops.push_back(DAG.getTargetConstant(C->getValue(), Op.getValueType()));
1572         return;
1573       }
1574     }
1575     break;
1576   }
1577   }
1578 }
1579
1580 std::vector<unsigned> TargetLowering::
1581 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1582                                   MVT::ValueType VT) const {
1583   return std::vector<unsigned>();
1584 }
1585
1586
1587 std::pair<unsigned, const TargetRegisterClass*> TargetLowering::
1588 getRegForInlineAsmConstraint(const std::string &Constraint,
1589                              MVT::ValueType VT) const {
1590   if (Constraint[0] != '{')
1591     return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
1592   assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
1593
1594   // Remove the braces from around the name.
1595   std::string RegName(Constraint.begin()+1, Constraint.end()-1);
1596
1597   // Figure out which register class contains this reg.
1598   const MRegisterInfo *RI = TM.getRegisterInfo();
1599   for (MRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
1600        E = RI->regclass_end(); RCI != E; ++RCI) {
1601     const TargetRegisterClass *RC = *RCI;
1602     
1603     // If none of the the value types for this register class are valid, we 
1604     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
1605     bool isLegal = false;
1606     for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1607          I != E; ++I) {
1608       if (isTypeLegal(*I)) {
1609         isLegal = true;
1610         break;
1611       }
1612     }
1613     
1614     if (!isLegal) continue;
1615     
1616     for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); 
1617          I != E; ++I) {
1618       if (StringsEqualNoCase(RegName, RI->get(*I).Name))
1619         return std::make_pair(*I, RC);
1620     }
1621   }
1622   
1623   return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
1624 }
1625
1626 //===----------------------------------------------------------------------===//
1627 //  Loop Strength Reduction hooks
1628 //===----------------------------------------------------------------------===//
1629
1630 /// isLegalAddressingMode - Return true if the addressing mode represented
1631 /// by AM is legal for this target, for a load/store of the specified type.
1632 bool TargetLowering::isLegalAddressingMode(const AddrMode &AM, 
1633                                            const Type *Ty) const {
1634   // The default implementation of this implements a conservative RISCy, r+r and
1635   // r+i addr mode.
1636
1637   // Allows a sign-extended 16-bit immediate field.
1638   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
1639     return false;
1640   
1641   // No global is ever allowed as a base.
1642   if (AM.BaseGV)
1643     return false;
1644   
1645   // Only support r+r, 
1646   switch (AM.Scale) {
1647   case 0:  // "r+i" or just "i", depending on HasBaseReg.
1648     break;
1649   case 1:
1650     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
1651       return false;
1652     // Otherwise we have r+r or r+i.
1653     break;
1654   case 2:
1655     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
1656       return false;
1657     // Allow 2*r as r+r.
1658     break;
1659   }
1660   
1661   return true;
1662 }
1663
1664 // Magic for divide replacement
1665
1666 struct ms {
1667   int64_t m;  // magic number
1668   int64_t s;  // shift amount
1669 };
1670
1671 struct mu {
1672   uint64_t m; // magic number
1673   int64_t a;  // add indicator
1674   int64_t s;  // shift amount
1675 };
1676
1677 /// magic - calculate the magic numbers required to codegen an integer sdiv as
1678 /// a sequence of multiply and shifts.  Requires that the divisor not be 0, 1,
1679 /// or -1.
1680 static ms magic32(int32_t d) {
1681   int32_t p;
1682   uint32_t ad, anc, delta, q1, r1, q2, r2, t;
1683   const uint32_t two31 = 0x80000000U;
1684   struct ms mag;
1685   
1686   ad = abs(d);
1687   t = two31 + ((uint32_t)d >> 31);
1688   anc = t - 1 - t%ad;   // absolute value of nc
1689   p = 31;               // initialize p
1690   q1 = two31/anc;       // initialize q1 = 2p/abs(nc)
1691   r1 = two31 - q1*anc;  // initialize r1 = rem(2p,abs(nc))
1692   q2 = two31/ad;        // initialize q2 = 2p/abs(d)
1693   r2 = two31 - q2*ad;   // initialize r2 = rem(2p,abs(d))
1694   do {
1695     p = p + 1;
1696     q1 = 2*q1;        // update q1 = 2p/abs(nc)
1697     r1 = 2*r1;        // update r1 = rem(2p/abs(nc))
1698     if (r1 >= anc) {  // must be unsigned comparison
1699       q1 = q1 + 1;
1700       r1 = r1 - anc;
1701     }
1702     q2 = 2*q2;        // update q2 = 2p/abs(d)
1703     r2 = 2*r2;        // update r2 = rem(2p/abs(d))
1704     if (r2 >= ad) {   // must be unsigned comparison
1705       q2 = q2 + 1;
1706       r2 = r2 - ad;
1707     }
1708     delta = ad - r2;
1709   } while (q1 < delta || (q1 == delta && r1 == 0));
1710   
1711   mag.m = (int32_t)(q2 + 1); // make sure to sign extend
1712   if (d < 0) mag.m = -mag.m; // resulting magic number
1713   mag.s = p - 32;            // resulting shift
1714   return mag;
1715 }
1716
1717 /// magicu - calculate the magic numbers required to codegen an integer udiv as
1718 /// a sequence of multiply, add and shifts.  Requires that the divisor not be 0.
1719 static mu magicu32(uint32_t d) {
1720   int32_t p;
1721   uint32_t nc, delta, q1, r1, q2, r2;
1722   struct mu magu;
1723   magu.a = 0;               // initialize "add" indicator
1724   nc = - 1 - (-d)%d;
1725   p = 31;                   // initialize p
1726   q1 = 0x80000000/nc;       // initialize q1 = 2p/nc
1727   r1 = 0x80000000 - q1*nc;  // initialize r1 = rem(2p,nc)
1728   q2 = 0x7FFFFFFF/d;        // initialize q2 = (2p-1)/d
1729   r2 = 0x7FFFFFFF - q2*d;   // initialize r2 = rem((2p-1),d)
1730   do {
1731     p = p + 1;
1732     if (r1 >= nc - r1 ) {
1733       q1 = 2*q1 + 1;  // update q1
1734       r1 = 2*r1 - nc; // update r1
1735     }
1736     else {
1737       q1 = 2*q1; // update q1
1738       r1 = 2*r1; // update r1
1739     }
1740     if (r2 + 1 >= d - r2) {
1741       if (q2 >= 0x7FFFFFFF) magu.a = 1;
1742       q2 = 2*q2 + 1;     // update q2
1743       r2 = 2*r2 + 1 - d; // update r2
1744     }
1745     else {
1746       if (q2 >= 0x80000000) magu.a = 1;
1747       q2 = 2*q2;     // update q2
1748       r2 = 2*r2 + 1; // update r2
1749     }
1750     delta = d - 1 - r2;
1751   } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
1752   magu.m = q2 + 1; // resulting magic number
1753   magu.s = p - 32;  // resulting shift
1754   return magu;
1755 }
1756
1757 /// magic - calculate the magic numbers required to codegen an integer sdiv as
1758 /// a sequence of multiply and shifts.  Requires that the divisor not be 0, 1,
1759 /// or -1.
1760 static ms magic64(int64_t d) {
1761   int64_t p;
1762   uint64_t ad, anc, delta, q1, r1, q2, r2, t;
1763   const uint64_t two63 = 9223372036854775808ULL; // 2^63
1764   struct ms mag;
1765   
1766   ad = d >= 0 ? d : -d;
1767   t = two63 + ((uint64_t)d >> 63);
1768   anc = t - 1 - t%ad;   // absolute value of nc
1769   p = 63;               // initialize p
1770   q1 = two63/anc;       // initialize q1 = 2p/abs(nc)
1771   r1 = two63 - q1*anc;  // initialize r1 = rem(2p,abs(nc))
1772   q2 = two63/ad;        // initialize q2 = 2p/abs(d)
1773   r2 = two63 - q2*ad;   // initialize r2 = rem(2p,abs(d))
1774   do {
1775     p = p + 1;
1776     q1 = 2*q1;        // update q1 = 2p/abs(nc)
1777     r1 = 2*r1;        // update r1 = rem(2p/abs(nc))
1778     if (r1 >= anc) {  // must be unsigned comparison
1779       q1 = q1 + 1;
1780       r1 = r1 - anc;
1781     }
1782     q2 = 2*q2;        // update q2 = 2p/abs(d)
1783     r2 = 2*r2;        // update r2 = rem(2p/abs(d))
1784     if (r2 >= ad) {   // must be unsigned comparison
1785       q2 = q2 + 1;
1786       r2 = r2 - ad;
1787     }
1788     delta = ad - r2;
1789   } while (q1 < delta || (q1 == delta && r1 == 0));
1790   
1791   mag.m = q2 + 1;
1792   if (d < 0) mag.m = -mag.m; // resulting magic number
1793   mag.s = p - 64;            // resulting shift
1794   return mag;
1795 }
1796
1797 /// magicu - calculate the magic numbers required to codegen an integer udiv as
1798 /// a sequence of multiply, add and shifts.  Requires that the divisor not be 0.
1799 static mu magicu64(uint64_t d)
1800 {
1801   int64_t p;
1802   uint64_t nc, delta, q1, r1, q2, r2;
1803   struct mu magu;
1804   magu.a = 0;               // initialize "add" indicator
1805   nc = - 1 - (-d)%d;
1806   p = 63;                   // initialize p
1807   q1 = 0x8000000000000000ull/nc;       // initialize q1 = 2p/nc
1808   r1 = 0x8000000000000000ull - q1*nc;  // initialize r1 = rem(2p,nc)
1809   q2 = 0x7FFFFFFFFFFFFFFFull/d;        // initialize q2 = (2p-1)/d
1810   r2 = 0x7FFFFFFFFFFFFFFFull - q2*d;   // initialize r2 = rem((2p-1),d)
1811   do {
1812     p = p + 1;
1813     if (r1 >= nc - r1 ) {
1814       q1 = 2*q1 + 1;  // update q1
1815       r1 = 2*r1 - nc; // update r1
1816     }
1817     else {
1818       q1 = 2*q1; // update q1
1819       r1 = 2*r1; // update r1
1820     }
1821     if (r2 + 1 >= d - r2) {
1822       if (q2 >= 0x7FFFFFFFFFFFFFFFull) magu.a = 1;
1823       q2 = 2*q2 + 1;     // update q2
1824       r2 = 2*r2 + 1 - d; // update r2
1825     }
1826     else {
1827       if (q2 >= 0x8000000000000000ull) magu.a = 1;
1828       q2 = 2*q2;     // update q2
1829       r2 = 2*r2 + 1; // update r2
1830     }
1831     delta = d - 1 - r2;
1832   } while (p < 128 && (q1 < delta || (q1 == delta && r1 == 0)));
1833   magu.m = q2 + 1; // resulting magic number
1834   magu.s = p - 64;  // resulting shift
1835   return magu;
1836 }
1837
1838 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
1839 /// return a DAG expression to select that will generate the same value by
1840 /// multiplying by a magic number.  See:
1841 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
1842 SDOperand TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 
1843                                     std::vector<SDNode*>* Created) const {
1844   MVT::ValueType VT = N->getValueType(0);
1845   
1846   // Check to see if we can do this.
1847   if (!isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
1848     return SDOperand();       // BuildSDIV only operates on i32 or i64
1849   
1850   int64_t d = cast<ConstantSDNode>(N->getOperand(1))->getSignExtended();
1851   ms magics = (VT == MVT::i32) ? magic32(d) : magic64(d);
1852   
1853   // Multiply the numerator (operand 0) by the magic value
1854   SDOperand Q;
1855   if (isOperationLegal(ISD::MULHS, VT))
1856     Q = DAG.getNode(ISD::MULHS, VT, N->getOperand(0),
1857                     DAG.getConstant(magics.m, VT));
1858   else if (isOperationLegal(ISD::SMUL_LOHI, VT))
1859     Q = SDOperand(DAG.getNode(ISD::SMUL_LOHI, DAG.getVTList(VT, VT),
1860                               N->getOperand(0),
1861                               DAG.getConstant(magics.m, VT)).Val, 1);
1862   else
1863     return SDOperand();       // No mulhs or equvialent
1864   // If d > 0 and m < 0, add the numerator
1865   if (d > 0 && magics.m < 0) { 
1866     Q = DAG.getNode(ISD::ADD, VT, Q, N->getOperand(0));
1867     if (Created)
1868       Created->push_back(Q.Val);
1869   }
1870   // If d < 0 and m > 0, subtract the numerator.
1871   if (d < 0 && magics.m > 0) {
1872     Q = DAG.getNode(ISD::SUB, VT, Q, N->getOperand(0));
1873     if (Created)
1874       Created->push_back(Q.Val);
1875   }
1876   // Shift right algebraic if shift value is nonzero
1877   if (magics.s > 0) {
1878     Q = DAG.getNode(ISD::SRA, VT, Q, 
1879                     DAG.getConstant(magics.s, getShiftAmountTy()));
1880     if (Created)
1881       Created->push_back(Q.Val);
1882   }
1883   // Extract the sign bit and add it to the quotient
1884   SDOperand T =
1885     DAG.getNode(ISD::SRL, VT, Q, DAG.getConstant(MVT::getSizeInBits(VT)-1,
1886                                                  getShiftAmountTy()));
1887   if (Created)
1888     Created->push_back(T.Val);
1889   return DAG.getNode(ISD::ADD, VT, Q, T);
1890 }
1891
1892 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
1893 /// return a DAG expression to select that will generate the same value by
1894 /// multiplying by a magic number.  See:
1895 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
1896 SDOperand TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
1897                                     std::vector<SDNode*>* Created) const {
1898   MVT::ValueType VT = N->getValueType(0);
1899   
1900   // Check to see if we can do this.
1901   if (!isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
1902     return SDOperand();       // BuildUDIV only operates on i32 or i64
1903   
1904   uint64_t d = cast<ConstantSDNode>(N->getOperand(1))->getValue();
1905   mu magics = (VT == MVT::i32) ? magicu32(d) : magicu64(d);
1906   
1907   // Multiply the numerator (operand 0) by the magic value
1908   SDOperand Q;
1909   if (isOperationLegal(ISD::MULHU, VT))
1910     Q = DAG.getNode(ISD::MULHU, VT, N->getOperand(0),
1911                     DAG.getConstant(magics.m, VT));
1912   else if (isOperationLegal(ISD::UMUL_LOHI, VT))
1913     Q = SDOperand(DAG.getNode(ISD::UMUL_LOHI, DAG.getVTList(VT, VT),
1914                               N->getOperand(0),
1915                               DAG.getConstant(magics.m, VT)).Val, 1);
1916   else
1917     return SDOperand();       // No mulhu or equvialent
1918   if (Created)
1919     Created->push_back(Q.Val);
1920
1921   if (magics.a == 0) {
1922     return DAG.getNode(ISD::SRL, VT, Q, 
1923                        DAG.getConstant(magics.s, getShiftAmountTy()));
1924   } else {
1925     SDOperand NPQ = DAG.getNode(ISD::SUB, VT, N->getOperand(0), Q);
1926     if (Created)
1927       Created->push_back(NPQ.Val);
1928     NPQ = DAG.getNode(ISD::SRL, VT, NPQ, 
1929                       DAG.getConstant(1, getShiftAmountTy()));
1930     if (Created)
1931       Created->push_back(NPQ.Val);
1932     NPQ = DAG.getNode(ISD::ADD, VT, NPQ, Q);
1933     if (Created)
1934       Created->push_back(NPQ.Val);
1935     return DAG.getNode(ISD::SRL, VT, NPQ, 
1936                        DAG.getConstant(magics.s-1, getShiftAmountTy()));
1937   }
1938 }