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