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