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