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