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