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