1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the TargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Target/TargetLowering.h"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/CodeGen/Analysis.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineJumpTableInfo.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
36 /// InitLibcallNames - Set default libcall names.
38 static void InitLibcallNames(const char **Names) {
39 Names[RTLIB::SHL_I16] = "__ashlhi3";
40 Names[RTLIB::SHL_I32] = "__ashlsi3";
41 Names[RTLIB::SHL_I64] = "__ashldi3";
42 Names[RTLIB::SHL_I128] = "__ashlti3";
43 Names[RTLIB::SRL_I16] = "__lshrhi3";
44 Names[RTLIB::SRL_I32] = "__lshrsi3";
45 Names[RTLIB::SRL_I64] = "__lshrdi3";
46 Names[RTLIB::SRL_I128] = "__lshrti3";
47 Names[RTLIB::SRA_I16] = "__ashrhi3";
48 Names[RTLIB::SRA_I32] = "__ashrsi3";
49 Names[RTLIB::SRA_I64] = "__ashrdi3";
50 Names[RTLIB::SRA_I128] = "__ashrti3";
51 Names[RTLIB::MUL_I8] = "__mulqi3";
52 Names[RTLIB::MUL_I16] = "__mulhi3";
53 Names[RTLIB::MUL_I32] = "__mulsi3";
54 Names[RTLIB::MUL_I64] = "__muldi3";
55 Names[RTLIB::MUL_I128] = "__multi3";
56 Names[RTLIB::MULO_I32] = "__mulosi4";
57 Names[RTLIB::MULO_I64] = "__mulodi4";
58 Names[RTLIB::MULO_I128] = "__muloti4";
59 Names[RTLIB::SDIV_I8] = "__divqi3";
60 Names[RTLIB::SDIV_I16] = "__divhi3";
61 Names[RTLIB::SDIV_I32] = "__divsi3";
62 Names[RTLIB::SDIV_I64] = "__divdi3";
63 Names[RTLIB::SDIV_I128] = "__divti3";
64 Names[RTLIB::UDIV_I8] = "__udivqi3";
65 Names[RTLIB::UDIV_I16] = "__udivhi3";
66 Names[RTLIB::UDIV_I32] = "__udivsi3";
67 Names[RTLIB::UDIV_I64] = "__udivdi3";
68 Names[RTLIB::UDIV_I128] = "__udivti3";
69 Names[RTLIB::SREM_I8] = "__modqi3";
70 Names[RTLIB::SREM_I16] = "__modhi3";
71 Names[RTLIB::SREM_I32] = "__modsi3";
72 Names[RTLIB::SREM_I64] = "__moddi3";
73 Names[RTLIB::SREM_I128] = "__modti3";
74 Names[RTLIB::UREM_I8] = "__umodqi3";
75 Names[RTLIB::UREM_I16] = "__umodhi3";
76 Names[RTLIB::UREM_I32] = "__umodsi3";
77 Names[RTLIB::UREM_I64] = "__umoddi3";
78 Names[RTLIB::UREM_I128] = "__umodti3";
80 // These are generally not available.
81 Names[RTLIB::SDIVREM_I8] = 0;
82 Names[RTLIB::SDIVREM_I16] = 0;
83 Names[RTLIB::SDIVREM_I32] = 0;
84 Names[RTLIB::SDIVREM_I64] = 0;
85 Names[RTLIB::SDIVREM_I128] = 0;
86 Names[RTLIB::UDIVREM_I8] = 0;
87 Names[RTLIB::UDIVREM_I16] = 0;
88 Names[RTLIB::UDIVREM_I32] = 0;
89 Names[RTLIB::UDIVREM_I64] = 0;
90 Names[RTLIB::UDIVREM_I128] = 0;
92 Names[RTLIB::NEG_I32] = "__negsi2";
93 Names[RTLIB::NEG_I64] = "__negdi2";
94 Names[RTLIB::ADD_F32] = "__addsf3";
95 Names[RTLIB::ADD_F64] = "__adddf3";
96 Names[RTLIB::ADD_F80] = "__addxf3";
97 Names[RTLIB::ADD_F128] = "__addtf3";
98 Names[RTLIB::ADD_PPCF128] = "__gcc_qadd";
99 Names[RTLIB::SUB_F32] = "__subsf3";
100 Names[RTLIB::SUB_F64] = "__subdf3";
101 Names[RTLIB::SUB_F80] = "__subxf3";
102 Names[RTLIB::SUB_F128] = "__subtf3";
103 Names[RTLIB::SUB_PPCF128] = "__gcc_qsub";
104 Names[RTLIB::MUL_F32] = "__mulsf3";
105 Names[RTLIB::MUL_F64] = "__muldf3";
106 Names[RTLIB::MUL_F80] = "__mulxf3";
107 Names[RTLIB::MUL_F128] = "__multf3";
108 Names[RTLIB::MUL_PPCF128] = "__gcc_qmul";
109 Names[RTLIB::DIV_F32] = "__divsf3";
110 Names[RTLIB::DIV_F64] = "__divdf3";
111 Names[RTLIB::DIV_F80] = "__divxf3";
112 Names[RTLIB::DIV_F128] = "__divtf3";
113 Names[RTLIB::DIV_PPCF128] = "__gcc_qdiv";
114 Names[RTLIB::REM_F32] = "fmodf";
115 Names[RTLIB::REM_F64] = "fmod";
116 Names[RTLIB::REM_F80] = "fmodl";
117 Names[RTLIB::REM_F128] = "fmodl";
118 Names[RTLIB::REM_PPCF128] = "fmodl";
119 Names[RTLIB::FMA_F32] = "fmaf";
120 Names[RTLIB::FMA_F64] = "fma";
121 Names[RTLIB::FMA_F80] = "fmal";
122 Names[RTLIB::FMA_F128] = "fmal";
123 Names[RTLIB::FMA_PPCF128] = "fmal";
124 Names[RTLIB::POWI_F32] = "__powisf2";
125 Names[RTLIB::POWI_F64] = "__powidf2";
126 Names[RTLIB::POWI_F80] = "__powixf2";
127 Names[RTLIB::POWI_F128] = "__powitf2";
128 Names[RTLIB::POWI_PPCF128] = "__powitf2";
129 Names[RTLIB::SQRT_F32] = "sqrtf";
130 Names[RTLIB::SQRT_F64] = "sqrt";
131 Names[RTLIB::SQRT_F80] = "sqrtl";
132 Names[RTLIB::SQRT_F128] = "sqrtl";
133 Names[RTLIB::SQRT_PPCF128] = "sqrtl";
134 Names[RTLIB::LOG_F32] = "logf";
135 Names[RTLIB::LOG_F64] = "log";
136 Names[RTLIB::LOG_F80] = "logl";
137 Names[RTLIB::LOG_F128] = "logl";
138 Names[RTLIB::LOG_PPCF128] = "logl";
139 Names[RTLIB::LOG2_F32] = "log2f";
140 Names[RTLIB::LOG2_F64] = "log2";
141 Names[RTLIB::LOG2_F80] = "log2l";
142 Names[RTLIB::LOG2_F128] = "log2l";
143 Names[RTLIB::LOG2_PPCF128] = "log2l";
144 Names[RTLIB::LOG10_F32] = "log10f";
145 Names[RTLIB::LOG10_F64] = "log10";
146 Names[RTLIB::LOG10_F80] = "log10l";
147 Names[RTLIB::LOG10_F128] = "log10l";
148 Names[RTLIB::LOG10_PPCF128] = "log10l";
149 Names[RTLIB::EXP_F32] = "expf";
150 Names[RTLIB::EXP_F64] = "exp";
151 Names[RTLIB::EXP_F80] = "expl";
152 Names[RTLIB::EXP_F128] = "expl";
153 Names[RTLIB::EXP_PPCF128] = "expl";
154 Names[RTLIB::EXP2_F32] = "exp2f";
155 Names[RTLIB::EXP2_F64] = "exp2";
156 Names[RTLIB::EXP2_F80] = "exp2l";
157 Names[RTLIB::EXP2_F128] = "exp2l";
158 Names[RTLIB::EXP2_PPCF128] = "exp2l";
159 Names[RTLIB::SIN_F32] = "sinf";
160 Names[RTLIB::SIN_F64] = "sin";
161 Names[RTLIB::SIN_F80] = "sinl";
162 Names[RTLIB::SIN_F128] = "sinl";
163 Names[RTLIB::SIN_PPCF128] = "sinl";
164 Names[RTLIB::COS_F32] = "cosf";
165 Names[RTLIB::COS_F64] = "cos";
166 Names[RTLIB::COS_F80] = "cosl";
167 Names[RTLIB::COS_F128] = "cosl";
168 Names[RTLIB::COS_PPCF128] = "cosl";
169 Names[RTLIB::POW_F32] = "powf";
170 Names[RTLIB::POW_F64] = "pow";
171 Names[RTLIB::POW_F80] = "powl";
172 Names[RTLIB::POW_F128] = "powl";
173 Names[RTLIB::POW_PPCF128] = "powl";
174 Names[RTLIB::CEIL_F32] = "ceilf";
175 Names[RTLIB::CEIL_F64] = "ceil";
176 Names[RTLIB::CEIL_F80] = "ceill";
177 Names[RTLIB::CEIL_F128] = "ceill";
178 Names[RTLIB::CEIL_PPCF128] = "ceill";
179 Names[RTLIB::TRUNC_F32] = "truncf";
180 Names[RTLIB::TRUNC_F64] = "trunc";
181 Names[RTLIB::TRUNC_F80] = "truncl";
182 Names[RTLIB::TRUNC_F128] = "truncl";
183 Names[RTLIB::TRUNC_PPCF128] = "truncl";
184 Names[RTLIB::RINT_F32] = "rintf";
185 Names[RTLIB::RINT_F64] = "rint";
186 Names[RTLIB::RINT_F80] = "rintl";
187 Names[RTLIB::RINT_F128] = "rintl";
188 Names[RTLIB::RINT_PPCF128] = "rintl";
189 Names[RTLIB::NEARBYINT_F32] = "nearbyintf";
190 Names[RTLIB::NEARBYINT_F64] = "nearbyint";
191 Names[RTLIB::NEARBYINT_F80] = "nearbyintl";
192 Names[RTLIB::NEARBYINT_F128] = "nearbyintl";
193 Names[RTLIB::NEARBYINT_PPCF128] = "nearbyintl";
194 Names[RTLIB::FLOOR_F32] = "floorf";
195 Names[RTLIB::FLOOR_F64] = "floor";
196 Names[RTLIB::FLOOR_F80] = "floorl";
197 Names[RTLIB::FLOOR_F128] = "floorl";
198 Names[RTLIB::FLOOR_PPCF128] = "floorl";
199 Names[RTLIB::COPYSIGN_F32] = "copysignf";
200 Names[RTLIB::COPYSIGN_F64] = "copysign";
201 Names[RTLIB::COPYSIGN_F80] = "copysignl";
202 Names[RTLIB::COPYSIGN_F128] = "copysignl";
203 Names[RTLIB::COPYSIGN_PPCF128] = "copysignl";
204 Names[RTLIB::FPEXT_F64_F128] = "__extenddftf2";
205 Names[RTLIB::FPEXT_F32_F128] = "__extendsftf2";
206 Names[RTLIB::FPEXT_F32_F64] = "__extendsfdf2";
207 Names[RTLIB::FPEXT_F16_F32] = "__gnu_h2f_ieee";
208 Names[RTLIB::FPROUND_F32_F16] = "__gnu_f2h_ieee";
209 Names[RTLIB::FPROUND_F64_F32] = "__truncdfsf2";
210 Names[RTLIB::FPROUND_F80_F32] = "__truncxfsf2";
211 Names[RTLIB::FPROUND_F128_F32] = "__trunctfsf2";
212 Names[RTLIB::FPROUND_PPCF128_F32] = "__trunctfsf2";
213 Names[RTLIB::FPROUND_F80_F64] = "__truncxfdf2";
214 Names[RTLIB::FPROUND_F128_F64] = "__trunctfdf2";
215 Names[RTLIB::FPROUND_PPCF128_F64] = "__trunctfdf2";
216 Names[RTLIB::FPTOSINT_F32_I8] = "__fixsfqi";
217 Names[RTLIB::FPTOSINT_F32_I16] = "__fixsfhi";
218 Names[RTLIB::FPTOSINT_F32_I32] = "__fixsfsi";
219 Names[RTLIB::FPTOSINT_F32_I64] = "__fixsfdi";
220 Names[RTLIB::FPTOSINT_F32_I128] = "__fixsfti";
221 Names[RTLIB::FPTOSINT_F64_I8] = "__fixdfqi";
222 Names[RTLIB::FPTOSINT_F64_I16] = "__fixdfhi";
223 Names[RTLIB::FPTOSINT_F64_I32] = "__fixdfsi";
224 Names[RTLIB::FPTOSINT_F64_I64] = "__fixdfdi";
225 Names[RTLIB::FPTOSINT_F64_I128] = "__fixdfti";
226 Names[RTLIB::FPTOSINT_F80_I32] = "__fixxfsi";
227 Names[RTLIB::FPTOSINT_F80_I64] = "__fixxfdi";
228 Names[RTLIB::FPTOSINT_F80_I128] = "__fixxfti";
229 Names[RTLIB::FPTOSINT_F128_I32] = "__fixtfsi";
230 Names[RTLIB::FPTOSINT_F128_I64] = "__fixtfdi";
231 Names[RTLIB::FPTOSINT_F128_I128] = "__fixtfti";
232 Names[RTLIB::FPTOSINT_PPCF128_I32] = "__fixtfsi";
233 Names[RTLIB::FPTOSINT_PPCF128_I64] = "__fixtfdi";
234 Names[RTLIB::FPTOSINT_PPCF128_I128] = "__fixtfti";
235 Names[RTLIB::FPTOUINT_F32_I8] = "__fixunssfqi";
236 Names[RTLIB::FPTOUINT_F32_I16] = "__fixunssfhi";
237 Names[RTLIB::FPTOUINT_F32_I32] = "__fixunssfsi";
238 Names[RTLIB::FPTOUINT_F32_I64] = "__fixunssfdi";
239 Names[RTLIB::FPTOUINT_F32_I128] = "__fixunssfti";
240 Names[RTLIB::FPTOUINT_F64_I8] = "__fixunsdfqi";
241 Names[RTLIB::FPTOUINT_F64_I16] = "__fixunsdfhi";
242 Names[RTLIB::FPTOUINT_F64_I32] = "__fixunsdfsi";
243 Names[RTLIB::FPTOUINT_F64_I64] = "__fixunsdfdi";
244 Names[RTLIB::FPTOUINT_F64_I128] = "__fixunsdfti";
245 Names[RTLIB::FPTOUINT_F80_I32] = "__fixunsxfsi";
246 Names[RTLIB::FPTOUINT_F80_I64] = "__fixunsxfdi";
247 Names[RTLIB::FPTOUINT_F80_I128] = "__fixunsxfti";
248 Names[RTLIB::FPTOUINT_F128_I32] = "__fixunstfsi";
249 Names[RTLIB::FPTOUINT_F128_I64] = "__fixunstfdi";
250 Names[RTLIB::FPTOUINT_F128_I128] = "__fixunstfti";
251 Names[RTLIB::FPTOUINT_PPCF128_I32] = "__fixunstfsi";
252 Names[RTLIB::FPTOUINT_PPCF128_I64] = "__fixunstfdi";
253 Names[RTLIB::FPTOUINT_PPCF128_I128] = "__fixunstfti";
254 Names[RTLIB::SINTTOFP_I32_F32] = "__floatsisf";
255 Names[RTLIB::SINTTOFP_I32_F64] = "__floatsidf";
256 Names[RTLIB::SINTTOFP_I32_F80] = "__floatsixf";
257 Names[RTLIB::SINTTOFP_I32_F128] = "__floatsitf";
258 Names[RTLIB::SINTTOFP_I32_PPCF128] = "__floatsitf";
259 Names[RTLIB::SINTTOFP_I64_F32] = "__floatdisf";
260 Names[RTLIB::SINTTOFP_I64_F64] = "__floatdidf";
261 Names[RTLIB::SINTTOFP_I64_F80] = "__floatdixf";
262 Names[RTLIB::SINTTOFP_I64_F128] = "__floatditf";
263 Names[RTLIB::SINTTOFP_I64_PPCF128] = "__floatditf";
264 Names[RTLIB::SINTTOFP_I128_F32] = "__floattisf";
265 Names[RTLIB::SINTTOFP_I128_F64] = "__floattidf";
266 Names[RTLIB::SINTTOFP_I128_F80] = "__floattixf";
267 Names[RTLIB::SINTTOFP_I128_F128] = "__floattitf";
268 Names[RTLIB::SINTTOFP_I128_PPCF128] = "__floattitf";
269 Names[RTLIB::UINTTOFP_I32_F32] = "__floatunsisf";
270 Names[RTLIB::UINTTOFP_I32_F64] = "__floatunsidf";
271 Names[RTLIB::UINTTOFP_I32_F80] = "__floatunsixf";
272 Names[RTLIB::UINTTOFP_I32_F128] = "__floatunsitf";
273 Names[RTLIB::UINTTOFP_I32_PPCF128] = "__floatunsitf";
274 Names[RTLIB::UINTTOFP_I64_F32] = "__floatundisf";
275 Names[RTLIB::UINTTOFP_I64_F64] = "__floatundidf";
276 Names[RTLIB::UINTTOFP_I64_F80] = "__floatundixf";
277 Names[RTLIB::UINTTOFP_I64_F128] = "__floatunditf";
278 Names[RTLIB::UINTTOFP_I64_PPCF128] = "__floatunditf";
279 Names[RTLIB::UINTTOFP_I128_F32] = "__floatuntisf";
280 Names[RTLIB::UINTTOFP_I128_F64] = "__floatuntidf";
281 Names[RTLIB::UINTTOFP_I128_F80] = "__floatuntixf";
282 Names[RTLIB::UINTTOFP_I128_F128] = "__floatuntitf";
283 Names[RTLIB::UINTTOFP_I128_PPCF128] = "__floatuntitf";
284 Names[RTLIB::OEQ_F32] = "__eqsf2";
285 Names[RTLIB::OEQ_F64] = "__eqdf2";
286 Names[RTLIB::OEQ_F128] = "__eqtf2";
287 Names[RTLIB::UNE_F32] = "__nesf2";
288 Names[RTLIB::UNE_F64] = "__nedf2";
289 Names[RTLIB::UNE_F128] = "__netf2";
290 Names[RTLIB::OGE_F32] = "__gesf2";
291 Names[RTLIB::OGE_F64] = "__gedf2";
292 Names[RTLIB::OGE_F128] = "__getf2";
293 Names[RTLIB::OLT_F32] = "__ltsf2";
294 Names[RTLIB::OLT_F64] = "__ltdf2";
295 Names[RTLIB::OLT_F128] = "__lttf2";
296 Names[RTLIB::OLE_F32] = "__lesf2";
297 Names[RTLIB::OLE_F64] = "__ledf2";
298 Names[RTLIB::OLE_F128] = "__letf2";
299 Names[RTLIB::OGT_F32] = "__gtsf2";
300 Names[RTLIB::OGT_F64] = "__gtdf2";
301 Names[RTLIB::OGT_F128] = "__gttf2";
302 Names[RTLIB::UO_F32] = "__unordsf2";
303 Names[RTLIB::UO_F64] = "__unorddf2";
304 Names[RTLIB::UO_F128] = "__unordtf2";
305 Names[RTLIB::O_F32] = "__unordsf2";
306 Names[RTLIB::O_F64] = "__unorddf2";
307 Names[RTLIB::O_F128] = "__unordtf2";
308 Names[RTLIB::MEMCPY] = "memcpy";
309 Names[RTLIB::MEMMOVE] = "memmove";
310 Names[RTLIB::MEMSET] = "memset";
311 Names[RTLIB::UNWIND_RESUME] = "_Unwind_Resume";
312 Names[RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1] = "__sync_val_compare_and_swap_1";
313 Names[RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2] = "__sync_val_compare_and_swap_2";
314 Names[RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4] = "__sync_val_compare_and_swap_4";
315 Names[RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8] = "__sync_val_compare_and_swap_8";
316 Names[RTLIB::SYNC_LOCK_TEST_AND_SET_1] = "__sync_lock_test_and_set_1";
317 Names[RTLIB::SYNC_LOCK_TEST_AND_SET_2] = "__sync_lock_test_and_set_2";
318 Names[RTLIB::SYNC_LOCK_TEST_AND_SET_4] = "__sync_lock_test_and_set_4";
319 Names[RTLIB::SYNC_LOCK_TEST_AND_SET_8] = "__sync_lock_test_and_set_8";
320 Names[RTLIB::SYNC_FETCH_AND_ADD_1] = "__sync_fetch_and_add_1";
321 Names[RTLIB::SYNC_FETCH_AND_ADD_2] = "__sync_fetch_and_add_2";
322 Names[RTLIB::SYNC_FETCH_AND_ADD_4] = "__sync_fetch_and_add_4";
323 Names[RTLIB::SYNC_FETCH_AND_ADD_8] = "__sync_fetch_and_add_8";
324 Names[RTLIB::SYNC_FETCH_AND_SUB_1] = "__sync_fetch_and_sub_1";
325 Names[RTLIB::SYNC_FETCH_AND_SUB_2] = "__sync_fetch_and_sub_2";
326 Names[RTLIB::SYNC_FETCH_AND_SUB_4] = "__sync_fetch_and_sub_4";
327 Names[RTLIB::SYNC_FETCH_AND_SUB_8] = "__sync_fetch_and_sub_8";
328 Names[RTLIB::SYNC_FETCH_AND_AND_1] = "__sync_fetch_and_and_1";
329 Names[RTLIB::SYNC_FETCH_AND_AND_2] = "__sync_fetch_and_and_2";
330 Names[RTLIB::SYNC_FETCH_AND_AND_4] = "__sync_fetch_and_and_4";
331 Names[RTLIB::SYNC_FETCH_AND_AND_8] = "__sync_fetch_and_and_8";
332 Names[RTLIB::SYNC_FETCH_AND_OR_1] = "__sync_fetch_and_or_1";
333 Names[RTLIB::SYNC_FETCH_AND_OR_2] = "__sync_fetch_and_or_2";
334 Names[RTLIB::SYNC_FETCH_AND_OR_4] = "__sync_fetch_and_or_4";
335 Names[RTLIB::SYNC_FETCH_AND_OR_8] = "__sync_fetch_and_or_8";
336 Names[RTLIB::SYNC_FETCH_AND_XOR_1] = "__sync_fetch_and_xor_1";
337 Names[RTLIB::SYNC_FETCH_AND_XOR_2] = "__sync_fetch_and_xor_2";
338 Names[RTLIB::SYNC_FETCH_AND_XOR_4] = "__sync_fetch_and_xor_4";
339 Names[RTLIB::SYNC_FETCH_AND_XOR_8] = "__sync_fetch_and_xor_8";
340 Names[RTLIB::SYNC_FETCH_AND_NAND_1] = "__sync_fetch_and_nand_1";
341 Names[RTLIB::SYNC_FETCH_AND_NAND_2] = "__sync_fetch_and_nand_2";
342 Names[RTLIB::SYNC_FETCH_AND_NAND_4] = "__sync_fetch_and_nand_4";
343 Names[RTLIB::SYNC_FETCH_AND_NAND_8] = "__sync_fetch_and_nand_8";
346 /// InitLibcallCallingConvs - Set default libcall CallingConvs.
348 static void InitLibcallCallingConvs(CallingConv::ID *CCs) {
349 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) {
350 CCs[i] = CallingConv::C;
354 /// getFPEXT - Return the FPEXT_*_* value for the given types, or
355 /// UNKNOWN_LIBCALL if there is none.
356 RTLIB::Libcall RTLIB::getFPEXT(EVT OpVT, EVT RetVT) {
357 if (OpVT == MVT::f32) {
358 if (RetVT == MVT::f64)
359 return FPEXT_F32_F64;
360 if (RetVT == MVT::f128)
361 return FPEXT_F32_F128;
362 } else if (OpVT == MVT::f64) {
363 if (RetVT == MVT::f128)
364 return FPEXT_F64_F128;
367 return UNKNOWN_LIBCALL;
370 /// getFPROUND - Return the FPROUND_*_* value for the given types, or
371 /// UNKNOWN_LIBCALL if there is none.
372 RTLIB::Libcall RTLIB::getFPROUND(EVT OpVT, EVT RetVT) {
373 if (RetVT == MVT::f32) {
374 if (OpVT == MVT::f64)
375 return FPROUND_F64_F32;
376 if (OpVT == MVT::f80)
377 return FPROUND_F80_F32;
378 if (OpVT == MVT::f128)
379 return FPROUND_F128_F32;
380 if (OpVT == MVT::ppcf128)
381 return FPROUND_PPCF128_F32;
382 } else if (RetVT == MVT::f64) {
383 if (OpVT == MVT::f80)
384 return FPROUND_F80_F64;
385 if (OpVT == MVT::f128)
386 return FPROUND_F128_F64;
387 if (OpVT == MVT::ppcf128)
388 return FPROUND_PPCF128_F64;
391 return UNKNOWN_LIBCALL;
394 /// getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or
395 /// UNKNOWN_LIBCALL if there is none.
396 RTLIB::Libcall RTLIB::getFPTOSINT(EVT OpVT, EVT RetVT) {
397 if (OpVT == MVT::f32) {
398 if (RetVT == MVT::i8)
399 return FPTOSINT_F32_I8;
400 if (RetVT == MVT::i16)
401 return FPTOSINT_F32_I16;
402 if (RetVT == MVT::i32)
403 return FPTOSINT_F32_I32;
404 if (RetVT == MVT::i64)
405 return FPTOSINT_F32_I64;
406 if (RetVT == MVT::i128)
407 return FPTOSINT_F32_I128;
408 } else if (OpVT == MVT::f64) {
409 if (RetVT == MVT::i8)
410 return FPTOSINT_F64_I8;
411 if (RetVT == MVT::i16)
412 return FPTOSINT_F64_I16;
413 if (RetVT == MVT::i32)
414 return FPTOSINT_F64_I32;
415 if (RetVT == MVT::i64)
416 return FPTOSINT_F64_I64;
417 if (RetVT == MVT::i128)
418 return FPTOSINT_F64_I128;
419 } else if (OpVT == MVT::f80) {
420 if (RetVT == MVT::i32)
421 return FPTOSINT_F80_I32;
422 if (RetVT == MVT::i64)
423 return FPTOSINT_F80_I64;
424 if (RetVT == MVT::i128)
425 return FPTOSINT_F80_I128;
426 } else if (OpVT == MVT::f128) {
427 if (RetVT == MVT::i32)
428 return FPTOSINT_F128_I32;
429 if (RetVT == MVT::i64)
430 return FPTOSINT_F128_I64;
431 if (RetVT == MVT::i128)
432 return FPTOSINT_F128_I128;
433 } else if (OpVT == MVT::ppcf128) {
434 if (RetVT == MVT::i32)
435 return FPTOSINT_PPCF128_I32;
436 if (RetVT == MVT::i64)
437 return FPTOSINT_PPCF128_I64;
438 if (RetVT == MVT::i128)
439 return FPTOSINT_PPCF128_I128;
441 return UNKNOWN_LIBCALL;
444 /// getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or
445 /// UNKNOWN_LIBCALL if there is none.
446 RTLIB::Libcall RTLIB::getFPTOUINT(EVT OpVT, EVT RetVT) {
447 if (OpVT == MVT::f32) {
448 if (RetVT == MVT::i8)
449 return FPTOUINT_F32_I8;
450 if (RetVT == MVT::i16)
451 return FPTOUINT_F32_I16;
452 if (RetVT == MVT::i32)
453 return FPTOUINT_F32_I32;
454 if (RetVT == MVT::i64)
455 return FPTOUINT_F32_I64;
456 if (RetVT == MVT::i128)
457 return FPTOUINT_F32_I128;
458 } else if (OpVT == MVT::f64) {
459 if (RetVT == MVT::i8)
460 return FPTOUINT_F64_I8;
461 if (RetVT == MVT::i16)
462 return FPTOUINT_F64_I16;
463 if (RetVT == MVT::i32)
464 return FPTOUINT_F64_I32;
465 if (RetVT == MVT::i64)
466 return FPTOUINT_F64_I64;
467 if (RetVT == MVT::i128)
468 return FPTOUINT_F64_I128;
469 } else if (OpVT == MVT::f80) {
470 if (RetVT == MVT::i32)
471 return FPTOUINT_F80_I32;
472 if (RetVT == MVT::i64)
473 return FPTOUINT_F80_I64;
474 if (RetVT == MVT::i128)
475 return FPTOUINT_F80_I128;
476 } else if (OpVT == MVT::f128) {
477 if (RetVT == MVT::i32)
478 return FPTOUINT_F128_I32;
479 if (RetVT == MVT::i64)
480 return FPTOUINT_F128_I64;
481 if (RetVT == MVT::i128)
482 return FPTOUINT_F128_I128;
483 } else if (OpVT == MVT::ppcf128) {
484 if (RetVT == MVT::i32)
485 return FPTOUINT_PPCF128_I32;
486 if (RetVT == MVT::i64)
487 return FPTOUINT_PPCF128_I64;
488 if (RetVT == MVT::i128)
489 return FPTOUINT_PPCF128_I128;
491 return UNKNOWN_LIBCALL;
494 /// getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or
495 /// UNKNOWN_LIBCALL if there is none.
496 RTLIB::Libcall RTLIB::getSINTTOFP(EVT OpVT, EVT RetVT) {
497 if (OpVT == MVT::i32) {
498 if (RetVT == MVT::f32)
499 return SINTTOFP_I32_F32;
500 if (RetVT == MVT::f64)
501 return SINTTOFP_I32_F64;
502 if (RetVT == MVT::f80)
503 return SINTTOFP_I32_F80;
504 if (RetVT == MVT::f128)
505 return SINTTOFP_I32_F128;
506 if (RetVT == MVT::ppcf128)
507 return SINTTOFP_I32_PPCF128;
508 } else if (OpVT == MVT::i64) {
509 if (RetVT == MVT::f32)
510 return SINTTOFP_I64_F32;
511 if (RetVT == MVT::f64)
512 return SINTTOFP_I64_F64;
513 if (RetVT == MVT::f80)
514 return SINTTOFP_I64_F80;
515 if (RetVT == MVT::f128)
516 return SINTTOFP_I64_F128;
517 if (RetVT == MVT::ppcf128)
518 return SINTTOFP_I64_PPCF128;
519 } else if (OpVT == MVT::i128) {
520 if (RetVT == MVT::f32)
521 return SINTTOFP_I128_F32;
522 if (RetVT == MVT::f64)
523 return SINTTOFP_I128_F64;
524 if (RetVT == MVT::f80)
525 return SINTTOFP_I128_F80;
526 if (RetVT == MVT::f128)
527 return SINTTOFP_I128_F128;
528 if (RetVT == MVT::ppcf128)
529 return SINTTOFP_I128_PPCF128;
531 return UNKNOWN_LIBCALL;
534 /// getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or
535 /// UNKNOWN_LIBCALL if there is none.
536 RTLIB::Libcall RTLIB::getUINTTOFP(EVT OpVT, EVT RetVT) {
537 if (OpVT == MVT::i32) {
538 if (RetVT == MVT::f32)
539 return UINTTOFP_I32_F32;
540 if (RetVT == MVT::f64)
541 return UINTTOFP_I32_F64;
542 if (RetVT == MVT::f80)
543 return UINTTOFP_I32_F80;
544 if (RetVT == MVT::f128)
545 return UINTTOFP_I32_F128;
546 if (RetVT == MVT::ppcf128)
547 return UINTTOFP_I32_PPCF128;
548 } else if (OpVT == MVT::i64) {
549 if (RetVT == MVT::f32)
550 return UINTTOFP_I64_F32;
551 if (RetVT == MVT::f64)
552 return UINTTOFP_I64_F64;
553 if (RetVT == MVT::f80)
554 return UINTTOFP_I64_F80;
555 if (RetVT == MVT::f128)
556 return UINTTOFP_I64_F128;
557 if (RetVT == MVT::ppcf128)
558 return UINTTOFP_I64_PPCF128;
559 } else if (OpVT == MVT::i128) {
560 if (RetVT == MVT::f32)
561 return UINTTOFP_I128_F32;
562 if (RetVT == MVT::f64)
563 return UINTTOFP_I128_F64;
564 if (RetVT == MVT::f80)
565 return UINTTOFP_I128_F80;
566 if (RetVT == MVT::f128)
567 return UINTTOFP_I128_F128;
568 if (RetVT == MVT::ppcf128)
569 return UINTTOFP_I128_PPCF128;
571 return UNKNOWN_LIBCALL;
574 /// InitCmpLibcallCCs - Set default comparison libcall CC.
576 static void InitCmpLibcallCCs(ISD::CondCode *CCs) {
577 memset(CCs, ISD::SETCC_INVALID, sizeof(ISD::CondCode)*RTLIB::UNKNOWN_LIBCALL);
578 CCs[RTLIB::OEQ_F32] = ISD::SETEQ;
579 CCs[RTLIB::OEQ_F64] = ISD::SETEQ;
580 CCs[RTLIB::OEQ_F128] = ISD::SETEQ;
581 CCs[RTLIB::UNE_F32] = ISD::SETNE;
582 CCs[RTLIB::UNE_F64] = ISD::SETNE;
583 CCs[RTLIB::UNE_F128] = ISD::SETNE;
584 CCs[RTLIB::OGE_F32] = ISD::SETGE;
585 CCs[RTLIB::OGE_F64] = ISD::SETGE;
586 CCs[RTLIB::OGE_F128] = ISD::SETGE;
587 CCs[RTLIB::OLT_F32] = ISD::SETLT;
588 CCs[RTLIB::OLT_F64] = ISD::SETLT;
589 CCs[RTLIB::OLT_F128] = ISD::SETLT;
590 CCs[RTLIB::OLE_F32] = ISD::SETLE;
591 CCs[RTLIB::OLE_F64] = ISD::SETLE;
592 CCs[RTLIB::OLE_F128] = ISD::SETLE;
593 CCs[RTLIB::OGT_F32] = ISD::SETGT;
594 CCs[RTLIB::OGT_F64] = ISD::SETGT;
595 CCs[RTLIB::OGT_F128] = ISD::SETGT;
596 CCs[RTLIB::UO_F32] = ISD::SETNE;
597 CCs[RTLIB::UO_F64] = ISD::SETNE;
598 CCs[RTLIB::UO_F128] = ISD::SETNE;
599 CCs[RTLIB::O_F32] = ISD::SETEQ;
600 CCs[RTLIB::O_F64] = ISD::SETEQ;
601 CCs[RTLIB::O_F128] = ISD::SETEQ;
604 /// NOTE: The constructor takes ownership of TLOF.
605 TargetLowering::TargetLowering(const TargetMachine &tm,
606 const TargetLoweringObjectFile *tlof)
607 : TM(tm), TD(TM.getDataLayout()), TLOF(*tlof) {
608 // All operations default to being supported.
609 memset(OpActions, 0, sizeof(OpActions));
610 memset(LoadExtActions, 0, sizeof(LoadExtActions));
611 memset(TruncStoreActions, 0, sizeof(TruncStoreActions));
612 memset(IndexedModeActions, 0, sizeof(IndexedModeActions));
613 memset(CondCodeActions, 0, sizeof(CondCodeActions));
615 // Set default actions for various operations.
616 for (unsigned VT = 0; VT != (unsigned)MVT::LAST_VALUETYPE; ++VT) {
617 // Default all indexed load / store to expand.
618 for (unsigned IM = (unsigned)ISD::PRE_INC;
619 IM != (unsigned)ISD::LAST_INDEXED_MODE; ++IM) {
620 setIndexedLoadAction(IM, (MVT::SimpleValueType)VT, Expand);
621 setIndexedStoreAction(IM, (MVT::SimpleValueType)VT, Expand);
624 // These operations default to expand.
625 setOperationAction(ISD::FGETSIGN, (MVT::SimpleValueType)VT, Expand);
626 setOperationAction(ISD::CONCAT_VECTORS, (MVT::SimpleValueType)VT, Expand);
629 // Most targets ignore the @llvm.prefetch intrinsic.
630 setOperationAction(ISD::PREFETCH, MVT::Other, Expand);
632 // ConstantFP nodes default to expand. Targets can either change this to
633 // Legal, in which case all fp constants are legal, or use isFPImmLegal()
634 // to optimize expansions for certain constants.
635 setOperationAction(ISD::ConstantFP, MVT::f16, Expand);
636 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
637 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
638 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
639 setOperationAction(ISD::ConstantFP, MVT::f128, Expand);
641 // These library functions default to expand.
642 setOperationAction(ISD::FLOG , MVT::f16, Expand);
643 setOperationAction(ISD::FLOG2, MVT::f16, Expand);
644 setOperationAction(ISD::FLOG10, MVT::f16, Expand);
645 setOperationAction(ISD::FEXP , MVT::f16, Expand);
646 setOperationAction(ISD::FEXP2, MVT::f16, Expand);
647 setOperationAction(ISD::FFLOOR, MVT::f16, Expand);
648 setOperationAction(ISD::FNEARBYINT, MVT::f16, Expand);
649 setOperationAction(ISD::FCEIL, MVT::f16, Expand);
650 setOperationAction(ISD::FRINT, MVT::f16, Expand);
651 setOperationAction(ISD::FTRUNC, MVT::f16, Expand);
652 setOperationAction(ISD::FLOG , MVT::f32, Expand);
653 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
654 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
655 setOperationAction(ISD::FEXP , MVT::f32, Expand);
656 setOperationAction(ISD::FEXP2, MVT::f32, Expand);
657 setOperationAction(ISD::FFLOOR, MVT::f32, Expand);
658 setOperationAction(ISD::FNEARBYINT, MVT::f32, Expand);
659 setOperationAction(ISD::FCEIL, MVT::f32, Expand);
660 setOperationAction(ISD::FRINT, MVT::f32, Expand);
661 setOperationAction(ISD::FTRUNC, MVT::f32, Expand);
662 setOperationAction(ISD::FLOG , MVT::f64, Expand);
663 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
664 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
665 setOperationAction(ISD::FEXP , MVT::f64, Expand);
666 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
667 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
668 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
669 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
670 setOperationAction(ISD::FRINT, MVT::f64, Expand);
671 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
672 setOperationAction(ISD::FLOG , MVT::f128, Expand);
673 setOperationAction(ISD::FLOG2, MVT::f128, Expand);
674 setOperationAction(ISD::FLOG10, MVT::f128, Expand);
675 setOperationAction(ISD::FEXP , MVT::f128, Expand);
676 setOperationAction(ISD::FEXP2, MVT::f128, Expand);
677 setOperationAction(ISD::FFLOOR, MVT::f128, Expand);
678 setOperationAction(ISD::FNEARBYINT, MVT::f128, Expand);
679 setOperationAction(ISD::FCEIL, MVT::f128, Expand);
680 setOperationAction(ISD::FRINT, MVT::f128, Expand);
681 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
683 // Default ISD::TRAP to expand (which turns it into abort).
684 setOperationAction(ISD::TRAP, MVT::Other, Expand);
686 // On most systems, DEBUGTRAP and TRAP have no difference. The "Expand"
687 // here is to inform DAG Legalizer to replace DEBUGTRAP with TRAP.
689 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Expand);
691 IsLittleEndian = TD->isLittleEndian();
692 PointerTy = MVT::getIntegerVT(8*TD->getPointerSize(0));
693 memset(RegClassForVT, 0,MVT::LAST_VALUETYPE*sizeof(TargetRegisterClass*));
694 memset(TargetDAGCombineArray, 0, array_lengthof(TargetDAGCombineArray));
695 maxStoresPerMemset = maxStoresPerMemcpy = maxStoresPerMemmove = 8;
696 maxStoresPerMemsetOptSize = maxStoresPerMemcpyOptSize
697 = maxStoresPerMemmoveOptSize = 4;
698 benefitFromCodePlacementOpt = false;
699 UseUnderscoreSetJmp = false;
700 UseUnderscoreLongJmp = false;
701 SelectIsExpensive = false;
702 IntDivIsCheap = false;
703 Pow2DivIsCheap = false;
704 JumpIsExpensive = false;
705 predictableSelectIsExpensive = false;
706 StackPointerRegisterToSaveRestore = 0;
707 ExceptionPointerRegister = 0;
708 ExceptionSelectorRegister = 0;
709 BooleanContents = UndefinedBooleanContent;
710 BooleanVectorContents = UndefinedBooleanContent;
711 SchedPreferenceInfo = Sched::ILP;
713 JumpBufAlignment = 0;
714 MinFunctionAlignment = 0;
715 PrefFunctionAlignment = 0;
716 PrefLoopAlignment = 0;
717 MinStackArgumentAlignment = 1;
718 ShouldFoldAtomicFences = false;
719 InsertFencesForAtomic = false;
720 SupportJumpTables = true;
721 MinimumJumpTableEntries = 4;
723 InitLibcallNames(LibcallRoutineNames);
724 InitCmpLibcallCCs(CmpLibcallCCs);
725 InitLibcallCallingConvs(LibcallCallingConvs);
728 TargetLowering::~TargetLowering() {
732 MVT TargetLowering::getShiftAmountTy(EVT LHSTy) const {
733 return MVT::getIntegerVT(8*TD->getPointerSize(0));
736 /// canOpTrap - Returns true if the operation can trap for the value type.
737 /// VT must be a legal type.
738 bool TargetLowering::canOpTrap(unsigned Op, EVT VT) const {
739 assert(isTypeLegal(VT));
754 static unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
755 unsigned &NumIntermediates,
757 TargetLowering *TLI) {
758 // Figure out the right, legal destination reg to copy into.
759 unsigned NumElts = VT.getVectorNumElements();
760 MVT EltTy = VT.getVectorElementType();
762 unsigned NumVectorRegs = 1;
764 // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we
765 // could break down into LHS/RHS like LegalizeDAG does.
766 if (!isPowerOf2_32(NumElts)) {
767 NumVectorRegs = NumElts;
771 // Divide the input until we get to a supported size. This will always
772 // end with a scalar if the target doesn't support vectors.
773 while (NumElts > 1 && !TLI->isTypeLegal(MVT::getVectorVT(EltTy, NumElts))) {
778 NumIntermediates = NumVectorRegs;
780 MVT NewVT = MVT::getVectorVT(EltTy, NumElts);
781 if (!TLI->isTypeLegal(NewVT))
783 IntermediateVT = NewVT;
785 unsigned NewVTSize = NewVT.getSizeInBits();
787 // Convert sizes such as i33 to i64.
788 if (!isPowerOf2_32(NewVTSize))
789 NewVTSize = NextPowerOf2(NewVTSize);
791 MVT DestVT = TLI->getRegisterType(NewVT);
793 if (EVT(DestVT).bitsLT(NewVT)) // Value is expanded, e.g. i64 -> i16.
794 return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
796 // Otherwise, promotion or legal types use the same number of registers as
797 // the vector decimated to the appropriate level.
798 return NumVectorRegs;
801 /// isLegalRC - Return true if the value types that can be represented by the
802 /// specified register class are all legal.
803 bool TargetLowering::isLegalRC(const TargetRegisterClass *RC) const {
804 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
812 /// findRepresentativeClass - Return the largest legal super-reg register class
813 /// of the register class for the specified type and its associated "cost".
814 std::pair<const TargetRegisterClass*, uint8_t>
815 TargetLowering::findRepresentativeClass(MVT VT) const {
816 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
817 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
819 return std::make_pair(RC, 0);
821 // Compute the set of all super-register classes.
822 BitVector SuperRegRC(TRI->getNumRegClasses());
823 for (SuperRegClassIterator RCI(RC, TRI); RCI.isValid(); ++RCI)
824 SuperRegRC.setBitsInMask(RCI.getMask());
826 // Find the first legal register class with the largest spill size.
827 const TargetRegisterClass *BestRC = RC;
828 for (int i = SuperRegRC.find_first(); i >= 0; i = SuperRegRC.find_next(i)) {
829 const TargetRegisterClass *SuperRC = TRI->getRegClass(i);
830 // We want the largest possible spill size.
831 if (SuperRC->getSize() <= BestRC->getSize())
833 if (!isLegalRC(SuperRC))
837 return std::make_pair(BestRC, 1);
840 /// computeRegisterProperties - Once all of the register classes are added,
841 /// this allows us to compute derived properties we expose.
842 void TargetLowering::computeRegisterProperties() {
843 assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE &&
844 "Too many value types for ValueTypeActions to hold!");
846 // Everything defaults to needing one register.
847 for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
848 NumRegistersForVT[i] = 1;
849 RegisterTypeForVT[i] = TransformToType[i] = (MVT::SimpleValueType)i;
851 // ...except isVoid, which doesn't need any registers.
852 NumRegistersForVT[MVT::isVoid] = 0;
854 // Find the largest integer register class.
855 unsigned LargestIntReg = MVT::LAST_INTEGER_VALUETYPE;
856 for (; RegClassForVT[LargestIntReg] == 0; --LargestIntReg)
857 assert(LargestIntReg != MVT::i1 && "No integer registers defined!");
859 // Every integer value type larger than this largest register takes twice as
860 // many registers to represent as the previous ValueType.
861 for (unsigned ExpandedReg = LargestIntReg + 1;
862 ExpandedReg <= MVT::LAST_INTEGER_VALUETYPE; ++ExpandedReg) {
863 NumRegistersForVT[ExpandedReg] = 2*NumRegistersForVT[ExpandedReg-1];
864 RegisterTypeForVT[ExpandedReg] = (MVT::SimpleValueType)LargestIntReg;
865 TransformToType[ExpandedReg] = (MVT::SimpleValueType)(ExpandedReg - 1);
866 ValueTypeActions.setTypeAction((MVT::SimpleValueType)ExpandedReg,
870 // Inspect all of the ValueType's smaller than the largest integer
871 // register to see which ones need promotion.
872 unsigned LegalIntReg = LargestIntReg;
873 for (unsigned IntReg = LargestIntReg - 1;
874 IntReg >= (unsigned)MVT::i1; --IntReg) {
875 MVT IVT = (MVT::SimpleValueType)IntReg;
876 if (isTypeLegal(IVT)) {
877 LegalIntReg = IntReg;
879 RegisterTypeForVT[IntReg] = TransformToType[IntReg] =
880 (const MVT::SimpleValueType)LegalIntReg;
881 ValueTypeActions.setTypeAction(IVT, TypePromoteInteger);
885 // ppcf128 type is really two f64's.
886 if (!isTypeLegal(MVT::ppcf128)) {
887 NumRegistersForVT[MVT::ppcf128] = 2*NumRegistersForVT[MVT::f64];
888 RegisterTypeForVT[MVT::ppcf128] = MVT::f64;
889 TransformToType[MVT::ppcf128] = MVT::f64;
890 ValueTypeActions.setTypeAction(MVT::ppcf128, TypeExpandFloat);
893 // Decide how to handle f64. If the target does not have native f64 support,
894 // expand it to i64 and we will be generating soft float library calls.
895 if (!isTypeLegal(MVT::f64)) {
896 NumRegistersForVT[MVT::f64] = NumRegistersForVT[MVT::i64];
897 RegisterTypeForVT[MVT::f64] = RegisterTypeForVT[MVT::i64];
898 TransformToType[MVT::f64] = MVT::i64;
899 ValueTypeActions.setTypeAction(MVT::f64, TypeSoftenFloat);
902 // Decide how to handle f32. If the target does not have native support for
903 // f32, promote it to f64 if it is legal. Otherwise, expand it to i32.
904 if (!isTypeLegal(MVT::f32)) {
905 if (isTypeLegal(MVT::f64)) {
906 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::f64];
907 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::f64];
908 TransformToType[MVT::f32] = MVT::f64;
909 ValueTypeActions.setTypeAction(MVT::f32, TypePromoteInteger);
911 NumRegistersForVT[MVT::f32] = NumRegistersForVT[MVT::i32];
912 RegisterTypeForVT[MVT::f32] = RegisterTypeForVT[MVT::i32];
913 TransformToType[MVT::f32] = MVT::i32;
914 ValueTypeActions.setTypeAction(MVT::f32, TypeSoftenFloat);
918 // Loop over all of the vector value types to see which need transformations.
919 for (unsigned i = MVT::FIRST_VECTOR_VALUETYPE;
920 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
921 MVT VT = (MVT::SimpleValueType)i;
922 if (isTypeLegal(VT)) continue;
924 // Determine if there is a legal wider type. If so, we should promote to
925 // that wider vector type.
926 MVT EltVT = VT.getVectorElementType();
927 unsigned NElts = VT.getVectorNumElements();
928 if (NElts != 1 && !shouldSplitVectorElementType(EltVT)) {
929 bool IsLegalWiderType = false;
930 // First try to promote the elements of integer vectors. If no legal
931 // promotion was found, fallback to the widen-vector method.
932 for (unsigned nVT = i+1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
933 MVT SVT = (MVT::SimpleValueType)nVT;
934 // Promote vectors of integers to vectors with the same number
935 // of elements, with a wider element type.
936 if (SVT.getVectorElementType().getSizeInBits() > EltVT.getSizeInBits()
937 && SVT.getVectorNumElements() == NElts &&
938 isTypeLegal(SVT) && SVT.getScalarType().isInteger()) {
939 TransformToType[i] = SVT;
940 RegisterTypeForVT[i] = SVT;
941 NumRegistersForVT[i] = 1;
942 ValueTypeActions.setTypeAction(VT, TypePromoteInteger);
943 IsLegalWiderType = true;
948 if (IsLegalWiderType) continue;
950 // Try to widen the vector.
951 for (unsigned nVT = i+1; nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
952 MVT SVT = (MVT::SimpleValueType)nVT;
953 if (SVT.getVectorElementType() == EltVT &&
954 SVT.getVectorNumElements() > NElts &&
956 TransformToType[i] = SVT;
957 RegisterTypeForVT[i] = SVT;
958 NumRegistersForVT[i] = 1;
959 ValueTypeActions.setTypeAction(VT, TypeWidenVector);
960 IsLegalWiderType = true;
964 if (IsLegalWiderType) continue;
969 unsigned NumIntermediates;
970 NumRegistersForVT[i] =
971 getVectorTypeBreakdownMVT(VT, IntermediateVT, NumIntermediates,
973 RegisterTypeForVT[i] = RegisterVT;
975 MVT NVT = VT.getPow2VectorType();
977 // Type is already a power of 2. The default action is to split.
978 TransformToType[i] = MVT::Other;
979 unsigned NumElts = VT.getVectorNumElements();
980 ValueTypeActions.setTypeAction(VT,
981 NumElts > 1 ? TypeSplitVector : TypeScalarizeVector);
983 TransformToType[i] = NVT;
984 ValueTypeActions.setTypeAction(VT, TypeWidenVector);
988 // Determine the 'representative' register class for each value type.
989 // An representative register class is the largest (meaning one which is
990 // not a sub-register class / subreg register class) legal register class for
991 // a group of value types. For example, on i386, i8, i16, and i32
992 // representative would be GR32; while on x86_64 it's GR64.
993 for (unsigned i = 0; i != MVT::LAST_VALUETYPE; ++i) {
994 const TargetRegisterClass* RRC;
996 tie(RRC, Cost) = findRepresentativeClass((MVT::SimpleValueType)i);
997 RepRegClassForVT[i] = RRC;
998 RepRegClassCostForVT[i] = Cost;
1002 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
1006 EVT TargetLowering::getSetCCResultType(EVT VT) const {
1007 assert(!VT.isVector() && "No default SetCC type for vectors!");
1008 return getPointerTy(0).SimpleTy;
1011 MVT::SimpleValueType TargetLowering::getCmpLibcallReturnType() const {
1012 return MVT::i32; // return the default value
1015 /// Check whether a given call node is in tail position within its function. If
1016 /// so, it sets Chain to the input chain of the tail call.
1017 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
1018 SDValue &Chain) const {
1019 const Function *F = DAG.getMachineFunction().getFunction();
1021 // Conservatively require the attributes of the call to match those of
1022 // the return. Ignore noalias because it doesn't affect the call sequence.
1023 Attribute CallerRetAttr = F->getAttributes().getRetAttributes();
1024 if (AttrBuilder(CallerRetAttr)
1025 .removeAttribute(Attribute::NoAlias).hasAttributes())
1028 // It's not safe to eliminate the sign / zero extension of the return value.
1029 if (CallerRetAttr.hasAttribute(Attribute::ZExt) ||
1030 CallerRetAttr.hasAttribute(Attribute::SExt))
1033 // Check if the only use is a function return node.
1034 return isUsedByReturnOnly(Node, Chain);
1038 /// Generate a libcall taking the given operands as arguments and returning a
1039 /// result of type RetVT.
1040 SDValue TargetLowering::makeLibCall(SelectionDAG &DAG,
1041 RTLIB::Libcall LC, EVT RetVT,
1042 const SDValue *Ops, unsigned NumOps,
1043 bool isSigned, DebugLoc dl) const {
1044 TargetLowering::ArgListTy Args;
1045 Args.reserve(NumOps);
1047 TargetLowering::ArgListEntry Entry;
1048 for (unsigned i = 0; i != NumOps; ++i) {
1049 Entry.Node = Ops[i];
1050 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
1051 Entry.isSExt = isSigned;
1052 Entry.isZExt = !isSigned;
1053 Args.push_back(Entry);
1055 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), getPointerTy());
1057 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
1059 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
1060 false, 0, getLibcallCallingConv(LC),
1061 /*isTailCall=*/false,
1062 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
1063 Callee, Args, DAG, dl);
1064 std::pair<SDValue,SDValue> CallInfo = LowerCallTo(CLI);
1066 return CallInfo.first;
1070 /// SoftenSetCCOperands - Soften the operands of a comparison. This code is
1071 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
1072 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
1073 SDValue &NewLHS, SDValue &NewRHS,
1074 ISD::CondCode &CCCode,
1075 DebugLoc dl) const {
1076 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
1077 && "Unsupported setcc type!");
1079 // Expand into one or more soft-fp libcall(s).
1080 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
1084 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
1085 (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128;
1089 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
1090 (VT == MVT::f64) ? RTLIB::UNE_F64 : RTLIB::UNE_F128;
1094 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
1095 (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128;
1099 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
1100 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
1104 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
1105 (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128;
1109 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
1110 (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128;
1113 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
1114 (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128;
1117 LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
1118 (VT == MVT::f64) ? RTLIB::O_F64 : RTLIB::O_F128;
1121 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
1122 (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128;
1125 // SETONE = SETOLT | SETOGT
1126 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
1127 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
1130 LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
1131 (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128;
1134 LC2 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
1135 (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128;
1138 LC2 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
1139 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
1142 LC2 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
1143 (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128;
1146 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
1147 (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128;
1149 default: llvm_unreachable("Do not know how to soften this setcc!");
1153 // Use the target specific return value for comparions lib calls.
1154 EVT RetVT = getCmpLibcallReturnType();
1155 SDValue Ops[2] = { NewLHS, NewRHS };
1156 NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, 2, false/*sign irrelevant*/, dl);
1157 NewRHS = DAG.getConstant(0, RetVT);
1158 CCCode = getCmpLibcallCC(LC1);
1159 if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
1160 SDValue Tmp = DAG.getNode(ISD::SETCC, dl, getSetCCResultType(RetVT),
1161 NewLHS, NewRHS, DAG.getCondCode(CCCode));
1162 NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, 2, false/*sign irrelevant*/, dl);
1163 NewLHS = DAG.getNode(ISD::SETCC, dl, getSetCCResultType(RetVT), NewLHS,
1164 NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
1165 NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
1170 /// getVectorTypeBreakdown - Vector types are broken down into some number of
1171 /// legal first class types. For example, MVT::v8f32 maps to 2 MVT::v4f32
1172 /// with Altivec or SSE1, or 8 promoted MVT::f64 values with the X86 FP stack.
1173 /// Similarly, MVT::v2i64 turns into 4 MVT::i32 values with both PPC and X86.
1175 /// This method returns the number of registers needed, and the VT for each
1176 /// register. It also returns the VT and quantity of the intermediate values
1177 /// before they are promoted/expanded.
1179 unsigned TargetLowering::getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
1180 EVT &IntermediateVT,
1181 unsigned &NumIntermediates,
1182 MVT &RegisterVT) const {
1183 unsigned NumElts = VT.getVectorNumElements();
1185 // If there is a wider vector type with the same element type as this one,
1186 // or a promoted vector type that has the same number of elements which
1187 // are wider, then we should convert to that legal vector type.
1188 // This handles things like <2 x float> -> <4 x float> and
1189 // <4 x i1> -> <4 x i32>.
1190 LegalizeTypeAction TA = getTypeAction(Context, VT);
1191 if (NumElts != 1 && (TA == TypeWidenVector || TA == TypePromoteInteger)) {
1192 EVT RegisterEVT = getTypeToTransformTo(Context, VT);
1193 if (isTypeLegal(RegisterEVT)) {
1194 IntermediateVT = RegisterEVT;
1195 RegisterVT = RegisterEVT.getSimpleVT();
1196 NumIntermediates = 1;
1201 // Figure out the right, legal destination reg to copy into.
1202 EVT EltTy = VT.getVectorElementType();
1204 unsigned NumVectorRegs = 1;
1206 // FIXME: We don't support non-power-of-2-sized vectors for now. Ideally we
1207 // could break down into LHS/RHS like LegalizeDAG does.
1208 if (!isPowerOf2_32(NumElts)) {
1209 NumVectorRegs = NumElts;
1213 // Divide the input until we get to a supported size. This will always
1214 // end with a scalar if the target doesn't support vectors.
1215 while (NumElts > 1 && !isTypeLegal(
1216 EVT::getVectorVT(Context, EltTy, NumElts))) {
1218 NumVectorRegs <<= 1;
1221 NumIntermediates = NumVectorRegs;
1223 EVT NewVT = EVT::getVectorVT(Context, EltTy, NumElts);
1224 if (!isTypeLegal(NewVT))
1226 IntermediateVT = NewVT;
1228 MVT DestVT = getRegisterType(Context, NewVT);
1229 RegisterVT = DestVT;
1230 unsigned NewVTSize = NewVT.getSizeInBits();
1232 // Convert sizes such as i33 to i64.
1233 if (!isPowerOf2_32(NewVTSize))
1234 NewVTSize = NextPowerOf2(NewVTSize);
1236 if (EVT(DestVT).bitsLT(NewVT)) // Value is expanded, e.g. i64 -> i16.
1237 return NumVectorRegs*(NewVTSize/DestVT.getSizeInBits());
1239 // Otherwise, promotion or legal types use the same number of registers as
1240 // the vector decimated to the appropriate level.
1241 return NumVectorRegs;
1244 /// Get the EVTs and ArgFlags collections that represent the legalized return
1245 /// type of the given function. This does not require a DAG or a return value,
1246 /// and is suitable for use before any DAGs for the function are constructed.
1247 /// TODO: Move this out of TargetLowering.cpp.
1248 void llvm::GetReturnInfo(Type* ReturnType, AttributeSet attr,
1249 SmallVectorImpl<ISD::OutputArg> &Outs,
1250 const TargetLowering &TLI) {
1251 SmallVector<EVT, 4> ValueVTs;
1252 ComputeValueVTs(TLI, ReturnType, ValueVTs);
1253 unsigned NumValues = ValueVTs.size();
1254 if (NumValues == 0) return;
1256 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1257 EVT VT = ValueVTs[j];
1258 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1260 if (attr.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
1261 ExtendKind = ISD::SIGN_EXTEND;
1262 else if (attr.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt))
1263 ExtendKind = ISD::ZERO_EXTEND;
1265 // FIXME: C calling convention requires the return type to be promoted to
1266 // at least 32-bit. But this is not necessary for non-C calling
1267 // conventions. The frontend should mark functions whose return values
1268 // require promoting with signext or zeroext attributes.
1269 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
1270 MVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
1271 if (VT.bitsLT(MinVT))
1275 unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
1276 MVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
1278 // 'inreg' on function refers to return value
1279 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1280 if (attr.hasAttribute(AttributeSet::ReturnIndex, Attribute::InReg))
1283 // Propagate extension type if any
1284 if (attr.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
1286 else if (attr.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt))
1289 for (unsigned i = 0; i < NumParts; ++i)
1290 Outs.push_back(ISD::OutputArg(Flags, PartVT, /*isFixed=*/true, 0, 0));
1294 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1295 /// function arguments in the caller parameter area. This is the actual
1296 /// alignment, not its logarithm.
1297 unsigned TargetLowering::getByValTypeAlignment(Type *Ty) const {
1298 return TD->getCallFrameTypeAlignment(Ty);
1301 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1302 /// current function. The returned value is a member of the
1303 /// MachineJumpTableInfo::JTEntryKind enum.
1304 unsigned TargetLowering::getJumpTableEncoding() const {
1305 // In non-pic modes, just use the address of a block.
1306 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
1307 return MachineJumpTableInfo::EK_BlockAddress;
1309 // In PIC mode, if the target supports a GPRel32 directive, use it.
1310 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != 0)
1311 return MachineJumpTableInfo::EK_GPRel32BlockAddress;
1313 // Otherwise, use a label difference.
1314 return MachineJumpTableInfo::EK_LabelDifference32;
1317 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1318 SelectionDAG &DAG) const {
1319 // If our PIC model is GP relative, use the global offset table as the base.
1320 unsigned JTEncoding = getJumpTableEncoding();
1322 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
1323 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
1324 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(0));
1329 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1330 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1333 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
1334 unsigned JTI,MCContext &Ctx) const{
1335 // The normal PIC reloc base is the label at the start of the jump table.
1336 return MCSymbolRefExpr::Create(MF->getJTISymbol(JTI, Ctx), Ctx);
1340 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1341 // Assume that everything is safe in static mode.
1342 if (getTargetMachine().getRelocationModel() == Reloc::Static)
1345 // In dynamic-no-pic mode, assume that known defined values are safe.
1346 if (getTargetMachine().getRelocationModel() == Reloc::DynamicNoPIC &&
1348 !GA->getGlobal()->isDeclaration() &&
1349 !GA->getGlobal()->isWeakForLinker())
1352 // Otherwise assume nothing is safe.
1356 //===----------------------------------------------------------------------===//
1357 // TargetTransformInfo Helpers
1358 //===----------------------------------------------------------------------===//
1360 int TargetLowering::InstructionOpcodeToISD(unsigned Opcode) const {
1361 enum InstructionOpcodes {
1362 #define HANDLE_INST(NUM, OPCODE, CLASS) OPCODE = NUM,
1363 #define LAST_OTHER_INST(NUM) InstructionOpcodesCount = NUM
1364 #include "llvm/IR/Instruction.def"
1366 switch (static_cast<InstructionOpcodes>(Opcode)) {
1369 case Switch: return 0;
1370 case IndirectBr: return 0;
1371 case Invoke: return 0;
1372 case Resume: return 0;
1373 case Unreachable: return 0;
1374 case Add: return ISD::ADD;
1375 case FAdd: return ISD::FADD;
1376 case Sub: return ISD::SUB;
1377 case FSub: return ISD::FSUB;
1378 case Mul: return ISD::MUL;
1379 case FMul: return ISD::FMUL;
1380 case UDiv: return ISD::UDIV;
1381 case SDiv: return ISD::UDIV;
1382 case FDiv: return ISD::FDIV;
1383 case URem: return ISD::UREM;
1384 case SRem: return ISD::SREM;
1385 case FRem: return ISD::FREM;
1386 case Shl: return ISD::SHL;
1387 case LShr: return ISD::SRL;
1388 case AShr: return ISD::SRA;
1389 case And: return ISD::AND;
1390 case Or: return ISD::OR;
1391 case Xor: return ISD::XOR;
1392 case Alloca: return 0;
1393 case Load: return ISD::LOAD;
1394 case Store: return ISD::STORE;
1395 case GetElementPtr: return 0;
1396 case Fence: return 0;
1397 case AtomicCmpXchg: return 0;
1398 case AtomicRMW: return 0;
1399 case Trunc: return ISD::TRUNCATE;
1400 case ZExt: return ISD::ZERO_EXTEND;
1401 case SExt: return ISD::SIGN_EXTEND;
1402 case FPToUI: return ISD::FP_TO_UINT;
1403 case FPToSI: return ISD::FP_TO_SINT;
1404 case UIToFP: return ISD::UINT_TO_FP;
1405 case SIToFP: return ISD::SINT_TO_FP;
1406 case FPTrunc: return ISD::FP_ROUND;
1407 case FPExt: return ISD::FP_EXTEND;
1408 case PtrToInt: return ISD::BITCAST;
1409 case IntToPtr: return ISD::BITCAST;
1410 case BitCast: return ISD::BITCAST;
1411 case ICmp: return ISD::SETCC;
1412 case FCmp: return ISD::SETCC;
1414 case Call: return 0;
1415 case Select: return ISD::SELECT;
1416 case UserOp1: return 0;
1417 case UserOp2: return 0;
1418 case VAArg: return 0;
1419 case ExtractElement: return ISD::EXTRACT_VECTOR_ELT;
1420 case InsertElement: return ISD::INSERT_VECTOR_ELT;
1421 case ShuffleVector: return ISD::VECTOR_SHUFFLE;
1422 case ExtractValue: return ISD::MERGE_VALUES;
1423 case InsertValue: return ISD::MERGE_VALUES;
1424 case LandingPad: return 0;
1427 llvm_unreachable("Unknown instruction type encountered!");
1430 std::pair<unsigned, MVT>
1431 TargetLowering::getTypeLegalizationCost(Type *Ty) const {
1432 LLVMContext &C = Ty->getContext();
1433 EVT MTy = getValueType(Ty);
1436 // We keep legalizing the type until we find a legal kind. We assume that
1437 // the only operation that costs anything is the split. After splitting
1438 // we need to handle two types.
1440 LegalizeKind LK = getTypeConversion(C, MTy);
1442 if (LK.first == TypeLegal)
1443 return std::make_pair(Cost, MTy.getSimpleVT());
1445 if (LK.first == TypeSplitVector || LK.first == TypeExpandInteger)
1448 // Keep legalizing the type.
1453 //===----------------------------------------------------------------------===//
1454 // Optimization Methods
1455 //===----------------------------------------------------------------------===//
1457 /// ShrinkDemandedConstant - Check to see if the specified operand of the
1458 /// specified instruction is a constant integer. If so, check to see if there
1459 /// are any bits set in the constant that are not demanded. If so, shrink the
1460 /// constant and return true.
1461 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op,
1462 const APInt &Demanded) {
1463 DebugLoc dl = Op.getDebugLoc();
1465 // FIXME: ISD::SELECT, ISD::SELECT_CC
1466 switch (Op.getOpcode()) {
1471 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1472 if (!C) return false;
1474 if (Op.getOpcode() == ISD::XOR &&
1475 (C->getAPIntValue() | (~Demanded)).isAllOnesValue())
1478 // if we can expand it to have all bits set, do it
1479 if (C->getAPIntValue().intersects(~Demanded)) {
1480 EVT VT = Op.getValueType();
1481 SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0),
1482 DAG.getConstant(Demanded &
1485 return CombineTo(Op, New);
1495 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
1496 /// casts are free. This uses isZExtFree and ZERO_EXTEND for the widening
1497 /// cast, but it could be generalized for targets with other types of
1498 /// implicit widening casts.
1500 TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
1502 const APInt &Demanded,
1504 assert(Op.getNumOperands() == 2 &&
1505 "ShrinkDemandedOp only supports binary operators!");
1506 assert(Op.getNode()->getNumValues() == 1 &&
1507 "ShrinkDemandedOp only supports nodes with one result!");
1509 // Don't do this if the node has another user, which may require the
1511 if (!Op.getNode()->hasOneUse())
1514 // Search for the smallest integer type with free casts to and from
1515 // Op's type. For expedience, just check power-of-2 integer types.
1516 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1517 unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
1518 unsigned SmallVTBits = DemandedSize;
1519 if (!isPowerOf2_32(SmallVTBits))
1520 SmallVTBits = NextPowerOf2(SmallVTBits);
1521 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
1522 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
1523 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
1524 TLI.isZExtFree(SmallVT, Op.getValueType())) {
1525 // We found a type with free casts.
1526 SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
1527 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
1528 Op.getNode()->getOperand(0)),
1529 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
1530 Op.getNode()->getOperand(1)));
1531 bool NeedZext = DemandedSize > SmallVTBits;
1532 SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
1533 dl, Op.getValueType(), X);
1534 return CombineTo(Op, Z);
1540 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
1541 /// DemandedMask bits of the result of Op are ever used downstream. If we can
1542 /// use this information to simplify Op, create a new simplified DAG node and
1543 /// return true, returning the original and new nodes in Old and New. Otherwise,
1544 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
1545 /// the expression (used to simplify the caller). The KnownZero/One bits may
1546 /// only be accurate for those bits in the DemandedMask.
1547 bool TargetLowering::SimplifyDemandedBits(SDValue Op,
1548 const APInt &DemandedMask,
1551 TargetLoweringOpt &TLO,
1552 unsigned Depth) const {
1553 unsigned BitWidth = DemandedMask.getBitWidth();
1554 assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth &&
1555 "Mask size mismatches value type size!");
1556 APInt NewMask = DemandedMask;
1557 DebugLoc dl = Op.getDebugLoc();
1559 // Don't know anything.
1560 KnownZero = KnownOne = APInt(BitWidth, 0);
1562 // Other users may use these bits.
1563 if (!Op.getNode()->hasOneUse()) {
1565 // If not at the root, Just compute the KnownZero/KnownOne bits to
1566 // simplify things downstream.
1567 TLO.DAG.ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
1570 // If this is the root being simplified, allow it to have multiple uses,
1571 // just set the NewMask to all bits.
1572 NewMask = APInt::getAllOnesValue(BitWidth);
1573 } else if (DemandedMask == 0) {
1574 // Not demanding any bits from Op.
1575 if (Op.getOpcode() != ISD::UNDEF)
1576 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
1578 } else if (Depth == 6) { // Limit search depth.
1582 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
1583 switch (Op.getOpcode()) {
1585 // We know all of the bits for a constant!
1586 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
1587 KnownZero = ~KnownOne;
1588 return false; // Don't fall through, will infinitely loop.
1590 // If the RHS is a constant, check to see if the LHS would be zero without
1591 // using the bits from the RHS. Below, we use knowledge about the RHS to
1592 // simplify the LHS, here we're using information from the LHS to simplify
1594 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1595 APInt LHSZero, LHSOne;
1596 // Do not increment Depth here; that can cause an infinite loop.
1597 TLO.DAG.ComputeMaskedBits(Op.getOperand(0), LHSZero, LHSOne, Depth);
1598 // If the LHS already has zeros where RHSC does, this and is dead.
1599 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
1600 return TLO.CombineTo(Op, Op.getOperand(0));
1601 // If any of the set bits in the RHS are known zero on the LHS, shrink
1603 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
1607 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
1608 KnownOne, TLO, Depth+1))
1610 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1611 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
1612 KnownZero2, KnownOne2, TLO, Depth+1))
1614 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1616 // If all of the demanded bits are known one on one side, return the other.
1617 // These bits cannot contribute to the result of the 'and'.
1618 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
1619 return TLO.CombineTo(Op, Op.getOperand(0));
1620 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
1621 return TLO.CombineTo(Op, Op.getOperand(1));
1622 // If all of the demanded bits in the inputs are known zeros, return zero.
1623 if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
1624 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType()));
1625 // If the RHS is a constant, see if we can simplify it.
1626 if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
1628 // If the operation can be done in a smaller type, do so.
1629 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1632 // Output known-1 bits are only known if set in both the LHS & RHS.
1633 KnownOne &= KnownOne2;
1634 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1635 KnownZero |= KnownZero2;
1638 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
1639 KnownOne, TLO, Depth+1))
1641 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1642 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
1643 KnownZero2, KnownOne2, TLO, Depth+1))
1645 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1647 // If all of the demanded bits are known zero on one side, return the other.
1648 // These bits cannot contribute to the result of the 'or'.
1649 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
1650 return TLO.CombineTo(Op, Op.getOperand(0));
1651 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
1652 return TLO.CombineTo(Op, Op.getOperand(1));
1653 // If all of the potentially set bits on one side are known to be set on
1654 // the other side, just use the 'other' side.
1655 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
1656 return TLO.CombineTo(Op, Op.getOperand(0));
1657 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
1658 return TLO.CombineTo(Op, Op.getOperand(1));
1659 // If the RHS is a constant, see if we can simplify it.
1660 if (TLO.ShrinkDemandedConstant(Op, NewMask))
1662 // If the operation can be done in a smaller type, do so.
1663 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1666 // Output known-0 bits are only known if clear in both the LHS & RHS.
1667 KnownZero &= KnownZero2;
1668 // Output known-1 are known to be set if set in either the LHS | RHS.
1669 KnownOne |= KnownOne2;
1672 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
1673 KnownOne, TLO, Depth+1))
1675 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1676 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
1677 KnownOne2, TLO, Depth+1))
1679 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1681 // If all of the demanded bits are known zero on one side, return the other.
1682 // These bits cannot contribute to the result of the 'xor'.
1683 if ((KnownZero & NewMask) == NewMask)
1684 return TLO.CombineTo(Op, Op.getOperand(0));
1685 if ((KnownZero2 & NewMask) == NewMask)
1686 return TLO.CombineTo(Op, Op.getOperand(1));
1687 // If the operation can be done in a smaller type, do so.
1688 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1691 // If all of the unknown bits are known to be zero on one side or the other
1692 // (but not both) turn this into an *inclusive* or.
1693 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1694 if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
1695 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
1699 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1700 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1701 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1702 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1704 // If all of the demanded bits on one side are known, and all of the set
1705 // bits on that side are also known to be set on the other side, turn this
1706 // into an AND, as we know the bits will be cleared.
1707 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1708 // NB: it is okay if more bits are known than are requested
1709 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
1710 if (KnownOne == KnownOne2) { // set bits are the same on both sides
1711 EVT VT = Op.getValueType();
1712 SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, VT);
1713 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
1714 Op.getOperand(0), ANDC));
1718 // If the RHS is a constant, see if we can simplify it.
1719 // for XOR, we prefer to force bits to 1 if they will make a -1.
1720 // if we can't force bits, try to shrink constant
1721 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1722 APInt Expanded = C->getAPIntValue() | (~NewMask);
1723 // if we can expand it to have all bits set, do it
1724 if (Expanded.isAllOnesValue()) {
1725 if (Expanded != C->getAPIntValue()) {
1726 EVT VT = Op.getValueType();
1727 SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
1728 TLO.DAG.getConstant(Expanded, VT));
1729 return TLO.CombineTo(Op, New);
1731 // if it already has all the bits set, nothing to change
1732 // but don't shrink either!
1733 } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
1738 KnownZero = KnownZeroOut;
1739 KnownOne = KnownOneOut;
1742 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
1743 KnownOne, TLO, Depth+1))
1745 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
1746 KnownOne2, TLO, Depth+1))
1748 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1749 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1751 // If the operands are constants, see if we can simplify them.
1752 if (TLO.ShrinkDemandedConstant(Op, NewMask))
1755 // Only known if known in both the LHS and RHS.
1756 KnownOne &= KnownOne2;
1757 KnownZero &= KnownZero2;
1759 case ISD::SELECT_CC:
1760 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
1761 KnownOne, TLO, Depth+1))
1763 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
1764 KnownOne2, TLO, Depth+1))
1766 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1767 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1769 // If the operands are constants, see if we can simplify them.
1770 if (TLO.ShrinkDemandedConstant(Op, NewMask))
1773 // Only known if known in both the LHS and RHS.
1774 KnownOne &= KnownOne2;
1775 KnownZero &= KnownZero2;
1778 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1779 unsigned ShAmt = SA->getZExtValue();
1780 SDValue InOp = Op.getOperand(0);
1782 // If the shift count is an invalid immediate, don't do anything.
1783 if (ShAmt >= BitWidth)
1786 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1787 // single shift. We can do this if the bottom bits (which are shifted
1788 // out) are never demanded.
1789 if (InOp.getOpcode() == ISD::SRL &&
1790 isa<ConstantSDNode>(InOp.getOperand(1))) {
1791 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
1792 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
1793 unsigned Opc = ISD::SHL;
1794 int Diff = ShAmt-C1;
1801 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
1802 EVT VT = Op.getValueType();
1803 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
1804 InOp.getOperand(0), NewSA));
1808 if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
1809 KnownZero, KnownOne, TLO, Depth+1))
1812 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1813 // are not demanded. This will likely allow the anyext to be folded away.
1814 if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
1815 SDValue InnerOp = InOp.getNode()->getOperand(0);
1816 EVT InnerVT = InnerOp.getValueType();
1817 unsigned InnerBits = InnerVT.getSizeInBits();
1818 if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 &&
1819 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
1820 EVT ShTy = getShiftAmountTy(InnerVT);
1821 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
1824 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
1825 TLO.DAG.getConstant(ShAmt, ShTy));
1828 TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
1833 KnownZero <<= SA->getZExtValue();
1834 KnownOne <<= SA->getZExtValue();
1835 // low bits known zero.
1836 KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
1840 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1841 EVT VT = Op.getValueType();
1842 unsigned ShAmt = SA->getZExtValue();
1843 unsigned VTSize = VT.getSizeInBits();
1844 SDValue InOp = Op.getOperand(0);
1846 // If the shift count is an invalid immediate, don't do anything.
1847 if (ShAmt >= BitWidth)
1850 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
1851 // single shift. We can do this if the top bits (which are shifted out)
1852 // are never demanded.
1853 if (InOp.getOpcode() == ISD::SHL &&
1854 isa<ConstantSDNode>(InOp.getOperand(1))) {
1855 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
1856 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
1857 unsigned Opc = ISD::SRL;
1858 int Diff = ShAmt-C1;
1865 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
1866 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
1867 InOp.getOperand(0), NewSA));
1871 // Compute the new bits that are at the top now.
1872 if (SimplifyDemandedBits(InOp, (NewMask << ShAmt),
1873 KnownZero, KnownOne, TLO, Depth+1))
1875 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1876 KnownZero = KnownZero.lshr(ShAmt);
1877 KnownOne = KnownOne.lshr(ShAmt);
1879 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
1880 KnownZero |= HighBits; // High bits known zero.
1884 // If this is an arithmetic shift right and only the low-bit is set, we can
1885 // always convert this into a logical shr, even if the shift amount is
1886 // variable. The low bit of the shift cannot be an input sign bit unless
1887 // the shift amount is >= the size of the datatype, which is undefined.
1889 return TLO.CombineTo(Op,
1890 TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
1891 Op.getOperand(0), Op.getOperand(1)));
1893 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1894 EVT VT = Op.getValueType();
1895 unsigned ShAmt = SA->getZExtValue();
1897 // If the shift count is an invalid immediate, don't do anything.
1898 if (ShAmt >= BitWidth)
1901 APInt InDemandedMask = (NewMask << ShAmt);
1903 // If any of the demanded bits are produced by the sign extension, we also
1904 // demand the input sign bit.
1905 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
1906 if (HighBits.intersects(NewMask))
1907 InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits());
1909 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
1910 KnownZero, KnownOne, TLO, Depth+1))
1912 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1913 KnownZero = KnownZero.lshr(ShAmt);
1914 KnownOne = KnownOne.lshr(ShAmt);
1916 // Handle the sign bit, adjusted to where it is now in the mask.
1917 APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
1919 // If the input sign bit is known to be zero, or if none of the top bits
1920 // are demanded, turn this into an unsigned shift right.
1921 if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
1922 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
1925 } else if (KnownOne.intersects(SignBit)) { // New bits are known one.
1926 KnownOne |= HighBits;
1930 case ISD::SIGN_EXTEND_INREG: {
1931 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1933 APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
1934 // If we only care about the highest bit, don't bother shifting right.
1935 if (MsbMask == DemandedMask) {
1936 unsigned ShAmt = ExVT.getScalarType().getSizeInBits();
1937 SDValue InOp = Op.getOperand(0);
1939 // Compute the correct shift amount type, which must be getShiftAmountTy
1940 // for scalar types after legalization.
1941 EVT ShiftAmtTy = Op.getValueType();
1942 if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
1943 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy);
1945 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, ShiftAmtTy);
1946 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1947 Op.getValueType(), InOp, ShiftAmt));
1950 // Sign extension. Compute the demanded bits in the result that are not
1951 // present in the input.
1953 APInt::getHighBitsSet(BitWidth,
1954 BitWidth - ExVT.getScalarType().getSizeInBits());
1956 // If none of the extended bits are demanded, eliminate the sextinreg.
1957 if ((NewBits & NewMask) == 0)
1958 return TLO.CombineTo(Op, Op.getOperand(0));
1961 APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidth);
1962 APInt InputDemandedBits =
1963 APInt::getLowBitsSet(BitWidth,
1964 ExVT.getScalarType().getSizeInBits()) &
1967 // Since the sign extended bits are demanded, we know that the sign
1969 InputDemandedBits |= InSignBit;
1971 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
1972 KnownZero, KnownOne, TLO, Depth+1))
1974 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1976 // If the sign bit of the input is known set or clear, then we know the
1977 // top bits of the result.
1979 // If the input sign bit is known zero, convert this into a zero extension.
1980 if (KnownZero.intersects(InSignBit))
1981 return TLO.CombineTo(Op,
1982 TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,ExVT));
1984 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1985 KnownOne |= NewBits;
1986 KnownZero &= ~NewBits;
1987 } else { // Input sign bit unknown
1988 KnownZero &= ~NewBits;
1989 KnownOne &= ~NewBits;
1993 case ISD::ZERO_EXTEND: {
1994 unsigned OperandBitWidth =
1995 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
1996 APInt InMask = NewMask.trunc(OperandBitWidth);
1998 // If none of the top bits are demanded, convert this into an any_extend.
2000 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
2001 if (!NewBits.intersects(NewMask))
2002 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
2006 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
2007 KnownZero, KnownOne, TLO, Depth+1))
2009 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
2010 KnownZero = KnownZero.zext(BitWidth);
2011 KnownOne = KnownOne.zext(BitWidth);
2012 KnownZero |= NewBits;
2015 case ISD::SIGN_EXTEND: {
2016 EVT InVT = Op.getOperand(0).getValueType();
2017 unsigned InBits = InVT.getScalarType().getSizeInBits();
2018 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits);
2019 APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
2020 APInt NewBits = ~InMask & NewMask;
2022 // If none of the top bits are demanded, convert this into an any_extend.
2024 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
2028 // Since some of the sign extended bits are demanded, we know that the sign
2030 APInt InDemandedBits = InMask & NewMask;
2031 InDemandedBits |= InSignBit;
2032 InDemandedBits = InDemandedBits.trunc(InBits);
2034 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
2035 KnownOne, TLO, Depth+1))
2037 KnownZero = KnownZero.zext(BitWidth);
2038 KnownOne = KnownOne.zext(BitWidth);
2040 // If the sign bit is known zero, convert this to a zero extend.
2041 if (KnownZero.intersects(InSignBit))
2042 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
2046 // If the sign bit is known one, the top bits match.
2047 if (KnownOne.intersects(InSignBit)) {
2048 KnownOne |= NewBits;
2049 assert((KnownZero & NewBits) == 0);
2050 } else { // Otherwise, top bits aren't known.
2051 assert((KnownOne & NewBits) == 0);
2052 assert((KnownZero & NewBits) == 0);
2056 case ISD::ANY_EXTEND: {
2057 unsigned OperandBitWidth =
2058 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
2059 APInt InMask = NewMask.trunc(OperandBitWidth);
2060 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
2061 KnownZero, KnownOne, TLO, Depth+1))
2063 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
2064 KnownZero = KnownZero.zext(BitWidth);
2065 KnownOne = KnownOne.zext(BitWidth);
2068 case ISD::TRUNCATE: {
2069 // Simplify the input, using demanded bit information, and compute the known
2070 // zero/one bits live out.
2071 unsigned OperandBitWidth =
2072 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
2073 APInt TruncMask = NewMask.zext(OperandBitWidth);
2074 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
2075 KnownZero, KnownOne, TLO, Depth+1))
2077 KnownZero = KnownZero.trunc(BitWidth);
2078 KnownOne = KnownOne.trunc(BitWidth);
2080 // If the input is only used by this truncate, see if we can shrink it based
2081 // on the known demanded bits.
2082 if (Op.getOperand(0).getNode()->hasOneUse()) {
2083 SDValue In = Op.getOperand(0);
2084 switch (In.getOpcode()) {
2087 // Shrink SRL by a constant if none of the high bits shifted in are
2089 if (TLO.LegalTypes() &&
2090 !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
2091 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
2094 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
2097 SDValue Shift = In.getOperand(1);
2098 if (TLO.LegalTypes()) {
2099 uint64_t ShVal = ShAmt->getZExtValue();
2101 TLO.DAG.getConstant(ShVal, getShiftAmountTy(Op.getValueType()));
2104 APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
2105 OperandBitWidth - BitWidth);
2106 HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
2108 if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
2109 // None of the shifted in bits are needed. Add a truncate of the
2110 // shift input, then shift it.
2111 SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
2114 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
2123 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
2126 case ISD::AssertZext: {
2127 // AssertZext demands all of the high bits, plus any of the low bits
2128 // demanded by its users.
2129 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2130 APInt InMask = APInt::getLowBitsSet(BitWidth,
2131 VT.getSizeInBits());
2132 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
2133 KnownZero, KnownOne, TLO, Depth+1))
2135 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
2137 KnownZero |= ~InMask & NewMask;
2141 // If this is an FP->Int bitcast and if the sign bit is the only
2142 // thing demanded, turn this into a FGETSIGN.
2143 if (!TLO.LegalOperations() &&
2144 !Op.getValueType().isVector() &&
2145 !Op.getOperand(0).getValueType().isVector() &&
2146 NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) &&
2147 Op.getOperand(0).getValueType().isFloatingPoint()) {
2148 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
2149 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
2150 if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple()) {
2151 EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
2152 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
2153 // place. We expect the SHL to be eliminated by other optimizations.
2154 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
2155 unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits();
2156 if (!OpVTLegal && OpVTSizeInBits > 32)
2157 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
2158 unsigned ShVal = Op.getValueType().getSizeInBits()-1;
2159 SDValue ShAmt = TLO.DAG.getConstant(ShVal, Op.getValueType());
2160 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
2169 // Add, Sub, and Mul don't demand any bits in positions beyond that
2170 // of the highest bit demanded of them.
2171 APInt LoMask = APInt::getLowBitsSet(BitWidth,
2172 BitWidth - NewMask.countLeadingZeros());
2173 if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
2174 KnownOne2, TLO, Depth+1))
2176 if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
2177 KnownOne2, TLO, Depth+1))
2179 // See if the operation should be performed at a smaller bit width.
2180 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
2185 // Just use ComputeMaskedBits to compute output bits.
2186 TLO.DAG.ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
2190 // If we know the value of all of the demanded bits, return this as a
2192 if ((NewMask & (KnownZero|KnownOne)) == NewMask)
2193 return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
2198 /// computeMaskedBitsForTargetNode - Determine which of the bits specified
2199 /// in Mask are known to be either zero or one and return them in the
2200 /// KnownZero/KnownOne bitsets.
2201 void TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
2204 const SelectionDAG &DAG,
2205 unsigned Depth) const {
2206 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2207 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2208 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2209 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2210 "Should use MaskedValueIsZero if you don't know whether Op"
2211 " is a target node!");
2212 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
2215 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
2216 /// targets that want to expose additional information about sign bits to the
2218 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
2219 unsigned Depth) const {
2220 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2221 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2222 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2223 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2224 "Should use ComputeNumSignBits if you don't know whether Op"
2225 " is a target node!");
2229 /// ValueHasExactlyOneBitSet - Test if the given value is known to have exactly
2230 /// one bit set. This differs from ComputeMaskedBits in that it doesn't need to
2231 /// determine which bit is set.
2233 static bool ValueHasExactlyOneBitSet(SDValue Val, const SelectionDAG &DAG) {
2234 // A left-shift of a constant one will have exactly one bit set, because
2235 // shifting the bit off the end is undefined.
2236 if (Val.getOpcode() == ISD::SHL)
2237 if (ConstantSDNode *C =
2238 dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
2239 if (C->getAPIntValue() == 1)
2242 // Similarly, a right-shift of a constant sign-bit will have exactly
2244 if (Val.getOpcode() == ISD::SRL)
2245 if (ConstantSDNode *C =
2246 dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
2247 if (C->getAPIntValue().isSignBit())
2250 // More could be done here, though the above checks are enough
2251 // to handle some common cases.
2253 // Fall back to ComputeMaskedBits to catch other known cases.
2254 EVT OpVT = Val.getValueType();
2255 unsigned BitWidth = OpVT.getScalarType().getSizeInBits();
2256 APInt KnownZero, KnownOne;
2257 DAG.ComputeMaskedBits(Val, KnownZero, KnownOne);
2258 return (KnownZero.countPopulation() == BitWidth - 1) &&
2259 (KnownOne.countPopulation() == 1);
2262 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
2263 /// and cc. If it is unable to simplify it, return a null SDValue.
2265 TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
2266 ISD::CondCode Cond, bool foldBooleans,
2267 DAGCombinerInfo &DCI, DebugLoc dl) const {
2268 SelectionDAG &DAG = DCI.DAG;
2270 // These setcc operations always fold.
2274 case ISD::SETFALSE2: return DAG.getConstant(0, VT);
2276 case ISD::SETTRUE2: return DAG.getConstant(1, VT);
2279 // Ensure that the constant occurs on the RHS, and fold constant
2281 if (isa<ConstantSDNode>(N0.getNode()))
2282 return DAG.getSetCC(dl, VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
2284 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
2285 const APInt &C1 = N1C->getAPIntValue();
2287 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
2288 // equality comparison, then we're just comparing whether X itself is
2290 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
2291 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
2292 N0.getOperand(1).getOpcode() == ISD::Constant) {
2294 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2295 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2296 ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
2297 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
2298 // (srl (ctlz x), 5) == 0 -> X != 0
2299 // (srl (ctlz x), 5) != 1 -> X != 0
2302 // (srl (ctlz x), 5) != 0 -> X == 0
2303 // (srl (ctlz x), 5) == 1 -> X == 0
2306 SDValue Zero = DAG.getConstant(0, N0.getValueType());
2307 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
2313 // Look through truncs that don't change the value of a ctpop.
2314 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
2315 CTPOP = N0.getOperand(0);
2317 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
2318 (N0 == CTPOP || N0.getValueType().getSizeInBits() >
2319 Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) {
2320 EVT CTVT = CTPOP.getValueType();
2321 SDValue CTOp = CTPOP.getOperand(0);
2323 // (ctpop x) u< 2 -> (x & x-1) == 0
2324 // (ctpop x) u> 1 -> (x & x-1) != 0
2325 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
2326 SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
2327 DAG.getConstant(1, CTVT));
2328 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
2329 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
2330 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, CTVT), CC);
2333 // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
2336 // (zext x) == C --> x == (trunc C)
2337 if (DCI.isBeforeLegalize() && N0->hasOneUse() &&
2338 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
2339 unsigned MinBits = N0.getValueSizeInBits();
2341 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
2343 MinBits = N0->getOperand(0).getValueSizeInBits();
2344 PreZExt = N0->getOperand(0);
2345 } else if (N0->getOpcode() == ISD::AND) {
2346 // DAGCombine turns costly ZExts into ANDs
2347 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
2348 if ((C->getAPIntValue()+1).isPowerOf2()) {
2349 MinBits = C->getAPIntValue().countTrailingOnes();
2350 PreZExt = N0->getOperand(0);
2352 } else if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(N0)) {
2354 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
2355 MinBits = LN0->getMemoryVT().getSizeInBits();
2360 // Make sure we're not losing bits from the constant.
2361 if (MinBits < C1.getBitWidth() && MinBits > C1.getActiveBits()) {
2362 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
2363 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
2364 // Will get folded away.
2365 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreZExt);
2366 SDValue C = DAG.getConstant(C1.trunc(MinBits), MinVT);
2367 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
2372 // If the LHS is '(and load, const)', the RHS is 0,
2373 // the test is for equality or unsigned, and all 1 bits of the const are
2374 // in the same partial word, see if we can shorten the load.
2375 if (DCI.isBeforeLegalize() &&
2376 N0.getOpcode() == ISD::AND && C1 == 0 &&
2377 N0.getNode()->hasOneUse() &&
2378 isa<LoadSDNode>(N0.getOperand(0)) &&
2379 N0.getOperand(0).getNode()->hasOneUse() &&
2380 isa<ConstantSDNode>(N0.getOperand(1))) {
2381 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
2383 unsigned bestWidth = 0, bestOffset = 0;
2384 if (!Lod->isVolatile() && Lod->isUnindexed()) {
2385 unsigned origWidth = N0.getValueType().getSizeInBits();
2386 unsigned maskWidth = origWidth;
2387 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
2388 // 8 bits, but have to be careful...
2389 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
2390 origWidth = Lod->getMemoryVT().getSizeInBits();
2392 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2393 for (unsigned width = origWidth / 2; width>=8; width /= 2) {
2394 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
2395 for (unsigned offset=0; offset<origWidth/width; offset++) {
2396 if ((newMask & Mask) == Mask) {
2397 if (!TD->isLittleEndian())
2398 bestOffset = (origWidth/width - offset - 1) * (width/8);
2400 bestOffset = (uint64_t)offset * (width/8);
2401 bestMask = Mask.lshr(offset * (width/8) * 8);
2405 newMask = newMask << width;
2410 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
2411 if (newVT.isRound()) {
2412 EVT PtrType = Lod->getOperand(1).getValueType();
2413 SDValue Ptr = Lod->getBasePtr();
2414 if (bestOffset != 0)
2415 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
2416 DAG.getConstant(bestOffset, PtrType));
2417 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
2418 SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
2419 Lod->getPointerInfo().getWithOffset(bestOffset),
2420 false, false, false, NewAlign);
2421 return DAG.getSetCC(dl, VT,
2422 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
2423 DAG.getConstant(bestMask.trunc(bestWidth),
2425 DAG.getConstant(0LL, newVT), Cond);
2430 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
2431 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
2432 unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
2434 // If the comparison constant has bits in the upper part, the
2435 // zero-extended value could never match.
2436 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
2437 C1.getBitWidth() - InSize))) {
2441 case ISD::SETEQ: return DAG.getConstant(0, VT);
2444 case ISD::SETNE: return DAG.getConstant(1, VT);
2447 // True if the sign bit of C1 is set.
2448 return DAG.getConstant(C1.isNegative(), VT);
2451 // True if the sign bit of C1 isn't set.
2452 return DAG.getConstant(C1.isNonNegative(), VT);
2458 // Otherwise, we can perform the comparison with the low bits.
2466 EVT newVT = N0.getOperand(0).getValueType();
2467 if (DCI.isBeforeLegalizeOps() ||
2468 (isOperationLegal(ISD::SETCC, newVT) &&
2469 getCondCodeAction(Cond, newVT.getSimpleVT())==Legal))
2470 return DAG.getSetCC(dl, VT, N0.getOperand(0),
2471 DAG.getConstant(C1.trunc(InSize), newVT),
2476 break; // todo, be more careful with signed comparisons
2478 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2479 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
2480 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
2481 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
2482 EVT ExtDstTy = N0.getValueType();
2483 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
2485 // If the constant doesn't fit into the number of bits for the source of
2486 // the sign extension, it is impossible for both sides to be equal.
2487 if (C1.getMinSignedBits() > ExtSrcTyBits)
2488 return DAG.getConstant(Cond == ISD::SETNE, VT);
2491 EVT Op0Ty = N0.getOperand(0).getValueType();
2492 if (Op0Ty == ExtSrcTy) {
2493 ZextOp = N0.getOperand(0);
2495 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
2496 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
2497 DAG.getConstant(Imm, Op0Ty));
2499 if (!DCI.isCalledByLegalizer())
2500 DCI.AddToWorklist(ZextOp.getNode());
2501 // Otherwise, make this a use of a zext.
2502 return DAG.getSetCC(dl, VT, ZextOp,
2503 DAG.getConstant(C1 & APInt::getLowBitsSet(
2508 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
2509 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
2510 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
2511 if (N0.getOpcode() == ISD::SETCC &&
2512 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
2513 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
2515 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
2516 // Invert the condition.
2517 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
2518 CC = ISD::getSetCCInverse(CC,
2519 N0.getOperand(0).getValueType().isInteger());
2520 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
2523 if ((N0.getOpcode() == ISD::XOR ||
2524 (N0.getOpcode() == ISD::AND &&
2525 N0.getOperand(0).getOpcode() == ISD::XOR &&
2526 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
2527 isa<ConstantSDNode>(N0.getOperand(1)) &&
2528 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
2529 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
2530 // can only do this if the top bits are known zero.
2531 unsigned BitWidth = N0.getValueSizeInBits();
2532 if (DAG.MaskedValueIsZero(N0,
2533 APInt::getHighBitsSet(BitWidth,
2535 // Okay, get the un-inverted input value.
2537 if (N0.getOpcode() == ISD::XOR)
2538 Val = N0.getOperand(0);
2540 assert(N0.getOpcode() == ISD::AND &&
2541 N0.getOperand(0).getOpcode() == ISD::XOR);
2542 // ((X^1)&1)^1 -> X & 1
2543 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
2544 N0.getOperand(0).getOperand(0),
2548 return DAG.getSetCC(dl, VT, Val, N1,
2549 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2551 } else if (N1C->getAPIntValue() == 1 &&
2553 getBooleanContents(false) == ZeroOrOneBooleanContent)) {
2555 if (Op0.getOpcode() == ISD::TRUNCATE)
2556 Op0 = Op0.getOperand(0);
2558 if ((Op0.getOpcode() == ISD::XOR) &&
2559 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
2560 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
2561 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
2562 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
2563 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
2566 if (Op0.getOpcode() == ISD::AND &&
2567 isa<ConstantSDNode>(Op0.getOperand(1)) &&
2568 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
2569 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
2570 if (Op0.getValueType().bitsGT(VT))
2571 Op0 = DAG.getNode(ISD::AND, dl, VT,
2572 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
2573 DAG.getConstant(1, VT));
2574 else if (Op0.getValueType().bitsLT(VT))
2575 Op0 = DAG.getNode(ISD::AND, dl, VT,
2576 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
2577 DAG.getConstant(1, VT));
2579 return DAG.getSetCC(dl, VT, Op0,
2580 DAG.getConstant(0, Op0.getValueType()),
2581 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2583 if (Op0.getOpcode() == ISD::AssertZext &&
2584 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
2585 return DAG.getSetCC(dl, VT, Op0,
2586 DAG.getConstant(0, Op0.getValueType()),
2587 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
2591 APInt MinVal, MaxVal;
2592 unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
2593 if (ISD::isSignedIntSetCC(Cond)) {
2594 MinVal = APInt::getSignedMinValue(OperandBitSize);
2595 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
2597 MinVal = APInt::getMinValue(OperandBitSize);
2598 MaxVal = APInt::getMaxValue(OperandBitSize);
2601 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
2602 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
2603 if (C1 == MinVal) return DAG.getConstant(1, VT); // X >= MIN --> true
2604 // X >= C0 --> X > (C0-1)
2605 return DAG.getSetCC(dl, VT, N0,
2606 DAG.getConstant(C1-1, N1.getValueType()),
2607 (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
2610 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
2611 if (C1 == MaxVal) return DAG.getConstant(1, VT); // X <= MAX --> true
2612 // X <= C0 --> X < (C0+1)
2613 return DAG.getSetCC(dl, VT, N0,
2614 DAG.getConstant(C1+1, N1.getValueType()),
2615 (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
2618 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
2619 return DAG.getConstant(0, VT); // X < MIN --> false
2620 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
2621 return DAG.getConstant(1, VT); // X >= MIN --> true
2622 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
2623 return DAG.getConstant(0, VT); // X > MAX --> false
2624 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
2625 return DAG.getConstant(1, VT); // X <= MAX --> true
2627 // Canonicalize setgt X, Min --> setne X, Min
2628 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
2629 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
2630 // Canonicalize setlt X, Max --> setne X, Max
2631 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
2632 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
2634 // If we have setult X, 1, turn it into seteq X, 0
2635 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
2636 return DAG.getSetCC(dl, VT, N0,
2637 DAG.getConstant(MinVal, N0.getValueType()),
2639 // If we have setugt X, Max-1, turn it into seteq X, Max
2640 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
2641 return DAG.getSetCC(dl, VT, N0,
2642 DAG.getConstant(MaxVal, N0.getValueType()),
2645 // If we have "setcc X, C0", check to see if we can shrink the immediate
2648 // SETUGT X, SINTMAX -> SETLT X, 0
2649 if (Cond == ISD::SETUGT &&
2650 C1 == APInt::getSignedMaxValue(OperandBitSize))
2651 return DAG.getSetCC(dl, VT, N0,
2652 DAG.getConstant(0, N1.getValueType()),
2655 // SETULT X, SINTMIN -> SETGT X, -1
2656 if (Cond == ISD::SETULT &&
2657 C1 == APInt::getSignedMinValue(OperandBitSize)) {
2658 SDValue ConstMinusOne =
2659 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize),
2661 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
2664 // Fold bit comparisons when we can.
2665 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2666 (VT == N0.getValueType() ||
2667 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
2668 N0.getOpcode() == ISD::AND)
2669 if (ConstantSDNode *AndRHS =
2670 dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2671 EVT ShiftTy = DCI.isBeforeLegalizeOps() ?
2672 getPointerTy() : getShiftAmountTy(N0.getValueType());
2673 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
2674 // Perform the xform if the AND RHS is a single bit.
2675 if (AndRHS->getAPIntValue().isPowerOf2()) {
2676 return DAG.getNode(ISD::TRUNCATE, dl, VT,
2677 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2678 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), ShiftTy)));
2680 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
2681 // (X & 8) == 8 --> (X & 8) >> 3
2682 // Perform the xform if C1 is a single bit.
2683 if (C1.isPowerOf2()) {
2684 return DAG.getNode(ISD::TRUNCATE, dl, VT,
2685 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2686 DAG.getConstant(C1.logBase2(), ShiftTy)));
2691 if (C1.getMinSignedBits() <= 64 &&
2692 !isLegalICmpImmediate(C1.getSExtValue())) {
2693 // (X & -256) == 256 -> (X >> 8) == 1
2694 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2695 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
2696 if (ConstantSDNode *AndRHS =
2697 dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2698 const APInt &AndRHSC = AndRHS->getAPIntValue();
2699 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
2700 unsigned ShiftBits = AndRHSC.countTrailingZeros();
2701 EVT ShiftTy = DCI.isBeforeLegalizeOps() ?
2702 getPointerTy() : getShiftAmountTy(N0.getValueType());
2703 EVT CmpTy = N0.getValueType();
2704 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
2705 DAG.getConstant(ShiftBits, ShiftTy));
2706 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), CmpTy);
2707 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
2710 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
2711 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
2712 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
2713 // X < 0x100000000 -> (X >> 32) < 1
2714 // X >= 0x100000000 -> (X >> 32) >= 1
2715 // X <= 0x0ffffffff -> (X >> 32) < 1
2716 // X > 0x0ffffffff -> (X >> 32) >= 1
2719 ISD::CondCode NewCond = Cond;
2721 ShiftBits = C1.countTrailingOnes();
2723 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2725 ShiftBits = C1.countTrailingZeros();
2727 NewC = NewC.lshr(ShiftBits);
2728 if (ShiftBits && isLegalICmpImmediate(NewC.getSExtValue())) {
2729 EVT ShiftTy = DCI.isBeforeLegalizeOps() ?
2730 getPointerTy() : getShiftAmountTy(N0.getValueType());
2731 EVT CmpTy = N0.getValueType();
2732 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
2733 DAG.getConstant(ShiftBits, ShiftTy));
2734 SDValue CmpRHS = DAG.getConstant(NewC, CmpTy);
2735 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
2741 if (isa<ConstantFPSDNode>(N0.getNode())) {
2742 // Constant fold or commute setcc.
2743 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
2744 if (O.getNode()) return O;
2745 } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
2746 // If the RHS of an FP comparison is a constant, simplify it away in
2748 if (CFP->getValueAPF().isNaN()) {
2749 // If an operand is known to be a nan, we can fold it.
2750 switch (ISD::getUnorderedFlavor(Cond)) {
2751 default: llvm_unreachable("Unknown flavor!");
2752 case 0: // Known false.
2753 return DAG.getConstant(0, VT);
2754 case 1: // Known true.
2755 return DAG.getConstant(1, VT);
2756 case 2: // Undefined.
2757 return DAG.getUNDEF(VT);
2761 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
2762 // constant if knowing that the operand is non-nan is enough. We prefer to
2763 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
2765 if (Cond == ISD::SETO || Cond == ISD::SETUO)
2766 return DAG.getSetCC(dl, VT, N0, N0, Cond);
2768 // If the condition is not legal, see if we can find an equivalent one
2770 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
2771 // If the comparison was an awkward floating-point == or != and one of
2772 // the comparison operands is infinity or negative infinity, convert the
2773 // condition to a less-awkward <= or >=.
2774 if (CFP->getValueAPF().isInfinity()) {
2775 if (CFP->getValueAPF().isNegative()) {
2776 if (Cond == ISD::SETOEQ &&
2777 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
2778 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
2779 if (Cond == ISD::SETUEQ &&
2780 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
2781 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
2782 if (Cond == ISD::SETUNE &&
2783 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
2784 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
2785 if (Cond == ISD::SETONE &&
2786 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
2787 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
2789 if (Cond == ISD::SETOEQ &&
2790 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
2791 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
2792 if (Cond == ISD::SETUEQ &&
2793 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
2794 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
2795 if (Cond == ISD::SETUNE &&
2796 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
2797 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
2798 if (Cond == ISD::SETONE &&
2799 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
2800 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
2807 // The sext(setcc()) => setcc() optimization relies on the appropriate
2808 // constant being emitted.
2810 switch (getBooleanContents(N0.getValueType().isVector())) {
2811 case UndefinedBooleanContent:
2812 case ZeroOrOneBooleanContent:
2813 EqVal = ISD::isTrueWhenEqual(Cond);
2815 case ZeroOrNegativeOneBooleanContent:
2816 EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
2820 // We can always fold X == X for integer setcc's.
2821 if (N0.getValueType().isInteger()) {
2822 return DAG.getConstant(EqVal, VT);
2824 unsigned UOF = ISD::getUnorderedFlavor(Cond);
2825 if (UOF == 2) // FP operators that are undefined on NaNs.
2826 return DAG.getConstant(EqVal, VT);
2827 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
2828 return DAG.getConstant(EqVal, VT);
2829 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
2830 // if it is not already.
2831 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
2832 if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
2833 getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
2834 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
2837 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2838 N0.getValueType().isInteger()) {
2839 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
2840 N0.getOpcode() == ISD::XOR) {
2841 // Simplify (X+Y) == (X+Z) --> Y == Z
2842 if (N0.getOpcode() == N1.getOpcode()) {
2843 if (N0.getOperand(0) == N1.getOperand(0))
2844 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
2845 if (N0.getOperand(1) == N1.getOperand(1))
2846 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
2847 if (DAG.isCommutativeBinOp(N0.getOpcode())) {
2848 // If X op Y == Y op X, try other combinations.
2849 if (N0.getOperand(0) == N1.getOperand(1))
2850 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
2852 if (N0.getOperand(1) == N1.getOperand(0))
2853 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
2858 // If RHS is a legal immediate value for a compare instruction, we need
2859 // to be careful about increasing register pressure needlessly.
2860 bool LegalRHSImm = false;
2862 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
2863 if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2864 // Turn (X+C1) == C2 --> X == C2-C1
2865 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
2866 return DAG.getSetCC(dl, VT, N0.getOperand(0),
2867 DAG.getConstant(RHSC->getAPIntValue()-
2868 LHSR->getAPIntValue(),
2869 N0.getValueType()), Cond);
2872 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
2873 if (N0.getOpcode() == ISD::XOR)
2874 // If we know that all of the inverted bits are zero, don't bother
2875 // performing the inversion.
2876 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
2878 DAG.getSetCC(dl, VT, N0.getOperand(0),
2879 DAG.getConstant(LHSR->getAPIntValue() ^
2880 RHSC->getAPIntValue(),
2885 // Turn (C1-X) == C2 --> X == C1-C2
2886 if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
2887 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
2889 DAG.getSetCC(dl, VT, N0.getOperand(1),
2890 DAG.getConstant(SUBC->getAPIntValue() -
2891 RHSC->getAPIntValue(),
2897 // Could RHSC fold directly into a compare?
2898 if (RHSC->getValueType(0).getSizeInBits() <= 64)
2899 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
2902 // Simplify (X+Z) == X --> Z == 0
2903 // Don't do this if X is an immediate that can fold into a cmp
2904 // instruction and X+Z has other uses. It could be an induction variable
2905 // chain, and the transform would increase register pressure.
2906 if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
2907 if (N0.getOperand(0) == N1)
2908 return DAG.getSetCC(dl, VT, N0.getOperand(1),
2909 DAG.getConstant(0, N0.getValueType()), Cond);
2910 if (N0.getOperand(1) == N1) {
2911 if (DAG.isCommutativeBinOp(N0.getOpcode()))
2912 return DAG.getSetCC(dl, VT, N0.getOperand(0),
2913 DAG.getConstant(0, N0.getValueType()), Cond);
2914 if (N0.getNode()->hasOneUse()) {
2915 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
2916 // (Z-X) == X --> Z == X<<1
2917 SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N1,
2918 DAG.getConstant(1, getShiftAmountTy(N1.getValueType())));
2919 if (!DCI.isCalledByLegalizer())
2920 DCI.AddToWorklist(SH.getNode());
2921 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
2927 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
2928 N1.getOpcode() == ISD::XOR) {
2929 // Simplify X == (X+Z) --> Z == 0
2930 if (N1.getOperand(0) == N0)
2931 return DAG.getSetCC(dl, VT, N1.getOperand(1),
2932 DAG.getConstant(0, N1.getValueType()), Cond);
2933 if (N1.getOperand(1) == N0) {
2934 if (DAG.isCommutativeBinOp(N1.getOpcode()))
2935 return DAG.getSetCC(dl, VT, N1.getOperand(0),
2936 DAG.getConstant(0, N1.getValueType()), Cond);
2937 if (N1.getNode()->hasOneUse()) {
2938 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
2939 // X == (Z-X) --> X<<1 == Z
2940 SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N0,
2941 DAG.getConstant(1, getShiftAmountTy(N0.getValueType())));
2942 if (!DCI.isCalledByLegalizer())
2943 DCI.AddToWorklist(SH.getNode());
2944 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
2949 // Simplify x&y == y to x&y != 0 if y has exactly one bit set.
2950 // Note that where y is variable and is known to have at most
2951 // one bit set (for example, if it is z&1) we cannot do this;
2952 // the expressions are not equivalent when y==0.
2953 if (N0.getOpcode() == ISD::AND)
2954 if (N0.getOperand(0) == N1 || N0.getOperand(1) == N1) {
2955 if (ValueHasExactlyOneBitSet(N1, DAG)) {
2956 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
2957 SDValue Zero = DAG.getConstant(0, N1.getValueType());
2958 return DAG.getSetCC(dl, VT, N0, Zero, Cond);
2961 if (N1.getOpcode() == ISD::AND)
2962 if (N1.getOperand(0) == N0 || N1.getOperand(1) == N0) {
2963 if (ValueHasExactlyOneBitSet(N0, DAG)) {
2964 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
2965 SDValue Zero = DAG.getConstant(0, N0.getValueType());
2966 return DAG.getSetCC(dl, VT, N1, Zero, Cond);
2971 // Fold away ALL boolean setcc's.
2973 if (N0.getValueType() == MVT::i1 && foldBooleans) {
2975 default: llvm_unreachable("Unknown integer setcc!");
2976 case ISD::SETEQ: // X == Y -> ~(X^Y)
2977 Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2978 N0 = DAG.getNOT(dl, Temp, MVT::i1);
2979 if (!DCI.isCalledByLegalizer())
2980 DCI.AddToWorklist(Temp.getNode());
2982 case ISD::SETNE: // X != Y --> (X^Y)
2983 N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2985 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
2986 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
2987 Temp = DAG.getNOT(dl, N0, MVT::i1);
2988 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
2989 if (!DCI.isCalledByLegalizer())
2990 DCI.AddToWorklist(Temp.getNode());
2992 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
2993 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
2994 Temp = DAG.getNOT(dl, N1, MVT::i1);
2995 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
2996 if (!DCI.isCalledByLegalizer())
2997 DCI.AddToWorklist(Temp.getNode());
2999 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
3000 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
3001 Temp = DAG.getNOT(dl, N0, MVT::i1);
3002 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
3003 if (!DCI.isCalledByLegalizer())
3004 DCI.AddToWorklist(Temp.getNode());
3006 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
3007 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
3008 Temp = DAG.getNOT(dl, N1, MVT::i1);
3009 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
3012 if (VT != MVT::i1) {
3013 if (!DCI.isCalledByLegalizer())
3014 DCI.AddToWorklist(N0.getNode());
3015 // FIXME: If running after legalize, we probably can't do this.
3016 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
3021 // Could not fold it.
3025 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
3026 /// node is a GlobalAddress + offset.
3027 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
3028 int64_t &Offset) const {
3029 if (isa<GlobalAddressSDNode>(N)) {
3030 GlobalAddressSDNode *GASD = cast<GlobalAddressSDNode>(N);
3031 GA = GASD->getGlobal();
3032 Offset += GASD->getOffset();
3036 if (N->getOpcode() == ISD::ADD) {
3037 SDValue N1 = N->getOperand(0);
3038 SDValue N2 = N->getOperand(1);
3039 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
3040 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
3042 Offset += V->getSExtValue();
3045 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
3046 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
3048 Offset += V->getSExtValue();
3058 SDValue TargetLowering::
3059 PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
3060 // Default implementation: no optimization.
3064 //===----------------------------------------------------------------------===//
3065 // Inline Assembler Implementation Methods
3066 //===----------------------------------------------------------------------===//
3069 TargetLowering::ConstraintType
3070 TargetLowering::getConstraintType(const std::string &Constraint) const {
3071 if (Constraint.size() == 1) {
3072 switch (Constraint[0]) {
3074 case 'r': return C_RegisterClass;
3076 case 'o': // offsetable
3077 case 'V': // not offsetable
3079 case 'i': // Simple Integer or Relocatable Constant
3080 case 'n': // Simple Integer
3081 case 'E': // Floating Point Constant
3082 case 'F': // Floating Point Constant
3083 case 's': // Relocatable Constant
3084 case 'p': // Address.
3085 case 'X': // Allow ANY value.
3086 case 'I': // Target registers.
3100 if (Constraint.size() > 1 && Constraint[0] == '{' &&
3101 Constraint[Constraint.size()-1] == '}')
3106 /// LowerXConstraint - try to replace an X constraint, which matches anything,
3107 /// with another that has more specific requirements based on the type of the
3108 /// corresponding operand.
3109 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
3110 if (ConstraintVT.isInteger())
3112 if (ConstraintVT.isFloatingPoint())
3113 return "f"; // works for many targets
3117 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3118 /// vector. If it is invalid, don't add anything to Ops.
3119 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3120 std::string &Constraint,
3121 std::vector<SDValue> &Ops,
3122 SelectionDAG &DAG) const {
3124 if (Constraint.length() > 1) return;
3126 char ConstraintLetter = Constraint[0];
3127 switch (ConstraintLetter) {
3129 case 'X': // Allows any operand; labels (basic block) use this.
3130 if (Op.getOpcode() == ISD::BasicBlock) {
3135 case 'i': // Simple Integer or Relocatable Constant
3136 case 'n': // Simple Integer
3137 case 's': { // Relocatable Constant
3138 // These operands are interested in values of the form (GV+C), where C may
3139 // be folded in as an offset of GV, or it may be explicitly added. Also, it
3140 // is possible and fine if either GV or C are missing.
3141 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3142 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
3144 // If we have "(add GV, C)", pull out GV/C
3145 if (Op.getOpcode() == ISD::ADD) {
3146 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
3147 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
3148 if (C == 0 || GA == 0) {
3149 C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
3150 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
3152 if (C == 0 || GA == 0)
3156 // If we find a valid operand, map to the TargetXXX version so that the
3157 // value itself doesn't get selected.
3158 if (GA) { // Either &GV or &GV+C
3159 if (ConstraintLetter != 'n') {
3160 int64_t Offs = GA->getOffset();
3161 if (C) Offs += C->getZExtValue();
3162 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
3163 C ? C->getDebugLoc() : DebugLoc(),
3164 Op.getValueType(), Offs));
3168 if (C) { // just C, no GV.
3169 // Simple constants are not allowed for 's'.
3170 if (ConstraintLetter != 's') {
3171 // gcc prints these as sign extended. Sign extend value to 64 bits
3172 // now; without this it would get ZExt'd later in
3173 // ScheduleDAGSDNodes::EmitNode, which is very generic.
3174 Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
3184 std::pair<unsigned, const TargetRegisterClass*> TargetLowering::
3185 getRegForInlineAsmConstraint(const std::string &Constraint,
3187 if (Constraint[0] != '{')
3188 return std::make_pair(0u, static_cast<TargetRegisterClass*>(0));
3189 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
3191 // Remove the braces from around the name.
3192 StringRef RegName(Constraint.data()+1, Constraint.size()-2);
3194 std::pair<unsigned, const TargetRegisterClass*> R =
3195 std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3197 // Figure out which register class contains this reg.
3198 const TargetRegisterInfo *RI = TM.getRegisterInfo();
3199 for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
3200 E = RI->regclass_end(); RCI != E; ++RCI) {
3201 const TargetRegisterClass *RC = *RCI;
3203 // If none of the value types for this register class are valid, we
3204 // can't use it. For example, 64-bit reg classes on 32-bit targets.
3208 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
3210 if (RegName.equals_lower(RI->getName(*I))) {
3211 std::pair<unsigned, const TargetRegisterClass*> S =
3212 std::make_pair(*I, RC);
3214 // If this register class has the requested value type, return it,
3215 // otherwise keep searching and return the first class found
3216 // if no other is found which explicitly has the requested type.
3217 if (RC->hasType(VT))
3228 //===----------------------------------------------------------------------===//
3229 // Constraint Selection.
3231 /// isMatchingInputConstraint - Return true of this is an input operand that is
3232 /// a matching constraint like "4".
3233 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
3234 assert(!ConstraintCode.empty() && "No known constraint!");
3235 return isdigit(ConstraintCode[0]);
3238 /// getMatchedOperand - If this is an input matching constraint, this method
3239 /// returns the output operand it matches.
3240 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
3241 assert(!ConstraintCode.empty() && "No known constraint!");
3242 return atoi(ConstraintCode.c_str());
3246 /// ParseConstraints - Split up the constraint string from the inline
3247 /// assembly value into the specific constraints and their prefixes,
3248 /// and also tie in the associated operand values.
3249 /// If this returns an empty vector, and if the constraint string itself
3250 /// isn't empty, there was an error parsing.
3251 TargetLowering::AsmOperandInfoVector TargetLowering::ParseConstraints(
3252 ImmutableCallSite CS) const {
3253 /// ConstraintOperands - Information about all of the constraints.
3254 AsmOperandInfoVector ConstraintOperands;
3255 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
3256 unsigned maCount = 0; // Largest number of multiple alternative constraints.
3258 // Do a prepass over the constraints, canonicalizing them, and building up the
3259 // ConstraintOperands list.
3260 InlineAsm::ConstraintInfoVector
3261 ConstraintInfos = IA->ParseConstraints();
3263 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
3264 unsigned ResNo = 0; // ResNo - The result number of the next output.
3266 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3267 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
3268 AsmOperandInfo &OpInfo = ConstraintOperands.back();
3270 // Update multiple alternative constraint count.
3271 if (OpInfo.multipleAlternatives.size() > maCount)
3272 maCount = OpInfo.multipleAlternatives.size();
3274 OpInfo.ConstraintVT = MVT::Other;
3276 // Compute the value type for each operand.
3277 switch (OpInfo.Type) {
3278 case InlineAsm::isOutput:
3279 // Indirect outputs just consume an argument.
3280 if (OpInfo.isIndirect) {
3281 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
3285 // The return value of the call is this value. As such, there is no
3286 // corresponding argument.
3287 assert(!CS.getType()->isVoidTy() &&
3289 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
3290 OpInfo.ConstraintVT = getSimpleValueType(STy->getElementType(ResNo));
3292 assert(ResNo == 0 && "Asm only has one result!");
3293 OpInfo.ConstraintVT = getSimpleValueType(CS.getType());
3297 case InlineAsm::isInput:
3298 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
3300 case InlineAsm::isClobber:
3305 if (OpInfo.CallOperandVal) {
3306 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
3307 if (OpInfo.isIndirect) {
3308 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
3310 report_fatal_error("Indirect operand for inline asm not a pointer!");
3311 OpTy = PtrTy->getElementType();
3314 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
3315 if (StructType *STy = dyn_cast<StructType>(OpTy))
3316 if (STy->getNumElements() == 1)
3317 OpTy = STy->getElementType(0);
3319 // If OpTy is not a single value, it may be a struct/union that we
3320 // can tile with integers.
3321 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
3322 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3331 OpInfo.ConstraintVT =
3332 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
3335 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
3336 OpInfo.ConstraintVT = MVT::getIntegerVT(
3337 8*TD->getPointerSize(PT->getAddressSpace()));
3339 OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
3344 // If we have multiple alternative constraints, select the best alternative.
3345 if (ConstraintInfos.size()) {
3347 unsigned bestMAIndex = 0;
3348 int bestWeight = -1;
3349 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
3352 // Compute the sums of the weights for each alternative, keeping track
3353 // of the best (highest weight) one so far.
3354 for (maIndex = 0; maIndex < maCount; ++maIndex) {
3356 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
3357 cIndex != eIndex; ++cIndex) {
3358 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
3359 if (OpInfo.Type == InlineAsm::isClobber)
3362 // If this is an output operand with a matching input operand,
3363 // look up the matching input. If their types mismatch, e.g. one
3364 // is an integer, the other is floating point, or their sizes are
3365 // different, flag it as an maCantMatch.
3366 if (OpInfo.hasMatchingInput()) {
3367 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
3368 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
3369 if ((OpInfo.ConstraintVT.isInteger() !=
3370 Input.ConstraintVT.isInteger()) ||
3371 (OpInfo.ConstraintVT.getSizeInBits() !=
3372 Input.ConstraintVT.getSizeInBits())) {
3373 weightSum = -1; // Can't match.
3378 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
3383 weightSum += weight;
3386 if (weightSum > bestWeight) {
3387 bestWeight = weightSum;
3388 bestMAIndex = maIndex;
3392 // Now select chosen alternative in each constraint.
3393 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
3394 cIndex != eIndex; ++cIndex) {
3395 AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
3396 if (cInfo.Type == InlineAsm::isClobber)
3398 cInfo.selectAlternative(bestMAIndex);
3403 // Check and hook up tied operands, choose constraint code to use.
3404 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
3405 cIndex != eIndex; ++cIndex) {
3406 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
3408 // If this is an output operand with a matching input operand, look up the
3409 // matching input. If their types mismatch, e.g. one is an integer, the
3410 // other is floating point, or their sizes are different, flag it as an
3412 if (OpInfo.hasMatchingInput()) {
3413 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
3415 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
3416 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
3417 getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3418 OpInfo.ConstraintVT);
3419 std::pair<unsigned, const TargetRegisterClass*> InputRC =
3420 getRegForInlineAsmConstraint(Input.ConstraintCode,
3421 Input.ConstraintVT);
3422 if ((OpInfo.ConstraintVT.isInteger() !=
3423 Input.ConstraintVT.isInteger()) ||
3424 (MatchRC.second != InputRC.second)) {
3425 report_fatal_error("Unsupported asm: input constraint"
3426 " with a matching output constraint of"
3427 " incompatible type!");
3434 return ConstraintOperands;
3438 /// getConstraintGenerality - Return an integer indicating how general CT
3440 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3442 case TargetLowering::C_Other:
3443 case TargetLowering::C_Unknown:
3445 case TargetLowering::C_Register:
3447 case TargetLowering::C_RegisterClass:
3449 case TargetLowering::C_Memory:
3452 llvm_unreachable("Invalid constraint type");
3455 /// Examine constraint type and operand type and determine a weight value.
3456 /// This object must already have been set up with the operand type
3457 /// and the current alternative constraint selected.
3458 TargetLowering::ConstraintWeight
3459 TargetLowering::getMultipleConstraintMatchWeight(
3460 AsmOperandInfo &info, int maIndex) const {
3461 InlineAsm::ConstraintCodeVector *rCodes;
3462 if (maIndex >= (int)info.multipleAlternatives.size())
3463 rCodes = &info.Codes;
3465 rCodes = &info.multipleAlternatives[maIndex].Codes;
3466 ConstraintWeight BestWeight = CW_Invalid;
3468 // Loop over the options, keeping track of the most general one.
3469 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
3470 ConstraintWeight weight =
3471 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
3472 if (weight > BestWeight)
3473 BestWeight = weight;
3479 /// Examine constraint type and operand type and determine a weight value.
3480 /// This object must already have been set up with the operand type
3481 /// and the current alternative constraint selected.
3482 TargetLowering::ConstraintWeight
3483 TargetLowering::getSingleConstraintMatchWeight(
3484 AsmOperandInfo &info, const char *constraint) const {
3485 ConstraintWeight weight = CW_Invalid;
3486 Value *CallOperandVal = info.CallOperandVal;
3487 // If we don't have a value, we can't do a match,
3488 // but allow it at the lowest weight.
3489 if (CallOperandVal == NULL)
3491 // Look at the constraint type.
3492 switch (*constraint) {
3493 case 'i': // immediate integer.
3494 case 'n': // immediate integer with a known value.
3495 if (isa<ConstantInt>(CallOperandVal))
3496 weight = CW_Constant;
3498 case 's': // non-explicit intregal immediate.
3499 if (isa<GlobalValue>(CallOperandVal))
3500 weight = CW_Constant;
3502 case 'E': // immediate float if host format.
3503 case 'F': // immediate float.
3504 if (isa<ConstantFP>(CallOperandVal))
3505 weight = CW_Constant;
3507 case '<': // memory operand with autodecrement.
3508 case '>': // memory operand with autoincrement.
3509 case 'm': // memory operand.
3510 case 'o': // offsettable memory operand
3511 case 'V': // non-offsettable memory operand
3514 case 'r': // general register.
3515 case 'g': // general register, memory operand or immediate integer.
3516 // note: Clang converts "g" to "imr".
3517 if (CallOperandVal->getType()->isIntegerTy())
3518 weight = CW_Register;
3520 case 'X': // any operand.
3522 weight = CW_Default;
3528 /// ChooseConstraint - If there are multiple different constraints that we
3529 /// could pick for this operand (e.g. "imr") try to pick the 'best' one.
3530 /// This is somewhat tricky: constraints fall into four classes:
3531 /// Other -> immediates and magic values
3532 /// Register -> one specific register
3533 /// RegisterClass -> a group of regs
3534 /// Memory -> memory
3535 /// Ideally, we would pick the most specific constraint possible: if we have
3536 /// something that fits into a register, we would pick it. The problem here
3537 /// is that if we have something that could either be in a register or in
3538 /// memory that use of the register could cause selection of *other*
3539 /// operands to fail: they might only succeed if we pick memory. Because of
3540 /// this the heuristic we use is:
3542 /// 1) If there is an 'other' constraint, and if the operand is valid for
3543 /// that constraint, use it. This makes us take advantage of 'i'
3544 /// constraints when available.
3545 /// 2) Otherwise, pick the most general constraint present. This prefers
3546 /// 'm' over 'r', for example.
3548 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
3549 const TargetLowering &TLI,
3550 SDValue Op, SelectionDAG *DAG) {
3551 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
3552 unsigned BestIdx = 0;
3553 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
3554 int BestGenerality = -1;
3556 // Loop over the options, keeping track of the most general one.
3557 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
3558 TargetLowering::ConstraintType CType =
3559 TLI.getConstraintType(OpInfo.Codes[i]);
3561 // If this is an 'other' constraint, see if the operand is valid for it.
3562 // For example, on X86 we might have an 'rI' constraint. If the operand
3563 // is an integer in the range [0..31] we want to use I (saving a load
3564 // of a register), otherwise we must use 'r'.
3565 if (CType == TargetLowering::C_Other && Op.getNode()) {
3566 assert(OpInfo.Codes[i].size() == 1 &&
3567 "Unhandled multi-letter 'other' constraint");
3568 std::vector<SDValue> ResultOps;
3569 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
3571 if (!ResultOps.empty()) {
3578 // Things with matching constraints can only be registers, per gcc
3579 // documentation. This mainly affects "g" constraints.
3580 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
3583 // This constraint letter is more general than the previous one, use it.
3584 int Generality = getConstraintGenerality(CType);
3585 if (Generality > BestGenerality) {
3588 BestGenerality = Generality;
3592 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
3593 OpInfo.ConstraintType = BestType;
3596 /// ComputeConstraintToUse - Determines the constraint code and constraint
3597 /// type to use for the specific AsmOperandInfo, setting
3598 /// OpInfo.ConstraintCode and OpInfo.ConstraintType.
3599 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
3601 SelectionDAG *DAG) const {
3602 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
3604 // Single-letter constraints ('r') are very common.
3605 if (OpInfo.Codes.size() == 1) {
3606 OpInfo.ConstraintCode = OpInfo.Codes[0];
3607 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
3609 ChooseConstraint(OpInfo, *this, Op, DAG);
3612 // 'X' matches anything.
3613 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
3614 // Labels and constants are handled elsewhere ('X' is the only thing
3615 // that matches labels). For Functions, the type here is the type of
3616 // the result, which is not what we want to look at; leave them alone.
3617 Value *v = OpInfo.CallOperandVal;
3618 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
3619 OpInfo.CallOperandVal = v;
3623 // Otherwise, try to resolve it to something we know about by looking at
3624 // the actual operand type.
3625 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
3626 OpInfo.ConstraintCode = Repl;
3627 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
3632 //===----------------------------------------------------------------------===//
3633 // Loop Strength Reduction hooks
3634 //===----------------------------------------------------------------------===//
3636 /// isLegalAddressingMode - Return true if the addressing mode represented
3637 /// by AM is legal for this target, for a load/store of the specified type.
3638 bool TargetLowering::isLegalAddressingMode(const AddrMode &AM,
3640 // The default implementation of this implements a conservative RISCy, r+r and
3643 // Allows a sign-extended 16-bit immediate field.
3644 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
3647 // No global is ever allowed as a base.
3651 // Only support r+r,
3653 case 0: // "r+i" or just "i", depending on HasBaseReg.
3656 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
3658 // Otherwise we have r+r or r+i.
3661 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
3663 // Allow 2*r as r+r.
3670 /// BuildExactDiv - Given an exact SDIV by a constant, create a multiplication
3671 /// with the multiplicative inverse of the constant.
3672 SDValue TargetLowering::BuildExactSDIV(SDValue Op1, SDValue Op2, DebugLoc dl,
3673 SelectionDAG &DAG) const {
3674 ConstantSDNode *C = cast<ConstantSDNode>(Op2);
3675 APInt d = C->getAPIntValue();
3676 assert(d != 0 && "Division by zero!");
3678 // Shift the value upfront if it is even, so the LSB is one.
3679 unsigned ShAmt = d.countTrailingZeros();
3681 // TODO: For UDIV use SRL instead of SRA.
3682 SDValue Amt = DAG.getConstant(ShAmt, getShiftAmountTy(Op1.getValueType()));
3683 Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt);
3687 // Calculate the multiplicative inverse, using Newton's method.
3689 while ((t = d*xn) != 1)
3690 xn *= APInt(d.getBitWidth(), 2) - t;
3692 Op2 = DAG.getConstant(xn, Op1.getValueType());
3693 return DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
3696 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
3697 /// return a DAG expression to select that will generate the same value by
3698 /// multiplying by a magic number. See:
3699 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
3700 SDValue TargetLowering::
3701 BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
3702 std::vector<SDNode*> *Created) const {
3703 EVT VT = N->getValueType(0);
3704 DebugLoc dl= N->getDebugLoc();
3706 // Check to see if we can do this.
3707 // FIXME: We should be more aggressive here.
3708 if (!isTypeLegal(VT))
3711 APInt d = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
3712 APInt::ms magics = d.magic();
3714 // Multiply the numerator (operand 0) by the magic value
3715 // FIXME: We should support doing a MUL in a wider type
3717 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
3718 isOperationLegalOrCustom(ISD::MULHS, VT))
3719 Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
3720 DAG.getConstant(magics.m, VT));
3721 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
3722 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
3723 Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
3725 DAG.getConstant(magics.m, VT)).getNode(), 1);
3727 return SDValue(); // No mulhs or equvialent
3728 // If d > 0 and m < 0, add the numerator
3729 if (d.isStrictlyPositive() && magics.m.isNegative()) {
3730 Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
3732 Created->push_back(Q.getNode());
3734 // If d < 0 and m > 0, subtract the numerator.
3735 if (d.isNegative() && magics.m.isStrictlyPositive()) {
3736 Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
3738 Created->push_back(Q.getNode());
3740 // Shift right algebraic if shift value is nonzero
3742 Q = DAG.getNode(ISD::SRA, dl, VT, Q,
3743 DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
3745 Created->push_back(Q.getNode());
3747 // Extract the sign bit and add it to the quotient
3749 DAG.getNode(ISD::SRL, dl, VT, Q, DAG.getConstant(VT.getSizeInBits()-1,
3750 getShiftAmountTy(Q.getValueType())));
3752 Created->push_back(T.getNode());
3753 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
3756 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
3757 /// return a DAG expression to select that will generate the same value by
3758 /// multiplying by a magic number. See:
3759 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
3760 SDValue TargetLowering::
3761 BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
3762 std::vector<SDNode*> *Created) const {
3763 EVT VT = N->getValueType(0);
3764 DebugLoc dl = N->getDebugLoc();
3766 // Check to see if we can do this.
3767 // FIXME: We should be more aggressive here.
3768 if (!isTypeLegal(VT))
3771 // FIXME: We should use a narrower constant when the upper
3772 // bits are known to be zero.
3773 const APInt &N1C = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
3774 APInt::mu magics = N1C.magicu();
3776 SDValue Q = N->getOperand(0);
3778 // If the divisor is even, we can avoid using the expensive fixup by shifting
3779 // the divided value upfront.
3780 if (magics.a != 0 && !N1C[0]) {
3781 unsigned Shift = N1C.countTrailingZeros();
3782 Q = DAG.getNode(ISD::SRL, dl, VT, Q,
3783 DAG.getConstant(Shift, getShiftAmountTy(Q.getValueType())));
3785 Created->push_back(Q.getNode());
3787 // Get magic number for the shifted divisor.
3788 magics = N1C.lshr(Shift).magicu(Shift);
3789 assert(magics.a == 0 && "Should use cheap fixup now");
3792 // Multiply the numerator (operand 0) by the magic value
3793 // FIXME: We should support doing a MUL in a wider type
3794 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
3795 isOperationLegalOrCustom(ISD::MULHU, VT))
3796 Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, VT));
3797 else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
3798 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
3799 Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
3800 DAG.getConstant(magics.m, VT)).getNode(), 1);
3802 return SDValue(); // No mulhu or equvialent
3804 Created->push_back(Q.getNode());
3806 if (magics.a == 0) {
3807 assert(magics.s < N1C.getBitWidth() &&
3808 "We shouldn't generate an undefined shift!");
3809 return DAG.getNode(ISD::SRL, dl, VT, Q,
3810 DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
3812 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
3814 Created->push_back(NPQ.getNode());
3815 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ,
3816 DAG.getConstant(1, getShiftAmountTy(NPQ.getValueType())));
3818 Created->push_back(NPQ.getNode());
3819 NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
3821 Created->push_back(NPQ.getNode());
3822 return DAG.getNode(ISD::SRL, dl, VT, NPQ,
3823 DAG.getConstant(magics.s-1, getShiftAmountTy(NPQ.getValueType())));