New approach to r136737: insert the necessary fences for atomic ops in platform-indep...
[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/GlobalVariable.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/CodeGen/Analysis.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/CommandLine.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/MathExtras.h"
32 #include <cctype>
33 using namespace llvm;
34
35 /// We are in the process of implementing a new TypeLegalization action
36 /// - the promotion of vector elements. This feature is disabled by default
37 /// and only enabled using this flag.
38 static cl::opt<bool>
39 AllowPromoteIntElem("promote-elements", cl::Hidden,
40   cl::desc("Allow promotion of integer vector element types"));
41
42 namespace llvm {
43 TLSModel::Model getTLSModel(const GlobalValue *GV, Reloc::Model reloc) {
44   bool isLocal = GV->hasLocalLinkage();
45   bool isDeclaration = GV->isDeclaration();
46   // FIXME: what should we do for protected and internal visibility?
47   // For variables, is internal different from hidden?
48   bool isHidden = GV->hasHiddenVisibility();
49
50   if (reloc == Reloc::PIC_) {
51     if (isLocal || isHidden)
52       return TLSModel::LocalDynamic;
53     else
54       return TLSModel::GeneralDynamic;
55   } else {
56     if (!isDeclaration || isHidden)
57       return TLSModel::LocalExec;
58     else
59       return TLSModel::InitialExec;
60   }
61 }
62 }
63
64 /// InitLibcallNames - Set default libcall names.
65 ///
66 static void InitLibcallNames(const char **Names) {
67   Names[RTLIB::SHL_I16] = "__ashlhi3";
68   Names[RTLIB::SHL_I32] = "__ashlsi3";
69   Names[RTLIB::SHL_I64] = "__ashldi3";
70   Names[RTLIB::SHL_I128] = "__ashlti3";
71   Names[RTLIB::SRL_I16] = "__lshrhi3";
72   Names[RTLIB::SRL_I32] = "__lshrsi3";
73   Names[RTLIB::SRL_I64] = "__lshrdi3";
74   Names[RTLIB::SRL_I128] = "__lshrti3";
75   Names[RTLIB::SRA_I16] = "__ashrhi3";
76   Names[RTLIB::SRA_I32] = "__ashrsi3";
77   Names[RTLIB::SRA_I64] = "__ashrdi3";
78   Names[RTLIB::SRA_I128] = "__ashrti3";
79   Names[RTLIB::MUL_I8] = "__mulqi3";
80   Names[RTLIB::MUL_I16] = "__mulhi3";
81   Names[RTLIB::MUL_I32] = "__mulsi3";
82   Names[RTLIB::MUL_I64] = "__muldi3";
83   Names[RTLIB::MUL_I128] = "__multi3";
84   Names[RTLIB::MULO_I32] = "__mulosi4";
85   Names[RTLIB::MULO_I64] = "__mulodi4";
86   Names[RTLIB::MULO_I128] = "__muloti4";
87   Names[RTLIB::SDIV_I8] = "__divqi3";
88   Names[RTLIB::SDIV_I16] = "__divhi3";
89   Names[RTLIB::SDIV_I32] = "__divsi3";
90   Names[RTLIB::SDIV_I64] = "__divdi3";
91   Names[RTLIB::SDIV_I128] = "__divti3";
92   Names[RTLIB::UDIV_I8] = "__udivqi3";
93   Names[RTLIB::UDIV_I16] = "__udivhi3";
94   Names[RTLIB::UDIV_I32] = "__udivsi3";
95   Names[RTLIB::UDIV_I64] = "__udivdi3";
96   Names[RTLIB::UDIV_I128] = "__udivti3";
97   Names[RTLIB::SREM_I8] = "__modqi3";
98   Names[RTLIB::SREM_I16] = "__modhi3";
99   Names[RTLIB::SREM_I32] = "__modsi3";
100   Names[RTLIB::SREM_I64] = "__moddi3";
101   Names[RTLIB::SREM_I128] = "__modti3";
102   Names[RTLIB::UREM_I8] = "__umodqi3";
103   Names[RTLIB::UREM_I16] = "__umodhi3";
104   Names[RTLIB::UREM_I32] = "__umodsi3";
105   Names[RTLIB::UREM_I64] = "__umoddi3";
106   Names[RTLIB::UREM_I128] = "__umodti3";
107
108   // These are generally not available.
109   Names[RTLIB::SDIVREM_I8] = 0;
110   Names[RTLIB::SDIVREM_I16] = 0;
111   Names[RTLIB::SDIVREM_I32] = 0;
112   Names[RTLIB::SDIVREM_I64] = 0;
113   Names[RTLIB::SDIVREM_I128] = 0;
114   Names[RTLIB::UDIVREM_I8] = 0;
115   Names[RTLIB::UDIVREM_I16] = 0;
116   Names[RTLIB::UDIVREM_I32] = 0;
117   Names[RTLIB::UDIVREM_I64] = 0;
118   Names[RTLIB::UDIVREM_I128] = 0;
119
120   Names[RTLIB::NEG_I32] = "__negsi2";
121   Names[RTLIB::NEG_I64] = "__negdi2";
122   Names[RTLIB::ADD_F32] = "__addsf3";
123   Names[RTLIB::ADD_F64] = "__adddf3";
124   Names[RTLIB::ADD_F80] = "__addxf3";
125   Names[RTLIB::ADD_PPCF128] = "__gcc_qadd";
126   Names[RTLIB::SUB_F32] = "__subsf3";
127   Names[RTLIB::SUB_F64] = "__subdf3";
128   Names[RTLIB::SUB_F80] = "__subxf3";
129   Names[RTLIB::SUB_PPCF128] = "__gcc_qsub";
130   Names[RTLIB::MUL_F32] = "__mulsf3";
131   Names[RTLIB::MUL_F64] = "__muldf3";
132   Names[RTLIB::MUL_F80] = "__mulxf3";
133   Names[RTLIB::MUL_PPCF128] = "__gcc_qmul";
134   Names[RTLIB::DIV_F32] = "__divsf3";
135   Names[RTLIB::DIV_F64] = "__divdf3";
136   Names[RTLIB::DIV_F80] = "__divxf3";
137   Names[RTLIB::DIV_PPCF128] = "__gcc_qdiv";
138   Names[RTLIB::REM_F32] = "fmodf";
139   Names[RTLIB::REM_F64] = "fmod";
140   Names[RTLIB::REM_F80] = "fmodl";
141   Names[RTLIB::REM_PPCF128] = "fmodl";
142   Names[RTLIB::FMA_F32] = "fmaf";
143   Names[RTLIB::FMA_F64] = "fma";
144   Names[RTLIB::FMA_F80] = "fmal";
145   Names[RTLIB::FMA_PPCF128] = "fmal";
146   Names[RTLIB::POWI_F32] = "__powisf2";
147   Names[RTLIB::POWI_F64] = "__powidf2";
148   Names[RTLIB::POWI_F80] = "__powixf2";
149   Names[RTLIB::POWI_PPCF128] = "__powitf2";
150   Names[RTLIB::SQRT_F32] = "sqrtf";
151   Names[RTLIB::SQRT_F64] = "sqrt";
152   Names[RTLIB::SQRT_F80] = "sqrtl";
153   Names[RTLIB::SQRT_PPCF128] = "sqrtl";
154   Names[RTLIB::LOG_F32] = "logf";
155   Names[RTLIB::LOG_F64] = "log";
156   Names[RTLIB::LOG_F80] = "logl";
157   Names[RTLIB::LOG_PPCF128] = "logl";
158   Names[RTLIB::LOG2_F32] = "log2f";
159   Names[RTLIB::LOG2_F64] = "log2";
160   Names[RTLIB::LOG2_F80] = "log2l";
161   Names[RTLIB::LOG2_PPCF128] = "log2l";
162   Names[RTLIB::LOG10_F32] = "log10f";
163   Names[RTLIB::LOG10_F64] = "log10";
164   Names[RTLIB::LOG10_F80] = "log10l";
165   Names[RTLIB::LOG10_PPCF128] = "log10l";
166   Names[RTLIB::EXP_F32] = "expf";
167   Names[RTLIB::EXP_F64] = "exp";
168   Names[RTLIB::EXP_F80] = "expl";
169   Names[RTLIB::EXP_PPCF128] = "expl";
170   Names[RTLIB::EXP2_F32] = "exp2f";
171   Names[RTLIB::EXP2_F64] = "exp2";
172   Names[RTLIB::EXP2_F80] = "exp2l";
173   Names[RTLIB::EXP2_PPCF128] = "exp2l";
174   Names[RTLIB::SIN_F32] = "sinf";
175   Names[RTLIB::SIN_F64] = "sin";
176   Names[RTLIB::SIN_F80] = "sinl";
177   Names[RTLIB::SIN_PPCF128] = "sinl";
178   Names[RTLIB::COS_F32] = "cosf";
179   Names[RTLIB::COS_F64] = "cos";
180   Names[RTLIB::COS_F80] = "cosl";
181   Names[RTLIB::COS_PPCF128] = "cosl";
182   Names[RTLIB::POW_F32] = "powf";
183   Names[RTLIB::POW_F64] = "pow";
184   Names[RTLIB::POW_F80] = "powl";
185   Names[RTLIB::POW_PPCF128] = "powl";
186   Names[RTLIB::CEIL_F32] = "ceilf";
187   Names[RTLIB::CEIL_F64] = "ceil";
188   Names[RTLIB::CEIL_F80] = "ceill";
189   Names[RTLIB::CEIL_PPCF128] = "ceill";
190   Names[RTLIB::TRUNC_F32] = "truncf";
191   Names[RTLIB::TRUNC_F64] = "trunc";
192   Names[RTLIB::TRUNC_F80] = "truncl";
193   Names[RTLIB::TRUNC_PPCF128] = "truncl";
194   Names[RTLIB::RINT_F32] = "rintf";
195   Names[RTLIB::RINT_F64] = "rint";
196   Names[RTLIB::RINT_F80] = "rintl";
197   Names[RTLIB::RINT_PPCF128] = "rintl";
198   Names[RTLIB::NEARBYINT_F32] = "nearbyintf";
199   Names[RTLIB::NEARBYINT_F64] = "nearbyint";
200   Names[RTLIB::NEARBYINT_F80] = "nearbyintl";
201   Names[RTLIB::NEARBYINT_PPCF128] = "nearbyintl";
202   Names[RTLIB::FLOOR_F32] = "floorf";
203   Names[RTLIB::FLOOR_F64] = "floor";
204   Names[RTLIB::FLOOR_F80] = "floorl";
205   Names[RTLIB::FLOOR_PPCF128] = "floorl";
206   Names[RTLIB::COPYSIGN_F32] = "copysignf";
207   Names[RTLIB::COPYSIGN_F64] = "copysign";
208   Names[RTLIB::COPYSIGN_F80] = "copysignl";
209   Names[RTLIB::COPYSIGN_PPCF128] = "copysignl";
210   Names[RTLIB::FPEXT_F32_F64] = "__extendsfdf2";
211   Names[RTLIB::FPEXT_F16_F32] = "__gnu_h2f_ieee";
212   Names[RTLIB::FPROUND_F32_F16] = "__gnu_f2h_ieee";
213   Names[RTLIB::FPROUND_F64_F32] = "__truncdfsf2";
214   Names[RTLIB::FPROUND_F80_F32] = "__truncxfsf2";
215   Names[RTLIB::FPROUND_PPCF128_F32] = "__trunctfsf2";
216   Names[RTLIB::FPROUND_F80_F64] = "__truncxfdf2";
217   Names[RTLIB::FPROUND_PPCF128_F64] = "__trunctfdf2";
218   Names[RTLIB::FPTOSINT_F32_I8] = "__fixsfqi";
219   Names[RTLIB::FPTOSINT_F32_I16] = "__fixsfhi";
220   Names[RTLIB::FPTOSINT_F32_I32] = "__fixsfsi";
221   Names[RTLIB::FPTOSINT_F32_I64] = "__fixsfdi";
222   Names[RTLIB::FPTOSINT_F32_I128] = "__fixsfti";
223   Names[RTLIB::FPTOSINT_F64_I8] = "__fixdfqi";
224   Names[RTLIB::FPTOSINT_F64_I16] = "__fixdfhi";
225   Names[RTLIB::FPTOSINT_F64_I32] = "__fixdfsi";
226   Names[RTLIB::FPTOSINT_F64_I64] = "__fixdfdi";
227   Names[RTLIB::FPTOSINT_F64_I128] = "__fixdfti";
228   Names[RTLIB::FPTOSINT_F80_I32] = "__fixxfsi";
229   Names[RTLIB::FPTOSINT_F80_I64] = "__fixxfdi";
230   Names[RTLIB::FPTOSINT_F80_I128] = "__fixxfti";
231   Names[RTLIB::FPTOSINT_PPCF128_I32] = "__fixtfsi";
232   Names[RTLIB::FPTOSINT_PPCF128_I64] = "__fixtfdi";
233   Names[RTLIB::FPTOSINT_PPCF128_I128] = "__fixtfti";
234   Names[RTLIB::FPTOUINT_F32_I8] = "__fixunssfqi";
235   Names[RTLIB::FPTOUINT_F32_I16] = "__fixunssfhi";
236   Names[RTLIB::FPTOUINT_F32_I32] = "__fixunssfsi";
237   Names[RTLIB::FPTOUINT_F32_I64] = "__fixunssfdi";
238   Names[RTLIB::FPTOUINT_F32_I128] = "__fixunssfti";
239   Names[RTLIB::FPTOUINT_F64_I8] = "__fixunsdfqi";
240   Names[RTLIB::FPTOUINT_F64_I16] = "__fixunsdfhi";
241   Names[RTLIB::FPTOUINT_F64_I32] = "__fixunsdfsi";
242   Names[RTLIB::FPTOUINT_F64_I64] = "__fixunsdfdi";
243   Names[RTLIB::FPTOUINT_F64_I128] = "__fixunsdfti";
244   Names[RTLIB::FPTOUINT_F80_I32] = "__fixunsxfsi";
245   Names[RTLIB::FPTOUINT_F80_I64] = "__fixunsxfdi";
246   Names[RTLIB::FPTOUINT_F80_I128] = "__fixunsxfti";
247   Names[RTLIB::FPTOUINT_PPCF128_I32] = "__fixunstfsi";
248   Names[RTLIB::FPTOUINT_PPCF128_I64] = "__fixunstfdi";
249   Names[RTLIB::FPTOUINT_PPCF128_I128] = "__fixunstfti";
250   Names[RTLIB::SINTTOFP_I32_F32] = "__floatsisf";
251   Names[RTLIB::SINTTOFP_I32_F64] = "__floatsidf";
252   Names[RTLIB::SINTTOFP_I32_F80] = "__floatsixf";
253   Names[RTLIB::SINTTOFP_I32_PPCF128] = "__floatsitf";
254   Names[RTLIB::SINTTOFP_I64_F32] = "__floatdisf";
255   Names[RTLIB::SINTTOFP_I64_F64] = "__floatdidf";
256   Names[RTLIB::SINTTOFP_I64_F80] = "__floatdixf";
257   Names[RTLIB::SINTTOFP_I64_PPCF128] = "__floatditf";
258   Names[RTLIB::SINTTOFP_I128_F32] = "__floattisf";
259   Names[RTLIB::SINTTOFP_I128_F64] = "__floattidf";
260   Names[RTLIB::SINTTOFP_I128_F80] = "__floattixf";
261   Names[RTLIB::SINTTOFP_I128_PPCF128] = "__floattitf";
262   Names[RTLIB::UINTTOFP_I32_F32] = "__floatunsisf";
263   Names[RTLIB::UINTTOFP_I32_F64] = "__floatunsidf";
264   Names[RTLIB::UINTTOFP_I32_F80] = "__floatunsixf";
265   Names[RTLIB::UINTTOFP_I32_PPCF128] = "__floatunsitf";
266   Names[RTLIB::UINTTOFP_I64_F32] = "__floatundisf";
267   Names[RTLIB::UINTTOFP_I64_F64] = "__floatundidf";
268   Names[RTLIB::UINTTOFP_I64_F80] = "__floatundixf";
269   Names[RTLIB::UINTTOFP_I64_PPCF128] = "__floatunditf";
270   Names[RTLIB::UINTTOFP_I128_F32] = "__floatuntisf";
271   Names[RTLIB::UINTTOFP_I128_F64] = "__floatuntidf";
272   Names[RTLIB::UINTTOFP_I128_F80] = "__floatuntixf";
273   Names[RTLIB::UINTTOFP_I128_PPCF128] = "__floatuntitf";
274   Names[RTLIB::OEQ_F32] = "__eqsf2";
275   Names[RTLIB::OEQ_F64] = "__eqdf2";
276   Names[RTLIB::UNE_F32] = "__nesf2";
277   Names[RTLIB::UNE_F64] = "__nedf2";
278   Names[RTLIB::OGE_F32] = "__gesf2";
279   Names[RTLIB::OGE_F64] = "__gedf2";
280   Names[RTLIB::OLT_F32] = "__ltsf2";
281   Names[RTLIB::OLT_F64] = "__ltdf2";
282   Names[RTLIB::OLE_F32] = "__lesf2";
283   Names[RTLIB::OLE_F64] = "__ledf2";
284   Names[RTLIB::OGT_F32] = "__gtsf2";
285   Names[RTLIB::OGT_F64] = "__gtdf2";
286   Names[RTLIB::UO_F32] = "__unordsf2";
287   Names[RTLIB::UO_F64] = "__unorddf2";
288   Names[RTLIB::O_F32] = "__unordsf2";
289   Names[RTLIB::O_F64] = "__unorddf2";
290   Names[RTLIB::MEMCPY] = "memcpy";
291   Names[RTLIB::MEMMOVE] = "memmove";
292   Names[RTLIB::MEMSET] = "memset";
293   Names[RTLIB::UNWIND_RESUME] = "_Unwind_Resume";
294   Names[RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1] = "__sync_val_compare_and_swap_1";
295   Names[RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2] = "__sync_val_compare_and_swap_2";
296   Names[RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4] = "__sync_val_compare_and_swap_4";
297   Names[RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8] = "__sync_val_compare_and_swap_8";
298   Names[RTLIB::SYNC_LOCK_TEST_AND_SET_1] = "__sync_lock_test_and_set_1";
299   Names[RTLIB::SYNC_LOCK_TEST_AND_SET_2] = "__sync_lock_test_and_set_2";
300   Names[RTLIB::SYNC_LOCK_TEST_AND_SET_4] = "__sync_lock_test_and_set_4";
301   Names[RTLIB::SYNC_LOCK_TEST_AND_SET_8] = "__sync_lock_test_and_set_8";
302   Names[RTLIB::SYNC_FETCH_AND_ADD_1] = "__sync_fetch_and_add_1";
303   Names[RTLIB::SYNC_FETCH_AND_ADD_2] = "__sync_fetch_and_add_2";
304   Names[RTLIB::SYNC_FETCH_AND_ADD_4] = "__sync_fetch_and_add_4";
305   Names[RTLIB::SYNC_FETCH_AND_ADD_8] = "__sync_fetch_and_add_8";
306   Names[RTLIB::SYNC_FETCH_AND_SUB_1] = "__sync_fetch_and_sub_1";
307   Names[RTLIB::SYNC_FETCH_AND_SUB_2] = "__sync_fetch_and_sub_2";
308   Names[RTLIB::SYNC_FETCH_AND_SUB_4] = "__sync_fetch_and_sub_4";
309   Names[RTLIB::SYNC_FETCH_AND_SUB_8] = "__sync_fetch_and_sub_8";
310   Names[RTLIB::SYNC_FETCH_AND_AND_1] = "__sync_fetch_and_and_1";
311   Names[RTLIB::SYNC_FETCH_AND_AND_2] = "__sync_fetch_and_and_2";
312   Names[RTLIB::SYNC_FETCH_AND_AND_4] = "__sync_fetch_and_and_4";
313   Names[RTLIB::SYNC_FETCH_AND_AND_8] = "__sync_fetch_and_and_8";
314   Names[RTLIB::SYNC_FETCH_AND_OR_1] = "__sync_fetch_and_or_1";
315   Names[RTLIB::SYNC_FETCH_AND_OR_2] = "__sync_fetch_and_or_2";
316   Names[RTLIB::SYNC_FETCH_AND_OR_4] = "__sync_fetch_and_or_4";
317   Names[RTLIB::SYNC_FETCH_AND_OR_8] = "__sync_fetch_and_or_8";
318   Names[RTLIB::SYNC_FETCH_AND_XOR_1] = "__sync_fetch_and_xor_1";
319   Names[RTLIB::SYNC_FETCH_AND_XOR_2] = "__sync_fetch_and_xor_2";
320   Names[RTLIB::SYNC_FETCH_AND_XOR_4] = "__sync_fetch_and-xor_4";
321   Names[RTLIB::SYNC_FETCH_AND_XOR_8] = "__sync_fetch_and_xor_8";
322   Names[RTLIB::SYNC_FETCH_AND_NAND_1] = "__sync_fetch_and_nand_1";
323   Names[RTLIB::SYNC_FETCH_AND_NAND_2] = "__sync_fetch_and_nand_2";
324   Names[RTLIB::SYNC_FETCH_AND_NAND_4] = "__sync_fetch_and_nand_4";
325   Names[RTLIB::SYNC_FETCH_AND_NAND_8] = "__sync_fetch_and_nand_8";
326 }
327
328 /// InitLibcallCallingConvs - Set default libcall CallingConvs.
329 ///
330 static void InitLibcallCallingConvs(CallingConv::ID *CCs) {
331   for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) {
332     CCs[i] = CallingConv::C;
333   }
334 }
335
336 /// getFPEXT - Return the FPEXT_*_* value for the given types, or
337 /// UNKNOWN_LIBCALL if there is none.
338 RTLIB::Libcall RTLIB::getFPEXT(EVT OpVT, EVT RetVT) {
339   if (OpVT == MVT::f32) {
340     if (RetVT == MVT::f64)
341       return FPEXT_F32_F64;
342   }
343
344   return UNKNOWN_LIBCALL;
345 }
346
347 /// getFPROUND - Return the FPROUND_*_* value for the given types, or
348 /// UNKNOWN_LIBCALL if there is none.
349 RTLIB::Libcall RTLIB::getFPROUND(EVT OpVT, EVT RetVT) {
350   if (RetVT == MVT::f32) {
351     if (OpVT == MVT::f64)
352       return FPROUND_F64_F32;
353     if (OpVT == MVT::f80)
354       return FPROUND_F80_F32;
355     if (OpVT == MVT::ppcf128)
356       return FPROUND_PPCF128_F32;
357   } else if (RetVT == MVT::f64) {
358     if (OpVT == MVT::f80)
359       return FPROUND_F80_F64;
360     if (OpVT == MVT::ppcf128)
361       return FPROUND_PPCF128_F64;
362   }
363
364   return UNKNOWN_LIBCALL;
365 }
366
367 /// getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or
368 /// UNKNOWN_LIBCALL if there is none.
369 RTLIB::Libcall RTLIB::getFPTOSINT(EVT OpVT, EVT RetVT) {
370   if (OpVT == MVT::f32) {
371     if (RetVT == MVT::i8)
372       return FPTOSINT_F32_I8;
373     if (RetVT == MVT::i16)
374       return FPTOSINT_F32_I16;
375     if (RetVT == MVT::i32)
376       return FPTOSINT_F32_I32;
377     if (RetVT == MVT::i64)
378       return FPTOSINT_F32_I64;
379     if (RetVT == MVT::i128)
380       return FPTOSINT_F32_I128;
381   } else if (OpVT == MVT::f64) {
382     if (RetVT == MVT::i8)
383       return FPTOSINT_F64_I8;
384     if (RetVT == MVT::i16)
385       return FPTOSINT_F64_I16;
386     if (RetVT == MVT::i32)
387       return FPTOSINT_F64_I32;
388     if (RetVT == MVT::i64)
389       return FPTOSINT_F64_I64;
390     if (RetVT == MVT::i128)
391       return FPTOSINT_F64_I128;
392   } else if (OpVT == MVT::f80) {
393     if (RetVT == MVT::i32)
394       return FPTOSINT_F80_I32;
395     if (RetVT == MVT::i64)
396       return FPTOSINT_F80_I64;
397     if (RetVT == MVT::i128)
398       return FPTOSINT_F80_I128;
399   } else if (OpVT == MVT::ppcf128) {
400     if (RetVT == MVT::i32)
401       return FPTOSINT_PPCF128_I32;
402     if (RetVT == MVT::i64)
403       return FPTOSINT_PPCF128_I64;
404     if (RetVT == MVT::i128)
405       return FPTOSINT_PPCF128_I128;
406   }
407   return UNKNOWN_LIBCALL;
408 }
409
410 /// getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or
411 /// UNKNOWN_LIBCALL if there is none.
412 RTLIB::Libcall RTLIB::getFPTOUINT(EVT OpVT, EVT RetVT) {
413   if (OpVT == MVT::f32) {
414     if (RetVT == MVT::i8)
415       return FPTOUINT_F32_I8;
416     if (RetVT == MVT::i16)
417       return FPTOUINT_F32_I16;
418     if (RetVT == MVT::i32)
419       return FPTOUINT_F32_I32;
420     if (RetVT == MVT::i64)
421       return FPTOUINT_F32_I64;
422     if (RetVT == MVT::i128)
423       return FPTOUINT_F32_I128;
424   } else if (OpVT == MVT::f64) {
425     if (RetVT == MVT::i8)
426       return FPTOUINT_F64_I8;
427     if (RetVT == MVT::i16)
428       return FPTOUINT_F64_I16;
429     if (RetVT == MVT::i32)
430       return FPTOUINT_F64_I32;
431     if (RetVT == MVT::i64)
432       return FPTOUINT_F64_I64;
433     if (RetVT == MVT::i128)
434       return FPTOUINT_F64_I128;
435   } else if (OpVT == MVT::f80) {
436     if (RetVT == MVT::i32)
437       return FPTOUINT_F80_I32;
438     if (RetVT == MVT::i64)
439       return FPTOUINT_F80_I64;
440     if (RetVT == MVT::i128)
441       return FPTOUINT_F80_I128;
442   } else if (OpVT == MVT::ppcf128) {
443     if (RetVT == MVT::i32)
444       return FPTOUINT_PPCF128_I32;
445     if (RetVT == MVT::i64)
446       return FPTOUINT_PPCF128_I64;
447     if (RetVT == MVT::i128)
448       return FPTOUINT_PPCF128_I128;
449   }
450   return UNKNOWN_LIBCALL;
451 }
452
453 /// getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or
454 /// UNKNOWN_LIBCALL if there is none.
455 RTLIB::Libcall RTLIB::getSINTTOFP(EVT OpVT, EVT RetVT) {
456   if (OpVT == MVT::i32) {
457     if (RetVT == MVT::f32)
458       return SINTTOFP_I32_F32;
459     else if (RetVT == MVT::f64)
460       return SINTTOFP_I32_F64;
461     else if (RetVT == MVT::f80)
462       return SINTTOFP_I32_F80;
463     else if (RetVT == MVT::ppcf128)
464       return SINTTOFP_I32_PPCF128;
465   } else if (OpVT == MVT::i64) {
466     if (RetVT == MVT::f32)
467       return SINTTOFP_I64_F32;
468     else if (RetVT == MVT::f64)
469       return SINTTOFP_I64_F64;
470     else if (RetVT == MVT::f80)
471       return SINTTOFP_I64_F80;
472     else if (RetVT == MVT::ppcf128)
473       return SINTTOFP_I64_PPCF128;
474   } else if (OpVT == MVT::i128) {
475     if (RetVT == MVT::f32)
476       return SINTTOFP_I128_F32;
477     else if (RetVT == MVT::f64)
478       return SINTTOFP_I128_F64;
479     else if (RetVT == MVT::f80)
480       return SINTTOFP_I128_F80;
481     else if (RetVT == MVT::ppcf128)
482       return SINTTOFP_I128_PPCF128;
483   }
484   return UNKNOWN_LIBCALL;
485 }
486
487 /// getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or
488 /// UNKNOWN_LIBCALL if there is none.
489 RTLIB::Libcall RTLIB::getUINTTOFP(EVT OpVT, EVT RetVT) {
490   if (OpVT == MVT::i32) {
491     if (RetVT == MVT::f32)
492       return UINTTOFP_I32_F32;
493     else if (RetVT == MVT::f64)
494       return UINTTOFP_I32_F64;
495     else if (RetVT == MVT::f80)
496       return UINTTOFP_I32_F80;
497     else if (RetVT == MVT::ppcf128)
498       return UINTTOFP_I32_PPCF128;
499   } else if (OpVT == MVT::i64) {
500     if (RetVT == MVT::f32)
501       return UINTTOFP_I64_F32;
502     else if (RetVT == MVT::f64)
503       return UINTTOFP_I64_F64;
504     else if (RetVT == MVT::f80)
505       return UINTTOFP_I64_F80;
506     else if (RetVT == MVT::ppcf128)
507       return UINTTOFP_I64_PPCF128;
508   } else if (OpVT == MVT::i128) {
509     if (RetVT == MVT::f32)
510       return UINTTOFP_I128_F32;
511     else if (RetVT == MVT::f64)
512       return UINTTOFP_I128_F64;
513     else if (RetVT == MVT::f80)
514       return UINTTOFP_I128_F80;
515     else if (RetVT == MVT::ppcf128)
516       return UINTTOFP_I128_PPCF128;
517   }
518   return UNKNOWN_LIBCALL;
519 }
520
521 /// InitCmpLibcallCCs - Set default comparison libcall CC.
522 ///
523 static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
524   memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL);
525   CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
526   CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
527   CCs[RTLIB::UNE_F32] = ISD::SETNE;
528   CCs[RTLIB::UNE_F64] = ISD::SETNE;
529   CCs[RTLIB::OGE_F32] = ISD::SETGE;
530   CCs[RTLIB::OGE_F64] = ISD::SETGE;
531   CCs[RTLIB::OLT_F32] = ISD::SETLT;
532   CCs[RTLIB::OLT_F64] = ISD::SETLT;
533   CCs[RTLIB::OLE_F32] = ISD::SETLE;
534   CCs[RTLIB::OLE_F64] = ISD::SETLE;
535   CCs[RTLIB::OGT_F32] = ISD::SETGT;
536   CCs[RTLIB::OGT_F64] = ISD::SETGT;
537   CCs[RTLIB::UO_F32] = ISD::SETNE;
538   CCs[RTLIB::UO_F64] = ISD::SETNE;
539   CCs[RTLIB::O_F32] = ISD::SETEQ;
540   CCs[RTLIB::O_F64] = ISD::SETEQ;
541 }
542
543 /// NOTE: The constructor takes ownership of TLOF.
544 TargetLowering::TargetLowering(const TargetMachine &tm,
545                                const TargetLoweringObjectFile *tlof)
546   : TM(tm), TD(TM.getTargetData()), TLOF(*tlof),
547   mayPromoteElements(AllowPromoteIntElem) {
548   // All operations default to being supported.
549   memset(OpActions, 0, sizeof(OpActions));
550   memset(LoadExtActions, 0, sizeof(LoadExtActions));
551   memset(TruncStoreActions, 0, sizeof(TruncStoreActions));
552   memset(IndexedModeActions, 0, sizeof(IndexedModeActions));
553   memset(CondCodeActions, 0, sizeof(CondCodeActions));
554
555   // Set default actions for various operations.
556   for (unsigned VT = 0; VT != (unsigned)MVT::LAST_VALUETYPE; ++VT) {
557     // Default all indexed load / store to expand.
558     for (unsigned IM = (unsigned)ISD::PRE_INC;
559          IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
560       setIndexedLoadAction(IM, (MVT::SimpleValueType)VT, Expand);
561       setIndexedStoreAction(IM, (MVT::SimpleValueType)VT, Expand);
562     }
563
564     // These operations default to expand.
565     setOperationAction(ISD::FGETSIGN, (MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::CONCAT_VECTORS, (MVT::SimpleValueType)VT, Expand);
567   }
568
569   // Most targets ignore the @llvm.prefetch intrinsic.
570   setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
571
572   // ConstantFP nodes default to expand.  Targets can either change this to
573   // Legal, in which case all fp constants are legal, or use isFPImmLegal()
574   // to optimize expansions for certain constants.
575   setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
576   setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
577   setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
578
579   // These library functions default to expand.
580   setOperationAction(ISD::FLOG , MVT::f64, Expand);
581   setOperationAction(ISD::FLOG2, MVT::f64, Expand);
582   setOperationAction(ISD::FLOG10,MVT::f64, Expand);
583   setOperationAction(ISD::FEXP , MVT::f64, Expand);
584   setOperationAction(ISD::FEXP2, MVT::f64, Expand);
585   setOperationAction(ISD::FLOG , MVT::f32, Expand);
586   setOperationAction(ISD::FLOG2, MVT::f32, Expand);
587   setOperationAction(ISD::FLOG10,MVT::f32, Expand);
588   setOperationAction(ISD::FEXP , MVT::f32, Expand);
589   setOperationAction(ISD::FEXP2, MVT::f32, Expand);
590
591   // Default ISD::TRAP to expand (which turns it into abort).
592   setOperationAction(ISD::TRAP, MVT::Other, Expand);
593
594   IsLittleEndian = TD->isLittleEndian();
595   PointerTy = MVT::getIntegerVT(8*TD->getPointerSize());
596   memset(RegClassForVT, 0,MVT::LAST_VALUETYPE*sizeof(TargetRegisterClass*));
597   memset(TargetDAGCombineArray, 0, array_lengthof(TargetDAGCombineArray));
598   maxStoresPerMemset = maxStoresPerMemcpy = maxStoresPerMemmove = 8;
599   maxStoresPerMemsetOptSize = maxStoresPerMemcpyOptSize
600     = maxStoresPerMemmoveOptSize = 4;
601   benefitFromCodePlacementOpt = false;
602   UseUnderscoreSetJmp = false;
603   UseUnderscoreLongJmp = false;
604   SelectIsExpensive = false;
605   IntDivIsCheap = false;
606   Pow2DivIsCheap = false;
607   JumpIsExpensive = false;
608   StackPointerRegisterToSaveRestore = 0;
609   ExceptionPointerRegister = 0;
610   ExceptionSelectorRegister = 0;
611   BooleanContents = UndefinedBooleanContent;
612   SchedPreferenceInfo = Sched::Latency;
613   JumpBufSize = 0;
614   JumpBufAlignment = 0;
615   MinFunctionAlignment = 0;
616   PrefFunctionAlignment = 0;
617   PrefLoopAlignment = 0;
618   MinStackArgumentAlignment = 1;
619   ShouldFoldAtomicFences = false;
620   InsertFencesForAtomic = false;
621
622   InitLibcallNames(LibcallRoutineNames);
623   InitCmpLibcallCCs(CmpLibcallCCs);
624   InitLibcallCallingConvs(LibcallCallingConvs);
625 }
626
627 TargetLowering::~TargetLowering() {
628   delete &TLOF;
629 }
630
631 MVT TargetLowering::getShiftAmountTy(EVT LHSTy) const {
632   return MVT::getIntegerVT(8*TD->getPointerSize());
633 }
634
635 /// canOpTrap - Returns true if the operation can trap for the value type.
636 /// VT must be a legal type.
637 bool TargetLowering::canOpTrap(unsigned Op, EVT VT) const {
638   assert(isTypeLegal(VT));
639   switch (Op) {
640   default:
641     return false;
642   case ISD::FDIV:
643   case ISD::FREM:
644   case ISD::SDIV:
645   case ISD::UDIV:
646   case ISD::SREM:
647   case ISD::UREM:
648     return true;
649   }
650 }
651
652
653 static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
654                                           unsigned &NumIntermediates,
655                                           EVT &RegisterVT,
656                                           TargetLowering *TLI) {
657   // Figure out the right, legal destination reg to copy into.
658   unsigned NumElts = VT.getVectorNumElements();
659   MVT EltTy = VT.getVectorElementType();
660
661   unsigned NumVectorRegs = 1;
662
663   // FIXME: We don't support non-power-of-2-sized vectors for now.  Ideally we
664   // could break down into LHS/RHS like LegalizeDAG does.
665   if (!isPowerOf2_32(NumElts)) {
666     NumVectorRegs = NumElts;
667     NumElts = 1;
668   }
669
670   // Divide the input until we get to a supported size.  This will always
671   // end with a scalar if the target doesn't support vectors.
672   while (NumElts > 1 && !TLI->isTypeLegal(MVT::getVectorVT(EltTy, NumElts))) {
673     NumElts >>= 1;
674     NumVectorRegs <<= 1;
675   }
676
677   NumIntermediates = NumVectorRegs;
678
679   MVT NewVT = MVT::getVectorVT(EltTy, NumElts);
680   if (!TLI->isTypeLegal(NewVT))
681     NewVT = EltTy;
682   IntermediateVT = NewVT;
683
684   unsigned NewVTSize = NewVT.getSizeInBits();
685
686   // Convert sizes such as i33 to i64.
687   if (!isPowerOf2_32(NewVTSize))
688     NewVTSize = NextPowerOf2(NewVTSize);
689
690   EVT DestVT = TLI->getRegisterType(NewVT);
691   RegisterVT = DestVT;
692   if (EVT(DestVT).bitsLT(NewVT))    // Value is expanded, e.g. i64 -> i16.
693     return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
694
695   // Otherwise, promotion or legal types use the same number of registers as
696   // the vector decimated to the appropriate level.
697   return NumVectorRegs;
698 }
699
700 /// isLegalRC - Return true if the value types that can be represented by the
701 /// specified register class are all legal.
702 bool TargetLowering::isLegalRC(const TargetRegisterClass *RC) const {
703   for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
704        I != E; ++I) {
705     if (isTypeLegal(*I))
706       return true;
707   }
708   return false;
709 }
710
711 /// hasLegalSuperRegRegClasses - Return true if the specified register class
712 /// has one or more super-reg register classes that are legal.
713 bool
714 TargetLowering::hasLegalSuperRegRegClasses(const TargetRegisterClass *RC) const{
715   if (*RC->superregclasses_begin() == 0)
716     return false;
717   for (TargetRegisterInfo::regclass_iterator I = RC->superregclasses_begin(),
718          E = RC->superregclasses_end(); I != E; ++I) {
719     const TargetRegisterClass *RRC = *I;
720     if (isLegalRC(RRC))
721       return true;
722   }
723   return false;
724 }
725
726 /// findRepresentativeClass - Return the largest legal super-reg register class
727 /// of the register class for the specified type and its associated "cost".
728 std::pair<const TargetRegisterClass*, uint8_t>
729 TargetLowering::findRepresentativeClass(EVT VT) const {
730   const TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT().SimpleTy];
731   if (!RC)
732     return std::make_pair(RC, 0);
733   const TargetRegisterClass *BestRC = RC;
734   for (TargetRegisterInfo::regclass_iterator I = RC->superregclasses_begin(),
735          E = RC->superregclasses_end(); I != E; ++I) {
736     const TargetRegisterClass *RRC = *I;
737     if (RRC->isASubClass() || !isLegalRC(RRC))
738       continue;
739     if (!hasLegalSuperRegRegClasses(RRC))
740       return std::make_pair(RRC, 1);
741     BestRC = RRC;
742   }
743   return std::make_pair(BestRC, 1);
744 }
745
746
747 /// computeRegisterProperties - Once all of the register classes are added,
748 /// this allows us to compute derived properties we expose.
749 void TargetLowering::computeRegisterProperties() {
750   assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE &&
751          "Too many value types for ValueTypeActions to hold!");
752
753   // Everything defaults to needing one register.
754   for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
755     NumRegistersForVT[i] = 1;
756     RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
757   }
758   // ...except isVoid, which doesn't need any registers.
759   NumRegistersForVT[MVT::isVoid] = 0;
760
761   // Find the largest integer register class.
762   unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
763   for (; RegClassForVT[LargestIntReg] == 0; --LargestIntReg)
764     assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
765
766   // Every integer value type larger than this largest register takes twice as
767   // many registers to represent as the previous ValueType.
768   for (unsigned ExpandedReg = LargestIntReg + 1; ; ++ExpandedReg) {
769     EVT ExpandedVT = (MVT::SimpleValueType)ExpandedReg;
770     if (!ExpandedVT.isInteger())
771       break;
772     NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
773     RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
774     TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
775     ValueTypeActions.setTypeAction(ExpandedVT, TypeExpandInteger);
776   }
777
778   // Inspect all of the ValueType's smaller than the largest integer
779   // register to see which ones need promotion.
780   unsigned LegalIntReg = LargestIntReg;
781   for (unsigned IntReg = LargestIntReg - 1;
782        IntReg >= (unsigned)MVT::i1; --IntReg) {
783     EVT IVT = (MVT::SimpleValueType)IntReg;
784     if (isTypeLegal(IVT)) {
785       LegalIntReg = IntReg;
786     } else {
787       RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
788         (MVT::SimpleValueType)LegalIntReg;
789       ValueTypeActions.setTypeAction(IVT, TypePromoteInteger);
790     }
791   }
792
793   // ppcf128 type is really two f64's.
794   if (!isTypeLegal(MVT::ppcf128)) {
795     NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
796     RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
797     TransformToType[MVT::ppcf128] = MVT::f64;
798     ValueTypeActions.setTypeAction(MVT::ppcf128, TypeExpandFloat);
799   }
800
801   // Decide how to handle f64. If the target does not have native f64 support,
802   // expand it to i64 and we will be generating soft float library calls.
803   if (!isTypeLegal(MVT::f64)) {
804     NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
805     RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
806     TransformToType[MVT::f64] = MVT::i64;
807     ValueTypeActions.setTypeAction(MVT::f64, TypeSoftenFloat);
808   }
809
810   // Decide how to handle f32. If the target does not have native support for
811   // f32, promote it to f64 if it is legal. Otherwise, expand it to i32.
812   if (!isTypeLegal(MVT::f32)) {
813     if (isTypeLegal(MVT::f64)) {
814       NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::f64];
815       RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::f64];
816       TransformToType[MVT::f32] = MVT::f64;
817       ValueTypeActions.setTypeAction(MVT::f32, TypePromoteInteger);
818     } else {
819       NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
820       RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
821       TransformToType[MVT::f32] = MVT::i32;
822       ValueTypeActions.setTypeAction(MVT::f32, TypeSoftenFloat);
823     }
824   }
825
826   // Loop over all of the vector value types to see which need transformations.
827   for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
828        i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
829     MVT VT = (MVT::SimpleValueType)i;
830     if (isTypeLegal(VT)) continue;
831
832     // Determine if there is a legal wider type.  If so, we should promote to
833     // that wider vector type.
834     EVT EltVT = VT.getVectorElementType();
835     unsigned NElts = VT.getVectorNumElements();
836     if (NElts != 1) {
837       bool IsLegalWiderType = false;
838       // If we allow the promotion of vector elements using a flag,
839       // then return TypePromoteInteger on vector elements.
840       // First try to promote the elements of integer vectors. If no legal
841       // promotion was found, fallback to the widen-vector method.
842       if (mayPromoteElements)
843       for (unsigned nVT = i+1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
844         EVT SVT = (MVT::SimpleValueType)nVT;
845         // Promote vectors of integers to vectors with the same number
846         // of elements, with a wider element type.
847         if (SVT.getVectorElementType().getSizeInBits() > EltVT.getSizeInBits()
848             && SVT.getVectorNumElements() == NElts &&
849             isTypeLegal(SVT) && SVT.getScalarType().isInteger()) {
850           TransformToType[i] = SVT;
851           RegisterTypeForVT[i] = SVT;
852           NumRegistersForVT[i] = 1;
853           ValueTypeActions.setTypeAction(VT, TypePromoteInteger);
854           IsLegalWiderType = true;
855           break;
856         }
857       }
858
859       if (IsLegalWiderType) continue;
860
861       // Try to widen the vector.
862       for (unsigned nVT = i+1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
863         EVT SVT = (MVT::SimpleValueType)nVT;
864         if (SVT.getVectorElementType() == EltVT &&
865             SVT.getVectorNumElements() > NElts &&
866             isTypeLegal(SVT)) {
867           TransformToType[i] = SVT;
868           RegisterTypeForVT[i] = SVT;
869           NumRegistersForVT[i] = 1;
870           ValueTypeActions.setTypeAction(VT, TypeWidenVector);
871           IsLegalWiderType = true;
872           break;
873         }
874       }
875       if (IsLegalWiderType) continue;
876     }
877
878     MVT IntermediateVT;
879     EVT RegisterVT;
880     unsigned NumIntermediates;
881     NumRegistersForVT[i] =
882       getVectorTypeBreakdownMVT(VT, IntermediateVT, NumIntermediates,
883                                 RegisterVT, this);
884     RegisterTypeForVT[i] = RegisterVT;
885
886     EVT NVT = VT.getPow2VectorType();
887     if (NVT == VT) {
888       // Type is already a power of 2.  The default action is to split.
889       TransformToType[i] = MVT::Other;
890       unsigned NumElts = VT.getVectorNumElements();
891       ValueTypeActions.setTypeAction(VT,
892             NumElts > 1 ? TypeSplitVector : TypeScalarizeVector);
893     } else {
894       TransformToType[i] = NVT;
895       ValueTypeActions.setTypeAction(VT, TypeWidenVector);
896     }
897   }
898
899   // Determine the 'representative' register class for each value type.
900   // An representative register class is the largest (meaning one which is
901   // not a sub-register class / subreg register class) legal register class for
902   // a group of value types. For example, on i386, i8, i16, and i32
903   // representative would be GR32; while on x86_64 it's GR64.
904   for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
905     const TargetRegisterClass* RRC;
906     uint8_t Cost;
907     tie(RRC, Cost) =  findRepresentativeClass((MVT::SimpleValueType)i);
908     RepRegClassForVT[i] = RRC;
909     RepRegClassCostForVT[i] = Cost;
910   }
911 }
912
913 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
914   return NULL;
915 }
916
917
918 MVT::SimpleValueType TargetLowering::getSetCCResultType(EVT VT) const {
919   return PointerTy.SimpleTy;
920 }
921
922 MVT::SimpleValueType TargetLowering::getCmpLibcallReturnType() const {
923   return MVT::i32; // return the default value
924 }
925
926 /// getVectorTypeBreakdown - Vector types are broken down into some number of
927 /// legal first class types.  For example, MVT::v8f32 maps to 2 MVT::v4f32
928 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
929 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
930 ///
931 /// This method returns the number of registers needed, and the VT for each
932 /// register.  It also returns the VT and quantity of the intermediate values
933 /// before they are promoted/expanded.
934 ///
935 unsigned TargetLowering::getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
936                                                 EVT &IntermediateVT,
937                                                 unsigned &NumIntermediates,
938                                                 EVT &RegisterVT) const {
939   unsigned NumElts = VT.getVectorNumElements();
940
941   // If there is a wider vector type with the same element type as this one,
942   // we should widen to that legal vector type.  This handles things like
943   // <2 x float> -> <4 x float>.
944   if (NumElts != 1 && getTypeAction(Context, VT) == TypeWidenVector) {
945     RegisterVT = getTypeToTransformTo(Context, VT);
946     if (isTypeLegal(RegisterVT)) {
947       IntermediateVT = RegisterVT;
948       NumIntermediates = 1;
949       return 1;
950     }
951   }
952
953   // Figure out the right, legal destination reg to copy into.
954   EVT EltTy = VT.getVectorElementType();
955
956   unsigned NumVectorRegs = 1;
957
958   // FIXME: We don't support non-power-of-2-sized vectors for now.  Ideally we
959   // could break down into LHS/RHS like LegalizeDAG does.
960   if (!isPowerOf2_32(NumElts)) {
961     NumVectorRegs = NumElts;
962     NumElts = 1;
963   }
964
965   // Divide the input until we get to a supported size.  This will always
966   // end with a scalar if the target doesn't support vectors.
967   while (NumElts > 1 && !isTypeLegal(
968                                    EVT::getVectorVT(Context, EltTy, NumElts))) {
969     NumElts >>= 1;
970     NumVectorRegs <<= 1;
971   }
972
973   NumIntermediates = NumVectorRegs;
974
975   EVT NewVT = EVT::getVectorVT(Context, EltTy, NumElts);
976   if (!isTypeLegal(NewVT))
977     NewVT = EltTy;
978   IntermediateVT = NewVT;
979
980   EVT DestVT = getRegisterType(Context, NewVT);
981   RegisterVT = DestVT;
982   unsigned NewVTSize = NewVT.getSizeInBits();
983
984   // Convert sizes such as i33 to i64.
985   if (!isPowerOf2_32(NewVTSize))
986     NewVTSize = NextPowerOf2(NewVTSize);
987
988   if (DestVT.bitsLT(NewVT))   // Value is expanded, e.g. i64 -> i16.
989     return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
990
991   // Otherwise, promotion or legal types use the same number of registers as
992   // the vector decimated to the appropriate level.
993   return NumVectorRegs;
994 }
995
996 /// Get the EVTs and ArgFlags collections that represent the legalized return
997 /// type of the given function.  This does not require a DAG or a return value,
998 /// and is suitable for use before any DAGs for the function are constructed.
999 /// TODO: Move this out of TargetLowering.cpp.
1000 void llvm::GetReturnInfo(Type* ReturnType, Attributes attr,
1001                          SmallVectorImpl<ISD::OutputArg> &Outs,
1002                          const TargetLowering &TLI,
1003                          SmallVectorImpl<uint64_t> *Offsets) {
1004   SmallVector<EVT, 4> ValueVTs;
1005   ComputeValueVTs(TLI, ReturnType, ValueVTs);
1006   unsigned NumValues = ValueVTs.size();
1007   if (NumValues == 0) return;
1008   unsigned Offset = 0;
1009
1010   for (unsigned j = 0, f = NumValues; j != f; ++j) {
1011     EVT VT = ValueVTs[j];
1012     ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1013
1014     if (attr & Attribute::SExt)
1015       ExtendKind = ISD::SIGN_EXTEND;
1016     else if (attr & Attribute::ZExt)
1017       ExtendKind = ISD::ZERO_EXTEND;
1018
1019     // FIXME: C calling convention requires the return type to be promoted to
1020     // at least 32-bit. But this is not necessary for non-C calling
1021     // conventions. The frontend should mark functions whose return values
1022     // require promoting with signext or zeroext attributes.
1023     if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
1024       EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
1025       if (VT.bitsLT(MinVT))
1026         VT = MinVT;
1027     }
1028
1029     unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
1030     EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
1031     unsigned PartSize = TLI.getTargetData()->getTypeAllocSize(
1032                         PartVT.getTypeForEVT(ReturnType->getContext()));
1033
1034     // 'inreg' on function refers to return value
1035     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1036     if (attr & Attribute::InReg)
1037       Flags.setInReg();
1038
1039     // Propagate extension type if any
1040     if (attr & Attribute::SExt)
1041       Flags.setSExt();
1042     else if (attr & Attribute::ZExt)
1043       Flags.setZExt();
1044
1045     for (unsigned i = 0; i < NumParts; ++i) {
1046       Outs.push_back(ISD::OutputArg(Flags, PartVT, /*isFixed=*/true));
1047       if (Offsets) {
1048         Offsets->push_back(Offset);
1049         Offset += PartSize;
1050       }
1051     }
1052   }
1053 }
1054
1055 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1056 /// function arguments in the caller parameter area.  This is the actual
1057 /// alignment, not its logarithm.
1058 unsigned TargetLowering::getByValTypeAlignment(Type *Ty) const {
1059   return TD->getCallFrameTypeAlignment(Ty);
1060 }
1061
1062 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1063 /// current function.  The returned value is a member of the
1064 /// MachineJumpTableInfo::JTEntryKind enum.
1065 unsigned TargetLowering::getJumpTableEncoding() const {
1066   // In non-pic modes, just use the address of a block.
1067   if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
1068     return MachineJumpTableInfo::EK_BlockAddress;
1069
1070   // In PIC mode, if the target supports a GPRel32 directive, use it.
1071   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != 0)
1072     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
1073
1074   // Otherwise, use a label difference.
1075   return MachineJumpTableInfo::EK_LabelDifference32;
1076 }
1077
1078 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1079                                                  SelectionDAG &DAG) const {
1080   // If our PIC model is GP relative, use the global offset table as the base.
1081   if (getJumpTableEncoding() == MachineJumpTableInfo::EK_GPRel32BlockAddress)
1082     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
1083   return Table;
1084 }
1085
1086 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1087 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1088 /// MCExpr.
1089 const MCExpr *
1090 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
1091                                              unsigned JTI,MCContext &Ctx) const{
1092   // The normal PIC reloc base is the label at the start of the jump table.
1093   return MCSymbolRefExpr::Create(MF->getJTISymbol(JTI, Ctx), Ctx);
1094 }
1095
1096 bool
1097 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1098   // Assume that everything is safe in static mode.
1099   if (getTargetMachine().getRelocationModel() == Reloc::Static)
1100     return true;
1101
1102   // In dynamic-no-pic mode, assume that known defined values are safe.
1103   if (getTargetMachine().getRelocationModel() == Reloc::DynamicNoPIC &&
1104       GA &&
1105       !GA->getGlobal()->isDeclaration() &&
1106       !GA->getGlobal()->isWeakForLinker())
1107     return true;
1108
1109   // Otherwise assume nothing is safe.
1110   return false;
1111 }
1112
1113 //===----------------------------------------------------------------------===//
1114 //  Optimization Methods
1115 //===----------------------------------------------------------------------===//
1116
1117 /// ShrinkDemandedConstant - Check to see if the specified operand of the
1118 /// specified instruction is a constant integer.  If so, check to see if there
1119 /// are any bits set in the constant that are not demanded.  If so, shrink the
1120 /// constant and return true.
1121 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op,
1122                                                         const APInt &Demanded) {
1123   DebugLoc dl = Op.getDebugLoc();
1124
1125   // FIXME: ISD::SELECT, ISD::SELECT_CC
1126   switch (Op.getOpcode()) {
1127   default: break;
1128   case ISD::XOR:
1129   case ISD::AND:
1130   case ISD::OR: {
1131     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1132     if (!C) return false;
1133
1134     if (Op.getOpcode() == ISD::XOR &&
1135         (C->getAPIntValue() | (~Demanded)).isAllOnesValue())
1136       return false;
1137
1138     // if we can expand it to have all bits set, do it
1139     if (C->getAPIntValue().intersects(~Demanded)) {
1140       EVT VT = Op.getValueType();
1141       SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0),
1142                                 DAG.getConstant(Demanded &
1143                                                 C->getAPIntValue(),
1144                                                 VT));
1145       return CombineTo(Op, New);
1146     }
1147
1148     break;
1149   }
1150   }
1151
1152   return false;
1153 }
1154
1155 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
1156 /// casts are free.  This uses isZExtFree and ZERO_EXTEND for the widening
1157 /// cast, but it could be generalized for targets with other types of
1158 /// implicit widening casts.
1159 bool
1160 TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
1161                                                     unsigned BitWidth,
1162                                                     const APInt &Demanded,
1163                                                     DebugLoc dl) {
1164   assert(Op.getNumOperands() == 2 &&
1165          "ShrinkDemandedOp only supports binary operators!");
1166   assert(Op.getNode()->getNumValues() == 1 &&
1167          "ShrinkDemandedOp only supports nodes with one result!");
1168
1169   // Don't do this if the node has another user, which may require the
1170   // full value.
1171   if (!Op.getNode()->hasOneUse())
1172     return false;
1173
1174   // Search for the smallest integer type with free casts to and from
1175   // Op's type. For expedience, just check power-of-2 integer types.
1176   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1177   unsigned SmallVTBits = BitWidth - Demanded.countLeadingZeros();
1178   if (!isPowerOf2_32(SmallVTBits))
1179     SmallVTBits = NextPowerOf2(SmallVTBits);
1180   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
1181     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
1182     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
1183         TLI.isZExtFree(SmallVT, Op.getValueType())) {
1184       // We found a type with free casts.
1185       SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
1186                               DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
1187                                           Op.getNode()->getOperand(0)),
1188                               DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
1189                                           Op.getNode()->getOperand(1)));
1190       SDValue Z = DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), X);
1191       return CombineTo(Op, Z);
1192     }
1193   }
1194   return false;
1195 }
1196
1197 /// SimplifyDemandedBits - Look at Op.  At this point, we know that only the
1198 /// DemandedMask bits of the result of Op are ever used downstream.  If we can
1199 /// use this information to simplify Op, create a new simplified DAG node and
1200 /// return true, returning the original and new nodes in Old and New. Otherwise,
1201 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
1202 /// the expression (used to simplify the caller).  The KnownZero/One bits may
1203 /// only be accurate for those bits in the DemandedMask.
1204 bool TargetLowering::SimplifyDemandedBits(SDValue Op,
1205                                           const APInt &DemandedMask,
1206                                           APInt &KnownZero,
1207                                           APInt &KnownOne,
1208                                           TargetLoweringOpt &TLO,
1209                                           unsigned Depth) const {
1210   unsigned BitWidth = DemandedMask.getBitWidth();
1211   assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth &&
1212          "Mask size mismatches value type size!");
1213   APInt NewMask = DemandedMask;
1214   DebugLoc dl = Op.getDebugLoc();
1215
1216   // Don't know anything.
1217   KnownZero = KnownOne = APInt(BitWidth, 0);
1218
1219   // Other users may use these bits.
1220   if (!Op.getNode()->hasOneUse()) {
1221     if (Depth != 0) {
1222       // If not at the root, Just compute the KnownZero/KnownOne bits to
1223       // simplify things downstream.
1224       TLO.DAG.ComputeMaskedBits(Op, DemandedMask, KnownZero, KnownOne, Depth);
1225       return false;
1226     }
1227     // If this is the root being simplified, allow it to have multiple uses,
1228     // just set the NewMask to all bits.
1229     NewMask = APInt::getAllOnesValue(BitWidth);
1230   } else if (DemandedMask == 0) {
1231     // Not demanding any bits from Op.
1232     if (Op.getOpcode() != ISD::UNDEF)
1233       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
1234     return false;
1235   } else if (Depth == 6) {        // Limit search depth.
1236     return false;
1237   }
1238
1239   APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
1240   switch (Op.getOpcode()) {
1241   case ISD::Constant:
1242     // We know all of the bits for a constant!
1243     KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & NewMask;
1244     KnownZero = ~KnownOne & NewMask;
1245     return false;   // Don't fall through, will infinitely loop.
1246   case ISD::AND:
1247     // If the RHS is a constant, check to see if the LHS would be zero without
1248     // using the bits from the RHS.  Below, we use knowledge about the RHS to
1249     // simplify the LHS, here we're using information from the LHS to simplify
1250     // the RHS.
1251     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1252       APInt LHSZero, LHSOne;
1253       // Do not increment Depth here; that can cause an infinite loop.
1254       TLO.DAG.ComputeMaskedBits(Op.getOperand(0), NewMask,
1255                                 LHSZero, LHSOne, Depth);
1256       // If the LHS already has zeros where RHSC does, this and is dead.
1257       if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
1258         return TLO.CombineTo(Op, Op.getOperand(0));
1259       // If any of the set bits in the RHS are known zero on the LHS, shrink
1260       // the constant.
1261       if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
1262         return true;
1263     }
1264
1265     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
1266                              KnownOne, TLO, Depth+1))
1267       return true;
1268     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1269     if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
1270                              KnownZero2, KnownOne2, TLO, Depth+1))
1271       return true;
1272     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1273
1274     // If all of the demanded bits are known one on one side, return the other.
1275     // These bits cannot contribute to the result of the 'and'.
1276     if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
1277       return TLO.CombineTo(Op, Op.getOperand(0));
1278     if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
1279       return TLO.CombineTo(Op, Op.getOperand(1));
1280     // If all of the demanded bits in the inputs are known zeros, return zero.
1281     if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
1282       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType()));
1283     // If the RHS is a constant, see if we can simplify it.
1284     if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
1285       return true;
1286     // If the operation can be done in a smaller type, do so.
1287     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1288       return true;
1289
1290     // Output known-1 bits are only known if set in both the LHS & RHS.
1291     KnownOne &= KnownOne2;
1292     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1293     KnownZero |= KnownZero2;
1294     break;
1295   case ISD::OR:
1296     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
1297                              KnownOne, TLO, Depth+1))
1298       return true;
1299     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1300     if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
1301                              KnownZero2, KnownOne2, TLO, Depth+1))
1302       return true;
1303     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1304
1305     // If all of the demanded bits are known zero on one side, return the other.
1306     // These bits cannot contribute to the result of the 'or'.
1307     if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
1308       return TLO.CombineTo(Op, Op.getOperand(0));
1309     if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
1310       return TLO.CombineTo(Op, Op.getOperand(1));
1311     // If all of the potentially set bits on one side are known to be set on
1312     // the other side, just use the 'other' side.
1313     if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
1314       return TLO.CombineTo(Op, Op.getOperand(0));
1315     if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
1316       return TLO.CombineTo(Op, Op.getOperand(1));
1317     // If the RHS is a constant, see if we can simplify it.
1318     if (TLO.ShrinkDemandedConstant(Op, NewMask))
1319       return true;
1320     // If the operation can be done in a smaller type, do so.
1321     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1322       return true;
1323
1324     // Output known-0 bits are only known if clear in both the LHS & RHS.
1325     KnownZero &= KnownZero2;
1326     // Output known-1 are known to be set if set in either the LHS | RHS.
1327     KnownOne |= KnownOne2;
1328     break;
1329   case ISD::XOR:
1330     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
1331                              KnownOne, TLO, Depth+1))
1332       return true;
1333     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1334     if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
1335                              KnownOne2, TLO, Depth+1))
1336       return true;
1337     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1338
1339     // If all of the demanded bits are known zero on one side, return the other.
1340     // These bits cannot contribute to the result of the 'xor'.
1341     if ((KnownZero & NewMask) == NewMask)
1342       return TLO.CombineTo(Op, Op.getOperand(0));
1343     if ((KnownZero2 & NewMask) == NewMask)
1344       return TLO.CombineTo(Op, Op.getOperand(1));
1345     // If the operation can be done in a smaller type, do so.
1346     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1347       return true;
1348
1349     // If all of the unknown bits are known to be zero on one side or the other
1350     // (but not both) turn this into an *inclusive* or.
1351     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1352     if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
1353       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
1354                                                Op.getOperand(0),
1355                                                Op.getOperand(1)));
1356
1357     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1358     KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1359     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1360     KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1361
1362     // If all of the demanded bits on one side are known, and all of the set
1363     // bits on that side are also known to be set on the other side, turn this
1364     // into an AND, as we know the bits will be cleared.
1365     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1366     if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known
1367       if ((KnownOne & KnownOne2) == KnownOne) {
1368         EVT VT = Op.getValueType();
1369         SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, VT);
1370         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
1371                                                  Op.getOperand(0), ANDC));
1372       }
1373     }
1374
1375     // If the RHS is a constant, see if we can simplify it.
1376     // for XOR, we prefer to force bits to 1 if they will make a -1.
1377     // if we can't force bits, try to shrink constant
1378     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1379       APInt Expanded = C->getAPIntValue() | (~NewMask);
1380       // if we can expand it to have all bits set, do it
1381       if (Expanded.isAllOnesValue()) {
1382         if (Expanded != C->getAPIntValue()) {
1383           EVT VT = Op.getValueType();
1384           SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
1385                                           TLO.DAG.getConstant(Expanded, VT));
1386           return TLO.CombineTo(Op, New);
1387         }
1388         // if it already has all the bits set, nothing to change
1389         // but don't shrink either!
1390       } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
1391         return true;
1392       }
1393     }
1394
1395     KnownZero = KnownZeroOut;
1396     KnownOne  = KnownOneOut;
1397     break;
1398   case ISD::SELECT:
1399     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
1400                              KnownOne, TLO, Depth+1))
1401       return true;
1402     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
1403                              KnownOne2, TLO, Depth+1))
1404       return true;
1405     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1406     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1407
1408     // If the operands are constants, see if we can simplify them.
1409     if (TLO.ShrinkDemandedConstant(Op, NewMask))
1410       return true;
1411
1412     // Only known if known in both the LHS and RHS.
1413     KnownOne &= KnownOne2;
1414     KnownZero &= KnownZero2;
1415     break;
1416   case ISD::SELECT_CC:
1417     if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
1418                              KnownOne, TLO, Depth+1))
1419       return true;
1420     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
1421                              KnownOne2, TLO, Depth+1))
1422       return true;
1423     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1424     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1425
1426     // If the operands are constants, see if we can simplify them.
1427     if (TLO.ShrinkDemandedConstant(Op, NewMask))
1428       return true;
1429
1430     // Only known if known in both the LHS and RHS.
1431     KnownOne &= KnownOne2;
1432     KnownZero &= KnownZero2;
1433     break;
1434   case ISD::SHL:
1435     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1436       unsigned ShAmt = SA->getZExtValue();
1437       SDValue InOp = Op.getOperand(0);
1438
1439       // If the shift count is an invalid immediate, don't do anything.
1440       if (ShAmt >= BitWidth)
1441         break;
1442
1443       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1444       // single shift.  We can do this if the bottom bits (which are shifted
1445       // out) are never demanded.
1446       if (InOp.getOpcode() == ISD::SRL &&
1447           isa<ConstantSDNode>(InOp.getOperand(1))) {
1448         if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
1449           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
1450           unsigned Opc = ISD::SHL;
1451           int Diff = ShAmt-C1;
1452           if (Diff < 0) {
1453             Diff = -Diff;
1454             Opc = ISD::SRL;
1455           }
1456
1457           SDValue NewSA =
1458             TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
1459           EVT VT = Op.getValueType();
1460           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
1461                                                    InOp.getOperand(0), NewSA));
1462         }
1463       }
1464
1465       if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
1466                                KnownZero, KnownOne, TLO, Depth+1))
1467         return true;
1468
1469       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1470       // are not demanded. This will likely allow the anyext to be folded away.
1471       if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
1472         SDValue InnerOp = InOp.getNode()->getOperand(0);
1473         EVT InnerVT = InnerOp.getValueType();
1474         if ((APInt::getHighBitsSet(BitWidth,
1475                                    BitWidth - InnerVT.getSizeInBits()) &
1476                DemandedMask) == 0 &&
1477             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
1478           EVT ShTy = getShiftAmountTy(InnerVT);
1479           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
1480             ShTy = InnerVT;
1481           SDValue NarrowShl =
1482             TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
1483                             TLO.DAG.getConstant(ShAmt, ShTy));
1484           return
1485             TLO.CombineTo(Op,
1486                           TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
1487                                           NarrowShl));
1488         }
1489       }
1490
1491       KnownZero <<= SA->getZExtValue();
1492       KnownOne  <<= SA->getZExtValue();
1493       // low bits known zero.
1494       KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
1495     }
1496     break;
1497   case ISD::SRL:
1498     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1499       EVT VT = Op.getValueType();
1500       unsigned ShAmt = SA->getZExtValue();
1501       unsigned VTSize = VT.getSizeInBits();
1502       SDValue InOp = Op.getOperand(0);
1503
1504       // If the shift count is an invalid immediate, don't do anything.
1505       if (ShAmt >= BitWidth)
1506         break;
1507
1508       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
1509       // single shift.  We can do this if the top bits (which are shifted out)
1510       // are never demanded.
1511       if (InOp.getOpcode() == ISD::SHL &&
1512           isa<ConstantSDNode>(InOp.getOperand(1))) {
1513         if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
1514           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
1515           unsigned Opc = ISD::SRL;
1516           int Diff = ShAmt-C1;
1517           if (Diff < 0) {
1518             Diff = -Diff;
1519             Opc = ISD::SHL;
1520           }
1521
1522           SDValue NewSA =
1523             TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
1524           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
1525                                                    InOp.getOperand(0), NewSA));
1526         }
1527       }
1528
1529       // Compute the new bits that are at the top now.
1530       if (SimplifyDemandedBits(InOp, (NewMask << ShAmt),
1531                                KnownZero, KnownOne, TLO, Depth+1))
1532         return true;
1533       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1534       KnownZero = KnownZero.lshr(ShAmt);
1535       KnownOne  = KnownOne.lshr(ShAmt);
1536
1537       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
1538       KnownZero |= HighBits;  // High bits known zero.
1539     }
1540     break;
1541   case ISD::SRA:
1542     // If this is an arithmetic shift right and only the low-bit is set, we can
1543     // always convert this into a logical shr, even if the shift amount is
1544     // variable.  The low bit of the shift cannot be an input sign bit unless
1545     // the shift amount is >= the size of the datatype, which is undefined.
1546     if (DemandedMask == 1)
1547       return TLO.CombineTo(Op,
1548                            TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
1549                                            Op.getOperand(0), Op.getOperand(1)));
1550
1551     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1552       EVT VT = Op.getValueType();
1553       unsigned ShAmt = SA->getZExtValue();
1554
1555       // If the shift count is an invalid immediate, don't do anything.
1556       if (ShAmt >= BitWidth)
1557         break;
1558
1559       APInt InDemandedMask = (NewMask << ShAmt);
1560
1561       // If any of the demanded bits are produced by the sign extension, we also
1562       // demand the input sign bit.
1563       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
1564       if (HighBits.intersects(NewMask))
1565         InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits());
1566
1567       if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
1568                                KnownZero, KnownOne, TLO, Depth+1))
1569         return true;
1570       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1571       KnownZero = KnownZero.lshr(ShAmt);
1572       KnownOne  = KnownOne.lshr(ShAmt);
1573
1574       // Handle the sign bit, adjusted to where it is now in the mask.
1575       APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
1576
1577       // If the input sign bit is known to be zero, or if none of the top bits
1578       // are demanded, turn this into an unsigned shift right.
1579       if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
1580         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
1581                                                  Op.getOperand(0),
1582                                                  Op.getOperand(1)));
1583       } else if (KnownOne.intersects(SignBit)) { // New bits are known one.
1584         KnownOne |= HighBits;
1585       }
1586     }
1587     break;
1588   case ISD::SIGN_EXTEND_INREG: {
1589     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1590
1591     // Sign extension.  Compute the demanded bits in the result that are not
1592     // present in the input.
1593     APInt NewBits =
1594       APInt::getHighBitsSet(BitWidth,
1595                             BitWidth - EVT.getScalarType().getSizeInBits());
1596
1597     // If none of the extended bits are demanded, eliminate the sextinreg.
1598     if ((NewBits & NewMask) == 0)
1599       return TLO.CombineTo(Op, Op.getOperand(0));
1600
1601     APInt InSignBit =
1602       APInt::getSignBit(EVT.getScalarType().getSizeInBits()).zext(BitWidth);
1603     APInt InputDemandedBits =
1604       APInt::getLowBitsSet(BitWidth,
1605                            EVT.getScalarType().getSizeInBits()) &
1606       NewMask;
1607
1608     // Since the sign extended bits are demanded, we know that the sign
1609     // bit is demanded.
1610     InputDemandedBits |= InSignBit;
1611
1612     if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
1613                              KnownZero, KnownOne, TLO, Depth+1))
1614       return true;
1615     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1616
1617     // If the sign bit of the input is known set or clear, then we know the
1618     // top bits of the result.
1619
1620     // If the input sign bit is known zero, convert this into a zero extension.
1621     if (KnownZero.intersects(InSignBit))
1622       return TLO.CombineTo(Op,
1623                            TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,EVT));
1624
1625     if (KnownOne.intersects(InSignBit)) {    // Input sign bit known set
1626       KnownOne |= NewBits;
1627       KnownZero &= ~NewBits;
1628     } else {                       // Input sign bit unknown
1629       KnownZero &= ~NewBits;
1630       KnownOne &= ~NewBits;
1631     }
1632     break;
1633   }
1634   case ISD::ZERO_EXTEND: {
1635     unsigned OperandBitWidth =
1636       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
1637     APInt InMask = NewMask.trunc(OperandBitWidth);
1638
1639     // If none of the top bits are demanded, convert this into an any_extend.
1640     APInt NewBits =
1641       APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
1642     if (!NewBits.intersects(NewMask))
1643       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
1644                                                Op.getValueType(),
1645                                                Op.getOperand(0)));
1646
1647     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1648                              KnownZero, KnownOne, TLO, Depth+1))
1649       return true;
1650     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1651     KnownZero = KnownZero.zext(BitWidth);
1652     KnownOne = KnownOne.zext(BitWidth);
1653     KnownZero |= NewBits;
1654     break;
1655   }
1656   case ISD::SIGN_EXTEND: {
1657     EVT InVT = Op.getOperand(0).getValueType();
1658     unsigned InBits = InVT.getScalarType().getSizeInBits();
1659     APInt InMask    = APInt::getLowBitsSet(BitWidth, InBits);
1660     APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
1661     APInt NewBits   = ~InMask & NewMask;
1662
1663     // If none of the top bits are demanded, convert this into an any_extend.
1664     if (NewBits == 0)
1665       return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
1666                                               Op.getValueType(),
1667                                               Op.getOperand(0)));
1668
1669     // Since some of the sign extended bits are demanded, we know that the sign
1670     // bit is demanded.
1671     APInt InDemandedBits = InMask & NewMask;
1672     InDemandedBits |= InSignBit;
1673     InDemandedBits = InDemandedBits.trunc(InBits);
1674
1675     if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
1676                              KnownOne, TLO, Depth+1))
1677       return true;
1678     KnownZero = KnownZero.zext(BitWidth);
1679     KnownOne = KnownOne.zext(BitWidth);
1680
1681     // If the sign bit is known zero, convert this to a zero extend.
1682     if (KnownZero.intersects(InSignBit))
1683       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
1684                                                Op.getValueType(),
1685                                                Op.getOperand(0)));
1686
1687     // If the sign bit is known one, the top bits match.
1688     if (KnownOne.intersects(InSignBit)) {
1689       KnownOne  |= NewBits;
1690       KnownZero &= ~NewBits;
1691     } else {   // Otherwise, top bits aren't known.
1692       KnownOne  &= ~NewBits;
1693       KnownZero &= ~NewBits;
1694     }
1695     break;
1696   }
1697   case ISD::ANY_EXTEND: {
1698     unsigned OperandBitWidth =
1699       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
1700     APInt InMask = NewMask.trunc(OperandBitWidth);
1701     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1702                              KnownZero, KnownOne, TLO, Depth+1))
1703       return true;
1704     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1705     KnownZero = KnownZero.zext(BitWidth);
1706     KnownOne = KnownOne.zext(BitWidth);
1707     break;
1708   }
1709   case ISD::TRUNCATE: {
1710     // Simplify the input, using demanded bit information, and compute the known
1711     // zero/one bits live out.
1712     unsigned OperandBitWidth =
1713       Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
1714     APInt TruncMask = NewMask.zext(OperandBitWidth);
1715     if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
1716                              KnownZero, KnownOne, TLO, Depth+1))
1717       return true;
1718     KnownZero = KnownZero.trunc(BitWidth);
1719     KnownOne = KnownOne.trunc(BitWidth);
1720
1721     // If the input is only used by this truncate, see if we can shrink it based
1722     // on the known demanded bits.
1723     if (Op.getOperand(0).getNode()->hasOneUse()) {
1724       SDValue In = Op.getOperand(0);
1725       switch (In.getOpcode()) {
1726       default: break;
1727       case ISD::SRL:
1728         // Shrink SRL by a constant if none of the high bits shifted in are
1729         // demanded.
1730         if (TLO.LegalTypes() &&
1731             !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
1732           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1733           // undesirable.
1734           break;
1735         ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
1736         if (!ShAmt)
1737           break;
1738         SDValue Shift = In.getOperand(1);
1739         if (TLO.LegalTypes()) {
1740           uint64_t ShVal = ShAmt->getZExtValue();
1741           Shift =
1742             TLO.DAG.getConstant(ShVal, getShiftAmountTy(Op.getValueType()));
1743         }
1744
1745         APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
1746                                                OperandBitWidth - BitWidth);
1747         HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
1748
1749         if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
1750           // None of the shifted in bits are needed.  Add a truncate of the
1751           // shift input, then shift it.
1752           SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
1753                                              Op.getValueType(),
1754                                              In.getOperand(0));
1755           return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
1756                                                    Op.getValueType(),
1757                                                    NewTrunc,
1758                                                    Shift));
1759         }
1760         break;
1761       }
1762     }
1763
1764     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1765     break;
1766   }
1767   case ISD::AssertZext: {
1768     // Demand all the bits of the input that are demanded in the output.
1769     // The low bits are obvious; the high bits are demanded because we're
1770     // asserting that they're zero here.
1771     if (SimplifyDemandedBits(Op.getOperand(0), NewMask,
1772                              KnownZero, KnownOne, TLO, Depth+1))
1773       return true;
1774     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1775
1776     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1777     APInt InMask = APInt::getLowBitsSet(BitWidth,
1778                                         VT.getSizeInBits());
1779     KnownZero |= ~InMask & NewMask;
1780     break;
1781   }
1782   case ISD::BITCAST:
1783     // If this is an FP->Int bitcast and if the sign bit is the only
1784     // thing demanded, turn this into a FGETSIGN.
1785     if (!Op.getOperand(0).getValueType().isVector() &&
1786         NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) &&
1787         Op.getOperand(0).getValueType().isFloatingPoint()) {
1788       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
1789       bool i32Legal  = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
1790       if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple()) {
1791         EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
1792         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1793         // place.  We expect the SHL to be eliminated by other optimizations.
1794         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
1795         unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits();
1796         if (!OpVTLegal && OpVTSizeInBits > 32)
1797           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
1798         unsigned ShVal = Op.getValueType().getSizeInBits()-1;
1799         SDValue ShAmt = TLO.DAG.getConstant(ShVal, Op.getValueType());
1800         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1801                                                  Op.getValueType(),
1802                                                  Sign, ShAmt));
1803       }
1804     }
1805     break;
1806   case ISD::ADD:
1807   case ISD::MUL:
1808   case ISD::SUB: {
1809     // Add, Sub, and Mul don't demand any bits in positions beyond that
1810     // of the highest bit demanded of them.
1811     APInt LoMask = APInt::getLowBitsSet(BitWidth,
1812                                         BitWidth - NewMask.countLeadingZeros());
1813     if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
1814                              KnownOne2, TLO, Depth+1))
1815       return true;
1816     if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
1817                              KnownOne2, TLO, Depth+1))
1818       return true;
1819     // See if the operation should be performed at a smaller bit width.
1820     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1821       return true;
1822   }
1823   // FALL THROUGH
1824   default:
1825     // Just use ComputeMaskedBits to compute output bits.
1826     TLO.DAG.ComputeMaskedBits(Op, NewMask, KnownZero, KnownOne, Depth);
1827     break;
1828   }
1829
1830   // If we know the value of all of the demanded bits, return this as a
1831   // constant.
1832   if ((NewMask & (KnownZero|KnownOne)) == NewMask)
1833     return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
1834
1835   return false;
1836 }
1837
1838 /// computeMaskedBitsForTargetNode - Determine which of the bits specified
1839 /// in Mask are known to be either zero or one and return them in the
1840 /// KnownZero/KnownOne bitsets.
1841 void TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1842                                                     const APInt &Mask,
1843                                                     APInt &KnownZero,
1844                                                     APInt &KnownOne,
1845                                                     const SelectionDAG &DAG,
1846                                                     unsigned Depth) const {
1847   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1848           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1849           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1850           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1851          "Should use MaskedValueIsZero if you don't know whether Op"
1852          " is a target node!");
1853   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
1854 }
1855
1856 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
1857 /// targets that want to expose additional information about sign bits to the
1858 /// DAG Combiner.
1859 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
1860                                                          unsigned Depth) const {
1861   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1862           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1863           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1864           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1865          "Should use ComputeNumSignBits if you don't know whether Op"
1866          " is a target node!");
1867   return 1;
1868 }
1869
1870 /// ValueHasExactlyOneBitSet - Test if the given value is known to have exactly
1871 /// one bit set. This differs from ComputeMaskedBits in that it doesn't need to
1872 /// determine which bit is set.
1873 ///
1874 static bool ValueHasExactlyOneBitSet(SDValue Val, const SelectionDAG &DAG) {
1875   // A left-shift of a constant one will have exactly one bit set, because
1876   // shifting the bit off the end is undefined.
1877   if (Val.getOpcode() == ISD::SHL)
1878     if (ConstantSDNode *C =
1879          dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1880       if (C->getAPIntValue() == 1)
1881         return true;
1882
1883   // Similarly, a right-shift of a constant sign-bit will have exactly
1884   // one bit set.
1885   if (Val.getOpcode() == ISD::SRL)
1886     if (ConstantSDNode *C =
1887          dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1888       if (C->getAPIntValue().isSignBit())
1889         return true;
1890
1891   // More could be done here, though the above checks are enough
1892   // to handle some common cases.
1893
1894   // Fall back to ComputeMaskedBits to catch other known cases.
1895   EVT OpVT = Val.getValueType();
1896   unsigned BitWidth = OpVT.getScalarType().getSizeInBits();
1897   APInt Mask = APInt::getAllOnesValue(BitWidth);
1898   APInt KnownZero, KnownOne;
1899   DAG.ComputeMaskedBits(Val, Mask, KnownZero, KnownOne);
1900   return (KnownZero.countPopulation() == BitWidth - 1) &&
1901          (KnownOne.countPopulation() == 1);
1902 }
1903
1904 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
1905 /// and cc. If it is unable to simplify it, return a null SDValue.
1906 SDValue
1907 TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1908                               ISD::CondCode Cond, bool foldBooleans,
1909                               DAGCombinerInfo &DCI, DebugLoc dl) const {
1910   SelectionDAG &DAG = DCI.DAG;
1911
1912   // These setcc operations always fold.
1913   switch (Cond) {
1914   default: break;
1915   case ISD::SETFALSE:
1916   case ISD::SETFALSE2: return DAG.getConstant(0, VT);
1917   case ISD::SETTRUE:
1918   case ISD::SETTRUE2:  return DAG.getConstant(1, VT);
1919   }
1920
1921   // Ensure that the constant occurs on the RHS, and fold constant
1922   // comparisons.
1923   if (isa<ConstantSDNode>(N0.getNode()))
1924     return DAG.getSetCC(dl, VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
1925
1926   if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1927     const APInt &C1 = N1C->getAPIntValue();
1928
1929     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1930     // equality comparison, then we're just comparing whether X itself is
1931     // zero.
1932     if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1933         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1934         N0.getOperand(1).getOpcode() == ISD::Constant) {
1935       const APInt &ShAmt
1936         = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1937       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1938           ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
1939         if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1940           // (srl (ctlz x), 5) == 0  -> X != 0
1941           // (srl (ctlz x), 5) != 1  -> X != 0
1942           Cond = ISD::SETNE;
1943         } else {
1944           // (srl (ctlz x), 5) != 0  -> X == 0
1945           // (srl (ctlz x), 5) == 1  -> X == 0
1946           Cond = ISD::SETEQ;
1947         }
1948         SDValue Zero = DAG.getConstant(0, N0.getValueType());
1949         return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1950                             Zero, Cond);
1951       }
1952     }
1953
1954     SDValue CTPOP = N0;
1955     // Look through truncs that don't change the value of a ctpop.
1956     if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
1957       CTPOP = N0.getOperand(0);
1958
1959     if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
1960         (N0 == CTPOP || N0.getValueType().getSizeInBits() >
1961                         Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) {
1962       EVT CTVT = CTPOP.getValueType();
1963       SDValue CTOp = CTPOP.getOperand(0);
1964
1965       // (ctpop x) u< 2 -> (x & x-1) == 0
1966       // (ctpop x) u> 1 -> (x & x-1) != 0
1967       if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
1968         SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
1969                                   DAG.getConstant(1, CTVT));
1970         SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
1971         ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
1972         return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, CTVT), CC);
1973       }
1974
1975       // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
1976     }
1977
1978     // (zext x) == C --> x == (trunc C)
1979     if (DCI.isBeforeLegalize() && N0->hasOneUse() &&
1980         (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1981       unsigned MinBits = N0.getValueSizeInBits();
1982       SDValue PreZExt;
1983       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
1984         // ZExt
1985         MinBits = N0->getOperand(0).getValueSizeInBits();
1986         PreZExt = N0->getOperand(0);
1987       } else if (N0->getOpcode() == ISD::AND) {
1988         // DAGCombine turns costly ZExts into ANDs
1989         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
1990           if ((C->getAPIntValue()+1).isPowerOf2()) {
1991             MinBits = C->getAPIntValue().countTrailingOnes();
1992             PreZExt = N0->getOperand(0);
1993           }
1994       } else if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(N0)) {
1995         // ZEXTLOAD
1996         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
1997           MinBits = LN0->getMemoryVT().getSizeInBits();
1998           PreZExt = N0;
1999         }
2000       }
2001
2002       // Make sure we're not loosing bits from the constant.
2003       if (MinBits < C1.getBitWidth() && MinBits > C1.getActiveBits()) {
2004         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
2005         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
2006           // Will get folded away.
2007           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreZExt);
2008           SDValue C = DAG.getConstant(C1.trunc(MinBits), MinVT);
2009           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
2010         }
2011       }
2012     }
2013
2014     // If the LHS is '(and load, const)', the RHS is 0,
2015     // the test is for equality or unsigned, and all 1 bits of the const are
2016     // in the same partial word, see if we can shorten the load.
2017     if (DCI.isBeforeLegalize() &&
2018         N0.getOpcode() == ISD::AND && C1 == 0 &&
2019         N0.getNode()->hasOneUse() &&
2020         isa<LoadSDNode>(N0.getOperand(0)) &&
2021         N0.getOperand(0).getNode()->hasOneUse() &&
2022         isa<ConstantSDNode>(N0.getOperand(1))) {
2023       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
2024       APInt bestMask;
2025       unsigned bestWidth = 0, bestOffset = 0;
2026       if (!Lod->isVolatile() && Lod->isUnindexed()) {
2027         unsigned origWidth = N0.getValueType().getSizeInBits();
2028         unsigned maskWidth = origWidth;
2029         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
2030         // 8 bits, but have to be careful...
2031         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
2032           origWidth = Lod->getMemoryVT().getSizeInBits();
2033         const APInt &Mask =
2034           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2035         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
2036           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
2037           for (unsigned offset=0; offset<origWidth/width; offset++) {
2038             if ((newMask & Mask) == Mask) {
2039               if (!TD->isLittleEndian())
2040                 bestOffset = (origWidth/width - offset - 1) * (width/8);
2041               else
2042                 bestOffset = (uint64_t)offset * (width/8);
2043               bestMask = Mask.lshr(offset * (width/8) * 8);
2044               bestWidth = width;
2045               break;
2046             }
2047             newMask = newMask << width;
2048           }
2049         }
2050       }
2051       if (bestWidth) {
2052         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
2053         if (newVT.isRound()) {
2054           EVT PtrType = Lod->getOperand(1).getValueType();
2055           SDValue Ptr = Lod->getBasePtr();
2056           if (bestOffset != 0)
2057             Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
2058                               DAG.getConstant(bestOffset, PtrType));
2059           unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
2060           SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
2061                                 Lod->getPointerInfo().getWithOffset(bestOffset),
2062                                         false, false, NewAlign);
2063           return DAG.getSetCC(dl, VT,
2064                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
2065                                       DAG.getConstant(bestMask.trunc(bestWidth),
2066                                                       newVT)),
2067                               DAG.getConstant(0LL, newVT), Cond);
2068         }
2069       }
2070     }
2071
2072     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
2073     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
2074       unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
2075
2076       // If the comparison constant has bits in the upper part, the
2077       // zero-extended value could never match.
2078       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
2079                                               C1.getBitWidth() - InSize))) {
2080         switch (Cond) {
2081         case ISD::SETUGT:
2082         case ISD::SETUGE:
2083         case ISD::SETEQ: return DAG.getConstant(0, VT);
2084         case ISD::SETULT:
2085         case ISD::SETULE:
2086         case ISD::SETNE: return DAG.getConstant(1, VT);
2087         case ISD::SETGT:
2088         case ISD::SETGE:
2089           // True if the sign bit of C1 is set.
2090           return DAG.getConstant(C1.isNegative(), VT);
2091         case ISD::SETLT:
2092         case ISD::SETLE:
2093           // True if the sign bit of C1 isn't set.
2094           return DAG.getConstant(C1.isNonNegative(), VT);
2095         default:
2096           break;
2097         }
2098       }
2099
2100       // Otherwise, we can perform the comparison with the low bits.
2101       switch (Cond) {
2102       case ISD::SETEQ:
2103       case ISD::SETNE:
2104       case ISD::SETUGT:
2105       case ISD::SETUGE:
2106       case ISD::SETULT:
2107       case ISD::SETULE: {
2108         EVT newVT = N0.getOperand(0).getValueType();
2109         if (DCI.isBeforeLegalizeOps() ||
2110             (isOperationLegal(ISD::SETCC, newVT) &&
2111               getCondCodeAction(Cond, newVT)==Legal))
2112           return DAG.getSetCC(dl, VT, N0.getOperand(0),
2113                               DAG.getConstant(C1.trunc(InSize), newVT),
2114                               Cond);
2115         break;
2116       }
2117       default:
2118         break;   // todo, be more careful with signed comparisons
2119       }
2120     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2121                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
2122       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
2123       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
2124       EVT ExtDstTy = N0.getValueType();
2125       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
2126
2127       // If the constant doesn't fit into the number of bits for the source of
2128       // the sign extension, it is impossible for both sides to be equal.
2129       if (C1.getMinSignedBits() > ExtSrcTyBits)
2130         return DAG.getConstant(Cond == ISD::SETNE, VT);
2131
2132       SDValue ZextOp;
2133       EVT Op0Ty = N0.getOperand(0).getValueType();
2134       if (Op0Ty == ExtSrcTy) {
2135         ZextOp = N0.getOperand(0);
2136       } else {
2137         APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
2138         ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
2139                               DAG.getConstant(Imm, Op0Ty));
2140       }
2141       if (!DCI.isCalledByLegalizer())
2142         DCI.AddToWorklist(ZextOp.getNode());
2143       // Otherwise, make this a use of a zext.
2144       return DAG.getSetCC(dl, VT, ZextOp,
2145                           DAG.getConstant(C1 & APInt::getLowBitsSet(
2146                                                               ExtDstTyBits,
2147                                                               ExtSrcTyBits),
2148                                           ExtDstTy),
2149                           Cond);
2150     } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
2151                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
2152       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
2153       if (N0.getOpcode() == ISD::SETCC &&
2154           isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
2155         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
2156         if (TrueWhenTrue)
2157           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
2158         // Invert the condition.
2159         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
2160         CC = ISD::getSetCCInverse(CC,
2161                                   N0.getOperand(0).getValueType().isInteger());
2162         return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
2163       }
2164
2165       if ((N0.getOpcode() == ISD::XOR ||
2166            (N0.getOpcode() == ISD::AND &&
2167             N0.getOperand(0).getOpcode() == ISD::XOR &&
2168             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
2169           isa<ConstantSDNode>(N0.getOperand(1)) &&
2170           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
2171         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
2172         // can only do this if the top bits are known zero.
2173         unsigned BitWidth = N0.getValueSizeInBits();
2174         if (DAG.MaskedValueIsZero(N0,
2175                                   APInt::getHighBitsSet(BitWidth,
2176                                                         BitWidth-1))) {
2177           // Okay, get the un-inverted input value.
2178           SDValue Val;
2179           if (N0.getOpcode() == ISD::XOR)
2180             Val = N0.getOperand(0);
2181           else {
2182             assert(N0.getOpcode() == ISD::AND &&
2183                     N0.getOperand(0).getOpcode() == ISD::XOR);
2184             // ((X^1)&1)^1 -> X & 1
2185             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
2186                               N0.getOperand(0).getOperand(0),
2187                               N0.getOperand(1));
2188           }
2189
2190           return DAG.getSetCC(dl, VT, Val, N1,
2191                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2192         }
2193       } else if (N1C->getAPIntValue() == 1 &&
2194                  (VT == MVT::i1 ||
2195                   getBooleanContents() == ZeroOrOneBooleanContent)) {
2196         SDValue Op0 = N0;
2197         if (Op0.getOpcode() == ISD::TRUNCATE)
2198           Op0 = Op0.getOperand(0);
2199
2200         if ((Op0.getOpcode() == ISD::XOR) &&
2201             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
2202             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
2203           // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
2204           Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
2205           return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
2206                               Cond);
2207         } else if (Op0.getOpcode() == ISD::AND &&
2208                 isa<ConstantSDNode>(Op0.getOperand(1)) &&
2209                 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
2210           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
2211           if (Op0.getValueType().bitsGT(VT))
2212             Op0 = DAG.getNode(ISD::AND, dl, VT,
2213                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
2214                           DAG.getConstant(1, VT));
2215           else if (Op0.getValueType().bitsLT(VT))
2216             Op0 = DAG.getNode(ISD::AND, dl, VT,
2217                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
2218                         DAG.getConstant(1, VT));
2219
2220           return DAG.getSetCC(dl, VT, Op0,
2221                               DAG.getConstant(0, Op0.getValueType()),
2222                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2223         }
2224       }
2225     }
2226
2227     APInt MinVal, MaxVal;
2228     unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
2229     if (ISD::isSignedIntSetCC(Cond)) {
2230       MinVal = APInt::getSignedMinValue(OperandBitSize);
2231       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
2232     } else {
2233       MinVal = APInt::getMinValue(OperandBitSize);
2234       MaxVal = APInt::getMaxValue(OperandBitSize);
2235     }
2236
2237     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
2238     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
2239       if (C1 == MinVal) return DAG.getConstant(1, VT);   // X >= MIN --> true
2240       // X >= C0 --> X > (C0-1)
2241       return DAG.getSetCC(dl, VT, N0,
2242                           DAG.getConstant(C1-1, N1.getValueType()),
2243                           (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
2244     }
2245
2246     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
2247       if (C1 == MaxVal) return DAG.getConstant(1, VT);   // X <= MAX --> true
2248       // X <= C0 --> X < (C0+1)
2249       return DAG.getSetCC(dl, VT, N0,
2250                           DAG.getConstant(C1+1, N1.getValueType()),
2251                           (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
2252     }
2253
2254     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
2255       return DAG.getConstant(0, VT);      // X < MIN --> false
2256     if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
2257       return DAG.getConstant(1, VT);      // X >= MIN --> true
2258     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
2259       return DAG.getConstant(0, VT);      // X > MAX --> false
2260     if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
2261       return DAG.getConstant(1, VT);      // X <= MAX --> true
2262
2263     // Canonicalize setgt X, Min --> setne X, Min
2264     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
2265       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
2266     // Canonicalize setlt X, Max --> setne X, Max
2267     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
2268       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
2269
2270     // If we have setult X, 1, turn it into seteq X, 0
2271     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
2272       return DAG.getSetCC(dl, VT, N0,
2273                           DAG.getConstant(MinVal, N0.getValueType()),
2274                           ISD::SETEQ);
2275     // If we have setugt X, Max-1, turn it into seteq X, Max
2276     else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
2277       return DAG.getSetCC(dl, VT, N0,
2278                           DAG.getConstant(MaxVal, N0.getValueType()),
2279                           ISD::SETEQ);
2280
2281     // If we have "setcc X, C0", check to see if we can shrink the immediate
2282     // by changing cc.
2283
2284     // SETUGT X, SINTMAX  -> SETLT X, 0
2285     if (Cond == ISD::SETUGT &&
2286         C1 == APInt::getSignedMaxValue(OperandBitSize))
2287       return DAG.getSetCC(dl, VT, N0,
2288                           DAG.getConstant(0, N1.getValueType()),
2289                           ISD::SETLT);
2290
2291     // SETULT X, SINTMIN  -> SETGT X, -1
2292     if (Cond == ISD::SETULT &&
2293         C1 == APInt::getSignedMinValue(OperandBitSize)) {
2294       SDValue ConstMinusOne =
2295           DAG.getConstant(APInt::getAllOnesValue(OperandBitSize),
2296                           N1.getValueType());
2297       return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
2298     }
2299
2300     // Fold bit comparisons when we can.
2301     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2302         (VT == N0.getValueType() ||
2303          (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
2304         N0.getOpcode() == ISD::AND)
2305       if (ConstantSDNode *AndRHS =
2306                   dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2307         EVT ShiftTy = DCI.isBeforeLegalize() ?
2308           getPointerTy() : getShiftAmountTy(N0.getValueType());
2309         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
2310           // Perform the xform if the AND RHS is a single bit.
2311           if (AndRHS->getAPIntValue().isPowerOf2()) {
2312             return DAG.getNode(ISD::TRUNCATE, dl, VT,
2313                               DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2314                    DAG.getConstant(AndRHS->getAPIntValue().logBase2(), ShiftTy)));
2315           }
2316         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
2317           // (X & 8) == 8  -->  (X & 8) >> 3
2318           // Perform the xform if C1 is a single bit.
2319           if (C1.isPowerOf2()) {
2320             return DAG.getNode(ISD::TRUNCATE, dl, VT,
2321                                DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2322                                       DAG.getConstant(C1.logBase2(), ShiftTy)));
2323           }
2324         }
2325       }
2326   }
2327
2328   if (isa<ConstantFPSDNode>(N0.getNode())) {
2329     // Constant fold or commute setcc.
2330     SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
2331     if (O.getNode()) return O;
2332   } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
2333     // If the RHS of an FP comparison is a constant, simplify it away in
2334     // some cases.
2335     if (CFP->getValueAPF().isNaN()) {
2336       // If an operand is known to be a nan, we can fold it.
2337       switch (ISD::getUnorderedFlavor(Cond)) {
2338       default: llvm_unreachable("Unknown flavor!");
2339       case 0:  // Known false.
2340         return DAG.getConstant(0, VT);
2341       case 1:  // Known true.
2342         return DAG.getConstant(1, VT);
2343       case 2:  // Undefined.
2344         return DAG.getUNDEF(VT);
2345       }
2346     }
2347
2348     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
2349     // constant if knowing that the operand is non-nan is enough.  We prefer to
2350     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
2351     // materialize 0.0.
2352     if (Cond == ISD::SETO || Cond == ISD::SETUO)
2353       return DAG.getSetCC(dl, VT, N0, N0, Cond);
2354
2355     // If the condition is not legal, see if we can find an equivalent one
2356     // which is legal.
2357     if (!isCondCodeLegal(Cond, N0.getValueType())) {
2358       // If the comparison was an awkward floating-point == or != and one of
2359       // the comparison operands is infinity or negative infinity, convert the
2360       // condition to a less-awkward <= or >=.
2361       if (CFP->getValueAPF().isInfinity()) {
2362         if (CFP->getValueAPF().isNegative()) {
2363           if (Cond == ISD::SETOEQ &&
2364               isCondCodeLegal(ISD::SETOLE, N0.getValueType()))
2365             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
2366           if (Cond == ISD::SETUEQ &&
2367               isCondCodeLegal(ISD::SETOLE, N0.getValueType()))
2368             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
2369           if (Cond == ISD::SETUNE &&
2370               isCondCodeLegal(ISD::SETUGT, N0.getValueType()))
2371             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
2372           if (Cond == ISD::SETONE &&
2373               isCondCodeLegal(ISD::SETUGT, N0.getValueType()))
2374             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
2375         } else {
2376           if (Cond == ISD::SETOEQ &&
2377               isCondCodeLegal(ISD::SETOGE, N0.getValueType()))
2378             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
2379           if (Cond == ISD::SETUEQ &&
2380               isCondCodeLegal(ISD::SETOGE, N0.getValueType()))
2381             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
2382           if (Cond == ISD::SETUNE &&
2383               isCondCodeLegal(ISD::SETULT, N0.getValueType()))
2384             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
2385           if (Cond == ISD::SETONE &&
2386               isCondCodeLegal(ISD::SETULT, N0.getValueType()))
2387             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
2388         }
2389       }
2390     }
2391   }
2392
2393   if (N0 == N1) {
2394     // We can always fold X == X for integer setcc's.
2395     if (N0.getValueType().isInteger())
2396       return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
2397     unsigned UOF = ISD::getUnorderedFlavor(Cond);
2398     if (UOF == 2)   // FP operators that are undefined on NaNs.
2399       return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
2400     if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
2401       return DAG.getConstant(UOF, VT);
2402     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
2403     // if it is not already.
2404     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
2405     if (NewCond != Cond)
2406       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
2407   }
2408
2409   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2410       N0.getValueType().isInteger()) {
2411     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
2412         N0.getOpcode() == ISD::XOR) {
2413       // Simplify (X+Y) == (X+Z) -->  Y == Z
2414       if (N0.getOpcode() == N1.getOpcode()) {
2415         if (N0.getOperand(0) == N1.getOperand(0))
2416           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
2417         if (N0.getOperand(1) == N1.getOperand(1))
2418           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
2419         if (DAG.isCommutativeBinOp(N0.getOpcode())) {
2420           // If X op Y == Y op X, try other combinations.
2421           if (N0.getOperand(0) == N1.getOperand(1))
2422             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
2423                                 Cond);
2424           if (N0.getOperand(1) == N1.getOperand(0))
2425             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
2426                                 Cond);
2427         }
2428       }
2429
2430       if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
2431         if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2432           // Turn (X+C1) == C2 --> X == C2-C1
2433           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
2434             return DAG.getSetCC(dl, VT, N0.getOperand(0),
2435                                 DAG.getConstant(RHSC->getAPIntValue()-
2436                                                 LHSR->getAPIntValue(),
2437                                 N0.getValueType()), Cond);
2438           }
2439
2440           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
2441           if (N0.getOpcode() == ISD::XOR)
2442             // If we know that all of the inverted bits are zero, don't bother
2443             // performing the inversion.
2444             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
2445               return
2446                 DAG.getSetCC(dl, VT, N0.getOperand(0),
2447                              DAG.getConstant(LHSR->getAPIntValue() ^
2448                                                RHSC->getAPIntValue(),
2449                                              N0.getValueType()),
2450                              Cond);
2451         }
2452
2453         // Turn (C1-X) == C2 --> X == C1-C2
2454         if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
2455           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
2456             return
2457               DAG.getSetCC(dl, VT, N0.getOperand(1),
2458                            DAG.getConstant(SUBC->getAPIntValue() -
2459                                              RHSC->getAPIntValue(),
2460                                            N0.getValueType()),
2461                            Cond);
2462           }
2463         }
2464       }
2465
2466       // Simplify (X+Z) == X -->  Z == 0
2467       if (N0.getOperand(0) == N1)
2468         return DAG.getSetCC(dl, VT, N0.getOperand(1),
2469                         DAG.getConstant(0, N0.getValueType()), Cond);
2470       if (N0.getOperand(1) == N1) {
2471         if (DAG.isCommutativeBinOp(N0.getOpcode()))
2472           return DAG.getSetCC(dl, VT, N0.getOperand(0),
2473                           DAG.getConstant(0, N0.getValueType()), Cond);
2474         else if (N0.getNode()->hasOneUse()) {
2475           assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
2476           // (Z-X) == X  --> Z == X<<1
2477           SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(),
2478                                      N1,
2479                        DAG.getConstant(1, getShiftAmountTy(N1.getValueType())));
2480           if (!DCI.isCalledByLegalizer())
2481             DCI.AddToWorklist(SH.getNode());
2482           return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
2483         }
2484       }
2485     }
2486
2487     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
2488         N1.getOpcode() == ISD::XOR) {
2489       // Simplify  X == (X+Z) -->  Z == 0
2490       if (N1.getOperand(0) == N0) {
2491         return DAG.getSetCC(dl, VT, N1.getOperand(1),
2492                         DAG.getConstant(0, N1.getValueType()), Cond);
2493       } else if (N1.getOperand(1) == N0) {
2494         if (DAG.isCommutativeBinOp(N1.getOpcode())) {
2495           return DAG.getSetCC(dl, VT, N1.getOperand(0),
2496                           DAG.getConstant(0, N1.getValueType()), Cond);
2497         } else if (N1.getNode()->hasOneUse()) {
2498           assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
2499           // X == (Z-X)  --> X<<1 == Z
2500           SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N0,
2501                        DAG.getConstant(1, getShiftAmountTy(N0.getValueType())));
2502           if (!DCI.isCalledByLegalizer())
2503             DCI.AddToWorklist(SH.getNode());
2504           return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
2505         }
2506       }
2507     }
2508
2509     // Simplify x&y == y to x&y != 0 if y has exactly one bit set.
2510     // Note that where y is variable and is known to have at most
2511     // one bit set (for example, if it is z&1) we cannot do this;
2512     // the expressions are not equivalent when y==0.
2513     if (N0.getOpcode() == ISD::AND)
2514       if (N0.getOperand(0) == N1 || N0.getOperand(1) == N1) {
2515         if (ValueHasExactlyOneBitSet(N1, DAG)) {
2516           Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
2517           SDValue Zero = DAG.getConstant(0, N1.getValueType());
2518           return DAG.getSetCC(dl, VT, N0, Zero, Cond);
2519         }
2520       }
2521     if (N1.getOpcode() == ISD::AND)
2522       if (N1.getOperand(0) == N0 || N1.getOperand(1) == N0) {
2523         if (ValueHasExactlyOneBitSet(N0, DAG)) {
2524           Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
2525           SDValue Zero = DAG.getConstant(0, N0.getValueType());
2526           return DAG.getSetCC(dl, VT, N1, Zero, Cond);
2527         }
2528       }
2529   }
2530
2531   // Fold away ALL boolean setcc's.
2532   SDValue Temp;
2533   if (N0.getValueType() == MVT::i1 && foldBooleans) {
2534     switch (Cond) {
2535     default: llvm_unreachable("Unknown integer setcc!");
2536     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
2537       Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2538       N0 = DAG.getNOT(dl, Temp, MVT::i1);
2539       if (!DCI.isCalledByLegalizer())
2540         DCI.AddToWorklist(Temp.getNode());
2541       break;
2542     case ISD::SETNE:  // X != Y   -->  (X^Y)
2543       N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2544       break;
2545     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
2546     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
2547       Temp = DAG.getNOT(dl, N0, MVT::i1);
2548       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
2549       if (!DCI.isCalledByLegalizer())
2550         DCI.AddToWorklist(Temp.getNode());
2551       break;
2552     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
2553     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
2554       Temp = DAG.getNOT(dl, N1, MVT::i1);
2555       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
2556       if (!DCI.isCalledByLegalizer())
2557         DCI.AddToWorklist(Temp.getNode());
2558       break;
2559     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
2560     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
2561       Temp = DAG.getNOT(dl, N0, MVT::i1);
2562       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
2563       if (!DCI.isCalledByLegalizer())
2564         DCI.AddToWorklist(Temp.getNode());
2565       break;
2566     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
2567     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
2568       Temp = DAG.getNOT(dl, N1, MVT::i1);
2569       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
2570       break;
2571     }
2572     if (VT != MVT::i1) {
2573       if (!DCI.isCalledByLegalizer())
2574         DCI.AddToWorklist(N0.getNode());
2575       // FIXME: If running after legalize, we probably can't do this.
2576       N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
2577     }
2578     return N0;
2579   }
2580
2581   // Could not fold it.
2582   return SDValue();
2583 }
2584
2585 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
2586 /// node is a GlobalAddress + offset.
2587 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
2588                                     int64_t &Offset) const {
2589   if (isa<GlobalAddressSDNode>(N)) {
2590     GlobalAddressSDNode *GASD = cast<GlobalAddressSDNode>(N);
2591     GA = GASD->getGlobal();
2592     Offset += GASD->getOffset();
2593     return true;
2594   }
2595
2596   if (N->getOpcode() == ISD::ADD) {
2597     SDValue N1 = N->getOperand(0);
2598     SDValue N2 = N->getOperand(1);
2599     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
2600       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
2601       if (V) {
2602         Offset += V->getSExtValue();
2603         return true;
2604       }
2605     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
2606       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
2607       if (V) {
2608         Offset += V->getSExtValue();
2609         return true;
2610       }
2611     }
2612   }
2613
2614   return false;
2615 }
2616
2617
2618 SDValue TargetLowering::
2619 PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
2620   // Default implementation: no optimization.
2621   return SDValue();
2622 }
2623
2624 //===----------------------------------------------------------------------===//
2625 //  Inline Assembler Implementation Methods
2626 //===----------------------------------------------------------------------===//
2627
2628
2629 TargetLowering::ConstraintType
2630 TargetLowering::getConstraintType(const std::string &Constraint) const {
2631   if (Constraint.size() == 1) {
2632     switch (Constraint[0]) {
2633     default: break;
2634     case 'r': return C_RegisterClass;
2635     case 'm':    // memory
2636     case 'o':    // offsetable
2637     case 'V':    // not offsetable
2638       return C_Memory;
2639     case 'i':    // Simple Integer or Relocatable Constant
2640     case 'n':    // Simple Integer
2641     case 'E':    // Floating Point Constant
2642     case 'F':    // Floating Point Constant
2643     case 's':    // Relocatable Constant
2644     case 'p':    // Address.
2645     case 'X':    // Allow ANY value.
2646     case 'I':    // Target registers.
2647     case 'J':
2648     case 'K':
2649     case 'L':
2650     case 'M':
2651     case 'N':
2652     case 'O':
2653     case 'P':
2654     case '<':
2655     case '>':
2656       return C_Other;
2657     }
2658   }
2659
2660   if (Constraint.size() > 1 && Constraint[0] == '{' &&
2661       Constraint[Constraint.size()-1] == '}')
2662     return C_Register;
2663   return C_Unknown;
2664 }
2665
2666 /// LowerXConstraint - try to replace an X constraint, which matches anything,
2667 /// with another that has more specific requirements based on the type of the
2668 /// corresponding operand.
2669 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
2670   if (ConstraintVT.isInteger())
2671     return "r";
2672   if (ConstraintVT.isFloatingPoint())
2673     return "f";      // works for many targets
2674   return 0;
2675 }
2676
2677 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2678 /// vector.  If it is invalid, don't add anything to Ops.
2679 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2680                                                   std::string &Constraint,
2681                                                   std::vector<SDValue> &Ops,
2682                                                   SelectionDAG &DAG) const {
2683
2684   if (Constraint.length() > 1) return;
2685
2686   char ConstraintLetter = Constraint[0];
2687   switch (ConstraintLetter) {
2688   default: break;
2689   case 'X':     // Allows any operand; labels (basic block) use this.
2690     if (Op.getOpcode() == ISD::BasicBlock) {
2691       Ops.push_back(Op);
2692       return;
2693     }
2694     // fall through
2695   case 'i':    // Simple Integer or Relocatable Constant
2696   case 'n':    // Simple Integer
2697   case 's': {  // Relocatable Constant
2698     // These operands are interested in values of the form (GV+C), where C may
2699     // be folded in as an offset of GV, or it may be explicitly added.  Also, it
2700     // is possible and fine if either GV or C are missing.
2701     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2702     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2703
2704     // If we have "(add GV, C)", pull out GV/C
2705     if (Op.getOpcode() == ISD::ADD) {
2706       C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2707       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
2708       if (C == 0 || GA == 0) {
2709         C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2710         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2711       }
2712       if (C == 0 || GA == 0)
2713         C = 0, GA = 0;
2714     }
2715
2716     // If we find a valid operand, map to the TargetXXX version so that the
2717     // value itself doesn't get selected.
2718     if (GA) {   // Either &GV   or   &GV+C
2719       if (ConstraintLetter != 'n') {
2720         int64_t Offs = GA->getOffset();
2721         if (C) Offs += C->getZExtValue();
2722         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
2723                                                  C ? C->getDebugLoc() : DebugLoc(),
2724                                                  Op.getValueType(), Offs));
2725         return;
2726       }
2727     }
2728     if (C) {   // just C, no GV.
2729       // Simple constants are not allowed for 's'.
2730       if (ConstraintLetter != 's') {
2731         // gcc prints these as sign extended.  Sign extend value to 64 bits
2732         // now; without this it would get ZExt'd later in
2733         // ScheduleDAGSDNodes::EmitNode, which is very generic.
2734         Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
2735                                             MVT::i64));
2736         return;
2737       }
2738     }
2739     break;
2740   }
2741   }
2742 }
2743
2744 std::pair<unsigned, const TargetRegisterClass*> TargetLowering::
2745 getRegForInlineAsmConstraint(const std::string &Constraint,
2746                              EVT VT) const {
2747   if (Constraint[0] != '{')
2748     return std::make_pair(0u, static_cast<TargetRegisterClass*>(0));
2749   assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2750
2751   // Remove the braces from around the name.
2752   StringRef RegName(Constraint.data()+1, Constraint.size()-2);
2753
2754   // Figure out which register class contains this reg.
2755   const TargetRegisterInfo *RI = TM.getRegisterInfo();
2756   for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
2757        E = RI->regclass_end(); RCI != E; ++RCI) {
2758     const TargetRegisterClass *RC = *RCI;
2759
2760     // If none of the value types for this register class are valid, we
2761     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
2762     bool isLegal = false;
2763     for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2764          I != E; ++I) {
2765       if (isTypeLegal(*I)) {
2766         isLegal = true;
2767         break;
2768       }
2769     }
2770
2771     if (!isLegal) continue;
2772
2773     for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
2774          I != E; ++I) {
2775       if (RegName.equals_lower(RI->getName(*I)))
2776         return std::make_pair(*I, RC);
2777     }
2778   }
2779
2780   return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2781 }
2782
2783 //===----------------------------------------------------------------------===//
2784 // Constraint Selection.
2785
2786 /// isMatchingInputConstraint - Return true of this is an input operand that is
2787 /// a matching constraint like "4".
2788 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
2789   assert(!ConstraintCode.empty() && "No known constraint!");
2790   return isdigit(ConstraintCode[0]);
2791 }
2792
2793 /// getMatchedOperand - If this is an input matching constraint, this method
2794 /// returns the output operand it matches.
2795 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2796   assert(!ConstraintCode.empty() && "No known constraint!");
2797   return atoi(ConstraintCode.c_str());
2798 }
2799
2800
2801 /// ParseConstraints - Split up the constraint string from the inline
2802 /// assembly value into the specific constraints and their prefixes,
2803 /// and also tie in the associated operand values.
2804 /// If this returns an empty vector, and if the constraint string itself
2805 /// isn't empty, there was an error parsing.
2806 TargetLowering::AsmOperandInfoVector TargetLowering::ParseConstraints(
2807     ImmutableCallSite CS) const {
2808   /// ConstraintOperands - Information about all of the constraints.
2809   AsmOperandInfoVector ConstraintOperands;
2810   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
2811   unsigned maCount = 0; // Largest number of multiple alternative constraints.
2812
2813   // Do a prepass over the constraints, canonicalizing them, and building up the
2814   // ConstraintOperands list.
2815   InlineAsm::ConstraintInfoVector
2816     ConstraintInfos = IA->ParseConstraints();
2817
2818   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
2819   unsigned ResNo = 0;   // ResNo - The result number of the next output.
2820
2821   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
2822     ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
2823     AsmOperandInfo &OpInfo = ConstraintOperands.back();
2824
2825     // Update multiple alternative constraint count.
2826     if (OpInfo.multipleAlternatives.size() > maCount)
2827       maCount = OpInfo.multipleAlternatives.size();
2828
2829     OpInfo.ConstraintVT = MVT::Other;
2830
2831     // Compute the value type for each operand.
2832     switch (OpInfo.Type) {
2833     case InlineAsm::isOutput:
2834       // Indirect outputs just consume an argument.
2835       if (OpInfo.isIndirect) {
2836         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2837         break;
2838       }
2839
2840       // The return value of the call is this value.  As such, there is no
2841       // corresponding argument.
2842       assert(!CS.getType()->isVoidTy() &&
2843              "Bad inline asm!");
2844       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
2845         OpInfo.ConstraintVT = getValueType(STy->getElementType(ResNo));
2846       } else {
2847         assert(ResNo == 0 && "Asm only has one result!");
2848         OpInfo.ConstraintVT = getValueType(CS.getType());
2849       }
2850       ++ResNo;
2851       break;
2852     case InlineAsm::isInput:
2853       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2854       break;
2855     case InlineAsm::isClobber:
2856       // Nothing to do.
2857       break;
2858     }
2859
2860     if (OpInfo.CallOperandVal) {
2861       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
2862       if (OpInfo.isIndirect) {
2863         llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
2864         if (!PtrTy)
2865           report_fatal_error("Indirect operand for inline asm not a pointer!");
2866         OpTy = PtrTy->getElementType();
2867       }
2868
2869       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
2870       if (StructType *STy = dyn_cast<StructType>(OpTy))
2871         if (STy->getNumElements() == 1)
2872           OpTy = STy->getElementType(0);
2873
2874       // If OpTy is not a single value, it may be a struct/union that we
2875       // can tile with integers.
2876       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
2877         unsigned BitSize = TD->getTypeSizeInBits(OpTy);
2878         switch (BitSize) {
2879         default: break;
2880         case 1:
2881         case 8:
2882         case 16:
2883         case 32:
2884         case 64:
2885         case 128:
2886           OpInfo.ConstraintVT =
2887               EVT::getEVT(IntegerType::get(OpTy->getContext(), BitSize), true);
2888           break;
2889         }
2890       } else if (dyn_cast<PointerType>(OpTy)) {
2891         OpInfo.ConstraintVT = MVT::getIntegerVT(8*TD->getPointerSize());
2892       } else {
2893         OpInfo.ConstraintVT = EVT::getEVT(OpTy, true);
2894       }
2895     }
2896   }
2897
2898   // If we have multiple alternative constraints, select the best alternative.
2899   if (ConstraintInfos.size()) {
2900     if (maCount) {
2901       unsigned bestMAIndex = 0;
2902       int bestWeight = -1;
2903       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
2904       int weight = -1;
2905       unsigned maIndex;
2906       // Compute the sums of the weights for each alternative, keeping track
2907       // of the best (highest weight) one so far.
2908       for (maIndex = 0; maIndex < maCount; ++maIndex) {
2909         int weightSum = 0;
2910         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2911             cIndex != eIndex; ++cIndex) {
2912           AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2913           if (OpInfo.Type == InlineAsm::isClobber)
2914             continue;
2915
2916           // If this is an output operand with a matching input operand,
2917           // look up the matching input. If their types mismatch, e.g. one
2918           // is an integer, the other is floating point, or their sizes are
2919           // different, flag it as an maCantMatch.
2920           if (OpInfo.hasMatchingInput()) {
2921             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2922             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2923               if ((OpInfo.ConstraintVT.isInteger() !=
2924                    Input.ConstraintVT.isInteger()) ||
2925                   (OpInfo.ConstraintVT.getSizeInBits() !=
2926                    Input.ConstraintVT.getSizeInBits())) {
2927                 weightSum = -1;  // Can't match.
2928                 break;
2929               }
2930             }
2931           }
2932           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
2933           if (weight == -1) {
2934             weightSum = -1;
2935             break;
2936           }
2937           weightSum += weight;
2938         }
2939         // Update best.
2940         if (weightSum > bestWeight) {
2941           bestWeight = weightSum;
2942           bestMAIndex = maIndex;
2943         }
2944       }
2945
2946       // Now select chosen alternative in each constraint.
2947       for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2948           cIndex != eIndex; ++cIndex) {
2949         AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
2950         if (cInfo.Type == InlineAsm::isClobber)
2951           continue;
2952         cInfo.selectAlternative(bestMAIndex);
2953       }
2954     }
2955   }
2956
2957   // Check and hook up tied operands, choose constraint code to use.
2958   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2959       cIndex != eIndex; ++cIndex) {
2960     AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2961
2962     // If this is an output operand with a matching input operand, look up the
2963     // matching input. If their types mismatch, e.g. one is an integer, the
2964     // other is floating point, or their sizes are different, flag it as an
2965     // error.
2966     if (OpInfo.hasMatchingInput()) {
2967       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2968
2969       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2970         std::pair<unsigned, const TargetRegisterClass*> MatchRC =
2971           getRegForInlineAsmConstraint(OpInfo.ConstraintCode, OpInfo.ConstraintVT);
2972         std::pair<unsigned, const TargetRegisterClass*> InputRC =
2973           getRegForInlineAsmConstraint(Input.ConstraintCode, Input.ConstraintVT);
2974         if ((OpInfo.ConstraintVT.isInteger() !=
2975              Input.ConstraintVT.isInteger()) ||
2976             (MatchRC.second != InputRC.second)) {
2977           report_fatal_error("Unsupported asm: input constraint"
2978                              " with a matching output constraint of"
2979                              " incompatible type!");
2980         }
2981       }
2982
2983     }
2984   }
2985
2986   return ConstraintOperands;
2987 }
2988
2989
2990 /// getConstraintGenerality - Return an integer indicating how general CT
2991 /// is.
2992 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2993   switch (CT) {
2994   default: llvm_unreachable("Unknown constraint type!");
2995   case TargetLowering::C_Other:
2996   case TargetLowering::C_Unknown:
2997     return 0;
2998   case TargetLowering::C_Register:
2999     return 1;
3000   case TargetLowering::C_RegisterClass:
3001     return 2;
3002   case TargetLowering::C_Memory:
3003     return 3;
3004   }
3005 }
3006
3007 /// Examine constraint type and operand type and determine a weight value.
3008 /// This object must already have been set up with the operand type
3009 /// and the current alternative constraint selected.
3010 TargetLowering::ConstraintWeight
3011   TargetLowering::getMultipleConstraintMatchWeight(
3012     AsmOperandInfo &info, int maIndex) const {
3013   InlineAsm::ConstraintCodeVector *rCodes;
3014   if (maIndex >= (int)info.multipleAlternatives.size())
3015     rCodes = &info.Codes;
3016   else
3017     rCodes = &info.multipleAlternatives[maIndex].Codes;
3018   ConstraintWeight BestWeight = CW_Invalid;
3019
3020   // Loop over the options, keeping track of the most general one.
3021   for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
3022     ConstraintWeight weight =
3023       getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
3024     if (weight > BestWeight)
3025       BestWeight = weight;
3026   }
3027
3028   return BestWeight;
3029 }
3030
3031 /// Examine constraint type and operand type and determine a weight value.
3032 /// This object must already have been set up with the operand type
3033 /// and the current alternative constraint selected.
3034 TargetLowering::ConstraintWeight
3035   TargetLowering::getSingleConstraintMatchWeight(
3036     AsmOperandInfo &info, const char *constraint) const {
3037   ConstraintWeight weight = CW_Invalid;
3038   Value *CallOperandVal = info.CallOperandVal;
3039     // If we don't have a value, we can't do a match,
3040     // but allow it at the lowest weight.
3041   if (CallOperandVal == NULL)
3042     return CW_Default;
3043   // Look at the constraint type.
3044   switch (*constraint) {
3045     case 'i': // immediate integer.
3046     case 'n': // immediate integer with a known value.
3047       if (isa<ConstantInt>(CallOperandVal))
3048         weight = CW_Constant;
3049       break;
3050     case 's': // non-explicit intregal immediate.
3051       if (isa<GlobalValue>(CallOperandVal))
3052         weight = CW_Constant;
3053       break;
3054     case 'E': // immediate float if host format.
3055     case 'F': // immediate float.
3056       if (isa<ConstantFP>(CallOperandVal))
3057         weight = CW_Constant;
3058       break;
3059     case '<': // memory operand with autodecrement.
3060     case '>': // memory operand with autoincrement.
3061     case 'm': // memory operand.
3062     case 'o': // offsettable memory operand
3063     case 'V': // non-offsettable memory operand
3064       weight = CW_Memory;
3065       break;
3066     case 'r': // general register.
3067     case 'g': // general register, memory operand or immediate integer.
3068               // note: Clang converts "g" to "imr".
3069       if (CallOperandVal->getType()->isIntegerTy())
3070         weight = CW_Register;
3071       break;
3072     case 'X': // any operand.
3073     default:
3074       weight = CW_Default;
3075       break;
3076   }
3077   return weight;
3078 }
3079
3080 /// ChooseConstraint - If there are multiple different constraints that we
3081 /// could pick for this operand (e.g. "imr") try to pick the 'best' one.
3082 /// This is somewhat tricky: constraints fall into four classes:
3083 ///    Other         -> immediates and magic values
3084 ///    Register      -> one specific register
3085 ///    RegisterClass -> a group of regs
3086 ///    Memory        -> memory
3087 /// Ideally, we would pick the most specific constraint possible: if we have
3088 /// something that fits into a register, we would pick it.  The problem here
3089 /// is that if we have something that could either be in a register or in
3090 /// memory that use of the register could cause selection of *other*
3091 /// operands to fail: they might only succeed if we pick memory.  Because of
3092 /// this the heuristic we use is:
3093 ///
3094 ///  1) If there is an 'other' constraint, and if the operand is valid for
3095 ///     that constraint, use it.  This makes us take advantage of 'i'
3096 ///     constraints when available.
3097 ///  2) Otherwise, pick the most general constraint present.  This prefers
3098 ///     'm' over 'r', for example.
3099 ///
3100 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
3101                              const TargetLowering &TLI,
3102                              SDValue Op, SelectionDAG *DAG) {
3103   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
3104   unsigned BestIdx = 0;
3105   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
3106   int BestGenerality = -1;
3107
3108   // Loop over the options, keeping track of the most general one.
3109   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
3110     TargetLowering::ConstraintType CType =
3111       TLI.getConstraintType(OpInfo.Codes[i]);
3112
3113     // If this is an 'other' constraint, see if the operand is valid for it.
3114     // For example, on X86 we might have an 'rI' constraint.  If the operand
3115     // is an integer in the range [0..31] we want to use I (saving a load
3116     // of a register), otherwise we must use 'r'.
3117     if (CType == TargetLowering::C_Other && Op.getNode()) {
3118       assert(OpInfo.Codes[i].size() == 1 &&
3119              "Unhandled multi-letter 'other' constraint");
3120       std::vector<SDValue> ResultOps;
3121       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
3122                                        ResultOps, *DAG);
3123       if (!ResultOps.empty()) {
3124         BestType = CType;
3125         BestIdx = i;
3126         break;
3127       }
3128     }
3129
3130     // Things with matching constraints can only be registers, per gcc
3131     // documentation.  This mainly affects "g" constraints.
3132     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
3133       continue;
3134
3135     // This constraint letter is more general than the previous one, use it.
3136     int Generality = getConstraintGenerality(CType);
3137     if (Generality > BestGenerality) {
3138       BestType = CType;
3139       BestIdx = i;
3140       BestGenerality = Generality;
3141     }
3142   }
3143
3144   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
3145   OpInfo.ConstraintType = BestType;
3146 }
3147
3148 /// ComputeConstraintToUse - Determines the constraint code and constraint
3149 /// type to use for the specific AsmOperandInfo, setting
3150 /// OpInfo.ConstraintCode and OpInfo.ConstraintType.
3151 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
3152                                             SDValue Op,
3153                                             SelectionDAG *DAG) const {
3154   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
3155
3156   // Single-letter constraints ('r') are very common.
3157   if (OpInfo.Codes.size() == 1) {
3158     OpInfo.ConstraintCode = OpInfo.Codes[0];
3159     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
3160   } else {
3161     ChooseConstraint(OpInfo, *this, Op, DAG);
3162   }
3163
3164   // 'X' matches anything.
3165   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
3166     // Labels and constants are handled elsewhere ('X' is the only thing
3167     // that matches labels).  For Functions, the type here is the type of
3168     // the result, which is not what we want to look at; leave them alone.
3169     Value *v = OpInfo.CallOperandVal;
3170     if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
3171       OpInfo.CallOperandVal = v;
3172       return;
3173     }
3174
3175     // Otherwise, try to resolve it to something we know about by looking at
3176     // the actual operand type.
3177     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
3178       OpInfo.ConstraintCode = Repl;
3179       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
3180     }
3181   }
3182 }
3183
3184 //===----------------------------------------------------------------------===//
3185 //  Loop Strength Reduction hooks
3186 //===----------------------------------------------------------------------===//
3187
3188 /// isLegalAddressingMode - Return true if the addressing mode represented
3189 /// by AM is legal for this target, for a load/store of the specified type.
3190 bool TargetLowering::isLegalAddressingMode(const AddrMode &AM,
3191                                            Type *Ty) const {
3192   // The default implementation of this implements a conservative RISCy, r+r and
3193   // r+i addr mode.
3194
3195   // Allows a sign-extended 16-bit immediate field.
3196   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
3197     return false;
3198
3199   // No global is ever allowed as a base.
3200   if (AM.BaseGV)
3201     return false;
3202
3203   // Only support r+r,
3204   switch (AM.Scale) {
3205   case 0:  // "r+i" or just "i", depending on HasBaseReg.
3206     break;
3207   case 1:
3208     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
3209       return false;
3210     // Otherwise we have r+r or r+i.
3211     break;
3212   case 2:
3213     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
3214       return false;
3215     // Allow 2*r as r+r.
3216     break;
3217   }
3218
3219   return true;
3220 }
3221
3222 /// BuildExactDiv - Given an exact SDIV by a constant, create a multiplication
3223 /// with the multiplicative inverse of the constant.
3224 SDValue TargetLowering::BuildExactSDIV(SDValue Op1, SDValue Op2, DebugLoc dl,
3225                                        SelectionDAG &DAG) const {
3226   ConstantSDNode *C = cast<ConstantSDNode>(Op2);
3227   APInt d = C->getAPIntValue();
3228   assert(d != 0 && "Division by zero!");
3229
3230   // Shift the value upfront if it is even, so the LSB is one.
3231   unsigned ShAmt = d.countTrailingZeros();
3232   if (ShAmt) {
3233     // TODO: For UDIV use SRL instead of SRA.
3234     SDValue Amt = DAG.getConstant(ShAmt, getShiftAmountTy(Op1.getValueType()));
3235     Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt);
3236     d = d.ashr(ShAmt);
3237   }
3238
3239   // Calculate the multiplicative inverse, using Newton's method.
3240   APInt t, xn = d;
3241   while ((t = d*xn) != 1)
3242     xn *= APInt(d.getBitWidth(), 2) - t;
3243
3244   Op2 = DAG.getConstant(xn, Op1.getValueType());
3245   return DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
3246 }
3247
3248 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
3249 /// return a DAG expression to select that will generate the same value by
3250 /// multiplying by a magic number.  See:
3251 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
3252 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
3253                                   std::vector<SDNode*>* Created) const {
3254   EVT VT = N->getValueType(0);
3255   DebugLoc dl= N->getDebugLoc();
3256
3257   // Check to see if we can do this.
3258   // FIXME: We should be more aggressive here.
3259   if (!isTypeLegal(VT))
3260     return SDValue();
3261
3262   APInt d = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
3263   APInt::ms magics = d.magic();
3264
3265   // Multiply the numerator (operand 0) by the magic value
3266   // FIXME: We should support doing a MUL in a wider type
3267   SDValue Q;
3268   if (isOperationLegalOrCustom(ISD::MULHS, VT))
3269     Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
3270                     DAG.getConstant(magics.m, VT));
3271   else if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
3272     Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
3273                               N->getOperand(0),
3274                               DAG.getConstant(magics.m, VT)).getNode(), 1);
3275   else
3276     return SDValue();       // No mulhs or equvialent
3277   // If d > 0 and m < 0, add the numerator
3278   if (d.isStrictlyPositive() && magics.m.isNegative()) {
3279     Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
3280     if (Created)
3281       Created->push_back(Q.getNode());
3282   }
3283   // If d < 0 and m > 0, subtract the numerator.
3284   if (d.isNegative() && magics.m.isStrictlyPositive()) {
3285     Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
3286     if (Created)
3287       Created->push_back(Q.getNode());
3288   }
3289   // Shift right algebraic if shift value is nonzero
3290   if (magics.s > 0) {
3291     Q = DAG.getNode(ISD::SRA, dl, VT, Q,
3292                  DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
3293     if (Created)
3294       Created->push_back(Q.getNode());
3295   }
3296   // Extract the sign bit and add it to the quotient
3297   SDValue T =
3298     DAG.getNode(ISD::SRL, dl, VT, Q, DAG.getConstant(VT.getSizeInBits()-1,
3299                                            getShiftAmountTy(Q.getValueType())));
3300   if (Created)
3301     Created->push_back(T.getNode());
3302   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
3303 }
3304
3305 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
3306 /// return a DAG expression to select that will generate the same value by
3307 /// multiplying by a magic number.  See:
3308 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
3309 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
3310                                   std::vector<SDNode*>* Created) const {
3311   EVT VT = N->getValueType(0);
3312   DebugLoc dl = N->getDebugLoc();
3313
3314   // Check to see if we can do this.
3315   // FIXME: We should be more aggressive here.
3316   if (!isTypeLegal(VT))
3317     return SDValue();
3318
3319   // FIXME: We should use a narrower constant when the upper
3320   // bits are known to be zero.
3321   const APInt &N1C = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
3322   APInt::mu magics = N1C.magicu();
3323
3324   SDValue Q = N->getOperand(0);
3325
3326   // If the divisor is even, we can avoid using the expensive fixup by shifting
3327   // the divided value upfront.
3328   if (magics.a != 0 && !N1C[0]) {
3329     unsigned Shift = N1C.countTrailingZeros();
3330     Q = DAG.getNode(ISD::SRL, dl, VT, Q,
3331                     DAG.getConstant(Shift, getShiftAmountTy(Q.getValueType())));
3332     if (Created)
3333       Created->push_back(Q.getNode());
3334
3335     // Get magic number for the shifted divisor.
3336     magics = N1C.lshr(Shift).magicu(Shift);
3337     assert(magics.a == 0 && "Should use cheap fixup now");
3338   }
3339
3340   // Multiply the numerator (operand 0) by the magic value
3341   // FIXME: We should support doing a MUL in a wider type
3342   if (isOperationLegalOrCustom(ISD::MULHU, VT))
3343     Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, VT));
3344   else if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
3345     Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
3346                             DAG.getConstant(magics.m, VT)).getNode(), 1);
3347   else
3348     return SDValue();       // No mulhu or equvialent
3349   if (Created)
3350     Created->push_back(Q.getNode());
3351
3352   if (magics.a == 0) {
3353     assert(magics.s < N1C.getBitWidth() &&
3354            "We shouldn't generate an undefined shift!");
3355     return DAG.getNode(ISD::SRL, dl, VT, Q,
3356                  DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
3357   } else {
3358     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
3359     if (Created)
3360       Created->push_back(NPQ.getNode());
3361     NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ,
3362                       DAG.getConstant(1, getShiftAmountTy(NPQ.getValueType())));
3363     if (Created)
3364       Created->push_back(NPQ.getNode());
3365     NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
3366     if (Created)
3367       Created->push_back(NPQ.getNode());
3368     return DAG.getNode(ISD::SRL, dl, VT, NPQ,
3369              DAG.getConstant(magics.s-1, getShiftAmountTy(NPQ.getValueType())));
3370   }
3371 }