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