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