81c51c49b720d14bdcda72fde193d5bf35433049
[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/TargetLowering.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/Target/TargetData.h"
17 #include "llvm/Target/TargetLoweringObjectFile.h"
18 #include "llvm/Target/TargetMachine.h"
19 #include "llvm/Target/TargetRegisterInfo.h"
20 #include "llvm/Target/TargetSubtarget.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/SelectionDAG.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MathExtras.h"
28 using namespace llvm;
29
30 namespace llvm {
31 TLSModel::Model getTLSModel(const GlobalValue *GV, Reloc::Model reloc) {
32   bool isLocal = GV->hasLocalLinkage();
33   bool isDeclaration = GV->isDeclaration();
34   // FIXME: what should we do for protected and internal visibility?
35   // For variables, is internal different from hidden?
36   bool isHidden = GV->hasHiddenVisibility();
37
38   if (reloc == Reloc::PIC_) {
39     if (isLocal || isHidden)
40       return TLSModel::LocalDynamic;
41     else
42       return TLSModel::GeneralDynamic;
43   } else {
44     if (!isDeclaration || isHidden)
45       return TLSModel::LocalExec;
46     else
47       return TLSModel::InitialExec;
48   }
49 }
50 }
51
52 /// InitLibcallNames - Set default libcall names.
53 ///
54 static void InitLibcallNames(const char **Names) {
55   Names[RTLIB::SHL_I16] = "__ashlhi3";
56   Names[RTLIB::SHL_I32] = "__ashlsi3";
57   Names[RTLIB::SHL_I64] = "__ashldi3";
58   Names[RTLIB::SHL_I128] = "__ashlti3";
59   Names[RTLIB::SRL_I16] = "__lshrhi3";
60   Names[RTLIB::SRL_I32] = "__lshrsi3";
61   Names[RTLIB::SRL_I64] = "__lshrdi3";
62   Names[RTLIB::SRL_I128] = "__lshrti3";
63   Names[RTLIB::SRA_I16] = "__ashrhi3";
64   Names[RTLIB::SRA_I32] = "__ashrsi3";
65   Names[RTLIB::SRA_I64] = "__ashrdi3";
66   Names[RTLIB::SRA_I128] = "__ashrti3";
67   Names[RTLIB::MUL_I8] = "__mulqi3";
68   Names[RTLIB::MUL_I16] = "__mulhi3";
69   Names[RTLIB::MUL_I32] = "__mulsi3";
70   Names[RTLIB::MUL_I64] = "__muldi3";
71   Names[RTLIB::MUL_I128] = "__multi3";
72   Names[RTLIB::SDIV_I8] = "__divqi3";
73   Names[RTLIB::SDIV_I16] = "__divhi3";
74   Names[RTLIB::SDIV_I32] = "__divsi3";
75   Names[RTLIB::SDIV_I64] = "__divdi3";
76   Names[RTLIB::SDIV_I128] = "__divti3";
77   Names[RTLIB::UDIV_I8] = "__udivqi3";
78   Names[RTLIB::UDIV_I16] = "__udivhi3";
79   Names[RTLIB::UDIV_I32] = "__udivsi3";
80   Names[RTLIB::UDIV_I64] = "__udivdi3";
81   Names[RTLIB::UDIV_I128] = "__udivti3";
82   Names[RTLIB::SREM_I8] = "__modqi3";
83   Names[RTLIB::SREM_I16] = "__modhi3";
84   Names[RTLIB::SREM_I32] = "__modsi3";
85   Names[RTLIB::SREM_I64] = "__moddi3";
86   Names[RTLIB::SREM_I128] = "__modti3";
87   Names[RTLIB::UREM_I8] = "__umodqi3";
88   Names[RTLIB::UREM_I16] = "__umodhi3";
89   Names[RTLIB::UREM_I32] = "__umodsi3";
90   Names[RTLIB::UREM_I64] = "__umoddi3";
91   Names[RTLIB::UREM_I128] = "__umodti3";
92   Names[RTLIB::NEG_I32] = "__negsi2";
93   Names[RTLIB::NEG_I64] = "__negdi2";
94   Names[RTLIB::ADD_F32] = "__addsf3";
95   Names[RTLIB::ADD_F64] = "__adddf3";
96   Names[RTLIB::ADD_F80] = "__addxf3";
97   Names[RTLIB::ADD_PPCF128] = "__gcc_qadd";
98   Names[RTLIB::SUB_F32] = "__subsf3";
99   Names[RTLIB::SUB_F64] = "__subdf3";
100   Names[RTLIB::SUB_F80] = "__subxf3";
101   Names[RTLIB::SUB_PPCF128] = "__gcc_qsub";
102   Names[RTLIB::MUL_F32] = "__mulsf3";
103   Names[RTLIB::MUL_F64] = "__muldf3";
104   Names[RTLIB::MUL_F80] = "__mulxf3";
105   Names[RTLIB::MUL_PPCF128] = "__gcc_qmul";
106   Names[RTLIB::DIV_F32] = "__divsf3";
107   Names[RTLIB::DIV_F64] = "__divdf3";
108   Names[RTLIB::DIV_F80] = "__divxf3";
109   Names[RTLIB::DIV_PPCF128] = "__gcc_qdiv";
110   Names[RTLIB::REM_F32] = "fmodf";
111   Names[RTLIB::REM_F64] = "fmod";
112   Names[RTLIB::REM_F80] = "fmodl";
113   Names[RTLIB::REM_PPCF128] = "fmodl";
114   Names[RTLIB::POWI_F32] = "__powisf2";
115   Names[RTLIB::POWI_F64] = "__powidf2";
116   Names[RTLIB::POWI_F80] = "__powixf2";
117   Names[RTLIB::POWI_PPCF128] = "__powitf2";
118   Names[RTLIB::SQRT_F32] = "sqrtf";
119   Names[RTLIB::SQRT_F64] = "sqrt";
120   Names[RTLIB::SQRT_F80] = "sqrtl";
121   Names[RTLIB::SQRT_PPCF128] = "sqrtl";
122   Names[RTLIB::LOG_F32] = "logf";
123   Names[RTLIB::LOG_F64] = "log";
124   Names[RTLIB::LOG_F80] = "logl";
125   Names[RTLIB::LOG_PPCF128] = "logl";
126   Names[RTLIB::LOG2_F32] = "log2f";
127   Names[RTLIB::LOG2_F64] = "log2";
128   Names[RTLIB::LOG2_F80] = "log2l";
129   Names[RTLIB::LOG2_PPCF128] = "log2l";
130   Names[RTLIB::LOG10_F32] = "log10f";
131   Names[RTLIB::LOG10_F64] = "log10";
132   Names[RTLIB::LOG10_F80] = "log10l";
133   Names[RTLIB::LOG10_PPCF128] = "log10l";
134   Names[RTLIB::EXP_F32] = "expf";
135   Names[RTLIB::EXP_F64] = "exp";
136   Names[RTLIB::EXP_F80] = "expl";
137   Names[RTLIB::EXP_PPCF128] = "expl";
138   Names[RTLIB::EXP2_F32] = "exp2f";
139   Names[RTLIB::EXP2_F64] = "exp2";
140   Names[RTLIB::EXP2_F80] = "exp2l";
141   Names[RTLIB::EXP2_PPCF128] = "exp2l";
142   Names[RTLIB::SIN_F32] = "sinf";
143   Names[RTLIB::SIN_F64] = "sin";
144   Names[RTLIB::SIN_F80] = "sinl";
145   Names[RTLIB::SIN_PPCF128] = "sinl";
146   Names[RTLIB::COS_F32] = "cosf";
147   Names[RTLIB::COS_F64] = "cos";
148   Names[RTLIB::COS_F80] = "cosl";
149   Names[RTLIB::COS_PPCF128] = "cosl";
150   Names[RTLIB::POW_F32] = "powf";
151   Names[RTLIB::POW_F64] = "pow";
152   Names[RTLIB::POW_F80] = "powl";
153   Names[RTLIB::POW_PPCF128] = "powl";
154   Names[RTLIB::CEIL_F32] = "ceilf";
155   Names[RTLIB::CEIL_F64] = "ceil";
156   Names[RTLIB::CEIL_F80] = "ceill";
157   Names[RTLIB::CEIL_PPCF128] = "ceill";
158   Names[RTLIB::TRUNC_F32] = "truncf";
159   Names[RTLIB::TRUNC_F64] = "trunc";
160   Names[RTLIB::TRUNC_F80] = "truncl";
161   Names[RTLIB::TRUNC_PPCF128] = "truncl";
162   Names[RTLIB::RINT_F32] = "rintf";
163   Names[RTLIB::RINT_F64] = "rint";
164   Names[RTLIB::RINT_F80] = "rintl";
165   Names[RTLIB::RINT_PPCF128] = "rintl";
166   Names[RTLIB::NEARBYINT_F32] = "nearbyintf";
167   Names[RTLIB::NEARBYINT_F64] = "nearbyint";
168   Names[RTLIB::NEARBYINT_F80] = "nearbyintl";
169   Names[RTLIB::NEARBYINT_PPCF128] = "nearbyintl";
170   Names[RTLIB::FLOOR_F32] = "floorf";
171   Names[RTLIB::FLOOR_F64] = "floor";
172   Names[RTLIB::FLOOR_F80] = "floorl";
173   Names[RTLIB::FLOOR_PPCF128] = "floorl";
174   Names[RTLIB::FPEXT_F32_F64] = "__extendsfdf2";
175   Names[RTLIB::FPROUND_F64_F32] = "__truncdfsf2";
176   Names[RTLIB::FPROUND_F80_F32] = "__truncxfsf2";
177   Names[RTLIB::FPROUND_PPCF128_F32] = "__trunctfsf2";
178   Names[RTLIB::FPROUND_F80_F64] = "__truncxfdf2";
179   Names[RTLIB::FPROUND_PPCF128_F64] = "__trunctfdf2";
180   Names[RTLIB::FPTOSINT_F32_I8] = "__fixsfi8";
181   Names[RTLIB::FPTOSINT_F32_I16] = "__fixsfi16";
182   Names[RTLIB::FPTOSINT_F32_I32] = "__fixsfsi";
183   Names[RTLIB::FPTOSINT_F32_I64] = "__fixsfdi";
184   Names[RTLIB::FPTOSINT_F32_I128] = "__fixsfti";
185   Names[RTLIB::FPTOSINT_F64_I32] = "__fixdfsi";
186   Names[RTLIB::FPTOSINT_F64_I64] = "__fixdfdi";
187   Names[RTLIB::FPTOSINT_F64_I128] = "__fixdfti";
188   Names[RTLIB::FPTOSINT_F80_I32] = "__fixxfsi";
189   Names[RTLIB::FPTOSINT_F80_I64] = "__fixxfdi";
190   Names[RTLIB::FPTOSINT_F80_I128] = "__fixxfti";
191   Names[RTLIB::FPTOSINT_PPCF128_I32] = "__fixtfsi";
192   Names[RTLIB::FPTOSINT_PPCF128_I64] = "__fixtfdi";
193   Names[RTLIB::FPTOSINT_PPCF128_I128] = "__fixtfti";
194   Names[RTLIB::FPTOUINT_F32_I8] = "__fixunssfi8";
195   Names[RTLIB::FPTOUINT_F32_I16] = "__fixunssfi16";
196   Names[RTLIB::FPTOUINT_F32_I32] = "__fixunssfsi";
197   Names[RTLIB::FPTOUINT_F32_I64] = "__fixunssfdi";
198   Names[RTLIB::FPTOUINT_F32_I128] = "__fixunssfti";
199   Names[RTLIB::FPTOUINT_F64_I32] = "__fixunsdfsi";
200   Names[RTLIB::FPTOUINT_F64_I64] = "__fixunsdfdi";
201   Names[RTLIB::FPTOUINT_F64_I128] = "__fixunsdfti";
202   Names[RTLIB::FPTOUINT_F80_I32] = "__fixunsxfsi";
203   Names[RTLIB::FPTOUINT_F80_I64] = "__fixunsxfdi";
204   Names[RTLIB::FPTOUINT_F80_I128] = "__fixunsxfti";
205   Names[RTLIB::FPTOUINT_PPCF128_I32] = "__fixunstfsi";
206   Names[RTLIB::FPTOUINT_PPCF128_I64] = "__fixunstfdi";
207   Names[RTLIB::FPTOUINT_PPCF128_I128] = "__fixunstfti";
208   Names[RTLIB::SINTTOFP_I32_F32] = "__floatsisf";
209   Names[RTLIB::SINTTOFP_I32_F64] = "__floatsidf";
210   Names[RTLIB::SINTTOFP_I32_F80] = "__floatsixf";
211   Names[RTLIB::SINTTOFP_I32_PPCF128] = "__floatsitf";
212   Names[RTLIB::SINTTOFP_I64_F32] = "__floatdisf";
213   Names[RTLIB::SINTTOFP_I64_F64] = "__floatdidf";
214   Names[RTLIB::SINTTOFP_I64_F80] = "__floatdixf";
215   Names[RTLIB::SINTTOFP_I64_PPCF128] = "__floatditf";
216   Names[RTLIB::SINTTOFP_I128_F32] = "__floattisf";
217   Names[RTLIB::SINTTOFP_I128_F64] = "__floattidf";
218   Names[RTLIB::SINTTOFP_I128_F80] = "__floattixf";
219   Names[RTLIB::SINTTOFP_I128_PPCF128] = "__floattitf";
220   Names[RTLIB::UINTTOFP_I32_F32] = "__floatunsisf";
221   Names[RTLIB::UINTTOFP_I32_F64] = "__floatunsidf";
222   Names[RTLIB::UINTTOFP_I32_F80] = "__floatunsixf";
223   Names[RTLIB::UINTTOFP_I32_PPCF128] = "__floatunsitf";
224   Names[RTLIB::UINTTOFP_I64_F32] = "__floatundisf";
225   Names[RTLIB::UINTTOFP_I64_F64] = "__floatundidf";
226   Names[RTLIB::UINTTOFP_I64_F80] = "__floatundixf";
227   Names[RTLIB::UINTTOFP_I64_PPCF128] = "__floatunditf";
228   Names[RTLIB::UINTTOFP_I128_F32] = "__floatuntisf";
229   Names[RTLIB::UINTTOFP_I128_F64] = "__floatuntidf";
230   Names[RTLIB::UINTTOFP_I128_F80] = "__floatuntixf";
231   Names[RTLIB::UINTTOFP_I128_PPCF128] = "__floatuntitf";
232   Names[RTLIB::OEQ_F32] = "__eqsf2";
233   Names[RTLIB::OEQ_F64] = "__eqdf2";
234   Names[RTLIB::UNE_F32] = "__nesf2";
235   Names[RTLIB::UNE_F64] = "__nedf2";
236   Names[RTLIB::OGE_F32] = "__gesf2";
237   Names[RTLIB::OGE_F64] = "__gedf2";
238   Names[RTLIB::OLT_F32] = "__ltsf2";
239   Names[RTLIB::OLT_F64] = "__ltdf2";
240   Names[RTLIB::OLE_F32] = "__lesf2";
241   Names[RTLIB::OLE_F64] = "__ledf2";
242   Names[RTLIB::OGT_F32] = "__gtsf2";
243   Names[RTLIB::OGT_F64] = "__gtdf2";
244   Names[RTLIB::UO_F32] = "__unordsf2";
245   Names[RTLIB::UO_F64] = "__unorddf2";
246   Names[RTLIB::O_F32] = "__unordsf2";
247   Names[RTLIB::O_F64] = "__unorddf2";
248   Names[RTLIB::MEMCPY] = "memcpy";
249   Names[RTLIB::MEMMOVE] = "memmove";
250   Names[RTLIB::MEMSET] = "memset";
251   Names[RTLIB::UNWIND_RESUME] = "_Unwind_Resume";
252 }
253
254 /// InitLibcallCallingConvs - Set default libcall CallingConvs.
255 ///
256 static void InitLibcallCallingConvs(CallingConv::ID *CCs) {
257   for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) {
258     CCs[i] = CallingConv::C;
259   }
260 }
261
262 /// getFPEXT - Return the FPEXT_*_* value for the given types, or
263 /// UNKNOWN_LIBCALL if there is none.
264 RTLIB::Libcall RTLIB::getFPEXT(EVT OpVT, EVT RetVT) {
265   if (OpVT == MVT::f32) {
266     if (RetVT == MVT::f64)
267       return FPEXT_F32_F64;
268   }
269   return UNKNOWN_LIBCALL;
270 }
271
272 /// getFPROUND - Return the FPROUND_*_* value for the given types, or
273 /// UNKNOWN_LIBCALL if there is none.
274 RTLIB::Libcall RTLIB::getFPROUND(EVT OpVT, EVT RetVT) {
275   if (RetVT == MVT::f32) {
276     if (OpVT == MVT::f64)
277       return FPROUND_F64_F32;
278     if (OpVT == MVT::f80)
279       return FPROUND_F80_F32;
280     if (OpVT == MVT::ppcf128)
281       return FPROUND_PPCF128_F32;
282   } else if (RetVT == MVT::f64) {
283     if (OpVT == MVT::f80)
284       return FPROUND_F80_F64;
285     if (OpVT == MVT::ppcf128)
286       return FPROUND_PPCF128_F64;
287   }
288   return UNKNOWN_LIBCALL;
289 }
290
291 /// getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or
292 /// UNKNOWN_LIBCALL if there is none.
293 RTLIB::Libcall RTLIB::getFPTOSINT(EVT OpVT, EVT RetVT) {
294   if (OpVT == MVT::f32) {
295     if (RetVT == MVT::i8)
296       return FPTOSINT_F32_I8;
297     if (RetVT == MVT::i16)
298       return FPTOSINT_F32_I16;
299     if (RetVT == MVT::i32)
300       return FPTOSINT_F32_I32;
301     if (RetVT == MVT::i64)
302       return FPTOSINT_F32_I64;
303     if (RetVT == MVT::i128)
304       return FPTOSINT_F32_I128;
305   } else if (OpVT == MVT::f64) {
306     if (RetVT == MVT::i32)
307       return FPTOSINT_F64_I32;
308     if (RetVT == MVT::i64)
309       return FPTOSINT_F64_I64;
310     if (RetVT == MVT::i128)
311       return FPTOSINT_F64_I128;
312   } else if (OpVT == MVT::f80) {
313     if (RetVT == MVT::i32)
314       return FPTOSINT_F80_I32;
315     if (RetVT == MVT::i64)
316       return FPTOSINT_F80_I64;
317     if (RetVT == MVT::i128)
318       return FPTOSINT_F80_I128;
319   } else if (OpVT == MVT::ppcf128) {
320     if (RetVT == MVT::i32)
321       return FPTOSINT_PPCF128_I32;
322     if (RetVT == MVT::i64)
323       return FPTOSINT_PPCF128_I64;
324     if (RetVT == MVT::i128)
325       return FPTOSINT_PPCF128_I128;
326   }
327   return UNKNOWN_LIBCALL;
328 }
329
330 /// getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or
331 /// UNKNOWN_LIBCALL if there is none.
332 RTLIB::Libcall RTLIB::getFPTOUINT(EVT OpVT, EVT RetVT) {
333   if (OpVT == MVT::f32) {
334     if (RetVT == MVT::i8)
335       return FPTOUINT_F32_I8;
336     if (RetVT == MVT::i16)
337       return FPTOUINT_F32_I16;
338     if (RetVT == MVT::i32)
339       return FPTOUINT_F32_I32;
340     if (RetVT == MVT::i64)
341       return FPTOUINT_F32_I64;
342     if (RetVT == MVT::i128)
343       return FPTOUINT_F32_I128;
344   } else if (OpVT == MVT::f64) {
345     if (RetVT == MVT::i32)
346       return FPTOUINT_F64_I32;
347     if (RetVT == MVT::i64)
348       return FPTOUINT_F64_I64;
349     if (RetVT == MVT::i128)
350       return FPTOUINT_F64_I128;
351   } else if (OpVT == MVT::f80) {
352     if (RetVT == MVT::i32)
353       return FPTOUINT_F80_I32;
354     if (RetVT == MVT::i64)
355       return FPTOUINT_F80_I64;
356     if (RetVT == MVT::i128)
357       return FPTOUINT_F80_I128;
358   } else if (OpVT == MVT::ppcf128) {
359     if (RetVT == MVT::i32)
360       return FPTOUINT_PPCF128_I32;
361     if (RetVT == MVT::i64)
362       return FPTOUINT_PPCF128_I64;
363     if (RetVT == MVT::i128)
364       return FPTOUINT_PPCF128_I128;
365   }
366   return UNKNOWN_LIBCALL;
367 }
368
369 /// getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or
370 /// UNKNOWN_LIBCALL if there is none.
371 RTLIB::Libcall RTLIB::getSINTTOFP(EVT OpVT, EVT RetVT) {
372   if (OpVT == MVT::i32) {
373     if (RetVT == MVT::f32)
374       return SINTTOFP_I32_F32;
375     else if (RetVT == MVT::f64)
376       return SINTTOFP_I32_F64;
377     else if (RetVT == MVT::f80)
378       return SINTTOFP_I32_F80;
379     else if (RetVT == MVT::ppcf128)
380       return SINTTOFP_I32_PPCF128;
381   } else if (OpVT == MVT::i64) {
382     if (RetVT == MVT::f32)
383       return SINTTOFP_I64_F32;
384     else if (RetVT == MVT::f64)
385       return SINTTOFP_I64_F64;
386     else if (RetVT == MVT::f80)
387       return SINTTOFP_I64_F80;
388     else if (RetVT == MVT::ppcf128)
389       return SINTTOFP_I64_PPCF128;
390   } else if (OpVT == MVT::i128) {
391     if (RetVT == MVT::f32)
392       return SINTTOFP_I128_F32;
393     else if (RetVT == MVT::f64)
394       return SINTTOFP_I128_F64;
395     else if (RetVT == MVT::f80)
396       return SINTTOFP_I128_F80;
397     else if (RetVT == MVT::ppcf128)
398       return SINTTOFP_I128_PPCF128;
399   }
400   return UNKNOWN_LIBCALL;
401 }
402
403 /// getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or
404 /// UNKNOWN_LIBCALL if there is none.
405 RTLIB::Libcall RTLIB::getUINTTOFP(EVT OpVT, EVT RetVT) {
406   if (OpVT == MVT::i32) {
407     if (RetVT == MVT::f32)
408       return UINTTOFP_I32_F32;
409     else if (RetVT == MVT::f64)
410       return UINTTOFP_I32_F64;
411     else if (RetVT == MVT::f80)
412       return UINTTOFP_I32_F80;
413     else if (RetVT == MVT::ppcf128)
414       return UINTTOFP_I32_PPCF128;
415   } else if (OpVT == MVT::i64) {
416     if (RetVT == MVT::f32)
417       return UINTTOFP_I64_F32;
418     else if (RetVT == MVT::f64)
419       return UINTTOFP_I64_F64;
420     else if (RetVT == MVT::f80)
421       return UINTTOFP_I64_F80;
422     else if (RetVT == MVT::ppcf128)
423       return UINTTOFP_I64_PPCF128;
424   } else if (OpVT == MVT::i128) {
425     if (RetVT == MVT::f32)
426       return UINTTOFP_I128_F32;
427     else if (RetVT == MVT::f64)
428       return UINTTOFP_I128_F64;
429     else if (RetVT == MVT::f80)
430       return UINTTOFP_I128_F80;
431     else if (RetVT == MVT::ppcf128)
432       return UINTTOFP_I128_PPCF128;
433   }
434   return UNKNOWN_LIBCALL;
435 }
436
437 /// InitCmpLibcallCCs - Set default comparison libcall CC.
438 ///
439 static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
440   memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL);
441   CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
442   CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
443   CCs[RTLIB::UNE_F32] = ISD::SETNE;
444   CCs[RTLIB::UNE_F64] = ISD::SETNE;
445   CCs[RTLIB::OGE_F32] = ISD::SETGE;
446   CCs[RTLIB::OGE_F64] = ISD::SETGE;
447   CCs[RTLIB::OLT_F32] = ISD::SETLT;
448   CCs[RTLIB::OLT_F64] = ISD::SETLT;
449   CCs[RTLIB::OLE_F32] = ISD::SETLE;
450   CCs[RTLIB::OLE_F64] = ISD::SETLE;
451   CCs[RTLIB::OGT_F32] = ISD::SETGT;
452   CCs[RTLIB::OGT_F64] = ISD::SETGT;
453   CCs[RTLIB::UO_F32] = ISD::SETNE;
454   CCs[RTLIB::UO_F64] = ISD::SETNE;
455   CCs[RTLIB::O_F32] = ISD::SETEQ;
456   CCs[RTLIB::O_F64] = ISD::SETEQ;
457 }
458
459 /// NOTE: The constructor takes ownership of TLOF.
460 TargetLowering::TargetLowering(TargetMachine &tm,TargetLoweringObjectFile *tlof)
461   : TM(tm), TD(TM.getTargetData()), TLOF(*tlof) {
462   // All operations default to being supported.
463   memset(OpActions, 0, sizeof(OpActions));
464   memset(LoadExtActions, 0, sizeof(LoadExtActions));
465   memset(TruncStoreActions, 0, sizeof(TruncStoreActions));
466   memset(IndexedModeActions, 0, sizeof(IndexedModeActions));
467   memset(ConvertActions, 0, sizeof(ConvertActions));
468   memset(CondCodeActions, 0, sizeof(CondCodeActions));
469
470   // Set default actions for various operations.
471   for (unsigned VT = 0; VT != (unsigned)MVT::LAST_VALUETYPE; ++VT) {
472     // Default all indexed load / store to expand.
473     for (unsigned IM = (unsigned)ISD::PRE_INC;
474          IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
475       setIndexedLoadAction(IM, (MVT::SimpleValueType)VT, Expand);
476       setIndexedStoreAction(IM, (MVT::SimpleValueType)VT, Expand);
477     }
478     
479     // These operations default to expand.
480     setOperationAction(ISD::FGETSIGN, (MVT::SimpleValueType)VT, Expand);
481     setOperationAction(ISD::CONCAT_VECTORS, (MVT::SimpleValueType)VT, Expand);
482   }
483
484   // Most targets ignore the @llvm.prefetch intrinsic.
485   setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
486   
487   // ConstantFP nodes default to expand.  Targets can either change this to 
488   // Legal, in which case all fp constants are legal, or use isFPImmLegal()
489   // to optimize expansions for certain constants.
490   setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
491   setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
492   setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
493
494   // These library functions default to expand.
495   setOperationAction(ISD::FLOG , MVT::f64, Expand);
496   setOperationAction(ISD::FLOG2, MVT::f64, Expand);
497   setOperationAction(ISD::FLOG10,MVT::f64, Expand);
498   setOperationAction(ISD::FEXP , MVT::f64, Expand);
499   setOperationAction(ISD::FEXP2, MVT::f64, Expand);
500   setOperationAction(ISD::FLOG , MVT::f32, Expand);
501   setOperationAction(ISD::FLOG2, MVT::f32, Expand);
502   setOperationAction(ISD::FLOG10,MVT::f32, Expand);
503   setOperationAction(ISD::FEXP , MVT::f32, Expand);
504   setOperationAction(ISD::FEXP2, MVT::f32, Expand);
505
506   // Default ISD::TRAP to expand (which turns it into abort).
507   setOperationAction(ISD::TRAP, MVT::Other, Expand);
508     
509   IsLittleEndian = TD->isLittleEndian();
510   UsesGlobalOffsetTable = false;
511   ShiftAmountTy = PointerTy = MVT::getIntegerVT(8*TD->getPointerSize());
512   memset(RegClassForVT, 0,MVT::LAST_VALUETYPE*sizeof(TargetRegisterClass*));
513   memset(TargetDAGCombineArray, 0, array_lengthof(TargetDAGCombineArray));
514   maxStoresPerMemset = maxStoresPerMemcpy = maxStoresPerMemmove = 8;
515   benefitFromCodePlacementOpt = false;
516   UseUnderscoreSetJmp = false;
517   UseUnderscoreLongJmp = false;
518   SelectIsExpensive = false;
519   IntDivIsCheap = false;
520   Pow2DivIsCheap = false;
521   StackPointerRegisterToSaveRestore = 0;
522   ExceptionPointerRegister = 0;
523   ExceptionSelectorRegister = 0;
524   BooleanContents = UndefinedBooleanContent;
525   SchedPreferenceInfo = SchedulingForLatency;
526   JumpBufSize = 0;
527   JumpBufAlignment = 0;
528   IfCvtBlockSizeLimit = 2;
529   IfCvtDupBlockSizeLimit = 0;
530   PrefLoopAlignment = 0;
531
532   InitLibcallNames(LibcallRoutineNames);
533   InitCmpLibcallCCs(CmpLibcallCCs);
534   InitLibcallCallingConvs(LibcallCallingConvs);
535 }
536
537 TargetLowering::~TargetLowering() {
538   delete &TLOF;
539 }
540
541 static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
542                                        unsigned &NumIntermediates,
543                                        EVT &RegisterVT,
544                                        TargetLowering* TLI) {
545   // Figure out the right, legal destination reg to copy into.
546   unsigned NumElts = VT.getVectorNumElements();
547   MVT EltTy = VT.getVectorElementType();
548   
549   unsigned NumVectorRegs = 1;
550   
551   // FIXME: We don't support non-power-of-2-sized vectors for now.  Ideally we 
552   // could break down into LHS/RHS like LegalizeDAG does.
553   if (!isPowerOf2_32(NumElts)) {
554     NumVectorRegs = NumElts;
555     NumElts = 1;
556   }
557   
558   // Divide the input until we get to a supported size.  This will always
559   // end with a scalar if the target doesn't support vectors.
560   while (NumElts > 1 && !TLI->isTypeLegal(MVT::getVectorVT(EltTy, NumElts))) {
561     NumElts >>= 1;
562     NumVectorRegs <<= 1;
563   }
564
565   NumIntermediates = NumVectorRegs;
566   
567   MVT NewVT = MVT::getVectorVT(EltTy, NumElts);
568   if (!TLI->isTypeLegal(NewVT))
569     NewVT = EltTy;
570   IntermediateVT = NewVT;
571
572   EVT DestVT = TLI->getRegisterType(NewVT);
573   RegisterVT = DestVT;
574   if (EVT(DestVT).bitsLT(NewVT)) {
575     // Value is expanded, e.g. i64 -> i16.
576     return NumVectorRegs*(NewVT.getSizeInBits()/DestVT.getSizeInBits());
577   } else {
578     // Otherwise, promotion or legal types use the same number of registers as
579     // the vector decimated to the appropriate level.
580     return NumVectorRegs;
581   }
582   
583   return 1;
584 }
585
586 /// computeRegisterProperties - Once all of the register classes are added,
587 /// this allows us to compute derived properties we expose.
588 void TargetLowering::computeRegisterProperties() {
589   assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE &&
590          "Too many value types for ValueTypeActions to hold!");
591
592   // Everything defaults to needing one register.
593   for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
594     NumRegistersForVT[i] = 1;
595     RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
596   }
597   // ...except isVoid, which doesn't need any registers.
598   NumRegistersForVT[MVT::isVoid] = 0;
599
600   // Find the largest integer register class.
601   unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
602   for (; RegClassForVT[LargestIntReg] == 0; --LargestIntReg)
603     assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
604
605   // Every integer value type larger than this largest register takes twice as
606   // many registers to represent as the previous ValueType.
607   for (unsigned ExpandedReg = LargestIntReg + 1; ; ++ExpandedReg) {
608     EVT ExpandedVT = (MVT::SimpleValueType)ExpandedReg;
609     if (!ExpandedVT.isInteger())
610       break;
611     NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
612     RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
613     TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
614     ValueTypeActions.setTypeAction(ExpandedVT, Expand);
615   }
616
617   // Inspect all of the ValueType's smaller than the largest integer
618   // register to see which ones need promotion.
619   unsigned LegalIntReg = LargestIntReg;
620   for (unsigned IntReg = LargestIntReg - 1;
621        IntReg >= (unsigned)MVT::i1; --IntReg) {
622     EVT IVT = (MVT::SimpleValueType)IntReg;
623     if (isTypeLegal(IVT)) {
624       LegalIntReg = IntReg;
625     } else {
626       RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
627         (MVT::SimpleValueType)LegalIntReg;
628       ValueTypeActions.setTypeAction(IVT, Promote);
629     }
630   }
631
632   // ppcf128 type is really two f64's.
633   if (!isTypeLegal(MVT::ppcf128)) {
634     NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
635     RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
636     TransformToType[MVT::ppcf128] = MVT::f64;
637     ValueTypeActions.setTypeAction(MVT::ppcf128, Expand);
638   }    
639
640   // Decide how to handle f64. If the target does not have native f64 support,
641   // expand it to i64 and we will be generating soft float library calls.
642   if (!isTypeLegal(MVT::f64)) {
643     NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
644     RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
645     TransformToType[MVT::f64] = MVT::i64;
646     ValueTypeActions.setTypeAction(MVT::f64, Expand);
647   }
648
649   // Decide how to handle f32. If the target does not have native support for
650   // f32, promote it to f64 if it is legal. Otherwise, expand it to i32.
651   if (!isTypeLegal(MVT::f32)) {
652     if (isTypeLegal(MVT::f64)) {
653       NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::f64];
654       RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::f64];
655       TransformToType[MVT::f32] = MVT::f64;
656       ValueTypeActions.setTypeAction(MVT::f32, Promote);
657     } else {
658       NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
659       RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
660       TransformToType[MVT::f32] = MVT::i32;
661       ValueTypeActions.setTypeAction(MVT::f32, Expand);
662     }
663   }
664   
665   // Loop over all of the vector value types to see which need transformations.
666   for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
667        i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
668     MVT VT = (MVT::SimpleValueType)i;
669     if (!isTypeLegal(VT)) {
670       MVT IntermediateVT;
671       EVT RegisterVT;
672       unsigned NumIntermediates;
673       NumRegistersForVT[i] =
674         getVectorTypeBreakdownMVT(VT, IntermediateVT, NumIntermediates,
675                                   RegisterVT, this);
676       RegisterTypeForVT[i] = RegisterVT;
677       
678       // Determine if there is a legal wider type.
679       bool IsLegalWiderType = false;
680       EVT EltVT = VT.getVectorElementType();
681       unsigned NElts = VT.getVectorNumElements();
682       for (unsigned nVT = i+1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
683         EVT SVT = (MVT::SimpleValueType)nVT;
684         if (isTypeLegal(SVT) && SVT.getVectorElementType() == EltVT &&
685             SVT.getVectorNumElements() > NElts) {
686           TransformToType[i] = SVT;
687           ValueTypeActions.setTypeAction(VT, Promote);
688           IsLegalWiderType = true;
689           break;
690         }
691       }
692       if (!IsLegalWiderType) {
693         EVT NVT = VT.getPow2VectorType();
694         if (NVT == VT) {
695           // Type is already a power of 2.  The default action is to split.
696           TransformToType[i] = MVT::Other;
697           ValueTypeActions.setTypeAction(VT, Expand);
698         } else {
699           TransformToType[i] = NVT;
700           ValueTypeActions.setTypeAction(VT, Promote);
701         }
702       }
703     }
704   }
705 }
706
707 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
708   return NULL;
709 }
710
711
712 MVT::SimpleValueType TargetLowering::getSetCCResultType(EVT VT) const {
713   return PointerTy.SimpleTy;
714 }
715
716 MVT::SimpleValueType TargetLowering::getCmpLibcallReturnType() const {
717   return MVT::i32; // return the default value
718 }
719
720 /// getVectorTypeBreakdown - Vector types are broken down into some number of
721 /// legal first class types.  For example, MVT::v8f32 maps to 2 MVT::v4f32
722 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
723 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
724 ///
725 /// This method returns the number of registers needed, and the VT for each
726 /// register.  It also returns the VT and quantity of the intermediate values
727 /// before they are promoted/expanded.
728 ///
729 unsigned TargetLowering::getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
730                                                 EVT &IntermediateVT,
731                                                 unsigned &NumIntermediates,
732                                                 EVT &RegisterVT) const {
733   // Figure out the right, legal destination reg to copy into.
734   unsigned NumElts = VT.getVectorNumElements();
735   EVT EltTy = VT.getVectorElementType();
736   
737   unsigned NumVectorRegs = 1;
738   
739   // FIXME: We don't support non-power-of-2-sized vectors for now.  Ideally we 
740   // could break down into LHS/RHS like LegalizeDAG does.
741   if (!isPowerOf2_32(NumElts)) {
742     NumVectorRegs = NumElts;
743     NumElts = 1;
744   }
745   
746   // Divide the input until we get to a supported size.  This will always
747   // end with a scalar if the target doesn't support vectors.
748   while (NumElts > 1 && !isTypeLegal(
749                                    EVT::getVectorVT(Context, EltTy, NumElts))) {
750     NumElts >>= 1;
751     NumVectorRegs <<= 1;
752   }
753
754   NumIntermediates = NumVectorRegs;
755   
756   EVT NewVT = EVT::getVectorVT(Context, EltTy, NumElts);
757   if (!isTypeLegal(NewVT))
758     NewVT = EltTy;
759   IntermediateVT = NewVT;
760
761   EVT DestVT = getRegisterType(Context, NewVT);
762   RegisterVT = DestVT;
763   if (DestVT.bitsLT(NewVT)) {
764     // Value is expanded, e.g. i64 -> i16.
765     return NumVectorRegs*(NewVT.getSizeInBits()/DestVT.getSizeInBits());
766   } else {
767     // Otherwise, promotion or legal types use the same number of registers as
768     // the vector decimated to the appropriate level.
769     return NumVectorRegs;
770   }
771   
772   return 1;
773 }
774
775 /// getWidenVectorType: given a vector type, returns the type to widen to
776 /// (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
777 /// If there is no vector type that we want to widen to, returns MVT::Other
778 /// When and where to widen is target dependent based on the cost of
779 /// scalarizing vs using the wider vector type.
780 EVT TargetLowering::getWidenVectorType(EVT VT) const {
781   assert(VT.isVector());
782   if (isTypeLegal(VT))
783     return VT;
784  
785   // Default is not to widen until moved to LegalizeTypes
786   return MVT::Other;
787 }
788
789 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
790 /// function arguments in the caller parameter area.  This is the actual
791 /// alignment, not its logarithm.
792 unsigned TargetLowering::getByValTypeAlignment(const Type *Ty) const {
793   return TD->getCallFrameTypeAlignment(Ty);
794 }
795
796 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
797                                                  SelectionDAG &DAG) const {
798   if (usesGlobalOffsetTable())
799     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
800   return Table;
801 }
802
803 bool
804 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
805   // Assume that everything is safe in static mode.
806   if (getTargetMachine().getRelocationModel() == Reloc::Static)
807     return true;
808
809   // In dynamic-no-pic mode, assume that known defined values are safe.
810   if (getTargetMachine().getRelocationModel() == Reloc::DynamicNoPIC &&
811       GA &&
812       !GA->getGlobal()->isDeclaration() &&
813       !GA->getGlobal()->isWeakForLinker())
814     return true;
815
816   // Otherwise assume nothing is safe.
817   return false;
818 }
819
820 //===----------------------------------------------------------------------===//
821 //  Optimization Methods
822 //===----------------------------------------------------------------------===//
823
824 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
825 /// specified instruction is a constant integer.  If so, check to see if there
826 /// are any bits set in the constant that are not demanded.  If so, shrink the
827 /// constant and return true.
828 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op, 
829                                                         const APInt &Demanded) {
830   DebugLoc dl = Op.getDebugLoc();
831
832   // FIXME: ISD::SELECT, ISD::SELECT_CC
833   switch (Op.getOpcode()) {
834   default: break;
835   case ISD::XOR:
836   case ISD::AND:
837   case ISD::OR: {
838     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
839     if (!C) return false;
840
841     if (Op.getOpcode() == ISD::XOR &&
842         (C->getAPIntValue() | (~Demanded)).isAllOnesValue())
843       return false;
844
845     // if we can expand it to have all bits set, do it
846     if (C->getAPIntValue().intersects(~Demanded)) {
847       EVT VT = Op.getValueType();
848       SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0),
849                                 DAG.getConstant(Demanded &
850                                                 C->getAPIntValue(), 
851                                                 VT));
852       return CombineTo(Op, New);
853     }
854
855     break;
856   }
857   }
858
859   return false;
860 }
861
862 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
863 /// casts are free.  This uses isZExtFree and ZERO_EXTEND for the widening
864 /// cast, but it could be generalized for targets with other types of
865 /// implicit widening casts.
866 bool
867 TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
868                                                     unsigned BitWidth,
869                                                     const APInt &Demanded,
870                                                     DebugLoc dl) {
871   assert(Op.getNumOperands() == 2 &&
872          "ShrinkDemandedOp only supports binary operators!");
873   assert(Op.getNode()->getNumValues() == 1 &&
874          "ShrinkDemandedOp only supports nodes with one result!");
875
876   // Don't do this if the node has another user, which may require the
877   // full value.
878   if (!Op.getNode()->hasOneUse())
879     return false;
880
881   // Search for the smallest integer type with free casts to and from
882   // Op's type. For expedience, just check power-of-2 integer types.
883   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
884   unsigned SmallVTBits = BitWidth - Demanded.countLeadingZeros();
885   if (!isPowerOf2_32(SmallVTBits))
886     SmallVTBits = NextPowerOf2(SmallVTBits);
887   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
888     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
889     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
890         TLI.isZExtFree(SmallVT, Op.getValueType())) {
891       // We found a type with free casts.
892       SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
893                               DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
894                                           Op.getNode()->getOperand(0)),
895                               DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
896                                           Op.getNode()->getOperand(1)));
897       SDValue Z = DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), X);
898       return CombineTo(Op, Z);
899     }
900   }
901   return false;
902 }
903
904 /// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
905 /// DemandedMask bits of the result of Op are ever used downstream.  If we can
906 /// use this information to simplify Op, create a new simplified DAG node and
907 /// return true, returning the original and new nodes in Old and New. Otherwise,
908 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
909 /// the expression (used to simplify the caller).  The KnownZero/One bits may
910 /// only be accurate for those bits in the DemandedMask.
911 bool TargetLowering::SimplifyDemandedBits(SDValue Op,
912                                           const APInt &DemandedMask,
913                                           APInt &KnownZero,
914                                           APInt &KnownOne,
915                                           TargetLoweringOpt &TLO,
916                                           unsigned Depth) const {
917   unsigned BitWidth = DemandedMask.getBitWidth();
918   assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth &&
919          "Mask size mismatches value type size!");
920   APInt NewMask = DemandedMask;
921   DebugLoc dl = Op.getDebugLoc();
922
923   // Don't know anything.
924   KnownZero = KnownOne = APInt(BitWidth, 0);
925
926   // Other users may use these bits.
927   if (!Op.getNode()->hasOneUse()) { 
928     if (Depth != 0) {
929       // If not at the root, Just compute the KnownZero/KnownOne bits to 
930       // simplify things downstream.
931       TLO.DAG.ComputeMaskedBits(Op, DemandedMask, KnownZero, KnownOne, Depth);
932       return false;
933     }
934     // If this is the root being simplified, allow it to have multiple uses,
935     // just set the NewMask to all bits.
936     NewMask = APInt::getAllOnesValue(BitWidth);
937   } else if (DemandedMask == 0) {   
938     // Not demanding any bits from Op.
939     if (Op.getOpcode() != ISD::UNDEF)
940       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
941     return false;
942   } else if (Depth == 6) {        // Limit search depth.
943     return false;
944   }
945
946   APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
947   switch (Op.getOpcode()) {
948   case ISD::Constant:
949     // We know all of the bits for a constant!
950     KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & NewMask;
951     KnownZero = ~KnownOne & NewMask;
952     return false;   // Don't fall through, will infinitely loop.
953   case ISD::AND:
954     // If the RHS is a constant, check to see if the LHS would be zero without
955     // using the bits from the RHS.  Below, we use knowledge about the RHS to
956     // simplify the LHS, here we're using information from the LHS to simplify
957     // the RHS.
958     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
959       APInt LHSZero, LHSOne;
960       TLO.DAG.ComputeMaskedBits(Op.getOperand(0), NewMask,
961                                 LHSZero, LHSOne, Depth+1);
962       // If the LHS already has zeros where RHSC does, this and is dead.
963       if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
964         return TLO.CombineTo(Op, Op.getOperand(0));
965       // If any of the set bits in the RHS are known zero on the LHS, shrink
966       // the constant.
967       if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
968         return true;
969     }
970     
971     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
972                              KnownOne, TLO, Depth+1))
973       return true;
974     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
975     if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
976                              KnownZero2, KnownOne2, TLO, Depth+1))
977       return true;
978     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
979       
980     // If all of the demanded bits are known one on one side, return the other.
981     // These bits cannot contribute to the result of the 'and'.
982     if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
983       return TLO.CombineTo(Op, Op.getOperand(0));
984     if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
985       return TLO.CombineTo(Op, Op.getOperand(1));
986     // If all of the demanded bits in the inputs are known zeros, return zero.
987     if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
988       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType()));
989     // If the RHS is a constant, see if we can simplify it.
990     if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
991       return true;
992     // If the operation can be done in a smaller type, do so.
993     if (TLO.ShrinkOps && TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
994       return true;
995
996     // Output known-1 bits are only known if set in both the LHS & RHS.
997     KnownOne &= KnownOne2;
998     // Output known-0 are known to be clear if zero in either the LHS | RHS.
999     KnownZero |= KnownZero2;
1000     break;
1001   case ISD::OR:
1002     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero, 
1003                              KnownOne, TLO, Depth+1))
1004       return true;
1005     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1006     if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
1007                              KnownZero2, KnownOne2, TLO, Depth+1))
1008       return true;
1009     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1010     
1011     // If all of the demanded bits are known zero on one side, return the other.
1012     // These bits cannot contribute to the result of the 'or'.
1013     if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
1014       return TLO.CombineTo(Op, Op.getOperand(0));
1015     if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
1016       return TLO.CombineTo(Op, Op.getOperand(1));
1017     // If all of the potentially set bits on one side are known to be set on
1018     // the other side, just use the 'other' side.
1019     if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
1020       return TLO.CombineTo(Op, Op.getOperand(0));
1021     if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
1022       return TLO.CombineTo(Op, Op.getOperand(1));
1023     // If the RHS is a constant, see if we can simplify it.
1024     if (TLO.ShrinkDemandedConstant(Op, NewMask))
1025       return true;
1026     // If the operation can be done in a smaller type, do so.
1027     if (TLO.ShrinkOps && TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1028       return true;
1029
1030     // Output known-0 bits are only known if clear in both the LHS & RHS.
1031     KnownZero &= KnownZero2;
1032     // Output known-1 are known to be set if set in either the LHS | RHS.
1033     KnownOne |= KnownOne2;
1034     break;
1035   case ISD::XOR:
1036     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero, 
1037                              KnownOne, TLO, Depth+1))
1038       return true;
1039     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1040     if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
1041                              KnownOne2, TLO, Depth+1))
1042       return true;
1043     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1044     
1045     // If all of the demanded bits are known zero on one side, return the other.
1046     // These bits cannot contribute to the result of the 'xor'.
1047     if ((KnownZero & NewMask) == NewMask)
1048       return TLO.CombineTo(Op, Op.getOperand(0));
1049     if ((KnownZero2 & NewMask) == NewMask)
1050       return TLO.CombineTo(Op, Op.getOperand(1));
1051     // If the operation can be done in a smaller type, do so.
1052     if (TLO.ShrinkOps && TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1053       return true;
1054
1055     // If all of the unknown bits are known to be zero on one side or the other
1056     // (but not both) turn this into an *inclusive* or.
1057     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1058     if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
1059       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
1060                                                Op.getOperand(0),
1061                                                Op.getOperand(1)));
1062     
1063     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1064     KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1065     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1066     KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1067     
1068     // If all of the demanded bits on one side are known, and all of the set
1069     // bits on that side are also known to be set on the other side, turn this
1070     // into an AND, as we know the bits will be cleared.
1071     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1072     if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known
1073       if ((KnownOne & KnownOne2) == KnownOne) {
1074         EVT VT = Op.getValueType();
1075         SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, VT);
1076         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, 
1077                                                  Op.getOperand(0), ANDC));
1078       }
1079     }
1080     
1081     // If the RHS is a constant, see if we can simplify it.
1082     // for XOR, we prefer to force bits to 1 if they will make a -1.
1083     // if we can't force bits, try to shrink constant
1084     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1085       APInt Expanded = C->getAPIntValue() | (~NewMask);
1086       // if we can expand it to have all bits set, do it
1087       if (Expanded.isAllOnesValue()) {
1088         if (Expanded != C->getAPIntValue()) {
1089           EVT VT = Op.getValueType();
1090           SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
1091                                           TLO.DAG.getConstant(Expanded, VT));
1092           return TLO.CombineTo(Op, New);
1093         }
1094         // if it already has all the bits set, nothing to change
1095         // but don't shrink either!
1096       } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
1097         return true;
1098       }
1099     }
1100
1101     KnownZero = KnownZeroOut;
1102     KnownOne  = KnownOneOut;
1103     break;
1104   case ISD::SELECT:
1105     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero, 
1106                              KnownOne, TLO, Depth+1))
1107       return true;
1108     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
1109                              KnownOne2, TLO, Depth+1))
1110       return true;
1111     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1112     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1113     
1114     // If the operands are constants, see if we can simplify them.
1115     if (TLO.ShrinkDemandedConstant(Op, NewMask))
1116       return true;
1117     
1118     // Only known if known in both the LHS and RHS.
1119     KnownOne &= KnownOne2;
1120     KnownZero &= KnownZero2;
1121     break;
1122   case ISD::SELECT_CC:
1123     if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero, 
1124                              KnownOne, TLO, Depth+1))
1125       return true;
1126     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
1127                              KnownOne2, TLO, Depth+1))
1128       return true;
1129     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1130     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1131     
1132     // If the operands are constants, see if we can simplify them.
1133     if (TLO.ShrinkDemandedConstant(Op, NewMask))
1134       return true;
1135       
1136     // Only known if known in both the LHS and RHS.
1137     KnownOne &= KnownOne2;
1138     KnownZero &= KnownZero2;
1139     break;
1140   case ISD::SHL:
1141     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1142       unsigned ShAmt = SA->getZExtValue();
1143       SDValue InOp = Op.getOperand(0);
1144
1145       // If the shift count is an invalid immediate, don't do anything.
1146       if (ShAmt >= BitWidth)
1147         break;
1148
1149       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1150       // single shift.  We can do this if the bottom bits (which are shifted
1151       // out) are never demanded.
1152       if (InOp.getOpcode() == ISD::SRL &&
1153           isa<ConstantSDNode>(InOp.getOperand(1))) {
1154         if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
1155           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
1156           unsigned Opc = ISD::SHL;
1157           int Diff = ShAmt-C1;
1158           if (Diff < 0) {
1159             Diff = -Diff;
1160             Opc = ISD::SRL;
1161           }          
1162           
1163           SDValue NewSA = 
1164             TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
1165           EVT VT = Op.getValueType();
1166           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
1167                                                    InOp.getOperand(0), NewSA));
1168         }
1169       }      
1170       
1171       if (SimplifyDemandedBits(Op.getOperand(0), NewMask.lshr(ShAmt),
1172                                KnownZero, KnownOne, TLO, Depth+1))
1173         return true;
1174       KnownZero <<= SA->getZExtValue();
1175       KnownOne  <<= SA->getZExtValue();
1176       // low bits known zero.
1177       KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
1178     }
1179     break;
1180   case ISD::SRL:
1181     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1182       EVT VT = Op.getValueType();
1183       unsigned ShAmt = SA->getZExtValue();
1184       unsigned VTSize = VT.getSizeInBits();
1185       SDValue InOp = Op.getOperand(0);
1186       
1187       // If the shift count is an invalid immediate, don't do anything.
1188       if (ShAmt >= BitWidth)
1189         break;
1190
1191       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
1192       // single shift.  We can do this if the top bits (which are shifted out)
1193       // are never demanded.
1194       if (InOp.getOpcode() == ISD::SHL &&
1195           isa<ConstantSDNode>(InOp.getOperand(1))) {
1196         if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
1197           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
1198           unsigned Opc = ISD::SRL;
1199           int Diff = ShAmt-C1;
1200           if (Diff < 0) {
1201             Diff = -Diff;
1202             Opc = ISD::SHL;
1203           }          
1204           
1205           SDValue NewSA =
1206             TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
1207           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
1208                                                    InOp.getOperand(0), NewSA));
1209         }
1210       }      
1211       
1212       // Compute the new bits that are at the top now.
1213       if (SimplifyDemandedBits(InOp, (NewMask << ShAmt),
1214                                KnownZero, KnownOne, TLO, Depth+1))
1215         return true;
1216       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1217       KnownZero = KnownZero.lshr(ShAmt);
1218       KnownOne  = KnownOne.lshr(ShAmt);
1219
1220       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
1221       KnownZero |= HighBits;  // High bits known zero.
1222     }
1223     break;
1224   case ISD::SRA:
1225     // If this is an arithmetic shift right and only the low-bit is set, we can
1226     // always convert this into a logical shr, even if the shift amount is
1227     // variable.  The low bit of the shift cannot be an input sign bit unless
1228     // the shift amount is >= the size of the datatype, which is undefined.
1229     if (DemandedMask == 1)
1230       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
1231                                                Op.getOperand(0), Op.getOperand(1)));
1232
1233     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1234       EVT VT = Op.getValueType();
1235       unsigned ShAmt = SA->getZExtValue();
1236       
1237       // If the shift count is an invalid immediate, don't do anything.
1238       if (ShAmt >= BitWidth)
1239         break;
1240
1241       APInt InDemandedMask = (NewMask << ShAmt);
1242
1243       // If any of the demanded bits are produced by the sign extension, we also
1244       // demand the input sign bit.
1245       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
1246       if (HighBits.intersects(NewMask))
1247         InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits());
1248       
1249       if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
1250                                KnownZero, KnownOne, TLO, Depth+1))
1251         return true;
1252       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1253       KnownZero = KnownZero.lshr(ShAmt);
1254       KnownOne  = KnownOne.lshr(ShAmt);
1255       
1256       // Handle the sign bit, adjusted to where it is now in the mask.
1257       APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
1258       
1259       // If the input sign bit is known to be zero, or if none of the top bits
1260       // are demanded, turn this into an unsigned shift right.
1261       if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
1262         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, 
1263                                                  Op.getOperand(0),
1264                                                  Op.getOperand(1)));
1265       } else if (KnownOne.intersects(SignBit)) { // New bits are known one.
1266         KnownOne |= HighBits;
1267       }
1268     }
1269     break;
1270   case ISD::SIGN_EXTEND_INREG: {
1271     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1272
1273     // Sign extension.  Compute the demanded bits in the result that are not 
1274     // present in the input.
1275     APInt NewBits =
1276       APInt::getHighBitsSet(BitWidth,
1277                             BitWidth - EVT.getScalarType().getSizeInBits()) &
1278       NewMask;
1279     
1280     // If none of the extended bits are demanded, eliminate the sextinreg.
1281     if (NewBits == 0)
1282       return TLO.CombineTo(Op, Op.getOperand(0));
1283
1284     APInt InSignBit = APInt::getSignBit(EVT.getScalarType().getSizeInBits());
1285     InSignBit.zext(BitWidth);
1286     APInt InputDemandedBits =
1287       APInt::getLowBitsSet(BitWidth,
1288                            EVT.getScalarType().getSizeInBits()) &
1289       NewMask;
1290     
1291     // Since the sign extended bits are demanded, we know that the sign
1292     // bit is demanded.
1293     InputDemandedBits |= InSignBit;
1294
1295     if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
1296                              KnownZero, KnownOne, TLO, Depth+1))
1297       return true;
1298     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1299
1300     // If the sign bit of the input is known set or clear, then we know the
1301     // top bits of the result.
1302     
1303     // If the input sign bit is known zero, convert this into a zero extension.
1304     if (KnownZero.intersects(InSignBit))
1305       return TLO.CombineTo(Op, 
1306                            TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,EVT));
1307     
1308     if (KnownOne.intersects(InSignBit)) {    // Input sign bit known set
1309       KnownOne |= NewBits;
1310       KnownZero &= ~NewBits;
1311     } else {                       // Input sign bit unknown
1312       KnownZero &= ~NewBits;
1313       KnownOne &= ~NewBits;
1314     }
1315     break;
1316   }
1317   case ISD::ZERO_EXTEND: {
1318     unsigned OperandBitWidth =
1319       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
1320     APInt InMask = NewMask;
1321     InMask.trunc(OperandBitWidth);
1322     
1323     // If none of the top bits are demanded, convert this into an any_extend.
1324     APInt NewBits =
1325       APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
1326     if (!NewBits.intersects(NewMask))
1327       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
1328                                                Op.getValueType(), 
1329                                                Op.getOperand(0)));
1330     
1331     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1332                              KnownZero, KnownOne, TLO, Depth+1))
1333       return true;
1334     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1335     KnownZero.zext(BitWidth);
1336     KnownOne.zext(BitWidth);
1337     KnownZero |= NewBits;
1338     break;
1339   }
1340   case ISD::SIGN_EXTEND: {
1341     EVT InVT = Op.getOperand(0).getValueType();
1342     unsigned InBits = InVT.getScalarType().getSizeInBits();
1343     APInt InMask    = APInt::getLowBitsSet(BitWidth, InBits);
1344     APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
1345     APInt NewBits   = ~InMask & NewMask;
1346     
1347     // If none of the top bits are demanded, convert this into an any_extend.
1348     if (NewBits == 0)
1349       return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
1350                                               Op.getValueType(),
1351                                               Op.getOperand(0)));
1352     
1353     // Since some of the sign extended bits are demanded, we know that the sign
1354     // bit is demanded.
1355     APInt InDemandedBits = InMask & NewMask;
1356     InDemandedBits |= InSignBit;
1357     InDemandedBits.trunc(InBits);
1358     
1359     if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero, 
1360                              KnownOne, TLO, Depth+1))
1361       return true;
1362     KnownZero.zext(BitWidth);
1363     KnownOne.zext(BitWidth);
1364     
1365     // If the sign bit is known zero, convert this to a zero extend.
1366     if (KnownZero.intersects(InSignBit))
1367       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
1368                                                Op.getValueType(), 
1369                                                Op.getOperand(0)));
1370     
1371     // If the sign bit is known one, the top bits match.
1372     if (KnownOne.intersects(InSignBit)) {
1373       KnownOne  |= NewBits;
1374       KnownZero &= ~NewBits;
1375     } else {   // Otherwise, top bits aren't known.
1376       KnownOne  &= ~NewBits;
1377       KnownZero &= ~NewBits;
1378     }
1379     break;
1380   }
1381   case ISD::ANY_EXTEND: {
1382     unsigned OperandBitWidth =
1383       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
1384     APInt InMask = NewMask;
1385     InMask.trunc(OperandBitWidth);
1386     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1387                              KnownZero, KnownOne, TLO, Depth+1))
1388       return true;
1389     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1390     KnownZero.zext(BitWidth);
1391     KnownOne.zext(BitWidth);
1392     break;
1393   }
1394   case ISD::TRUNCATE: {
1395     // Simplify the input, using demanded bit information, and compute the known
1396     // zero/one bits live out.
1397     APInt TruncMask = NewMask;
1398     TruncMask.zext(Op.getOperand(0).getValueSizeInBits());
1399     if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
1400                              KnownZero, KnownOne, TLO, Depth+1))
1401       return true;
1402     KnownZero.trunc(BitWidth);
1403     KnownOne.trunc(BitWidth);
1404     
1405     // If the input is only used by this truncate, see if we can shrink it based
1406     // on the known demanded bits.
1407     if (Op.getOperand(0).getNode()->hasOneUse()) {
1408       SDValue In = Op.getOperand(0);
1409       unsigned InBitWidth = In.getValueSizeInBits();
1410       switch (In.getOpcode()) {
1411       default: break;
1412       case ISD::SRL:
1413         // Shrink SRL by a constant if none of the high bits shifted in are
1414         // demanded.
1415         if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1))){
1416           APInt HighBits = APInt::getHighBitsSet(InBitWidth,
1417                                                  InBitWidth - BitWidth);
1418           HighBits = HighBits.lshr(ShAmt->getZExtValue());
1419           HighBits.trunc(BitWidth);
1420           
1421           if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
1422             // None of the shifted in bits are needed.  Add a truncate of the
1423             // shift input, then shift it.
1424             SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
1425                                                  Op.getValueType(), 
1426                                                  In.getOperand(0));
1427             return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
1428                                                      Op.getValueType(),
1429                                                      NewTrunc, 
1430                                                      In.getOperand(1)));
1431           }
1432         }
1433         break;
1434       }
1435     }
1436     
1437     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1438     break;
1439   }
1440   case ISD::AssertZext: {
1441     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1442     APInt InMask = APInt::getLowBitsSet(BitWidth,
1443                                         VT.getSizeInBits());
1444     if (SimplifyDemandedBits(Op.getOperand(0), InMask & NewMask,
1445                              KnownZero, KnownOne, TLO, Depth+1))
1446       return true;
1447     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1448     KnownZero |= ~InMask & NewMask;
1449     break;
1450   }
1451   case ISD::BIT_CONVERT:
1452 #if 0
1453     // If this is an FP->Int bitcast and if the sign bit is the only thing that
1454     // is demanded, turn this into a FGETSIGN.
1455     if (NewMask == EVT::getIntegerVTSignBit(Op.getValueType()) &&
1456         MVT::isFloatingPoint(Op.getOperand(0).getValueType()) &&
1457         !MVT::isVector(Op.getOperand(0).getValueType())) {
1458       // Only do this xform if FGETSIGN is valid or if before legalize.
1459       if (!TLO.AfterLegalize ||
1460           isOperationLegal(ISD::FGETSIGN, Op.getValueType())) {
1461         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1462         // place.  We expect the SHL to be eliminated by other optimizations.
1463         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, Op.getValueType(), 
1464                                          Op.getOperand(0));
1465         unsigned ShVal = Op.getValueType().getSizeInBits()-1;
1466         SDValue ShAmt = TLO.DAG.getConstant(ShVal, getShiftAmountTy());
1467         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, Op.getValueType(),
1468                                                  Sign, ShAmt));
1469       }
1470     }
1471 #endif
1472     break;
1473   case ISD::ADD:
1474   case ISD::MUL:
1475   case ISD::SUB: {
1476     // Add, Sub, and Mul don't demand any bits in positions beyond that
1477     // of the highest bit demanded of them.
1478     APInt LoMask = APInt::getLowBitsSet(BitWidth,
1479                                         BitWidth - NewMask.countLeadingZeros());
1480     if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
1481                              KnownOne2, TLO, Depth+1))
1482       return true;
1483     if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
1484                              KnownOne2, TLO, Depth+1))
1485       return true;
1486     // See if the operation should be performed at a smaller bit width.
1487     if (TLO.ShrinkOps && TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1488       return true;
1489   }
1490   // FALL THROUGH
1491   default:
1492     // Just use ComputeMaskedBits to compute output bits.
1493     TLO.DAG.ComputeMaskedBits(Op, NewMask, KnownZero, KnownOne, Depth);
1494     break;
1495   }
1496   
1497   // If we know the value of all of the demanded bits, return this as a
1498   // constant.
1499   if ((NewMask & (KnownZero|KnownOne)) == NewMask)
1500     return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
1501   
1502   return false;
1503 }
1504
1505 /// computeMaskedBitsForTargetNode - Determine which of the bits specified 
1506 /// in Mask are known to be either zero or one and return them in the 
1507 /// KnownZero/KnownOne bitsets.
1508 void TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op, 
1509                                                     const APInt &Mask,
1510                                                     APInt &KnownZero, 
1511                                                     APInt &KnownOne,
1512                                                     const SelectionDAG &DAG,
1513                                                     unsigned Depth) const {
1514   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1515           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1516           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1517           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1518          "Should use MaskedValueIsZero if you don't know whether Op"
1519          " is a target node!");
1520   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
1521 }
1522
1523 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
1524 /// targets that want to expose additional information about sign bits to the
1525 /// DAG Combiner.
1526 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
1527                                                          unsigned Depth) const {
1528   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1529           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1530           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1531           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1532          "Should use ComputeNumSignBits if you don't know whether Op"
1533          " is a target node!");
1534   return 1;
1535 }
1536
1537 /// ValueHasExactlyOneBitSet - Test if the given value is known to have exactly
1538 /// one bit set. This differs from ComputeMaskedBits in that it doesn't need to
1539 /// determine which bit is set.
1540 ///
1541 static bool ValueHasExactlyOneBitSet(SDValue Val, const SelectionDAG &DAG) {
1542   // A left-shift of a constant one will have exactly one bit set, because
1543   // shifting the bit off the end is undefined.
1544   if (Val.getOpcode() == ISD::SHL)
1545     if (ConstantSDNode *C =
1546          dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1547       if (C->getAPIntValue() == 1)
1548         return true;
1549
1550   // Similarly, a right-shift of a constant sign-bit will have exactly
1551   // one bit set.
1552   if (Val.getOpcode() == ISD::SRL)
1553     if (ConstantSDNode *C =
1554          dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1555       if (C->getAPIntValue().isSignBit())
1556         return true;
1557
1558   // More could be done here, though the above checks are enough
1559   // to handle some common cases.
1560
1561   // Fall back to ComputeMaskedBits to catch other known cases.
1562   EVT OpVT = Val.getValueType();
1563   unsigned BitWidth = OpVT.getSizeInBits();
1564   APInt Mask = APInt::getAllOnesValue(BitWidth);
1565   APInt KnownZero, KnownOne;
1566   DAG.ComputeMaskedBits(Val, Mask, KnownZero, KnownOne);
1567   return (KnownZero.countPopulation() == BitWidth - 1) &&
1568          (KnownOne.countPopulation() == 1);
1569 }
1570
1571 /// SimplifySetCC - Try to simplify a setcc built with the specified operands 
1572 /// and cc. If it is unable to simplify it, return a null SDValue.
1573 SDValue
1574 TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1575                               ISD::CondCode Cond, bool foldBooleans,
1576                               DAGCombinerInfo &DCI, DebugLoc dl) const {
1577   SelectionDAG &DAG = DCI.DAG;
1578   LLVMContext &Context = *DAG.getContext();
1579
1580   // These setcc operations always fold.
1581   switch (Cond) {
1582   default: break;
1583   case ISD::SETFALSE:
1584   case ISD::SETFALSE2: return DAG.getConstant(0, VT);
1585   case ISD::SETTRUE:
1586   case ISD::SETTRUE2:  return DAG.getConstant(1, VT);
1587   }
1588
1589   if (isa<ConstantSDNode>(N0.getNode())) {
1590     // Ensure that the constant occurs on the RHS, and fold constant
1591     // comparisons.
1592     return DAG.getSetCC(dl, VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
1593   }
1594
1595   if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1596     const APInt &C1 = N1C->getAPIntValue();
1597
1598     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1599     // equality comparison, then we're just comparing whether X itself is
1600     // zero.
1601     if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1602         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1603         N0.getOperand(1).getOpcode() == ISD::Constant) {
1604       const APInt &ShAmt
1605         = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1606       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1607           ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
1608         if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1609           // (srl (ctlz x), 5) == 0  -> X != 0
1610           // (srl (ctlz x), 5) != 1  -> X != 0
1611           Cond = ISD::SETNE;
1612         } else {
1613           // (srl (ctlz x), 5) != 0  -> X == 0
1614           // (srl (ctlz x), 5) == 1  -> X == 0
1615           Cond = ISD::SETEQ;
1616         }
1617         SDValue Zero = DAG.getConstant(0, N0.getValueType());
1618         return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1619                             Zero, Cond);
1620       }
1621     }
1622
1623     // If the LHS is '(and load, const)', the RHS is 0,
1624     // the test is for equality or unsigned, and all 1 bits of the const are
1625     // in the same partial word, see if we can shorten the load.
1626     if (DCI.isBeforeLegalize() &&
1627         N0.getOpcode() == ISD::AND && C1 == 0 &&
1628         N0.getNode()->hasOneUse() &&
1629         isa<LoadSDNode>(N0.getOperand(0)) &&
1630         N0.getOperand(0).getNode()->hasOneUse() &&
1631         isa<ConstantSDNode>(N0.getOperand(1))) {
1632       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
1633       APInt bestMask;
1634       unsigned bestWidth = 0, bestOffset = 0;
1635       if (!Lod->isVolatile() && Lod->isUnindexed()) {
1636         unsigned origWidth = N0.getValueType().getSizeInBits();
1637         unsigned maskWidth = origWidth;
1638         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 
1639         // 8 bits, but have to be careful...
1640         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
1641           origWidth = Lod->getMemoryVT().getSizeInBits();
1642         const APInt &Mask =
1643           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1644         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
1645           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
1646           for (unsigned offset=0; offset<origWidth/width; offset++) {
1647             if ((newMask & Mask) == Mask) {
1648               if (!TD->isLittleEndian())
1649                 bestOffset = (origWidth/width - offset - 1) * (width/8);
1650               else
1651                 bestOffset = (uint64_t)offset * (width/8);
1652               bestMask = Mask.lshr(offset * (width/8) * 8);
1653               bestWidth = width;
1654               break;
1655             }
1656             newMask = newMask << width;
1657           }
1658         }
1659       }
1660       if (bestWidth) {
1661         EVT newVT = EVT::getIntegerVT(Context, bestWidth);
1662         if (newVT.isRound()) {
1663           EVT PtrType = Lod->getOperand(1).getValueType();
1664           SDValue Ptr = Lod->getBasePtr();
1665           if (bestOffset != 0)
1666             Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
1667                               DAG.getConstant(bestOffset, PtrType));
1668           unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
1669           SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
1670                                         Lod->getSrcValue(), 
1671                                         Lod->getSrcValueOffset() + bestOffset,
1672                                         false, NewAlign);
1673           return DAG.getSetCC(dl, VT, 
1674                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
1675                                       DAG.getConstant(bestMask.trunc(bestWidth),
1676                                                       newVT)),
1677                               DAG.getConstant(0LL, newVT), Cond);
1678         }
1679       }
1680     }
1681
1682     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1683     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1684       unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
1685
1686       // If the comparison constant has bits in the upper part, the
1687       // zero-extended value could never match.
1688       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1689                                               C1.getBitWidth() - InSize))) {
1690         switch (Cond) {
1691         case ISD::SETUGT:
1692         case ISD::SETUGE:
1693         case ISD::SETEQ: return DAG.getConstant(0, VT);
1694         case ISD::SETULT:
1695         case ISD::SETULE:
1696         case ISD::SETNE: return DAG.getConstant(1, VT);
1697         case ISD::SETGT:
1698         case ISD::SETGE:
1699           // True if the sign bit of C1 is set.
1700           return DAG.getConstant(C1.isNegative(), VT);
1701         case ISD::SETLT:
1702         case ISD::SETLE:
1703           // True if the sign bit of C1 isn't set.
1704           return DAG.getConstant(C1.isNonNegative(), VT);
1705         default:
1706           break;
1707         }
1708       }
1709
1710       // Otherwise, we can perform the comparison with the low bits.
1711       switch (Cond) {
1712       case ISD::SETEQ:
1713       case ISD::SETNE:
1714       case ISD::SETUGT:
1715       case ISD::SETUGE:
1716       case ISD::SETULT:
1717       case ISD::SETULE: {
1718         EVT newVT = N0.getOperand(0).getValueType();
1719         if (DCI.isBeforeLegalizeOps() ||
1720             (isOperationLegal(ISD::SETCC, newVT) &&
1721               getCondCodeAction(Cond, newVT)==Legal))
1722           return DAG.getSetCC(dl, VT, N0.getOperand(0),
1723                               DAG.getConstant(APInt(C1).trunc(InSize), newVT),
1724                               Cond);
1725         break;
1726       }
1727       default:
1728         break;   // todo, be more careful with signed comparisons
1729       }
1730     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1731                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1732       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
1733       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
1734       EVT ExtDstTy = N0.getValueType();
1735       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
1736
1737       // If the extended part has any inconsistent bits, it cannot ever
1738       // compare equal.  In other words, they have to be all ones or all
1739       // zeros.
1740       APInt ExtBits =
1741         APInt::getHighBitsSet(ExtDstTyBits, ExtDstTyBits - ExtSrcTyBits);
1742       if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits)
1743         return DAG.getConstant(Cond == ISD::SETNE, VT);
1744       
1745       SDValue ZextOp;
1746       EVT Op0Ty = N0.getOperand(0).getValueType();
1747       if (Op0Ty == ExtSrcTy) {
1748         ZextOp = N0.getOperand(0);
1749       } else {
1750         APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1751         ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
1752                               DAG.getConstant(Imm, Op0Ty));
1753       }
1754       if (!DCI.isCalledByLegalizer())
1755         DCI.AddToWorklist(ZextOp.getNode());
1756       // Otherwise, make this a use of a zext.
1757       return DAG.getSetCC(dl, VT, ZextOp, 
1758                           DAG.getConstant(C1 & APInt::getLowBitsSet(
1759                                                               ExtDstTyBits,
1760                                                               ExtSrcTyBits), 
1761                                           ExtDstTy),
1762                           Cond);
1763     } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1764                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1765       
1766       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
1767       if (N0.getOpcode() == ISD::SETCC) {
1768         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
1769         if (TrueWhenTrue)
1770           return N0;
1771         
1772         // Invert the condition.
1773         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1774         CC = ISD::getSetCCInverse(CC, 
1775                                   N0.getOperand(0).getValueType().isInteger());
1776         return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
1777       }
1778       
1779       if ((N0.getOpcode() == ISD::XOR ||
1780             (N0.getOpcode() == ISD::AND && 
1781             N0.getOperand(0).getOpcode() == ISD::XOR &&
1782             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1783           isa<ConstantSDNode>(N0.getOperand(1)) &&
1784           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
1785         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
1786         // can only do this if the top bits are known zero.
1787         unsigned BitWidth = N0.getValueSizeInBits();
1788         if (DAG.MaskedValueIsZero(N0,
1789                                   APInt::getHighBitsSet(BitWidth,
1790                                                         BitWidth-1))) {
1791           // Okay, get the un-inverted input value.
1792           SDValue Val;
1793           if (N0.getOpcode() == ISD::XOR)
1794             Val = N0.getOperand(0);
1795           else {
1796             assert(N0.getOpcode() == ISD::AND && 
1797                     N0.getOperand(0).getOpcode() == ISD::XOR);
1798             // ((X^1)&1)^1 -> X & 1
1799             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
1800                               N0.getOperand(0).getOperand(0),
1801                               N0.getOperand(1));
1802           }
1803           return DAG.getSetCC(dl, VT, Val, N1,
1804                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1805         }
1806       }
1807     }
1808     
1809     APInt MinVal, MaxVal;
1810     unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
1811     if (ISD::isSignedIntSetCC(Cond)) {
1812       MinVal = APInt::getSignedMinValue(OperandBitSize);
1813       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1814     } else {
1815       MinVal = APInt::getMinValue(OperandBitSize);
1816       MaxVal = APInt::getMaxValue(OperandBitSize);
1817     }
1818
1819     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1820     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1821       if (C1 == MinVal) return DAG.getConstant(1, VT);   // X >= MIN --> true
1822       // X >= C0 --> X > (C0-1)
1823       return DAG.getSetCC(dl, VT, N0, 
1824                           DAG.getConstant(C1-1, N1.getValueType()),
1825                           (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
1826     }
1827
1828     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1829       if (C1 == MaxVal) return DAG.getConstant(1, VT);   // X <= MAX --> true
1830       // X <= C0 --> X < (C0+1)
1831       return DAG.getSetCC(dl, VT, N0, 
1832                           DAG.getConstant(C1+1, N1.getValueType()),
1833                           (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
1834     }
1835
1836     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1837       return DAG.getConstant(0, VT);      // X < MIN --> false
1838     if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1839       return DAG.getConstant(1, VT);      // X >= MIN --> true
1840     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1841       return DAG.getConstant(0, VT);      // X > MAX --> false
1842     if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1843       return DAG.getConstant(1, VT);      // X <= MAX --> true
1844
1845     // Canonicalize setgt X, Min --> setne X, Min
1846     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1847       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1848     // Canonicalize setlt X, Max --> setne X, Max
1849     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1850       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1851
1852     // If we have setult X, 1, turn it into seteq X, 0
1853     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1854       return DAG.getSetCC(dl, VT, N0, 
1855                           DAG.getConstant(MinVal, N0.getValueType()), 
1856                           ISD::SETEQ);
1857     // If we have setugt X, Max-1, turn it into seteq X, Max
1858     else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1859       return DAG.getSetCC(dl, VT, N0, 
1860                           DAG.getConstant(MaxVal, N0.getValueType()),
1861                           ISD::SETEQ);
1862
1863     // If we have "setcc X, C0", check to see if we can shrink the immediate
1864     // by changing cc.
1865
1866     // SETUGT X, SINTMAX  -> SETLT X, 0
1867     if (Cond == ISD::SETUGT && 
1868         C1 == APInt::getSignedMaxValue(OperandBitSize))
1869       return DAG.getSetCC(dl, VT, N0, 
1870                           DAG.getConstant(0, N1.getValueType()),
1871                           ISD::SETLT);
1872
1873     // SETULT X, SINTMIN  -> SETGT X, -1
1874     if (Cond == ISD::SETULT &&
1875         C1 == APInt::getSignedMinValue(OperandBitSize)) {
1876       SDValue ConstMinusOne =
1877           DAG.getConstant(APInt::getAllOnesValue(OperandBitSize),
1878                           N1.getValueType());
1879       return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
1880     }
1881
1882     // Fold bit comparisons when we can.
1883     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1884         (VT == N0.getValueType() ||
1885          (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
1886         N0.getOpcode() == ISD::AND)
1887       if (ConstantSDNode *AndRHS =
1888                   dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1889         EVT ShiftTy = DCI.isBeforeLegalize() ?
1890           getPointerTy() : getShiftAmountTy();
1891         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
1892           // Perform the xform if the AND RHS is a single bit.
1893           if (AndRHS->getAPIntValue().isPowerOf2()) {
1894             return DAG.getNode(ISD::TRUNCATE, dl, VT,
1895                               DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
1896                    DAG.getConstant(AndRHS->getAPIntValue().logBase2(), ShiftTy)));
1897           }
1898         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
1899           // (X & 8) == 8  -->  (X & 8) >> 3
1900           // Perform the xform if C1 is a single bit.
1901           if (C1.isPowerOf2()) {
1902             return DAG.getNode(ISD::TRUNCATE, dl, VT,
1903                                DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
1904                                       DAG.getConstant(C1.logBase2(), ShiftTy)));
1905           }
1906         }
1907       }
1908   }
1909
1910   if (isa<ConstantFPSDNode>(N0.getNode())) {
1911     // Constant fold or commute setcc.
1912     SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
1913     if (O.getNode()) return O;
1914   } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1915     // If the RHS of an FP comparison is a constant, simplify it away in
1916     // some cases.
1917     if (CFP->getValueAPF().isNaN()) {
1918       // If an operand is known to be a nan, we can fold it.
1919       switch (ISD::getUnorderedFlavor(Cond)) {
1920       default: llvm_unreachable("Unknown flavor!");
1921       case 0:  // Known false.
1922         return DAG.getConstant(0, VT);
1923       case 1:  // Known true.
1924         return DAG.getConstant(1, VT);
1925       case 2:  // Undefined.
1926         return DAG.getUNDEF(VT);
1927       }
1928     }
1929     
1930     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
1931     // constant if knowing that the operand is non-nan is enough.  We prefer to
1932     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
1933     // materialize 0.0.
1934     if (Cond == ISD::SETO || Cond == ISD::SETUO)
1935       return DAG.getSetCC(dl, VT, N0, N0, Cond);
1936
1937     // If the condition is not legal, see if we can find an equivalent one
1938     // which is legal.
1939     if (!isCondCodeLegal(Cond, N0.getValueType())) {
1940       // If the comparison was an awkward floating-point == or != and one of
1941       // the comparison operands is infinity or negative infinity, convert the
1942       // condition to a less-awkward <= or >=.
1943       if (CFP->getValueAPF().isInfinity()) {
1944         if (CFP->getValueAPF().isNegative()) {
1945           if (Cond == ISD::SETOEQ &&
1946               isCondCodeLegal(ISD::SETOLE, N0.getValueType()))
1947             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
1948           if (Cond == ISD::SETUEQ &&
1949               isCondCodeLegal(ISD::SETOLE, N0.getValueType()))
1950             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
1951           if (Cond == ISD::SETUNE &&
1952               isCondCodeLegal(ISD::SETUGT, N0.getValueType()))
1953             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
1954           if (Cond == ISD::SETONE &&
1955               isCondCodeLegal(ISD::SETUGT, N0.getValueType()))
1956             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
1957         } else {
1958           if (Cond == ISD::SETOEQ &&
1959               isCondCodeLegal(ISD::SETOGE, N0.getValueType()))
1960             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
1961           if (Cond == ISD::SETUEQ &&
1962               isCondCodeLegal(ISD::SETOGE, N0.getValueType()))
1963             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
1964           if (Cond == ISD::SETUNE &&
1965               isCondCodeLegal(ISD::SETULT, N0.getValueType()))
1966             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
1967           if (Cond == ISD::SETONE &&
1968               isCondCodeLegal(ISD::SETULT, N0.getValueType()))
1969             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
1970         }
1971       }
1972     }
1973   }
1974
1975   if (N0 == N1) {
1976     // We can always fold X == X for integer setcc's.
1977     if (N0.getValueType().isInteger())
1978       return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
1979     unsigned UOF = ISD::getUnorderedFlavor(Cond);
1980     if (UOF == 2)   // FP operators that are undefined on NaNs.
1981       return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
1982     if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
1983       return DAG.getConstant(UOF, VT);
1984     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
1985     // if it is not already.
1986     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
1987     if (NewCond != Cond)
1988       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
1989   }
1990
1991   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1992       N0.getValueType().isInteger()) {
1993     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
1994         N0.getOpcode() == ISD::XOR) {
1995       // Simplify (X+Y) == (X+Z) -->  Y == Z
1996       if (N0.getOpcode() == N1.getOpcode()) {
1997         if (N0.getOperand(0) == N1.getOperand(0))
1998           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
1999         if (N0.getOperand(1) == N1.getOperand(1))
2000           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
2001         if (DAG.isCommutativeBinOp(N0.getOpcode())) {
2002           // If X op Y == Y op X, try other combinations.
2003           if (N0.getOperand(0) == N1.getOperand(1))
2004             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 
2005                                 Cond);
2006           if (N0.getOperand(1) == N1.getOperand(0))
2007             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 
2008                                 Cond);
2009         }
2010       }
2011       
2012       if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
2013         if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2014           // Turn (X+C1) == C2 --> X == C2-C1
2015           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
2016             return DAG.getSetCC(dl, VT, N0.getOperand(0),
2017                                 DAG.getConstant(RHSC->getAPIntValue()-
2018                                                 LHSR->getAPIntValue(),
2019                                 N0.getValueType()), Cond);
2020           }
2021           
2022           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
2023           if (N0.getOpcode() == ISD::XOR)
2024             // If we know that all of the inverted bits are zero, don't bother
2025             // performing the inversion.
2026             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
2027               return
2028                 DAG.getSetCC(dl, VT, N0.getOperand(0),
2029                              DAG.getConstant(LHSR->getAPIntValue() ^
2030                                                RHSC->getAPIntValue(),
2031                                              N0.getValueType()),
2032                              Cond);
2033         }
2034         
2035         // Turn (C1-X) == C2 --> X == C1-C2
2036         if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
2037           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
2038             return
2039               DAG.getSetCC(dl, VT, N0.getOperand(1),
2040                            DAG.getConstant(SUBC->getAPIntValue() -
2041                                              RHSC->getAPIntValue(),
2042                                            N0.getValueType()),
2043                            Cond);
2044           }
2045         }          
2046       }
2047
2048       // Simplify (X+Z) == X -->  Z == 0
2049       if (N0.getOperand(0) == N1)
2050         return DAG.getSetCC(dl, VT, N0.getOperand(1),
2051                         DAG.getConstant(0, N0.getValueType()), Cond);
2052       if (N0.getOperand(1) == N1) {
2053         if (DAG.isCommutativeBinOp(N0.getOpcode()))
2054           return DAG.getSetCC(dl, VT, N0.getOperand(0),
2055                           DAG.getConstant(0, N0.getValueType()), Cond);
2056         else if (N0.getNode()->hasOneUse()) {
2057           assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
2058           // (Z-X) == X  --> Z == X<<1
2059           SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(),
2060                                      N1, 
2061                                      DAG.getConstant(1, getShiftAmountTy()));
2062           if (!DCI.isCalledByLegalizer())
2063             DCI.AddToWorklist(SH.getNode());
2064           return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
2065         }
2066       }
2067     }
2068
2069     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
2070         N1.getOpcode() == ISD::XOR) {
2071       // Simplify  X == (X+Z) -->  Z == 0
2072       if (N1.getOperand(0) == N0) {
2073         return DAG.getSetCC(dl, VT, N1.getOperand(1),
2074                         DAG.getConstant(0, N1.getValueType()), Cond);
2075       } else if (N1.getOperand(1) == N0) {
2076         if (DAG.isCommutativeBinOp(N1.getOpcode())) {
2077           return DAG.getSetCC(dl, VT, N1.getOperand(0),
2078                           DAG.getConstant(0, N1.getValueType()), Cond);
2079         } else if (N1.getNode()->hasOneUse()) {
2080           assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
2081           // X == (Z-X)  --> X<<1 == Z
2082           SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N0, 
2083                                      DAG.getConstant(1, getShiftAmountTy()));
2084           if (!DCI.isCalledByLegalizer())
2085             DCI.AddToWorklist(SH.getNode());
2086           return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
2087         }
2088       }
2089     }
2090
2091     // Simplify x&y == y to x&y != 0 if y has exactly one bit set.
2092     // Note that where y is variable and is known to have at most
2093     // one bit set (for example, if it is z&1) we cannot do this;
2094     // the expressions are not equivalent when y==0.
2095     if (N0.getOpcode() == ISD::AND)
2096       if (N0.getOperand(0) == N1 || N0.getOperand(1) == N1) {
2097         if (ValueHasExactlyOneBitSet(N1, DAG)) {
2098           Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
2099           SDValue Zero = DAG.getConstant(0, N1.getValueType());
2100           return DAG.getSetCC(dl, VT, N0, Zero, Cond);
2101         }
2102       }
2103     if (N1.getOpcode() == ISD::AND)
2104       if (N1.getOperand(0) == N0 || N1.getOperand(1) == N0) {
2105         if (ValueHasExactlyOneBitSet(N0, DAG)) {
2106           Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
2107           SDValue Zero = DAG.getConstant(0, N0.getValueType());
2108           return DAG.getSetCC(dl, VT, N1, Zero, Cond);
2109         }
2110       }
2111   }
2112
2113   // Fold away ALL boolean setcc's.
2114   SDValue Temp;
2115   if (N0.getValueType() == MVT::i1 && foldBooleans) {
2116     switch (Cond) {
2117     default: llvm_unreachable("Unknown integer setcc!");
2118     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
2119       Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2120       N0 = DAG.getNOT(dl, Temp, MVT::i1);
2121       if (!DCI.isCalledByLegalizer())
2122         DCI.AddToWorklist(Temp.getNode());
2123       break;
2124     case ISD::SETNE:  // X != Y   -->  (X^Y)
2125       N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2126       break;
2127     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
2128     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
2129       Temp = DAG.getNOT(dl, N0, MVT::i1);
2130       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
2131       if (!DCI.isCalledByLegalizer())
2132         DCI.AddToWorklist(Temp.getNode());
2133       break;
2134     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
2135     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
2136       Temp = DAG.getNOT(dl, N1, MVT::i1);
2137       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
2138       if (!DCI.isCalledByLegalizer())
2139         DCI.AddToWorklist(Temp.getNode());
2140       break;
2141     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
2142     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
2143       Temp = DAG.getNOT(dl, N0, MVT::i1);
2144       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
2145       if (!DCI.isCalledByLegalizer())
2146         DCI.AddToWorklist(Temp.getNode());
2147       break;
2148     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
2149     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
2150       Temp = DAG.getNOT(dl, N1, MVT::i1);
2151       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
2152       break;
2153     }
2154     if (VT != MVT::i1) {
2155       if (!DCI.isCalledByLegalizer())
2156         DCI.AddToWorklist(N0.getNode());
2157       // FIXME: If running after legalize, we probably can't do this.
2158       N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
2159     }
2160     return N0;
2161   }
2162
2163   // Could not fold it.
2164   return SDValue();
2165 }
2166
2167 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
2168 /// node is a GlobalAddress + offset.
2169 bool TargetLowering::isGAPlusOffset(SDNode *N, GlobalValue* &GA,
2170                                     int64_t &Offset) const {
2171   if (isa<GlobalAddressSDNode>(N)) {
2172     GlobalAddressSDNode *GASD = cast<GlobalAddressSDNode>(N);
2173     GA = GASD->getGlobal();
2174     Offset += GASD->getOffset();
2175     return true;
2176   }
2177
2178   if (N->getOpcode() == ISD::ADD) {
2179     SDValue N1 = N->getOperand(0);
2180     SDValue N2 = N->getOperand(1);
2181     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
2182       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
2183       if (V) {
2184         Offset += V->getSExtValue();
2185         return true;
2186       }
2187     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
2188       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
2189       if (V) {
2190         Offset += V->getSExtValue();
2191         return true;
2192       }
2193     }
2194   }
2195   return false;
2196 }
2197
2198
2199 SDValue TargetLowering::
2200 PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
2201   // Default implementation: no optimization.
2202   return SDValue();
2203 }
2204
2205 //===----------------------------------------------------------------------===//
2206 //  Inline Assembler Implementation Methods
2207 //===----------------------------------------------------------------------===//
2208
2209
2210 TargetLowering::ConstraintType
2211 TargetLowering::getConstraintType(const std::string &Constraint) const {
2212   // FIXME: lots more standard ones to handle.
2213   if (Constraint.size() == 1) {
2214     switch (Constraint[0]) {
2215     default: break;
2216     case 'r': return C_RegisterClass;
2217     case 'm':    // memory
2218     case 'o':    // offsetable
2219     case 'V':    // not offsetable
2220       return C_Memory;
2221     case 'i':    // Simple Integer or Relocatable Constant
2222     case 'n':    // Simple Integer
2223     case 's':    // Relocatable Constant
2224     case 'X':    // Allow ANY value.
2225     case 'I':    // Target registers.
2226     case 'J':
2227     case 'K':
2228     case 'L':
2229     case 'M':
2230     case 'N':
2231     case 'O':
2232     case 'P':
2233       return C_Other;
2234     }
2235   }
2236   
2237   if (Constraint.size() > 1 && Constraint[0] == '{' && 
2238       Constraint[Constraint.size()-1] == '}')
2239     return C_Register;
2240   return C_Unknown;
2241 }
2242
2243 /// LowerXConstraint - try to replace an X constraint, which matches anything,
2244 /// with another that has more specific requirements based on the type of the
2245 /// corresponding operand.
2246 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
2247   if (ConstraintVT.isInteger())
2248     return "r";
2249   if (ConstraintVT.isFloatingPoint())
2250     return "f";      // works for many targets
2251   return 0;
2252 }
2253
2254 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2255 /// vector.  If it is invalid, don't add anything to Ops.
2256 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2257                                                   char ConstraintLetter,
2258                                                   bool hasMemory,
2259                                                   std::vector<SDValue> &Ops,
2260                                                   SelectionDAG &DAG) const {
2261   switch (ConstraintLetter) {
2262   default: break;
2263   case 'X':     // Allows any operand; labels (basic block) use this.
2264     if (Op.getOpcode() == ISD::BasicBlock) {
2265       Ops.push_back(Op);
2266       return;
2267     }
2268     // fall through
2269   case 'i':    // Simple Integer or Relocatable Constant
2270   case 'n':    // Simple Integer
2271   case 's': {  // Relocatable Constant
2272     // These operands are interested in values of the form (GV+C), where C may
2273     // be folded in as an offset of GV, or it may be explicitly added.  Also, it
2274     // is possible and fine if either GV or C are missing.
2275     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2276     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2277     
2278     // If we have "(add GV, C)", pull out GV/C
2279     if (Op.getOpcode() == ISD::ADD) {
2280       C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2281       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
2282       if (C == 0 || GA == 0) {
2283         C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2284         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2285       }
2286       if (C == 0 || GA == 0)
2287         C = 0, GA = 0;
2288     }
2289     
2290     // If we find a valid operand, map to the TargetXXX version so that the
2291     // value itself doesn't get selected.
2292     if (GA) {   // Either &GV   or   &GV+C
2293       if (ConstraintLetter != 'n') {
2294         int64_t Offs = GA->getOffset();
2295         if (C) Offs += C->getZExtValue();
2296         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
2297                                                  Op.getValueType(), Offs));
2298         return;
2299       }
2300     }
2301     if (C) {   // just C, no GV.
2302       // Simple constants are not allowed for 's'.
2303       if (ConstraintLetter != 's') {
2304         // gcc prints these as sign extended.  Sign extend value to 64 bits
2305         // now; without this it would get ZExt'd later in
2306         // ScheduleDAGSDNodes::EmitNode, which is very generic.
2307         Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
2308                                             MVT::i64));
2309         return;
2310       }
2311     }
2312     break;
2313   }
2314   }
2315 }
2316
2317 std::vector<unsigned> TargetLowering::
2318 getRegClassForInlineAsmConstraint(const std::string &Constraint,
2319                                   EVT VT) const {
2320   return std::vector<unsigned>();
2321 }
2322
2323
2324 std::pair<unsigned, const TargetRegisterClass*> TargetLowering::
2325 getRegForInlineAsmConstraint(const std::string &Constraint,
2326                              EVT VT) const {
2327   if (Constraint[0] != '{')
2328     return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
2329   assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2330
2331   // Remove the braces from around the name.
2332   StringRef RegName(Constraint.data()+1, Constraint.size()-2);
2333
2334   // Figure out which register class contains this reg.
2335   const TargetRegisterInfo *RI = TM.getRegisterInfo();
2336   for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
2337        E = RI->regclass_end(); RCI != E; ++RCI) {
2338     const TargetRegisterClass *RC = *RCI;
2339     
2340     // If none of the the value types for this register class are valid, we 
2341     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
2342     bool isLegal = false;
2343     for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2344          I != E; ++I) {
2345       if (isTypeLegal(*I)) {
2346         isLegal = true;
2347         break;
2348       }
2349     }
2350     
2351     if (!isLegal) continue;
2352     
2353     for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); 
2354          I != E; ++I) {
2355       if (RegName.equals_lower(RI->getName(*I)))
2356         return std::make_pair(*I, RC);
2357     }
2358   }
2359   
2360   return std::pair<unsigned, const TargetRegisterClass*>(0, 0);
2361 }
2362
2363 //===----------------------------------------------------------------------===//
2364 // Constraint Selection.
2365
2366 /// isMatchingInputConstraint - Return true of this is an input operand that is
2367 /// a matching constraint like "4".
2368 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
2369   assert(!ConstraintCode.empty() && "No known constraint!");
2370   return isdigit(ConstraintCode[0]);
2371 }
2372
2373 /// getMatchedOperand - If this is an input matching constraint, this method
2374 /// returns the output operand it matches.
2375 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2376   assert(!ConstraintCode.empty() && "No known constraint!");
2377   return atoi(ConstraintCode.c_str());
2378 }
2379
2380
2381 /// getConstraintGenerality - Return an integer indicating how general CT
2382 /// is.
2383 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2384   switch (CT) {
2385   default: llvm_unreachable("Unknown constraint type!");
2386   case TargetLowering::C_Other:
2387   case TargetLowering::C_Unknown:
2388     return 0;
2389   case TargetLowering::C_Register:
2390     return 1;
2391   case TargetLowering::C_RegisterClass:
2392     return 2;
2393   case TargetLowering::C_Memory:
2394     return 3;
2395   }
2396 }
2397
2398 /// ChooseConstraint - If there are multiple different constraints that we
2399 /// could pick for this operand (e.g. "imr") try to pick the 'best' one.
2400 /// This is somewhat tricky: constraints fall into four classes:
2401 ///    Other         -> immediates and magic values
2402 ///    Register      -> one specific register
2403 ///    RegisterClass -> a group of regs
2404 ///    Memory        -> memory
2405 /// Ideally, we would pick the most specific constraint possible: if we have
2406 /// something that fits into a register, we would pick it.  The problem here
2407 /// is that if we have something that could either be in a register or in
2408 /// memory that use of the register could cause selection of *other*
2409 /// operands to fail: they might only succeed if we pick memory.  Because of
2410 /// this the heuristic we use is:
2411 ///
2412 ///  1) If there is an 'other' constraint, and if the operand is valid for
2413 ///     that constraint, use it.  This makes us take advantage of 'i'
2414 ///     constraints when available.
2415 ///  2) Otherwise, pick the most general constraint present.  This prefers
2416 ///     'm' over 'r', for example.
2417 ///
2418 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
2419                              bool hasMemory,  const TargetLowering &TLI,
2420                              SDValue Op, SelectionDAG *DAG) {
2421   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
2422   unsigned BestIdx = 0;
2423   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
2424   int BestGenerality = -1;
2425   
2426   // Loop over the options, keeping track of the most general one.
2427   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
2428     TargetLowering::ConstraintType CType =
2429       TLI.getConstraintType(OpInfo.Codes[i]);
2430     
2431     // If this is an 'other' constraint, see if the operand is valid for it.
2432     // For example, on X86 we might have an 'rI' constraint.  If the operand
2433     // is an integer in the range [0..31] we want to use I (saving a load
2434     // of a register), otherwise we must use 'r'.
2435     if (CType == TargetLowering::C_Other && Op.getNode()) {
2436       assert(OpInfo.Codes[i].size() == 1 &&
2437              "Unhandled multi-letter 'other' constraint");
2438       std::vector<SDValue> ResultOps;
2439       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i][0], hasMemory,
2440                                        ResultOps, *DAG);
2441       if (!ResultOps.empty()) {
2442         BestType = CType;
2443         BestIdx = i;
2444         break;
2445       }
2446     }
2447     
2448     // This constraint letter is more general than the previous one, use it.
2449     int Generality = getConstraintGenerality(CType);
2450     if (Generality > BestGenerality) {
2451       BestType = CType;
2452       BestIdx = i;
2453       BestGenerality = Generality;
2454     }
2455   }
2456   
2457   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
2458   OpInfo.ConstraintType = BestType;
2459 }
2460
2461 /// ComputeConstraintToUse - Determines the constraint code and constraint
2462 /// type to use for the specific AsmOperandInfo, setting
2463 /// OpInfo.ConstraintCode and OpInfo.ConstraintType.
2464 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2465                                             SDValue Op, 
2466                                             bool hasMemory,
2467                                             SelectionDAG *DAG) const {
2468   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
2469   
2470   // Single-letter constraints ('r') are very common.
2471   if (OpInfo.Codes.size() == 1) {
2472     OpInfo.ConstraintCode = OpInfo.Codes[0];
2473     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2474   } else {
2475     ChooseConstraint(OpInfo, hasMemory, *this, Op, DAG);
2476   }
2477   
2478   // 'X' matches anything.
2479   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
2480     // Labels and constants are handled elsewhere ('X' is the only thing
2481     // that matches labels).  For Functions, the type here is the type of
2482     // the result, which is not what we want to look at; leave them alone.
2483     Value *v = OpInfo.CallOperandVal;
2484     if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
2485       OpInfo.CallOperandVal = v;
2486       return;
2487     }
2488     
2489     // Otherwise, try to resolve it to something we know about by looking at
2490     // the actual operand type.
2491     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
2492       OpInfo.ConstraintCode = Repl;
2493       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2494     }
2495   }
2496 }
2497
2498 //===----------------------------------------------------------------------===//
2499 //  Loop Strength Reduction hooks
2500 //===----------------------------------------------------------------------===//
2501
2502 /// isLegalAddressingMode - Return true if the addressing mode represented
2503 /// by AM is legal for this target, for a load/store of the specified type.
2504 bool TargetLowering::isLegalAddressingMode(const AddrMode &AM, 
2505                                            const Type *Ty) const {
2506   // The default implementation of this implements a conservative RISCy, r+r and
2507   // r+i addr mode.
2508
2509   // Allows a sign-extended 16-bit immediate field.
2510   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
2511     return false;
2512   
2513   // No global is ever allowed as a base.
2514   if (AM.BaseGV)
2515     return false;
2516   
2517   // Only support r+r, 
2518   switch (AM.Scale) {
2519   case 0:  // "r+i" or just "i", depending on HasBaseReg.
2520     break;
2521   case 1:
2522     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
2523       return false;
2524     // Otherwise we have r+r or r+i.
2525     break;
2526   case 2:
2527     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
2528       return false;
2529     // Allow 2*r as r+r.
2530     break;
2531   }
2532   
2533   return true;
2534 }
2535
2536 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
2537 /// return a DAG expression to select that will generate the same value by
2538 /// multiplying by a magic number.  See:
2539 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
2540 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 
2541                                   std::vector<SDNode*>* Created) const {
2542   EVT VT = N->getValueType(0);
2543   DebugLoc dl= N->getDebugLoc();
2544   
2545   // Check to see if we can do this.
2546   // FIXME: We should be more aggressive here.
2547   if (!isTypeLegal(VT))
2548     return SDValue();
2549   
2550   APInt d = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
2551   APInt::ms magics = d.magic();
2552   
2553   // Multiply the numerator (operand 0) by the magic value
2554   // FIXME: We should support doing a MUL in a wider type
2555   SDValue Q;
2556   if (isOperationLegalOrCustom(ISD::MULHS, VT))
2557     Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
2558                     DAG.getConstant(magics.m, VT));
2559   else if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
2560     Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
2561                               N->getOperand(0),
2562                               DAG.getConstant(magics.m, VT)).getNode(), 1);
2563   else
2564     return SDValue();       // No mulhs or equvialent
2565   // If d > 0 and m < 0, add the numerator
2566   if (d.isStrictlyPositive() && magics.m.isNegative()) { 
2567     Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
2568     if (Created)
2569       Created->push_back(Q.getNode());
2570   }
2571   // If d < 0 and m > 0, subtract the numerator.
2572   if (d.isNegative() && magics.m.isStrictlyPositive()) {
2573     Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
2574     if (Created)
2575       Created->push_back(Q.getNode());
2576   }
2577   // Shift right algebraic if shift value is nonzero
2578   if (magics.s > 0) {
2579     Q = DAG.getNode(ISD::SRA, dl, VT, Q, 
2580                     DAG.getConstant(magics.s, getShiftAmountTy()));
2581     if (Created)
2582       Created->push_back(Q.getNode());
2583   }
2584   // Extract the sign bit and add it to the quotient
2585   SDValue T =
2586     DAG.getNode(ISD::SRL, dl, VT, Q, DAG.getConstant(VT.getSizeInBits()-1,
2587                                                  getShiftAmountTy()));
2588   if (Created)
2589     Created->push_back(T.getNode());
2590   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
2591 }
2592
2593 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
2594 /// return a DAG expression to select that will generate the same value by
2595 /// multiplying by a magic number.  See:
2596 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
2597 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
2598                                   std::vector<SDNode*>* Created) const {
2599   EVT VT = N->getValueType(0);
2600   DebugLoc dl = N->getDebugLoc();
2601
2602   // Check to see if we can do this.
2603   // FIXME: We should be more aggressive here.
2604   if (!isTypeLegal(VT))
2605     return SDValue();
2606
2607   // FIXME: We should use a narrower constant when the upper
2608   // bits are known to be zero.
2609   ConstantSDNode *N1C = cast<ConstantSDNode>(N->getOperand(1));
2610   APInt::mu magics = N1C->getAPIntValue().magicu();
2611
2612   // Multiply the numerator (operand 0) by the magic value
2613   // FIXME: We should support doing a MUL in a wider type
2614   SDValue Q;
2615   if (isOperationLegalOrCustom(ISD::MULHU, VT))
2616     Q = DAG.getNode(ISD::MULHU, dl, VT, N->getOperand(0),
2617                     DAG.getConstant(magics.m, VT));
2618   else if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
2619     Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT),
2620                               N->getOperand(0),
2621                               DAG.getConstant(magics.m, VT)).getNode(), 1);
2622   else
2623     return SDValue();       // No mulhu or equvialent
2624   if (Created)
2625     Created->push_back(Q.getNode());
2626
2627   if (magics.a == 0) {
2628     assert(magics.s < N1C->getAPIntValue().getBitWidth() &&
2629            "We shouldn't generate an undefined shift!");
2630     return DAG.getNode(ISD::SRL, dl, VT, Q, 
2631                        DAG.getConstant(magics.s, getShiftAmountTy()));
2632   } else {
2633     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
2634     if (Created)
2635       Created->push_back(NPQ.getNode());
2636     NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, 
2637                       DAG.getConstant(1, getShiftAmountTy()));
2638     if (Created)
2639       Created->push_back(NPQ.getNode());
2640     NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
2641     if (Created)
2642       Created->push_back(NPQ.getNode());
2643     return DAG.getNode(ISD::SRL, dl, VT, NPQ, 
2644                        DAG.getConstant(magics.s-1, getShiftAmountTy()));
2645   }
2646 }