1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
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 file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86MCTargetExpr.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/PseudoSourceValue.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCSectionMachO.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
54 using namespace dwarf;
56 STATISTIC(NumTailCalls, "Number of tail calls");
59 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
61 // Disable16Bit - 16-bit operations typically have a larger encoding than
62 // corresponding 32-bit instructions, and 16-bit code is slow on some
63 // processors. This is an experimental flag to disable 16-bit operations
64 // (which forces them to be Legalized to 32-bit operations).
66 Disable16Bit("disable-16bit", cl::Hidden,
67 cl::desc("Disable use of 16-bit instructions"));
69 // Forward declarations.
70 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
73 // FIXME: This is for a test.
75 EnableX86EHTest("enable-x86-eh-test", cl::Hidden);
78 class X86_test_MachoTargetObjectFile : public TargetLoweringObjectFileMachO {
80 virtual void Initialize(MCContext &Ctx, const TargetMachine &TM) {
81 TargetLoweringObjectFileMachO::Initialize(Ctx, TM);
83 // Exception Handling.
84 LSDASection = getMachOSection("__TEXT", "__gcc_except_tab", 0,
85 SectionKind::getReadOnlyWithRel());
88 virtual unsigned getTTypeEncoding() const {
89 return DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4;
93 class X8664_test_MachoTargetObjectFile : public X8664_MachoTargetObjectFile {
95 virtual void Initialize(MCContext &Ctx, const TargetMachine &TM) {
96 TargetLoweringObjectFileMachO::Initialize(Ctx, TM);
98 // Exception Handling.
99 LSDASection = getMachOSection("__TEXT", "__gcc_except_tab", 0,
100 SectionKind::getReadOnlyWithRel());
103 virtual unsigned getTTypeEncoding() const {
104 return DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4;
109 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
110 switch (TM.getSubtarget<X86Subtarget>().TargetType) {
111 default: llvm_unreachable("unknown subtarget type");
112 case X86Subtarget::isDarwin:
113 // FIXME: This is for an EH test.
114 if (EnableX86EHTest) {
115 if (TM.getSubtarget<X86Subtarget>().is64Bit())
116 return new X8664_test_MachoTargetObjectFile();
118 return new X86_test_MachoTargetObjectFile();
121 if (TM.getSubtarget<X86Subtarget>().is64Bit())
122 return new X8664_MachoTargetObjectFile();
123 return new TargetLoweringObjectFileMachO();
124 case X86Subtarget::isELF:
125 if (TM.getSubtarget<X86Subtarget>().is64Bit())
126 return new X8664_ELFTargetObjectFile(TM);
127 return new X8632_ELFTargetObjectFile(TM);
128 case X86Subtarget::isMingw:
129 case X86Subtarget::isCygwin:
130 case X86Subtarget::isWindows:
131 return new TargetLoweringObjectFileCOFF();
135 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
136 : TargetLowering(TM, createTLOF(TM)) {
137 Subtarget = &TM.getSubtarget<X86Subtarget>();
138 X86ScalarSSEf64 = Subtarget->hasSSE2();
139 X86ScalarSSEf32 = Subtarget->hasSSE1();
140 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
142 RegInfo = TM.getRegisterInfo();
143 TD = getTargetData();
145 // Set up the TargetLowering object.
147 // X86 is weird, it always uses i8 for shift amounts and setcc results.
148 setShiftAmountType(MVT::i8);
149 setBooleanContents(ZeroOrOneBooleanContent);
150 setSchedulingPreference(SchedulingForRegPressure);
151 setStackPointerRegisterToSaveRestore(X86StackPtr);
153 if (Subtarget->isTargetDarwin()) {
154 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
155 setUseUnderscoreSetJmp(false);
156 setUseUnderscoreLongJmp(false);
157 } else if (Subtarget->isTargetMingw()) {
158 // MS runtime is weird: it exports _setjmp, but longjmp!
159 setUseUnderscoreSetJmp(true);
160 setUseUnderscoreLongJmp(false);
162 setUseUnderscoreSetJmp(true);
163 setUseUnderscoreLongJmp(true);
166 // Set up the register classes.
167 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
169 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
170 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
171 if (Subtarget->is64Bit())
172 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
174 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
176 // We don't accept any truncstore of integer registers.
177 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
179 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
180 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
182 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
183 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
184 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
186 // SETOEQ and SETUNE require checking two conditions.
187 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
188 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
189 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
190 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
191 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
192 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
194 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
196 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
197 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
198 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
200 if (Subtarget->is64Bit()) {
201 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
202 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
203 } else if (!UseSoftFloat) {
204 if (X86ScalarSSEf64) {
205 // We have an impenetrably clever algorithm for ui64->double only.
206 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
208 // We have an algorithm for SSE2, and we turn this into a 64-bit
209 // FILD for other targets.
210 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
213 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
215 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
216 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
219 // SSE has no i16 to fp conversion, only i32
220 if (X86ScalarSSEf32) {
221 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
222 // f32 and f64 cases are Legal, f80 case is not
223 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
225 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
226 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
229 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
230 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
233 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
234 // are Legal, f80 is custom lowered.
235 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
236 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
238 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
240 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
241 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
243 if (X86ScalarSSEf32) {
244 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
245 // f32 and f64 cases are Legal, f80 case is not
246 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
248 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
249 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
252 // Handle FP_TO_UINT by promoting the destination to a larger signed
254 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
255 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
256 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
258 if (Subtarget->is64Bit()) {
259 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
260 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
261 } else if (!UseSoftFloat) {
262 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
263 // Expand FP_TO_UINT into a select.
264 // FIXME: We would like to use a Custom expander here eventually to do
265 // the optimal thing for SSE vs. the default expansion in the legalizer.
266 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
268 // With SSE3 we can use fisttpll to convert to a signed i64; without
269 // SSE, we're stuck with a fistpll.
270 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
273 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
274 if (!X86ScalarSSEf64) {
275 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
276 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
279 // Scalar integer divide and remainder are lowered to use operations that
280 // produce two results, to match the available instructions. This exposes
281 // the two-result form to trivial CSE, which is able to combine x/y and x%y
282 // into a single instruction.
284 // Scalar integer multiply-high is also lowered to use two-result
285 // operations, to match the available instructions. However, plain multiply
286 // (low) operations are left as Legal, as there are single-result
287 // instructions for this in x86. Using the two-result multiply instructions
288 // when both high and low results are needed must be arranged by dagcombine.
289 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
290 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
291 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
292 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
293 setOperationAction(ISD::SREM , MVT::i8 , Expand);
294 setOperationAction(ISD::UREM , MVT::i8 , Expand);
295 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
296 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
297 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
298 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
299 setOperationAction(ISD::SREM , MVT::i16 , Expand);
300 setOperationAction(ISD::UREM , MVT::i16 , Expand);
301 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
302 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
303 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
304 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
305 setOperationAction(ISD::SREM , MVT::i32 , Expand);
306 setOperationAction(ISD::UREM , MVT::i32 , Expand);
307 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
308 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
309 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
310 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
311 setOperationAction(ISD::SREM , MVT::i64 , Expand);
312 setOperationAction(ISD::UREM , MVT::i64 , Expand);
314 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
315 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
316 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
317 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
318 if (Subtarget->is64Bit())
319 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
320 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
321 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
322 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
323 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
324 setOperationAction(ISD::FREM , MVT::f32 , Expand);
325 setOperationAction(ISD::FREM , MVT::f64 , Expand);
326 setOperationAction(ISD::FREM , MVT::f80 , Expand);
327 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
329 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
330 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
331 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
332 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
334 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
335 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
337 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
338 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
340 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
341 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
342 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
343 if (Subtarget->is64Bit()) {
344 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
345 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
346 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
349 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
350 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
352 // These should be promoted to a larger select which is supported.
353 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
354 // X86 wants to expand cmov itself.
355 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
357 setOperationAction(ISD::SELECT , MVT::i16 , Expand);
359 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
360 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
361 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
362 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
363 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
364 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
366 setOperationAction(ISD::SETCC , MVT::i16 , Expand);
368 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
369 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
370 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
371 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
372 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
373 if (Subtarget->is64Bit()) {
374 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
375 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
377 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
380 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
381 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
382 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
383 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
384 if (Subtarget->is64Bit())
385 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
386 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
387 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
388 if (Subtarget->is64Bit()) {
389 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
390 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
391 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
392 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
393 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
395 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
396 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
397 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
398 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
399 if (Subtarget->is64Bit()) {
400 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
401 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
402 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
405 if (Subtarget->hasSSE1())
406 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
408 if (!Subtarget->hasSSE2())
409 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
411 // Expand certain atomics
412 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
413 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
414 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
415 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
417 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
418 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
419 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
420 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
422 if (!Subtarget->is64Bit()) {
423 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
424 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
425 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
426 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
427 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
428 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
429 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
432 // FIXME - use subtarget debug flags
433 if (!Subtarget->isTargetDarwin() &&
434 !Subtarget->isTargetELF() &&
435 !Subtarget->isTargetCygMing()) {
436 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
439 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
440 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
441 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
442 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
443 if (Subtarget->is64Bit()) {
444 setExceptionPointerRegister(X86::RAX);
445 setExceptionSelectorRegister(X86::RDX);
447 setExceptionPointerRegister(X86::EAX);
448 setExceptionSelectorRegister(X86::EDX);
450 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
451 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
453 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
455 setOperationAction(ISD::TRAP, MVT::Other, Legal);
457 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
458 setOperationAction(ISD::VASTART , MVT::Other, Custom);
459 setOperationAction(ISD::VAEND , MVT::Other, Expand);
460 if (Subtarget->is64Bit()) {
461 setOperationAction(ISD::VAARG , MVT::Other, Custom);
462 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
464 setOperationAction(ISD::VAARG , MVT::Other, Expand);
465 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
468 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
469 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
470 if (Subtarget->is64Bit())
471 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
472 if (Subtarget->isTargetCygMing())
473 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
475 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
477 if (!UseSoftFloat && X86ScalarSSEf64) {
478 // f32 and f64 use SSE.
479 // Set up the FP register classes.
480 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
481 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
483 // Use ANDPD to simulate FABS.
484 setOperationAction(ISD::FABS , MVT::f64, Custom);
485 setOperationAction(ISD::FABS , MVT::f32, Custom);
487 // Use XORP to simulate FNEG.
488 setOperationAction(ISD::FNEG , MVT::f64, Custom);
489 setOperationAction(ISD::FNEG , MVT::f32, Custom);
491 // Use ANDPD and ORPD to simulate FCOPYSIGN.
492 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
493 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
495 // We don't support sin/cos/fmod
496 setOperationAction(ISD::FSIN , MVT::f64, Expand);
497 setOperationAction(ISD::FCOS , MVT::f64, Expand);
498 setOperationAction(ISD::FSIN , MVT::f32, Expand);
499 setOperationAction(ISD::FCOS , MVT::f32, Expand);
501 // Expand FP immediates into loads from the stack, except for the special
503 addLegalFPImmediate(APFloat(+0.0)); // xorpd
504 addLegalFPImmediate(APFloat(+0.0f)); // xorps
505 } else if (!UseSoftFloat && X86ScalarSSEf32) {
506 // Use SSE for f32, x87 for f64.
507 // Set up the FP register classes.
508 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
509 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
511 // Use ANDPS to simulate FABS.
512 setOperationAction(ISD::FABS , MVT::f32, Custom);
514 // Use XORP to simulate FNEG.
515 setOperationAction(ISD::FNEG , MVT::f32, Custom);
517 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
519 // Use ANDPS and ORPS to simulate FCOPYSIGN.
520 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
521 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
523 // We don't support sin/cos/fmod
524 setOperationAction(ISD::FSIN , MVT::f32, Expand);
525 setOperationAction(ISD::FCOS , MVT::f32, Expand);
527 // Special cases we handle for FP constants.
528 addLegalFPImmediate(APFloat(+0.0f)); // xorps
529 addLegalFPImmediate(APFloat(+0.0)); // FLD0
530 addLegalFPImmediate(APFloat(+1.0)); // FLD1
531 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
532 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
535 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
536 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
538 } else if (!UseSoftFloat) {
539 // f32 and f64 in x87.
540 // Set up the FP register classes.
541 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
542 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
544 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
545 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
546 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
547 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
550 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
551 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
553 addLegalFPImmediate(APFloat(+0.0)); // FLD0
554 addLegalFPImmediate(APFloat(+1.0)); // FLD1
555 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
556 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
557 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
558 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
559 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
560 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
563 // Long double always uses X87.
565 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
566 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
567 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
570 APFloat TmpFlt(+0.0);
571 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
573 addLegalFPImmediate(TmpFlt); // FLD0
575 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
576 APFloat TmpFlt2(+1.0);
577 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
579 addLegalFPImmediate(TmpFlt2); // FLD1
580 TmpFlt2.changeSign();
581 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
585 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
586 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
590 // Always use a library call for pow.
591 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
592 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
593 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
595 setOperationAction(ISD::FLOG, MVT::f80, Expand);
596 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
597 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
598 setOperationAction(ISD::FEXP, MVT::f80, Expand);
599 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
601 // First set operation action for all vector types to either promote
602 // (for widening) or expand (for scalarization). Then we will selectively
603 // turn on ones that can be effectively codegen'd.
604 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
605 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
606 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
607 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
608 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
609 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
610 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
611 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
612 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
613 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
614 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
615 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
616 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
617 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
618 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
619 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
620 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
621 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
622 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
623 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
624 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
625 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
626 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
627 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
628 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
629 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
630 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
631 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
632 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
633 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
634 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
635 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
636 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
637 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
638 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
639 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
640 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
641 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
642 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
643 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
644 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
645 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
646 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
647 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
648 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
649 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
650 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
651 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
652 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
653 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
654 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
655 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
656 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
657 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
658 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
659 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
660 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
661 setTruncStoreAction((MVT::SimpleValueType)VT,
662 (MVT::SimpleValueType)InnerVT, Expand);
663 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
664 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
665 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
668 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
669 // with -msoft-float, disable use of MMX as well.
670 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
671 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
672 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
673 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
674 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
675 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
677 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
678 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
679 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
680 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
682 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
683 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
684 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
685 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
687 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
688 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
690 setOperationAction(ISD::AND, MVT::v8i8, Promote);
691 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
692 setOperationAction(ISD::AND, MVT::v4i16, Promote);
693 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
694 setOperationAction(ISD::AND, MVT::v2i32, Promote);
695 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
696 setOperationAction(ISD::AND, MVT::v1i64, Legal);
698 setOperationAction(ISD::OR, MVT::v8i8, Promote);
699 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
700 setOperationAction(ISD::OR, MVT::v4i16, Promote);
701 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
702 setOperationAction(ISD::OR, MVT::v2i32, Promote);
703 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
704 setOperationAction(ISD::OR, MVT::v1i64, Legal);
706 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
707 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
708 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
709 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
710 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
711 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
712 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
714 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
715 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
716 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
717 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
718 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
719 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
720 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
721 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
722 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
724 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
725 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
726 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
727 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
728 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
730 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
731 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
732 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
733 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
735 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
736 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
737 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
738 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
740 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
742 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
743 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
744 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
745 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
746 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
747 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
748 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
751 if (!UseSoftFloat && Subtarget->hasSSE1()) {
752 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
754 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
755 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
756 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
757 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
758 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
759 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
760 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
761 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
762 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
763 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
764 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
765 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
768 if (!UseSoftFloat && Subtarget->hasSSE2()) {
769 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
771 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
772 // registers cannot be used even for integer operations.
773 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
774 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
775 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
776 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
778 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
779 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
780 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
781 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
782 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
783 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
784 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
785 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
786 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
787 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
788 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
789 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
790 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
791 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
792 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
793 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
795 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
796 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
797 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
798 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
800 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
801 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
802 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
803 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
804 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
806 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
807 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
808 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
809 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
810 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
812 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
813 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
814 EVT VT = (MVT::SimpleValueType)i;
815 // Do not attempt to custom lower non-power-of-2 vectors
816 if (!isPowerOf2_32(VT.getVectorNumElements()))
818 // Do not attempt to custom lower non-128-bit vectors
819 if (!VT.is128BitVector())
821 setOperationAction(ISD::BUILD_VECTOR,
822 VT.getSimpleVT().SimpleTy, Custom);
823 setOperationAction(ISD::VECTOR_SHUFFLE,
824 VT.getSimpleVT().SimpleTy, Custom);
825 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
826 VT.getSimpleVT().SimpleTy, Custom);
829 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
830 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
831 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
832 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
833 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
834 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
836 if (Subtarget->is64Bit()) {
837 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
838 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
841 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
842 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
843 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
846 // Do not attempt to promote non-128-bit vectors
847 if (!VT.is128BitVector()) {
850 setOperationAction(ISD::AND, SVT, Promote);
851 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
852 setOperationAction(ISD::OR, SVT, Promote);
853 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
854 setOperationAction(ISD::XOR, SVT, Promote);
855 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
856 setOperationAction(ISD::LOAD, SVT, Promote);
857 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
858 setOperationAction(ISD::SELECT, SVT, Promote);
859 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
862 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
864 // Custom lower v2i64 and v2f64 selects.
865 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
866 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
867 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
868 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
870 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
871 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
872 if (!DisableMMX && Subtarget->hasMMX()) {
873 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
874 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
878 if (Subtarget->hasSSE41()) {
879 // FIXME: Do we need to handle scalar-to-vector here?
880 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
882 // i8 and i16 vectors are custom , because the source register and source
883 // source memory operand types are not the same width. f32 vectors are
884 // custom since the immediate controlling the insert encodes additional
886 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
887 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
888 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
889 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
891 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
892 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
893 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
894 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
896 if (Subtarget->is64Bit()) {
897 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
898 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
902 if (Subtarget->hasSSE42()) {
903 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
906 if (!UseSoftFloat && Subtarget->hasAVX()) {
907 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
908 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
909 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
910 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
912 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
913 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
914 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
915 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
916 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
917 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
918 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
919 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
920 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
921 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
922 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
923 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
924 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
925 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
926 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
928 // Operations to consider commented out -v16i16 v32i8
929 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
930 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
931 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
932 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
933 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
934 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
935 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
936 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
937 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
938 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
939 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
940 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
941 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
942 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
944 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
945 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
946 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
947 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
949 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
950 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
951 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
952 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
953 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
955 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
956 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
957 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
958 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
959 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
960 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
963 // Not sure we want to do this since there are no 256-bit integer
966 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
967 // This includes 256-bit vectors
968 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
969 EVT VT = (MVT::SimpleValueType)i;
971 // Do not attempt to custom lower non-power-of-2 vectors
972 if (!isPowerOf2_32(VT.getVectorNumElements()))
975 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
976 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
977 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
980 if (Subtarget->is64Bit()) {
981 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
982 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
987 // Not sure we want to do this since there are no 256-bit integer
990 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
991 // Including 256-bit vectors
992 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
993 EVT VT = (MVT::SimpleValueType)i;
995 if (!VT.is256BitVector()) {
998 setOperationAction(ISD::AND, VT, Promote);
999 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1000 setOperationAction(ISD::OR, VT, Promote);
1001 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1002 setOperationAction(ISD::XOR, VT, Promote);
1003 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1004 setOperationAction(ISD::LOAD, VT, Promote);
1005 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1006 setOperationAction(ISD::SELECT, VT, Promote);
1007 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1010 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1014 // We want to custom lower some of our intrinsics.
1015 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1017 // Add/Sub/Mul with overflow operations are custom lowered.
1018 setOperationAction(ISD::SADDO, MVT::i32, Custom);
1019 setOperationAction(ISD::SADDO, MVT::i64, Custom);
1020 setOperationAction(ISD::UADDO, MVT::i32, Custom);
1021 setOperationAction(ISD::UADDO, MVT::i64, Custom);
1022 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1023 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
1024 setOperationAction(ISD::USUBO, MVT::i32, Custom);
1025 setOperationAction(ISD::USUBO, MVT::i64, Custom);
1026 setOperationAction(ISD::SMULO, MVT::i32, Custom);
1027 setOperationAction(ISD::SMULO, MVT::i64, Custom);
1029 if (!Subtarget->is64Bit()) {
1030 // These libcalls are not available in 32-bit.
1031 setLibcallName(RTLIB::SHL_I128, 0);
1032 setLibcallName(RTLIB::SRL_I128, 0);
1033 setLibcallName(RTLIB::SRA_I128, 0);
1036 // We have target-specific dag combine patterns for the following nodes:
1037 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1038 setTargetDAGCombine(ISD::BUILD_VECTOR);
1039 setTargetDAGCombine(ISD::SELECT);
1040 setTargetDAGCombine(ISD::SHL);
1041 setTargetDAGCombine(ISD::SRA);
1042 setTargetDAGCombine(ISD::SRL);
1043 setTargetDAGCombine(ISD::OR);
1044 setTargetDAGCombine(ISD::STORE);
1045 setTargetDAGCombine(ISD::MEMBARRIER);
1046 setTargetDAGCombine(ISD::ZERO_EXTEND);
1047 if (Subtarget->is64Bit())
1048 setTargetDAGCombine(ISD::MUL);
1050 computeRegisterProperties();
1052 // FIXME: These should be based on subtarget info. Plus, the values should
1053 // be smaller when we are in optimizing for size mode.
1054 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1055 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
1056 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1057 setPrefLoopAlignment(16);
1058 benefitFromCodePlacementOpt = true;
1062 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1067 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1068 /// the desired ByVal argument alignment.
1069 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1072 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1073 if (VTy->getBitWidth() == 128)
1075 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1076 unsigned EltAlign = 0;
1077 getMaxByValAlign(ATy->getElementType(), EltAlign);
1078 if (EltAlign > MaxAlign)
1079 MaxAlign = EltAlign;
1080 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1081 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1082 unsigned EltAlign = 0;
1083 getMaxByValAlign(STy->getElementType(i), EltAlign);
1084 if (EltAlign > MaxAlign)
1085 MaxAlign = EltAlign;
1093 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1094 /// function arguments in the caller parameter area. For X86, aggregates
1095 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1096 /// are at 4-byte boundaries.
1097 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1098 if (Subtarget->is64Bit()) {
1099 // Max of 8 and alignment of type.
1100 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1107 if (Subtarget->hasSSE1())
1108 getMaxByValAlign(Ty, Align);
1112 /// getOptimalMemOpType - Returns the target specific optimal type for load
1113 /// and store operations as a result of memset, memcpy, and memmove
1114 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1117 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1118 bool isSrcConst, bool isSrcStr,
1119 SelectionDAG &DAG) const {
1120 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1121 // linux. This is because the stack realignment code can't handle certain
1122 // cases like PR2962. This should be removed when PR2962 is fixed.
1123 const Function *F = DAG.getMachineFunction().getFunction();
1124 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1125 if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1126 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1128 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1131 if (Subtarget->is64Bit() && Size >= 8)
1136 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1137 /// current function. The returned value is a member of the
1138 /// MachineJumpTableInfo::JTEntryKind enum.
1139 unsigned X86TargetLowering::getJumpTableEncoding() const {
1140 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1142 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1143 Subtarget->isPICStyleGOT())
1144 return MachineJumpTableInfo::EK_Custom32;
1146 // Otherwise, use the normal jump table encoding heuristics.
1147 return TargetLowering::getJumpTableEncoding();
1150 /// getPICBaseSymbol - Return the X86-32 PIC base.
1152 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1153 MCContext &Ctx) const {
1154 const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1155 return Ctx.GetOrCreateTemporarySymbol(Twine(MAI.getPrivateGlobalPrefix())+
1156 Twine(MF->getFunctionNumber())+"$pb");
1161 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1162 const MachineBasicBlock *MBB,
1163 unsigned uid,MCContext &Ctx) const{
1164 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1165 Subtarget->isPICStyleGOT());
1166 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1168 return X86MCTargetExpr::Create(MBB->getSymbol(),
1169 X86MCTargetExpr::GOTOFF, Ctx);
1172 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1174 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1175 SelectionDAG &DAG) const {
1176 if (!Subtarget->is64Bit())
1177 // This doesn't have DebugLoc associated with it, but is not really the
1178 // same as a Register.
1179 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1184 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1185 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1187 const MCExpr *X86TargetLowering::
1188 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1189 MCContext &Ctx) const {
1190 // X86-64 uses RIP relative addressing based on the jump table label.
1191 if (Subtarget->isPICStyleRIPRel())
1192 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1194 // Otherwise, the reference is relative to the PIC base.
1195 return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1198 /// getFunctionAlignment - Return the Log2 alignment of this function.
1199 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1200 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1203 //===----------------------------------------------------------------------===//
1204 // Return Value Calling Convention Implementation
1205 //===----------------------------------------------------------------------===//
1207 #include "X86GenCallingConv.inc"
1210 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1211 const SmallVectorImpl<EVT> &OutTys,
1212 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1213 SelectionDAG &DAG) {
1214 SmallVector<CCValAssign, 16> RVLocs;
1215 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1216 RVLocs, *DAG.getContext());
1217 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1221 X86TargetLowering::LowerReturn(SDValue Chain,
1222 CallingConv::ID CallConv, bool isVarArg,
1223 const SmallVectorImpl<ISD::OutputArg> &Outs,
1224 DebugLoc dl, SelectionDAG &DAG) {
1226 SmallVector<CCValAssign, 16> RVLocs;
1227 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1228 RVLocs, *DAG.getContext());
1229 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1231 // Add the regs to the liveout set for the function.
1232 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1233 for (unsigned i = 0; i != RVLocs.size(); ++i)
1234 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1235 MRI.addLiveOut(RVLocs[i].getLocReg());
1239 SmallVector<SDValue, 6> RetOps;
1240 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1241 // Operand #1 = Bytes To Pop
1242 RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1244 // Copy the result values into the output registers.
1245 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1246 CCValAssign &VA = RVLocs[i];
1247 assert(VA.isRegLoc() && "Can only return in registers!");
1248 SDValue ValToCopy = Outs[i].Val;
1250 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1251 // the RET instruction and handled by the FP Stackifier.
1252 if (VA.getLocReg() == X86::ST0 ||
1253 VA.getLocReg() == X86::ST1) {
1254 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1255 // change the value to the FP stack register class.
1256 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1257 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1258 RetOps.push_back(ValToCopy);
1259 // Don't emit a copytoreg.
1263 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1264 // which is returned in RAX / RDX.
1265 if (Subtarget->is64Bit()) {
1266 EVT ValVT = ValToCopy.getValueType();
1267 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1268 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1269 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1270 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1274 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1275 Flag = Chain.getValue(1);
1278 // The x86-64 ABI for returning structs by value requires that we copy
1279 // the sret argument into %rax for the return. We saved the argument into
1280 // a virtual register in the entry block, so now we copy the value out
1282 if (Subtarget->is64Bit() &&
1283 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1284 MachineFunction &MF = DAG.getMachineFunction();
1285 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1286 unsigned Reg = FuncInfo->getSRetReturnReg();
1288 Reg = MRI.createVirtualRegister(getRegClassFor(MVT::i64));
1289 FuncInfo->setSRetReturnReg(Reg);
1291 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1293 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1294 Flag = Chain.getValue(1);
1296 // RAX now acts like a return value.
1297 MRI.addLiveOut(X86::RAX);
1300 RetOps[0] = Chain; // Update chain.
1302 // Add the flag if we have it.
1304 RetOps.push_back(Flag);
1306 return DAG.getNode(X86ISD::RET_FLAG, dl,
1307 MVT::Other, &RetOps[0], RetOps.size());
1310 /// LowerCallResult - Lower the result values of a call into the
1311 /// appropriate copies out of appropriate physical registers.
1314 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1315 CallingConv::ID CallConv, bool isVarArg,
1316 const SmallVectorImpl<ISD::InputArg> &Ins,
1317 DebugLoc dl, SelectionDAG &DAG,
1318 SmallVectorImpl<SDValue> &InVals) {
1320 // Assign locations to each value returned by this call.
1321 SmallVector<CCValAssign, 16> RVLocs;
1322 bool Is64Bit = Subtarget->is64Bit();
1323 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1324 RVLocs, *DAG.getContext());
1325 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1327 // Copy all of the result registers out of their specified physreg.
1328 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1329 CCValAssign &VA = RVLocs[i];
1330 EVT CopyVT = VA.getValVT();
1332 // If this is x86-64, and we disabled SSE, we can't return FP values
1333 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1334 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1335 llvm_report_error("SSE register return with SSE disabled");
1338 // If this is a call to a function that returns an fp value on the floating
1339 // point stack, but where we prefer to use the value in xmm registers, copy
1340 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1341 if ((VA.getLocReg() == X86::ST0 ||
1342 VA.getLocReg() == X86::ST1) &&
1343 isScalarFPTypeInSSEReg(VA.getValVT())) {
1348 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1349 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1350 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1351 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1352 MVT::v2i64, InFlag).getValue(1);
1353 Val = Chain.getValue(0);
1354 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1355 Val, DAG.getConstant(0, MVT::i64));
1357 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1358 MVT::i64, InFlag).getValue(1);
1359 Val = Chain.getValue(0);
1361 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1363 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1364 CopyVT, InFlag).getValue(1);
1365 Val = Chain.getValue(0);
1367 InFlag = Chain.getValue(2);
1369 if (CopyVT != VA.getValVT()) {
1370 // Round the F80 the right size, which also moves to the appropriate xmm
1372 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1373 // This truncation won't change the value.
1374 DAG.getIntPtrConstant(1));
1377 InVals.push_back(Val);
1384 //===----------------------------------------------------------------------===//
1385 // C & StdCall & Fast Calling Convention implementation
1386 //===----------------------------------------------------------------------===//
1387 // StdCall calling convention seems to be standard for many Windows' API
1388 // routines and around. It differs from C calling convention just a little:
1389 // callee should clean up the stack, not caller. Symbols should be also
1390 // decorated in some fancy way :) It doesn't support any vector arguments.
1391 // For info on fast calling convention see Fast Calling Convention (tail call)
1392 // implementation LowerX86_32FastCCCallTo.
1394 /// CallIsStructReturn - Determines whether a call uses struct return
1396 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1400 return Outs[0].Flags.isSRet();
1403 /// ArgsAreStructReturn - Determines whether a function uses struct
1404 /// return semantics.
1406 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1410 return Ins[0].Flags.isSRet();
1413 /// IsCalleePop - Determines whether the callee is required to pop its
1414 /// own arguments. Callee pop is necessary to support tail calls.
1415 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1419 switch (CallingConv) {
1422 case CallingConv::X86_StdCall:
1423 return !Subtarget->is64Bit();
1424 case CallingConv::X86_FastCall:
1425 return !Subtarget->is64Bit();
1426 case CallingConv::Fast:
1427 return GuaranteedTailCallOpt;
1428 case CallingConv::GHC:
1429 return GuaranteedTailCallOpt;
1433 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1434 /// given CallingConvention value.
1435 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1436 if (Subtarget->is64Bit()) {
1437 if (CC == CallingConv::GHC)
1438 return CC_X86_64_GHC;
1439 else if (Subtarget->isTargetWin64())
1440 return CC_X86_Win64_C;
1445 if (CC == CallingConv::X86_FastCall)
1446 return CC_X86_32_FastCall;
1447 else if (CC == CallingConv::Fast)
1448 return CC_X86_32_FastCC;
1449 else if (CC == CallingConv::GHC)
1450 return CC_X86_32_GHC;
1455 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1456 /// by "Src" to address "Dst" with size and alignment information specified by
1457 /// the specific parameter attribute. The copy will be passed as a byval
1458 /// function parameter.
1460 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1461 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1463 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1464 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1465 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1468 /// IsTailCallConvention - Return true if the calling convention is one that
1469 /// supports tail call optimization.
1470 static bool IsTailCallConvention(CallingConv::ID CC) {
1471 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1474 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1475 /// a tailcall target by changing its ABI.
1476 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1477 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1481 X86TargetLowering::LowerMemArgument(SDValue Chain,
1482 CallingConv::ID CallConv,
1483 const SmallVectorImpl<ISD::InputArg> &Ins,
1484 DebugLoc dl, SelectionDAG &DAG,
1485 const CCValAssign &VA,
1486 MachineFrameInfo *MFI,
1488 // Create the nodes corresponding to a load from this parameter slot.
1489 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1490 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1491 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1494 // If value is passed by pointer we have address passed instead of the value
1496 if (VA.getLocInfo() == CCValAssign::Indirect)
1497 ValVT = VA.getLocVT();
1499 ValVT = VA.getValVT();
1501 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1502 // changed with more analysis.
1503 // In case of tail call optimization mark all arguments mutable. Since they
1504 // could be overwritten by lowering of arguments in case of a tail call.
1505 if (Flags.isByVal()) {
1506 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1507 VA.getLocMemOffset(), isImmutable, false);
1508 return DAG.getFrameIndex(FI, getPointerTy());
1510 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1511 VA.getLocMemOffset(), isImmutable, false);
1512 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1513 return DAG.getLoad(ValVT, dl, Chain, FIN,
1514 PseudoSourceValue::getFixedStack(FI), 0,
1520 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1521 CallingConv::ID CallConv,
1523 const SmallVectorImpl<ISD::InputArg> &Ins,
1526 SmallVectorImpl<SDValue> &InVals) {
1528 MachineFunction &MF = DAG.getMachineFunction();
1529 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1531 const Function* Fn = MF.getFunction();
1532 if (Fn->hasExternalLinkage() &&
1533 Subtarget->isTargetCygMing() &&
1534 Fn->getName() == "main")
1535 FuncInfo->setForceFramePointer(true);
1537 MachineFrameInfo *MFI = MF.getFrameInfo();
1538 bool Is64Bit = Subtarget->is64Bit();
1539 bool IsWin64 = Subtarget->isTargetWin64();
1541 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1542 "Var args not supported with calling convention fastcc or ghc");
1544 // Assign locations to all of the incoming arguments.
1545 SmallVector<CCValAssign, 16> ArgLocs;
1546 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1547 ArgLocs, *DAG.getContext());
1548 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1550 unsigned LastVal = ~0U;
1552 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1553 CCValAssign &VA = ArgLocs[i];
1554 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1556 assert(VA.getValNo() != LastVal &&
1557 "Don't support value assigned to multiple locs yet");
1558 LastVal = VA.getValNo();
1560 if (VA.isRegLoc()) {
1561 EVT RegVT = VA.getLocVT();
1562 TargetRegisterClass *RC = NULL;
1563 if (RegVT == MVT::i32)
1564 RC = X86::GR32RegisterClass;
1565 else if (Is64Bit && RegVT == MVT::i64)
1566 RC = X86::GR64RegisterClass;
1567 else if (RegVT == MVT::f32)
1568 RC = X86::FR32RegisterClass;
1569 else if (RegVT == MVT::f64)
1570 RC = X86::FR64RegisterClass;
1571 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1572 RC = X86::VR128RegisterClass;
1573 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1574 RC = X86::VR64RegisterClass;
1576 llvm_unreachable("Unknown argument type!");
1578 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1579 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1581 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1582 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1584 if (VA.getLocInfo() == CCValAssign::SExt)
1585 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1586 DAG.getValueType(VA.getValVT()));
1587 else if (VA.getLocInfo() == CCValAssign::ZExt)
1588 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1589 DAG.getValueType(VA.getValVT()));
1590 else if (VA.getLocInfo() == CCValAssign::BCvt)
1591 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1593 if (VA.isExtInLoc()) {
1594 // Handle MMX values passed in XMM regs.
1595 if (RegVT.isVector()) {
1596 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1597 ArgValue, DAG.getConstant(0, MVT::i64));
1598 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1600 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1603 assert(VA.isMemLoc());
1604 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1607 // If value is passed via pointer - do a load.
1608 if (VA.getLocInfo() == CCValAssign::Indirect)
1609 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1612 InVals.push_back(ArgValue);
1615 // The x86-64 ABI for returning structs by value requires that we copy
1616 // the sret argument into %rax for the return. Save the argument into
1617 // a virtual register so that we can access it from the return points.
1618 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1619 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1620 unsigned Reg = FuncInfo->getSRetReturnReg();
1622 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1623 FuncInfo->setSRetReturnReg(Reg);
1625 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1626 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1629 unsigned StackSize = CCInfo.getNextStackOffset();
1630 // Align stack specially for tail calls.
1631 if (FuncIsMadeTailCallSafe(CallConv))
1632 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1634 // If the function takes variable number of arguments, make a frame index for
1635 // the start of the first vararg value... for expansion of llvm.va_start.
1637 if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1638 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1641 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1643 // FIXME: We should really autogenerate these arrays
1644 static const unsigned GPR64ArgRegsWin64[] = {
1645 X86::RCX, X86::RDX, X86::R8, X86::R9
1647 static const unsigned XMMArgRegsWin64[] = {
1648 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1650 static const unsigned GPR64ArgRegs64Bit[] = {
1651 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1653 static const unsigned XMMArgRegs64Bit[] = {
1654 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1655 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1657 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1660 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1661 GPR64ArgRegs = GPR64ArgRegsWin64;
1662 XMMArgRegs = XMMArgRegsWin64;
1664 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1665 GPR64ArgRegs = GPR64ArgRegs64Bit;
1666 XMMArgRegs = XMMArgRegs64Bit;
1668 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1670 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1673 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1674 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1675 "SSE register cannot be used when SSE is disabled!");
1676 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1677 "SSE register cannot be used when SSE is disabled!");
1678 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1679 // Kernel mode asks for SSE to be disabled, so don't push them
1681 TotalNumXMMRegs = 0;
1683 // For X86-64, if there are vararg parameters that are passed via
1684 // registers, then we must store them to their spots on the stack so they
1685 // may be loaded by deferencing the result of va_next.
1686 VarArgsGPOffset = NumIntRegs * 8;
1687 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1688 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1689 TotalNumXMMRegs * 16, 16,
1692 // Store the integer parameter registers.
1693 SmallVector<SDValue, 8> MemOps;
1694 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1695 unsigned Offset = VarArgsGPOffset;
1696 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1697 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1698 DAG.getIntPtrConstant(Offset));
1699 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1700 X86::GR64RegisterClass);
1701 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1703 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1704 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1705 Offset, false, false, 0);
1706 MemOps.push_back(Store);
1710 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1711 // Now store the XMM (fp + vector) parameter registers.
1712 SmallVector<SDValue, 11> SaveXMMOps;
1713 SaveXMMOps.push_back(Chain);
1715 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1716 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1717 SaveXMMOps.push_back(ALVal);
1719 SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1720 SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1722 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1723 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1724 X86::VR128RegisterClass);
1725 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1726 SaveXMMOps.push_back(Val);
1728 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1730 &SaveXMMOps[0], SaveXMMOps.size()));
1733 if (!MemOps.empty())
1734 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1735 &MemOps[0], MemOps.size());
1739 // Some CCs need callee pop.
1740 if (IsCalleePop(isVarArg, CallConv)) {
1741 BytesToPopOnReturn = StackSize; // Callee pops everything.
1743 BytesToPopOnReturn = 0; // Callee pops nothing.
1744 // If this is an sret function, the return should pop the hidden pointer.
1745 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1746 BytesToPopOnReturn = 4;
1750 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1751 if (CallConv == CallingConv::X86_FastCall)
1752 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1755 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1761 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1762 SDValue StackPtr, SDValue Arg,
1763 DebugLoc dl, SelectionDAG &DAG,
1764 const CCValAssign &VA,
1765 ISD::ArgFlagsTy Flags) {
1766 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1767 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1768 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1769 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1770 if (Flags.isByVal()) {
1771 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1773 return DAG.getStore(Chain, dl, Arg, PtrOff,
1774 PseudoSourceValue::getStack(), LocMemOffset,
1778 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1779 /// optimization is performed and it is required.
1781 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1782 SDValue &OutRetAddr, SDValue Chain,
1783 bool IsTailCall, bool Is64Bit,
1784 int FPDiff, DebugLoc dl) {
1785 // Adjust the Return address stack slot.
1786 EVT VT = getPointerTy();
1787 OutRetAddr = getReturnAddressFrameIndex(DAG);
1789 // Load the "old" Return address.
1790 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1791 return SDValue(OutRetAddr.getNode(), 1);
1794 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1795 /// optimization is performed and it is required (FPDiff!=0).
1797 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1798 SDValue Chain, SDValue RetAddrFrIdx,
1799 bool Is64Bit, int FPDiff, DebugLoc dl) {
1800 // Store the return address to the appropriate stack slot.
1801 if (!FPDiff) return Chain;
1802 // Calculate the new stack slot for the return address.
1803 int SlotSize = Is64Bit ? 8 : 4;
1804 int NewReturnAddrFI =
1805 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false, false);
1806 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1807 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1808 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1809 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1815 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1816 CallingConv::ID CallConv, bool isVarArg,
1818 const SmallVectorImpl<ISD::OutputArg> &Outs,
1819 const SmallVectorImpl<ISD::InputArg> &Ins,
1820 DebugLoc dl, SelectionDAG &DAG,
1821 SmallVectorImpl<SDValue> &InVals) {
1822 MachineFunction &MF = DAG.getMachineFunction();
1823 bool Is64Bit = Subtarget->is64Bit();
1824 bool IsStructRet = CallIsStructReturn(Outs);
1825 bool IsSibcall = false;
1828 // Check if it's really possible to do a tail call.
1829 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
1832 // Sibcalls are automatically detected tailcalls which do not require
1834 if (!GuaranteedTailCallOpt && isTailCall)
1841 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1842 "Var args not supported with calling convention fastcc or ghc");
1844 // Analyze operands of the call, assigning locations to each operand.
1845 SmallVector<CCValAssign, 16> ArgLocs;
1846 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1847 ArgLocs, *DAG.getContext());
1848 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1850 // Get a count of how many bytes are to be pushed on the stack.
1851 unsigned NumBytes = CCInfo.getNextStackOffset();
1853 // This is a sibcall. The memory operands are available in caller's
1854 // own caller's stack.
1856 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1857 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1860 if (isTailCall && !IsSibcall) {
1861 // Lower arguments at fp - stackoffset + fpdiff.
1862 unsigned NumBytesCallerPushed =
1863 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1864 FPDiff = NumBytesCallerPushed - NumBytes;
1866 // Set the delta of movement of the returnaddr stackslot.
1867 // But only set if delta is greater than previous delta.
1868 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1869 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1873 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1875 SDValue RetAddrFrIdx;
1876 // Load return adress for tail calls.
1877 if (isTailCall && FPDiff)
1878 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1879 Is64Bit, FPDiff, dl);
1881 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1882 SmallVector<SDValue, 8> MemOpChains;
1885 // Walk the register/memloc assignments, inserting copies/loads. In the case
1886 // of tail call optimization arguments are handle later.
1887 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1888 CCValAssign &VA = ArgLocs[i];
1889 EVT RegVT = VA.getLocVT();
1890 SDValue Arg = Outs[i].Val;
1891 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1892 bool isByVal = Flags.isByVal();
1894 // Promote the value if needed.
1895 switch (VA.getLocInfo()) {
1896 default: llvm_unreachable("Unknown loc info!");
1897 case CCValAssign::Full: break;
1898 case CCValAssign::SExt:
1899 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1901 case CCValAssign::ZExt:
1902 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1904 case CCValAssign::AExt:
1905 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1906 // Special case: passing MMX values in XMM registers.
1907 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1908 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1909 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1911 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1913 case CCValAssign::BCvt:
1914 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1916 case CCValAssign::Indirect: {
1917 // Store the argument.
1918 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1919 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1920 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1921 PseudoSourceValue::getFixedStack(FI), 0,
1928 if (VA.isRegLoc()) {
1929 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1930 } else if (!IsSibcall && (!isTailCall || isByVal)) {
1931 assert(VA.isMemLoc());
1932 if (StackPtr.getNode() == 0)
1933 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1934 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1935 dl, DAG, VA, Flags));
1939 if (!MemOpChains.empty())
1940 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1941 &MemOpChains[0], MemOpChains.size());
1943 // Build a sequence of copy-to-reg nodes chained together with token chain
1944 // and flag operands which copy the outgoing args into registers.
1946 // Tail call byval lowering might overwrite argument registers so in case of
1947 // tail call optimization the copies to registers are lowered later.
1949 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1950 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1951 RegsToPass[i].second, InFlag);
1952 InFlag = Chain.getValue(1);
1955 if (Subtarget->isPICStyleGOT()) {
1956 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1959 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1960 DAG.getNode(X86ISD::GlobalBaseReg,
1961 DebugLoc::getUnknownLoc(),
1964 InFlag = Chain.getValue(1);
1966 // If we are tail calling and generating PIC/GOT style code load the
1967 // address of the callee into ECX. The value in ecx is used as target of
1968 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1969 // for tail calls on PIC/GOT architectures. Normally we would just put the
1970 // address of GOT into ebx and then call target@PLT. But for tail calls
1971 // ebx would be restored (since ebx is callee saved) before jumping to the
1974 // Note: The actual moving to ECX is done further down.
1975 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1976 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1977 !G->getGlobal()->hasProtectedVisibility())
1978 Callee = LowerGlobalAddress(Callee, DAG);
1979 else if (isa<ExternalSymbolSDNode>(Callee))
1980 Callee = LowerExternalSymbol(Callee, DAG);
1984 if (Is64Bit && isVarArg) {
1985 // From AMD64 ABI document:
1986 // For calls that may call functions that use varargs or stdargs
1987 // (prototype-less calls or calls to functions containing ellipsis (...) in
1988 // the declaration) %al is used as hidden argument to specify the number
1989 // of SSE registers used. The contents of %al do not need to match exactly
1990 // the number of registers, but must be an ubound on the number of SSE
1991 // registers used and is in the range 0 - 8 inclusive.
1993 // FIXME: Verify this on Win64
1994 // Count the number of XMM registers allocated.
1995 static const unsigned XMMArgRegs[] = {
1996 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1997 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1999 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2000 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2001 && "SSE registers cannot be used when SSE is disabled");
2003 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2004 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2005 InFlag = Chain.getValue(1);
2009 // For tail calls lower the arguments to the 'real' stack slot.
2011 // Force all the incoming stack arguments to be loaded from the stack
2012 // before any new outgoing arguments are stored to the stack, because the
2013 // outgoing stack slots may alias the incoming argument stack slots, and
2014 // the alias isn't otherwise explicit. This is slightly more conservative
2015 // than necessary, because it means that each store effectively depends
2016 // on every argument instead of just those arguments it would clobber.
2017 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2019 SmallVector<SDValue, 8> MemOpChains2;
2022 // Do not flag preceeding copytoreg stuff together with the following stuff.
2024 if (GuaranteedTailCallOpt) {
2025 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2026 CCValAssign &VA = ArgLocs[i];
2029 assert(VA.isMemLoc());
2030 SDValue Arg = Outs[i].Val;
2031 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2032 // Create frame index.
2033 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2034 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2035 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
2036 FIN = DAG.getFrameIndex(FI, getPointerTy());
2038 if (Flags.isByVal()) {
2039 // Copy relative to framepointer.
2040 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2041 if (StackPtr.getNode() == 0)
2042 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2044 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2046 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2050 // Store relative to framepointer.
2051 MemOpChains2.push_back(
2052 DAG.getStore(ArgChain, dl, Arg, FIN,
2053 PseudoSourceValue::getFixedStack(FI), 0,
2059 if (!MemOpChains2.empty())
2060 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2061 &MemOpChains2[0], MemOpChains2.size());
2063 // Copy arguments to their registers.
2064 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2065 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2066 RegsToPass[i].second, InFlag);
2067 InFlag = Chain.getValue(1);
2071 // Store the return address to the appropriate stack slot.
2072 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2076 bool WasGlobalOrExternal = false;
2077 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2078 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2079 // In the 64-bit large code model, we have to make all calls
2080 // through a register, since the call instruction's 32-bit
2081 // pc-relative offset may not be large enough to hold the whole
2083 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2084 WasGlobalOrExternal = true;
2085 // If the callee is a GlobalAddress node (quite common, every direct call
2086 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2089 // We should use extra load for direct calls to dllimported functions in
2091 GlobalValue *GV = G->getGlobal();
2092 if (!GV->hasDLLImportLinkage()) {
2093 unsigned char OpFlags = 0;
2095 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2096 // external symbols most go through the PLT in PIC mode. If the symbol
2097 // has hidden or protected visibility, or if it is static or local, then
2098 // we don't need to use the PLT - we can directly call it.
2099 if (Subtarget->isTargetELF() &&
2100 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2101 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2102 OpFlags = X86II::MO_PLT;
2103 } else if (Subtarget->isPICStyleStubAny() &&
2104 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2105 Subtarget->getDarwinVers() < 9) {
2106 // PC-relative references to external symbols should go through $stub,
2107 // unless we're building with the leopard linker or later, which
2108 // automatically synthesizes these stubs.
2109 OpFlags = X86II::MO_DARWIN_STUB;
2112 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2113 G->getOffset(), OpFlags);
2115 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2116 WasGlobalOrExternal = true;
2117 unsigned char OpFlags = 0;
2119 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2120 // symbols should go through the PLT.
2121 if (Subtarget->isTargetELF() &&
2122 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2123 OpFlags = X86II::MO_PLT;
2124 } else if (Subtarget->isPICStyleStubAny() &&
2125 Subtarget->getDarwinVers() < 9) {
2126 // PC-relative references to external symbols should go through $stub,
2127 // unless we're building with the leopard linker or later, which
2128 // automatically synthesizes these stubs.
2129 OpFlags = X86II::MO_DARWIN_STUB;
2132 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2136 // Returns a chain & a flag for retval copy to use.
2137 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2138 SmallVector<SDValue, 8> Ops;
2140 if (!IsSibcall && isTailCall) {
2141 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2142 DAG.getIntPtrConstant(0, true), InFlag);
2143 InFlag = Chain.getValue(1);
2146 Ops.push_back(Chain);
2147 Ops.push_back(Callee);
2150 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2152 // Add argument registers to the end of the list so that they are known live
2154 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2155 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2156 RegsToPass[i].second.getValueType()));
2158 // Add an implicit use GOT pointer in EBX.
2159 if (!isTailCall && Subtarget->isPICStyleGOT())
2160 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2162 // Add an implicit use of AL for x86 vararg functions.
2163 if (Is64Bit && isVarArg)
2164 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2166 if (InFlag.getNode())
2167 Ops.push_back(InFlag);
2170 // If this is the first return lowered for this function, add the regs
2171 // to the liveout set for the function.
2172 if (MF.getRegInfo().liveout_empty()) {
2173 SmallVector<CCValAssign, 16> RVLocs;
2174 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2176 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2177 for (unsigned i = 0; i != RVLocs.size(); ++i)
2178 if (RVLocs[i].isRegLoc())
2179 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2181 return DAG.getNode(X86ISD::TC_RETURN, dl,
2182 NodeTys, &Ops[0], Ops.size());
2185 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2186 InFlag = Chain.getValue(1);
2188 // Create the CALLSEQ_END node.
2189 unsigned NumBytesForCalleeToPush;
2190 if (IsCalleePop(isVarArg, CallConv))
2191 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2192 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2193 // If this is a call to a struct-return function, the callee
2194 // pops the hidden struct pointer, so we have to push it back.
2195 // This is common for Darwin/X86, Linux & Mingw32 targets.
2196 NumBytesForCalleeToPush = 4;
2198 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2200 // Returns a flag for retval copy to use.
2202 Chain = DAG.getCALLSEQ_END(Chain,
2203 DAG.getIntPtrConstant(NumBytes, true),
2204 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2207 InFlag = Chain.getValue(1);
2210 // Handle result values, copying them out of physregs into vregs that we
2212 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2213 Ins, dl, DAG, InVals);
2217 //===----------------------------------------------------------------------===//
2218 // Fast Calling Convention (tail call) implementation
2219 //===----------------------------------------------------------------------===//
2221 // Like std call, callee cleans arguments, convention except that ECX is
2222 // reserved for storing the tail called function address. Only 2 registers are
2223 // free for argument passing (inreg). Tail call optimization is performed
2225 // * tailcallopt is enabled
2226 // * caller/callee are fastcc
2227 // On X86_64 architecture with GOT-style position independent code only local
2228 // (within module) calls are supported at the moment.
2229 // To keep the stack aligned according to platform abi the function
2230 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2231 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2232 // If a tail called function callee has more arguments than the caller the
2233 // caller needs to make sure that there is room to move the RETADDR to. This is
2234 // achieved by reserving an area the size of the argument delta right after the
2235 // original REtADDR, but before the saved framepointer or the spilled registers
2236 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2248 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2249 /// for a 16 byte align requirement.
2250 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2251 SelectionDAG& DAG) {
2252 MachineFunction &MF = DAG.getMachineFunction();
2253 const TargetMachine &TM = MF.getTarget();
2254 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2255 unsigned StackAlignment = TFI.getStackAlignment();
2256 uint64_t AlignMask = StackAlignment - 1;
2257 int64_t Offset = StackSize;
2258 uint64_t SlotSize = TD->getPointerSize();
2259 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2260 // Number smaller than 12 so just add the difference.
2261 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2263 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2264 Offset = ((~AlignMask) & Offset) + StackAlignment +
2265 (StackAlignment-SlotSize);
2270 /// MatchingStackOffset - Return true if the given stack call argument is
2271 /// already available in the same position (relatively) of the caller's
2272 /// incoming argument stack.
2274 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2275 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2276 const X86InstrInfo *TII) {
2277 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2279 if (Arg.getOpcode() == ISD::CopyFromReg) {
2280 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2281 if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2283 MachineInstr *Def = MRI->getVRegDef(VR);
2286 if (!Flags.isByVal()) {
2287 if (!TII->isLoadFromStackSlot(Def, FI))
2290 unsigned Opcode = Def->getOpcode();
2291 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2292 Def->getOperand(1).isFI()) {
2293 FI = Def->getOperand(1).getIndex();
2294 Bytes = Flags.getByValSize();
2298 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2299 if (Flags.isByVal())
2300 // ByVal argument is passed in as a pointer but it's now being
2301 // dereferenced. e.g.
2302 // define @foo(%struct.X* %A) {
2303 // tail call @bar(%struct.X* byval %A)
2306 SDValue Ptr = Ld->getBasePtr();
2307 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2310 FI = FINode->getIndex();
2314 assert(FI != INT_MAX);
2315 if (!MFI->isFixedObjectIndex(FI))
2317 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2320 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2321 /// for tail call optimization. Targets which want to do tail call
2322 /// optimization should implement this function.
2324 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2325 CallingConv::ID CalleeCC,
2327 const SmallVectorImpl<ISD::OutputArg> &Outs,
2328 const SmallVectorImpl<ISD::InputArg> &Ins,
2329 SelectionDAG& DAG) const {
2330 if (!IsTailCallConvention(CalleeCC) &&
2331 CalleeCC != CallingConv::C)
2334 // If -tailcallopt is specified, make fastcc functions tail-callable.
2335 const Function *CallerF = DAG.getMachineFunction().getFunction();
2336 if (GuaranteedTailCallOpt) {
2337 if (IsTailCallConvention(CalleeCC) &&
2338 CallerF->getCallingConv() == CalleeCC)
2343 // Look for obvious safe cases to perform tail call optimization that does not
2344 // requite ABI changes. This is what gcc calls sibcall.
2346 // Do not tail call optimize vararg calls for now.
2350 // If the callee takes no arguments then go on to check the results of the
2352 if (!Outs.empty()) {
2353 // Check if stack adjustment is needed. For now, do not do this if any
2354 // argument is passed on the stack.
2355 SmallVector<CCValAssign, 16> ArgLocs;
2356 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2357 ArgLocs, *DAG.getContext());
2358 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2359 if (CCInfo.getNextStackOffset()) {
2360 MachineFunction &MF = DAG.getMachineFunction();
2361 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2363 if (Subtarget->isTargetWin64())
2364 // Win64 ABI has additional complications.
2367 // Check if the arguments are already laid out in the right way as
2368 // the caller's fixed stack objects.
2369 MachineFrameInfo *MFI = MF.getFrameInfo();
2370 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2371 const X86InstrInfo *TII =
2372 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2373 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2374 CCValAssign &VA = ArgLocs[i];
2375 EVT RegVT = VA.getLocVT();
2376 SDValue Arg = Outs[i].Val;
2377 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2378 if (VA.getLocInfo() == CCValAssign::Indirect)
2380 if (!VA.isRegLoc()) {
2381 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2393 X86TargetLowering::createFastISel(MachineFunction &mf, MachineModuleInfo *mmo,
2395 DenseMap<const Value *, unsigned> &vm,
2396 DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2397 DenseMap<const AllocaInst *, int> &am
2399 , SmallSet<Instruction*, 8> &cil
2402 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2410 //===----------------------------------------------------------------------===//
2411 // Other Lowering Hooks
2412 //===----------------------------------------------------------------------===//
2415 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2416 MachineFunction &MF = DAG.getMachineFunction();
2417 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2418 int ReturnAddrIndex = FuncInfo->getRAIndex();
2420 if (ReturnAddrIndex == 0) {
2421 // Set up a frame object for the return address.
2422 uint64_t SlotSize = TD->getPointerSize();
2423 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2425 FuncInfo->setRAIndex(ReturnAddrIndex);
2428 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2432 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2433 bool hasSymbolicDisplacement) {
2434 // Offset should fit into 32 bit immediate field.
2435 if (!isInt32(Offset))
2438 // If we don't have a symbolic displacement - we don't have any extra
2440 if (!hasSymbolicDisplacement)
2443 // FIXME: Some tweaks might be needed for medium code model.
2444 if (M != CodeModel::Small && M != CodeModel::Kernel)
2447 // For small code model we assume that latest object is 16MB before end of 31
2448 // bits boundary. We may also accept pretty large negative constants knowing
2449 // that all objects are in the positive half of address space.
2450 if (M == CodeModel::Small && Offset < 16*1024*1024)
2453 // For kernel code model we know that all object resist in the negative half
2454 // of 32bits address space. We may not accept negative offsets, since they may
2455 // be just off and we may accept pretty large positive ones.
2456 if (M == CodeModel::Kernel && Offset > 0)
2462 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2463 /// specific condition code, returning the condition code and the LHS/RHS of the
2464 /// comparison to make.
2465 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2466 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2468 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2469 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2470 // X > -1 -> X == 0, jump !sign.
2471 RHS = DAG.getConstant(0, RHS.getValueType());
2472 return X86::COND_NS;
2473 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2474 // X < 0 -> X == 0, jump on sign.
2476 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2478 RHS = DAG.getConstant(0, RHS.getValueType());
2479 return X86::COND_LE;
2483 switch (SetCCOpcode) {
2484 default: llvm_unreachable("Invalid integer condition!");
2485 case ISD::SETEQ: return X86::COND_E;
2486 case ISD::SETGT: return X86::COND_G;
2487 case ISD::SETGE: return X86::COND_GE;
2488 case ISD::SETLT: return X86::COND_L;
2489 case ISD::SETLE: return X86::COND_LE;
2490 case ISD::SETNE: return X86::COND_NE;
2491 case ISD::SETULT: return X86::COND_B;
2492 case ISD::SETUGT: return X86::COND_A;
2493 case ISD::SETULE: return X86::COND_BE;
2494 case ISD::SETUGE: return X86::COND_AE;
2498 // First determine if it is required or is profitable to flip the operands.
2500 // If LHS is a foldable load, but RHS is not, flip the condition.
2501 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2502 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2503 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2504 std::swap(LHS, RHS);
2507 switch (SetCCOpcode) {
2513 std::swap(LHS, RHS);
2517 // On a floating point condition, the flags are set as follows:
2519 // 0 | 0 | 0 | X > Y
2520 // 0 | 0 | 1 | X < Y
2521 // 1 | 0 | 0 | X == Y
2522 // 1 | 1 | 1 | unordered
2523 switch (SetCCOpcode) {
2524 default: llvm_unreachable("Condcode should be pre-legalized away");
2526 case ISD::SETEQ: return X86::COND_E;
2527 case ISD::SETOLT: // flipped
2529 case ISD::SETGT: return X86::COND_A;
2530 case ISD::SETOLE: // flipped
2532 case ISD::SETGE: return X86::COND_AE;
2533 case ISD::SETUGT: // flipped
2535 case ISD::SETLT: return X86::COND_B;
2536 case ISD::SETUGE: // flipped
2538 case ISD::SETLE: return X86::COND_BE;
2540 case ISD::SETNE: return X86::COND_NE;
2541 case ISD::SETUO: return X86::COND_P;
2542 case ISD::SETO: return X86::COND_NP;
2544 case ISD::SETUNE: return X86::COND_INVALID;
2548 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2549 /// code. Current x86 isa includes the following FP cmov instructions:
2550 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2551 static bool hasFPCMov(unsigned X86CC) {
2567 /// isFPImmLegal - Returns true if the target can instruction select the
2568 /// specified FP immediate natively. If false, the legalizer will
2569 /// materialize the FP immediate as a load from a constant pool.
2570 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2571 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2572 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2578 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2579 /// the specified range (L, H].
2580 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2581 return (Val < 0) || (Val >= Low && Val < Hi);
2584 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2585 /// specified value.
2586 static bool isUndefOrEqual(int Val, int CmpVal) {
2587 if (Val < 0 || Val == CmpVal)
2592 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2593 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2594 /// the second operand.
2595 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2596 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2597 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2598 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2599 return (Mask[0] < 2 && Mask[1] < 2);
2603 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2604 SmallVector<int, 8> M;
2606 return ::isPSHUFDMask(M, N->getValueType(0));
2609 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2610 /// is suitable for input to PSHUFHW.
2611 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2612 if (VT != MVT::v8i16)
2615 // Lower quadword copied in order or undef.
2616 for (int i = 0; i != 4; ++i)
2617 if (Mask[i] >= 0 && Mask[i] != i)
2620 // Upper quadword shuffled.
2621 for (int i = 4; i != 8; ++i)
2622 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2628 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2629 SmallVector<int, 8> M;
2631 return ::isPSHUFHWMask(M, N->getValueType(0));
2634 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2635 /// is suitable for input to PSHUFLW.
2636 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2637 if (VT != MVT::v8i16)
2640 // Upper quadword copied in order.
2641 for (int i = 4; i != 8; ++i)
2642 if (Mask[i] >= 0 && Mask[i] != i)
2645 // Lower quadword shuffled.
2646 for (int i = 0; i != 4; ++i)
2653 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2654 SmallVector<int, 8> M;
2656 return ::isPSHUFLWMask(M, N->getValueType(0));
2659 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2660 /// is suitable for input to PALIGNR.
2661 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2663 int i, e = VT.getVectorNumElements();
2665 // Do not handle v2i64 / v2f64 shuffles with palignr.
2666 if (e < 4 || !hasSSSE3)
2669 for (i = 0; i != e; ++i)
2673 // All undef, not a palignr.
2677 // Determine if it's ok to perform a palignr with only the LHS, since we
2678 // don't have access to the actual shuffle elements to see if RHS is undef.
2679 bool Unary = Mask[i] < (int)e;
2680 bool NeedsUnary = false;
2682 int s = Mask[i] - i;
2684 // Check the rest of the elements to see if they are consecutive.
2685 for (++i; i != e; ++i) {
2690 Unary = Unary && (m < (int)e);
2691 NeedsUnary = NeedsUnary || (m < s);
2693 if (NeedsUnary && !Unary)
2695 if (Unary && m != ((s+i) & (e-1)))
2697 if (!Unary && m != (s+i))
2703 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2704 SmallVector<int, 8> M;
2706 return ::isPALIGNRMask(M, N->getValueType(0), true);
2709 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2710 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2711 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2712 int NumElems = VT.getVectorNumElements();
2713 if (NumElems != 2 && NumElems != 4)
2716 int Half = NumElems / 2;
2717 for (int i = 0; i < Half; ++i)
2718 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2720 for (int i = Half; i < NumElems; ++i)
2721 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2727 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2728 SmallVector<int, 8> M;
2730 return ::isSHUFPMask(M, N->getValueType(0));
2733 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2734 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2735 /// half elements to come from vector 1 (which would equal the dest.) and
2736 /// the upper half to come from vector 2.
2737 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2738 int NumElems = VT.getVectorNumElements();
2740 if (NumElems != 2 && NumElems != 4)
2743 int Half = NumElems / 2;
2744 for (int i = 0; i < Half; ++i)
2745 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2747 for (int i = Half; i < NumElems; ++i)
2748 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2753 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2754 SmallVector<int, 8> M;
2756 return isCommutedSHUFPMask(M, N->getValueType(0));
2759 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2760 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2761 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2762 if (N->getValueType(0).getVectorNumElements() != 4)
2765 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2766 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2767 isUndefOrEqual(N->getMaskElt(1), 7) &&
2768 isUndefOrEqual(N->getMaskElt(2), 2) &&
2769 isUndefOrEqual(N->getMaskElt(3), 3);
2772 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2773 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2775 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2776 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2781 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2782 isUndefOrEqual(N->getMaskElt(1), 3) &&
2783 isUndefOrEqual(N->getMaskElt(2), 2) &&
2784 isUndefOrEqual(N->getMaskElt(3), 3);
2787 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2788 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2789 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2790 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2792 if (NumElems != 2 && NumElems != 4)
2795 for (unsigned i = 0; i < NumElems/2; ++i)
2796 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2799 for (unsigned i = NumElems/2; i < NumElems; ++i)
2800 if (!isUndefOrEqual(N->getMaskElt(i), i))
2806 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2807 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2808 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2809 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2811 if (NumElems != 2 && NumElems != 4)
2814 for (unsigned i = 0; i < NumElems/2; ++i)
2815 if (!isUndefOrEqual(N->getMaskElt(i), i))
2818 for (unsigned i = 0; i < NumElems/2; ++i)
2819 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2825 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2826 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2827 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2828 bool V2IsSplat = false) {
2829 int NumElts = VT.getVectorNumElements();
2830 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2833 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2835 int BitI1 = Mask[i+1];
2836 if (!isUndefOrEqual(BitI, j))
2839 if (!isUndefOrEqual(BitI1, NumElts))
2842 if (!isUndefOrEqual(BitI1, j + NumElts))
2849 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2850 SmallVector<int, 8> M;
2852 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2855 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2856 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2857 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2858 bool V2IsSplat = false) {
2859 int NumElts = VT.getVectorNumElements();
2860 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2863 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2865 int BitI1 = Mask[i+1];
2866 if (!isUndefOrEqual(BitI, j + NumElts/2))
2869 if (isUndefOrEqual(BitI1, NumElts))
2872 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2879 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2880 SmallVector<int, 8> M;
2882 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2885 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2886 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2888 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2889 int NumElems = VT.getVectorNumElements();
2890 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2893 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2895 int BitI1 = Mask[i+1];
2896 if (!isUndefOrEqual(BitI, j))
2898 if (!isUndefOrEqual(BitI1, j))
2904 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2905 SmallVector<int, 8> M;
2907 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2910 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2911 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2913 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2914 int NumElems = VT.getVectorNumElements();
2915 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2918 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2920 int BitI1 = Mask[i+1];
2921 if (!isUndefOrEqual(BitI, j))
2923 if (!isUndefOrEqual(BitI1, j))
2929 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2930 SmallVector<int, 8> M;
2932 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2935 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2936 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2937 /// MOVSD, and MOVD, i.e. setting the lowest element.
2938 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2939 if (VT.getVectorElementType().getSizeInBits() < 32)
2942 int NumElts = VT.getVectorNumElements();
2944 if (!isUndefOrEqual(Mask[0], NumElts))
2947 for (int i = 1; i < NumElts; ++i)
2948 if (!isUndefOrEqual(Mask[i], i))
2954 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2955 SmallVector<int, 8> M;
2957 return ::isMOVLMask(M, N->getValueType(0));
2960 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2961 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2962 /// element of vector 2 and the other elements to come from vector 1 in order.
2963 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2964 bool V2IsSplat = false, bool V2IsUndef = false) {
2965 int NumOps = VT.getVectorNumElements();
2966 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2969 if (!isUndefOrEqual(Mask[0], 0))
2972 for (int i = 1; i < NumOps; ++i)
2973 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2974 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2975 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2981 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2982 bool V2IsUndef = false) {
2983 SmallVector<int, 8> M;
2985 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2988 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2989 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2990 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2991 if (N->getValueType(0).getVectorNumElements() != 4)
2994 // Expect 1, 1, 3, 3
2995 for (unsigned i = 0; i < 2; ++i) {
2996 int Elt = N->getMaskElt(i);
2997 if (Elt >= 0 && Elt != 1)
3002 for (unsigned i = 2; i < 4; ++i) {
3003 int Elt = N->getMaskElt(i);
3004 if (Elt >= 0 && Elt != 3)
3009 // Don't use movshdup if it can be done with a shufps.
3010 // FIXME: verify that matching u, u, 3, 3 is what we want.
3014 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3015 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3016 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3017 if (N->getValueType(0).getVectorNumElements() != 4)
3020 // Expect 0, 0, 2, 2
3021 for (unsigned i = 0; i < 2; ++i)
3022 if (N->getMaskElt(i) > 0)
3026 for (unsigned i = 2; i < 4; ++i) {
3027 int Elt = N->getMaskElt(i);
3028 if (Elt >= 0 && Elt != 2)
3033 // Don't use movsldup if it can be done with a shufps.
3037 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3038 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3039 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3040 int e = N->getValueType(0).getVectorNumElements() / 2;
3042 for (int i = 0; i < e; ++i)
3043 if (!isUndefOrEqual(N->getMaskElt(i), i))
3045 for (int i = 0; i < e; ++i)
3046 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3051 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3052 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3053 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3054 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3055 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3057 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3059 for (int i = 0; i < NumOperands; ++i) {
3060 int Val = SVOp->getMaskElt(NumOperands-i-1);
3061 if (Val < 0) Val = 0;
3062 if (Val >= NumOperands) Val -= NumOperands;
3064 if (i != NumOperands - 1)
3070 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3071 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3072 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3073 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3075 // 8 nodes, but we only care about the last 4.
3076 for (unsigned i = 7; i >= 4; --i) {
3077 int Val = SVOp->getMaskElt(i);
3086 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3087 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3088 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3089 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3091 // 8 nodes, but we only care about the first 4.
3092 for (int i = 3; i >= 0; --i) {
3093 int Val = SVOp->getMaskElt(i);
3102 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3103 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3104 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3105 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3106 EVT VVT = N->getValueType(0);
3107 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3111 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3112 Val = SVOp->getMaskElt(i);
3116 return (Val - i) * EltSize;
3119 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3121 bool X86::isZeroNode(SDValue Elt) {
3122 return ((isa<ConstantSDNode>(Elt) &&
3123 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3124 (isa<ConstantFPSDNode>(Elt) &&
3125 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3128 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3129 /// their permute mask.
3130 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3131 SelectionDAG &DAG) {
3132 EVT VT = SVOp->getValueType(0);
3133 unsigned NumElems = VT.getVectorNumElements();
3134 SmallVector<int, 8> MaskVec;
3136 for (unsigned i = 0; i != NumElems; ++i) {
3137 int idx = SVOp->getMaskElt(i);
3139 MaskVec.push_back(idx);
3140 else if (idx < (int)NumElems)
3141 MaskVec.push_back(idx + NumElems);
3143 MaskVec.push_back(idx - NumElems);
3145 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3146 SVOp->getOperand(0), &MaskVec[0]);
3149 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3150 /// the two vector operands have swapped position.
3151 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3152 unsigned NumElems = VT.getVectorNumElements();
3153 for (unsigned i = 0; i != NumElems; ++i) {
3157 else if (idx < (int)NumElems)
3158 Mask[i] = idx + NumElems;
3160 Mask[i] = idx - NumElems;
3164 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3165 /// match movhlps. The lower half elements should come from upper half of
3166 /// V1 (and in order), and the upper half elements should come from the upper
3167 /// half of V2 (and in order).
3168 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3169 if (Op->getValueType(0).getVectorNumElements() != 4)
3171 for (unsigned i = 0, e = 2; i != e; ++i)
3172 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3174 for (unsigned i = 2; i != 4; ++i)
3175 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3180 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3181 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3183 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3184 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3186 N = N->getOperand(0).getNode();
3187 if (!ISD::isNON_EXTLoad(N))
3190 *LD = cast<LoadSDNode>(N);
3194 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3195 /// match movlp{s|d}. The lower half elements should come from lower half of
3196 /// V1 (and in order), and the upper half elements should come from the upper
3197 /// half of V2 (and in order). And since V1 will become the source of the
3198 /// MOVLP, it must be either a vector load or a scalar load to vector.
3199 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3200 ShuffleVectorSDNode *Op) {
3201 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3203 // Is V2 is a vector load, don't do this transformation. We will try to use
3204 // load folding shufps op.
3205 if (ISD::isNON_EXTLoad(V2))
3208 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3210 if (NumElems != 2 && NumElems != 4)
3212 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3213 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3215 for (unsigned i = NumElems/2; i != NumElems; ++i)
3216 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3221 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3223 static bool isSplatVector(SDNode *N) {
3224 if (N->getOpcode() != ISD::BUILD_VECTOR)
3227 SDValue SplatValue = N->getOperand(0);
3228 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3229 if (N->getOperand(i) != SplatValue)
3234 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3235 /// to an zero vector.
3236 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3237 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3238 SDValue V1 = N->getOperand(0);
3239 SDValue V2 = N->getOperand(1);
3240 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3241 for (unsigned i = 0; i != NumElems; ++i) {
3242 int Idx = N->getMaskElt(i);
3243 if (Idx >= (int)NumElems) {
3244 unsigned Opc = V2.getOpcode();
3245 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3247 if (Opc != ISD::BUILD_VECTOR ||
3248 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3250 } else if (Idx >= 0) {
3251 unsigned Opc = V1.getOpcode();
3252 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3254 if (Opc != ISD::BUILD_VECTOR ||
3255 !X86::isZeroNode(V1.getOperand(Idx)))
3262 /// getZeroVector - Returns a vector of specified type with all zero elements.
3264 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3266 assert(VT.isVector() && "Expected a vector type");
3268 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3269 // type. This ensures they get CSE'd.
3271 if (VT.getSizeInBits() == 64) { // MMX
3272 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3273 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3274 } else if (HasSSE2) { // SSE2
3275 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3276 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3278 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3279 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3281 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3284 /// getOnesVector - Returns a vector of specified type with all bits set.
3286 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3287 assert(VT.isVector() && "Expected a vector type");
3289 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3290 // type. This ensures they get CSE'd.
3291 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3293 if (VT.getSizeInBits() == 64) // MMX
3294 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3296 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3297 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3301 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3302 /// that point to V2 points to its first element.
3303 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3304 EVT VT = SVOp->getValueType(0);
3305 unsigned NumElems = VT.getVectorNumElements();
3307 bool Changed = false;
3308 SmallVector<int, 8> MaskVec;
3309 SVOp->getMask(MaskVec);
3311 for (unsigned i = 0; i != NumElems; ++i) {
3312 if (MaskVec[i] > (int)NumElems) {
3313 MaskVec[i] = NumElems;
3318 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3319 SVOp->getOperand(1), &MaskVec[0]);
3320 return SDValue(SVOp, 0);
3323 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3324 /// operation of specified width.
3325 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3327 unsigned NumElems = VT.getVectorNumElements();
3328 SmallVector<int, 8> Mask;
3329 Mask.push_back(NumElems);
3330 for (unsigned i = 1; i != NumElems; ++i)
3332 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3335 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3336 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3338 unsigned NumElems = VT.getVectorNumElements();
3339 SmallVector<int, 8> Mask;
3340 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3342 Mask.push_back(i + NumElems);
3344 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3347 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3348 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3350 unsigned NumElems = VT.getVectorNumElements();
3351 unsigned Half = NumElems/2;
3352 SmallVector<int, 8> Mask;
3353 for (unsigned i = 0; i != Half; ++i) {
3354 Mask.push_back(i + Half);
3355 Mask.push_back(i + NumElems + Half);
3357 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3360 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3361 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3363 if (SV->getValueType(0).getVectorNumElements() <= 4)
3364 return SDValue(SV, 0);
3366 EVT PVT = MVT::v4f32;
3367 EVT VT = SV->getValueType(0);
3368 DebugLoc dl = SV->getDebugLoc();
3369 SDValue V1 = SV->getOperand(0);
3370 int NumElems = VT.getVectorNumElements();
3371 int EltNo = SV->getSplatIndex();
3373 // unpack elements to the correct location
3374 while (NumElems > 4) {
3375 if (EltNo < NumElems/2) {
3376 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3378 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3379 EltNo -= NumElems/2;
3384 // Perform the splat.
3385 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3386 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3387 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3388 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3391 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3392 /// vector of zero or undef vector. This produces a shuffle where the low
3393 /// element of V2 is swizzled into the zero/undef vector, landing at element
3394 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3395 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3396 bool isZero, bool HasSSE2,
3397 SelectionDAG &DAG) {
3398 EVT VT = V2.getValueType();
3400 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3401 unsigned NumElems = VT.getVectorNumElements();
3402 SmallVector<int, 16> MaskVec;
3403 for (unsigned i = 0; i != NumElems; ++i)
3404 // If this is the insertion idx, put the low elt of V2 here.
3405 MaskVec.push_back(i == Idx ? NumElems : i);
3406 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3409 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3410 /// a shuffle that is zero.
3412 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3413 bool Low, SelectionDAG &DAG) {
3414 unsigned NumZeros = 0;
3415 for (int i = 0; i < NumElems; ++i) {
3416 unsigned Index = Low ? i : NumElems-i-1;
3417 int Idx = SVOp->getMaskElt(Index);
3422 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3423 if (Elt.getNode() && X86::isZeroNode(Elt))
3431 /// isVectorShift - Returns true if the shuffle can be implemented as a
3432 /// logical left or right shift of a vector.
3433 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3434 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3435 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3436 int NumElems = SVOp->getValueType(0).getVectorNumElements();
3439 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3442 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3446 bool SeenV1 = false;
3447 bool SeenV2 = false;
3448 for (int i = NumZeros; i < NumElems; ++i) {
3449 int Val = isLeft ? (i - NumZeros) : i;
3450 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3462 if (SeenV1 && SeenV2)
3465 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3471 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3473 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3474 unsigned NumNonZero, unsigned NumZero,
3475 SelectionDAG &DAG, TargetLowering &TLI) {
3479 DebugLoc dl = Op.getDebugLoc();
3482 for (unsigned i = 0; i < 16; ++i) {
3483 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3484 if (ThisIsNonZero && First) {
3486 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3488 V = DAG.getUNDEF(MVT::v8i16);
3493 SDValue ThisElt(0, 0), LastElt(0, 0);
3494 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3495 if (LastIsNonZero) {
3496 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3497 MVT::i16, Op.getOperand(i-1));
3499 if (ThisIsNonZero) {
3500 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3501 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3502 ThisElt, DAG.getConstant(8, MVT::i8));
3504 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3508 if (ThisElt.getNode())
3509 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3510 DAG.getIntPtrConstant(i/2));
3514 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3517 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3519 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3520 unsigned NumNonZero, unsigned NumZero,
3521 SelectionDAG &DAG, TargetLowering &TLI) {
3525 DebugLoc dl = Op.getDebugLoc();
3528 for (unsigned i = 0; i < 8; ++i) {
3529 bool isNonZero = (NonZeros & (1 << i)) != 0;
3533 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3535 V = DAG.getUNDEF(MVT::v8i16);
3538 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3539 MVT::v8i16, V, Op.getOperand(i),
3540 DAG.getIntPtrConstant(i));
3547 /// getVShift - Return a vector logical shift node.
3549 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3550 unsigned NumBits, SelectionDAG &DAG,
3551 const TargetLowering &TLI, DebugLoc dl) {
3552 bool isMMX = VT.getSizeInBits() == 64;
3553 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3554 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3555 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3556 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3557 DAG.getNode(Opc, dl, ShVT, SrcOp,
3558 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3562 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3563 SelectionDAG &DAG) {
3565 // Check if the scalar load can be widened into a vector load. And if
3566 // the address is "base + cst" see if the cst can be "absorbed" into
3567 // the shuffle mask.
3568 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3569 SDValue Ptr = LD->getBasePtr();
3570 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3572 EVT PVT = LD->getValueType(0);
3573 if (PVT != MVT::i32 && PVT != MVT::f32)
3578 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3579 FI = FINode->getIndex();
3581 } else if (Ptr.getOpcode() == ISD::ADD &&
3582 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3583 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3584 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3585 Offset = Ptr.getConstantOperandVal(1);
3586 Ptr = Ptr.getOperand(0);
3591 SDValue Chain = LD->getChain();
3592 // Make sure the stack object alignment is at least 16.
3593 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3594 if (DAG.InferPtrAlignment(Ptr) < 16) {
3595 if (MFI->isFixedObjectIndex(FI)) {
3596 // Can't change the alignment. FIXME: It's possible to compute
3597 // the exact stack offset and reference FI + adjust offset instead.
3598 // If someone *really* cares about this. That's the way to implement it.
3601 MFI->setObjectAlignment(FI, 16);
3605 // (Offset % 16) must be multiple of 4. Then address is then
3606 // Ptr + (Offset & ~15).
3609 if ((Offset % 16) & 3)
3611 int64_t StartOffset = Offset & ~15;
3613 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3614 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3616 int EltNo = (Offset - StartOffset) >> 2;
3617 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3618 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3619 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3621 // Canonicalize it to a v4i32 shuffle.
3622 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3623 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3624 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3625 DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3632 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3633 DebugLoc dl = Op.getDebugLoc();
3634 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3635 if (ISD::isBuildVectorAllZeros(Op.getNode())
3636 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3637 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3638 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3639 // eliminated on x86-32 hosts.
3640 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3643 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3644 return getOnesVector(Op.getValueType(), DAG, dl);
3645 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3648 EVT VT = Op.getValueType();
3649 EVT ExtVT = VT.getVectorElementType();
3650 unsigned EVTBits = ExtVT.getSizeInBits();
3652 unsigned NumElems = Op.getNumOperands();
3653 unsigned NumZero = 0;
3654 unsigned NumNonZero = 0;
3655 unsigned NonZeros = 0;
3656 bool IsAllConstants = true;
3657 SmallSet<SDValue, 8> Values;
3658 for (unsigned i = 0; i < NumElems; ++i) {
3659 SDValue Elt = Op.getOperand(i);
3660 if (Elt.getOpcode() == ISD::UNDEF)
3663 if (Elt.getOpcode() != ISD::Constant &&
3664 Elt.getOpcode() != ISD::ConstantFP)
3665 IsAllConstants = false;
3666 if (X86::isZeroNode(Elt))
3669 NonZeros |= (1 << i);
3674 if (NumNonZero == 0) {
3675 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3676 return DAG.getUNDEF(VT);
3679 // Special case for single non-zero, non-undef, element.
3680 if (NumNonZero == 1) {
3681 unsigned Idx = CountTrailingZeros_32(NonZeros);
3682 SDValue Item = Op.getOperand(Idx);
3684 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3685 // the value are obviously zero, truncate the value to i32 and do the
3686 // insertion that way. Only do this if the value is non-constant or if the
3687 // value is a constant being inserted into element 0. It is cheaper to do
3688 // a constant pool load than it is to do a movd + shuffle.
3689 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3690 (!IsAllConstants || Idx == 0)) {
3691 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3692 // Handle MMX and SSE both.
3693 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3694 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3696 // Truncate the value (which may itself be a constant) to i32, and
3697 // convert it to a vector with movd (S2V+shuffle to zero extend).
3698 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3699 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3700 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3701 Subtarget->hasSSE2(), DAG);
3703 // Now we have our 32-bit value zero extended in the low element of
3704 // a vector. If Idx != 0, swizzle it into place.
3706 SmallVector<int, 4> Mask;
3707 Mask.push_back(Idx);
3708 for (unsigned i = 1; i != VecElts; ++i)
3710 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3711 DAG.getUNDEF(Item.getValueType()),
3714 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3718 // If we have a constant or non-constant insertion into the low element of
3719 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3720 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3721 // depending on what the source datatype is.
3724 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3725 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3726 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3727 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3728 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3729 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3731 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3732 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3733 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3734 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3735 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3736 Subtarget->hasSSE2(), DAG);
3737 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3741 // Is it a vector logical left shift?
3742 if (NumElems == 2 && Idx == 1 &&
3743 X86::isZeroNode(Op.getOperand(0)) &&
3744 !X86::isZeroNode(Op.getOperand(1))) {
3745 unsigned NumBits = VT.getSizeInBits();
3746 return getVShift(true, VT,
3747 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3748 VT, Op.getOperand(1)),
3749 NumBits/2, DAG, *this, dl);
3752 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3755 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3756 // is a non-constant being inserted into an element other than the low one,
3757 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3758 // movd/movss) to move this into the low element, then shuffle it into
3760 if (EVTBits == 32) {
3761 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3763 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3764 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3765 Subtarget->hasSSE2(), DAG);
3766 SmallVector<int, 8> MaskVec;
3767 for (unsigned i = 0; i < NumElems; i++)
3768 MaskVec.push_back(i == Idx ? 0 : 1);
3769 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3773 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3774 if (Values.size() == 1) {
3775 if (EVTBits == 32) {
3776 // Instead of a shuffle like this:
3777 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3778 // Check if it's possible to issue this instead.
3779 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3780 unsigned Idx = CountTrailingZeros_32(NonZeros);
3781 SDValue Item = Op.getOperand(Idx);
3782 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3783 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3788 // A vector full of immediates; various special cases are already
3789 // handled, so this is best done with a single constant-pool load.
3793 // Let legalizer expand 2-wide build_vectors.
3794 if (EVTBits == 64) {
3795 if (NumNonZero == 1) {
3796 // One half is zero or undef.
3797 unsigned Idx = CountTrailingZeros_32(NonZeros);
3798 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3799 Op.getOperand(Idx));
3800 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3801 Subtarget->hasSSE2(), DAG);
3806 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3807 if (EVTBits == 8 && NumElems == 16) {
3808 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3810 if (V.getNode()) return V;
3813 if (EVTBits == 16 && NumElems == 8) {
3814 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3816 if (V.getNode()) return V;
3819 // If element VT is == 32 bits, turn it into a number of shuffles.
3820 SmallVector<SDValue, 8> V;
3822 if (NumElems == 4 && NumZero > 0) {
3823 for (unsigned i = 0; i < 4; ++i) {
3824 bool isZero = !(NonZeros & (1 << i));
3826 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3828 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3831 for (unsigned i = 0; i < 2; ++i) {
3832 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3835 V[i] = V[i*2]; // Must be a zero vector.
3838 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3841 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3844 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3849 SmallVector<int, 8> MaskVec;
3850 bool Reverse = (NonZeros & 0x3) == 2;
3851 for (unsigned i = 0; i < 2; ++i)
3852 MaskVec.push_back(Reverse ? 1-i : i);
3853 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3854 for (unsigned i = 0; i < 2; ++i)
3855 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3856 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3859 if (Values.size() > 2) {
3860 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3861 // values to be inserted is equal to the number of elements, in which case
3862 // use the unpack code below in the hopes of matching the consecutive elts
3863 // load merge pattern for shuffles.
3864 // FIXME: We could probably just check that here directly.
3865 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3866 getSubtarget()->hasSSE41()) {
3867 V[0] = DAG.getUNDEF(VT);
3868 for (unsigned i = 0; i < NumElems; ++i)
3869 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3870 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3871 Op.getOperand(i), DAG.getIntPtrConstant(i));
3874 // Expand into a number of unpckl*.
3876 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3877 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3878 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3879 for (unsigned i = 0; i < NumElems; ++i)
3880 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3882 while (NumElems != 0) {
3883 for (unsigned i = 0; i < NumElems; ++i)
3884 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3894 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3895 // We support concatenate two MMX registers and place them in a MMX
3896 // register. This is better than doing a stack convert.
3897 DebugLoc dl = Op.getDebugLoc();
3898 EVT ResVT = Op.getValueType();
3899 assert(Op.getNumOperands() == 2);
3900 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
3901 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
3903 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
3904 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3905 InVec = Op.getOperand(1);
3906 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3907 unsigned NumElts = ResVT.getVectorNumElements();
3908 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3909 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
3910 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
3912 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
3913 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3914 Mask[0] = 0; Mask[1] = 2;
3915 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
3917 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3920 // v8i16 shuffles - Prefer shuffles in the following order:
3921 // 1. [all] pshuflw, pshufhw, optional move
3922 // 2. [ssse3] 1 x pshufb
3923 // 3. [ssse3] 2 x pshufb + 1 x por
3924 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3926 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3927 SelectionDAG &DAG, X86TargetLowering &TLI) {
3928 SDValue V1 = SVOp->getOperand(0);
3929 SDValue V2 = SVOp->getOperand(1);
3930 DebugLoc dl = SVOp->getDebugLoc();
3931 SmallVector<int, 8> MaskVals;
3933 // Determine if more than 1 of the words in each of the low and high quadwords
3934 // of the result come from the same quadword of one of the two inputs. Undef
3935 // mask values count as coming from any quadword, for better codegen.
3936 SmallVector<unsigned, 4> LoQuad(4);
3937 SmallVector<unsigned, 4> HiQuad(4);
3938 BitVector InputQuads(4);
3939 for (unsigned i = 0; i < 8; ++i) {
3940 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3941 int EltIdx = SVOp->getMaskElt(i);
3942 MaskVals.push_back(EltIdx);
3951 InputQuads.set(EltIdx / 4);
3954 int BestLoQuad = -1;
3955 unsigned MaxQuad = 1;
3956 for (unsigned i = 0; i < 4; ++i) {
3957 if (LoQuad[i] > MaxQuad) {
3959 MaxQuad = LoQuad[i];
3963 int BestHiQuad = -1;
3965 for (unsigned i = 0; i < 4; ++i) {
3966 if (HiQuad[i] > MaxQuad) {
3968 MaxQuad = HiQuad[i];
3972 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3973 // of the two input vectors, shuffle them into one input vector so only a
3974 // single pshufb instruction is necessary. If There are more than 2 input
3975 // quads, disable the next transformation since it does not help SSSE3.
3976 bool V1Used = InputQuads[0] || InputQuads[1];
3977 bool V2Used = InputQuads[2] || InputQuads[3];
3978 if (TLI.getSubtarget()->hasSSSE3()) {
3979 if (InputQuads.count() == 2 && V1Used && V2Used) {
3980 BestLoQuad = InputQuads.find_first();
3981 BestHiQuad = InputQuads.find_next(BestLoQuad);
3983 if (InputQuads.count() > 2) {
3989 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3990 // the shuffle mask. If a quad is scored as -1, that means that it contains
3991 // words from all 4 input quadwords.
3993 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3994 SmallVector<int, 8> MaskV;
3995 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3996 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3997 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3998 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3999 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4000 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4002 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4003 // source words for the shuffle, to aid later transformations.
4004 bool AllWordsInNewV = true;
4005 bool InOrder[2] = { true, true };
4006 for (unsigned i = 0; i != 8; ++i) {
4007 int idx = MaskVals[i];
4009 InOrder[i/4] = false;
4010 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4012 AllWordsInNewV = false;
4016 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4017 if (AllWordsInNewV) {
4018 for (int i = 0; i != 8; ++i) {
4019 int idx = MaskVals[i];
4022 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4023 if ((idx != i) && idx < 4)
4025 if ((idx != i) && idx > 3)
4034 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4035 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4036 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4037 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4038 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4042 // If we have SSSE3, and all words of the result are from 1 input vector,
4043 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4044 // is present, fall back to case 4.
4045 if (TLI.getSubtarget()->hasSSSE3()) {
4046 SmallVector<SDValue,16> pshufbMask;
4048 // If we have elements from both input vectors, set the high bit of the
4049 // shuffle mask element to zero out elements that come from V2 in the V1
4050 // mask, and elements that come from V1 in the V2 mask, so that the two
4051 // results can be OR'd together.
4052 bool TwoInputs = V1Used && V2Used;
4053 for (unsigned i = 0; i != 8; ++i) {
4054 int EltIdx = MaskVals[i] * 2;
4055 if (TwoInputs && (EltIdx >= 16)) {
4056 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4057 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4060 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4061 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4063 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4064 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4065 DAG.getNode(ISD::BUILD_VECTOR, dl,
4066 MVT::v16i8, &pshufbMask[0], 16));
4068 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4070 // Calculate the shuffle mask for the second input, shuffle it, and
4071 // OR it with the first shuffled input.
4073 for (unsigned i = 0; i != 8; ++i) {
4074 int EltIdx = MaskVals[i] * 2;
4076 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4077 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4080 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4081 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4083 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4084 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4085 DAG.getNode(ISD::BUILD_VECTOR, dl,
4086 MVT::v16i8, &pshufbMask[0], 16));
4087 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4088 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4091 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4092 // and update MaskVals with new element order.
4093 BitVector InOrder(8);
4094 if (BestLoQuad >= 0) {
4095 SmallVector<int, 8> MaskV;
4096 for (int i = 0; i != 4; ++i) {
4097 int idx = MaskVals[i];
4099 MaskV.push_back(-1);
4101 } else if ((idx / 4) == BestLoQuad) {
4102 MaskV.push_back(idx & 3);
4105 MaskV.push_back(-1);
4108 for (unsigned i = 4; i != 8; ++i)
4110 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4114 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4115 // and update MaskVals with the new element order.
4116 if (BestHiQuad >= 0) {
4117 SmallVector<int, 8> MaskV;
4118 for (unsigned i = 0; i != 4; ++i)
4120 for (unsigned i = 4; i != 8; ++i) {
4121 int idx = MaskVals[i];
4123 MaskV.push_back(-1);
4125 } else if ((idx / 4) == BestHiQuad) {
4126 MaskV.push_back((idx & 3) + 4);
4129 MaskV.push_back(-1);
4132 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4136 // In case BestHi & BestLo were both -1, which means each quadword has a word
4137 // from each of the four input quadwords, calculate the InOrder bitvector now
4138 // before falling through to the insert/extract cleanup.
4139 if (BestLoQuad == -1 && BestHiQuad == -1) {
4141 for (int i = 0; i != 8; ++i)
4142 if (MaskVals[i] < 0 || MaskVals[i] == i)
4146 // The other elements are put in the right place using pextrw and pinsrw.
4147 for (unsigned i = 0; i != 8; ++i) {
4150 int EltIdx = MaskVals[i];
4153 SDValue ExtOp = (EltIdx < 8)
4154 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4155 DAG.getIntPtrConstant(EltIdx))
4156 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4157 DAG.getIntPtrConstant(EltIdx - 8));
4158 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4159 DAG.getIntPtrConstant(i));
4164 // v16i8 shuffles - Prefer shuffles in the following order:
4165 // 1. [ssse3] 1 x pshufb
4166 // 2. [ssse3] 2 x pshufb + 1 x por
4167 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4169 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4170 SelectionDAG &DAG, X86TargetLowering &TLI) {
4171 SDValue V1 = SVOp->getOperand(0);
4172 SDValue V2 = SVOp->getOperand(1);
4173 DebugLoc dl = SVOp->getDebugLoc();
4174 SmallVector<int, 16> MaskVals;
4175 SVOp->getMask(MaskVals);
4177 // If we have SSSE3, case 1 is generated when all result bytes come from
4178 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4179 // present, fall back to case 3.
4180 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4183 for (unsigned i = 0; i < 16; ++i) {
4184 int EltIdx = MaskVals[i];
4193 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4194 if (TLI.getSubtarget()->hasSSSE3()) {
4195 SmallVector<SDValue,16> pshufbMask;
4197 // If all result elements are from one input vector, then only translate
4198 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4200 // Otherwise, we have elements from both input vectors, and must zero out
4201 // elements that come from V2 in the first mask, and V1 in the second mask
4202 // so that we can OR them together.
4203 bool TwoInputs = !(V1Only || V2Only);
4204 for (unsigned i = 0; i != 16; ++i) {
4205 int EltIdx = MaskVals[i];
4206 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4207 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4210 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4212 // If all the elements are from V2, assign it to V1 and return after
4213 // building the first pshufb.
4216 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4217 DAG.getNode(ISD::BUILD_VECTOR, dl,
4218 MVT::v16i8, &pshufbMask[0], 16));
4222 // Calculate the shuffle mask for the second input, shuffle it, and
4223 // OR it with the first shuffled input.
4225 for (unsigned i = 0; i != 16; ++i) {
4226 int EltIdx = MaskVals[i];
4228 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4231 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4233 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4234 DAG.getNode(ISD::BUILD_VECTOR, dl,
4235 MVT::v16i8, &pshufbMask[0], 16));
4236 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4239 // No SSSE3 - Calculate in place words and then fix all out of place words
4240 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4241 // the 16 different words that comprise the two doublequadword input vectors.
4242 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4243 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4244 SDValue NewV = V2Only ? V2 : V1;
4245 for (int i = 0; i != 8; ++i) {
4246 int Elt0 = MaskVals[i*2];
4247 int Elt1 = MaskVals[i*2+1];
4249 // This word of the result is all undef, skip it.
4250 if (Elt0 < 0 && Elt1 < 0)
4253 // This word of the result is already in the correct place, skip it.
4254 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4256 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4259 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4260 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4263 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4264 // using a single extract together, load it and store it.
4265 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4266 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4267 DAG.getIntPtrConstant(Elt1 / 2));
4268 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4269 DAG.getIntPtrConstant(i));
4273 // If Elt1 is defined, extract it from the appropriate source. If the
4274 // source byte is not also odd, shift the extracted word left 8 bits
4275 // otherwise clear the bottom 8 bits if we need to do an or.
4277 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4278 DAG.getIntPtrConstant(Elt1 / 2));
4279 if ((Elt1 & 1) == 0)
4280 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4281 DAG.getConstant(8, TLI.getShiftAmountTy()));
4283 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4284 DAG.getConstant(0xFF00, MVT::i16));
4286 // If Elt0 is defined, extract it from the appropriate source. If the
4287 // source byte is not also even, shift the extracted word right 8 bits. If
4288 // Elt1 was also defined, OR the extracted values together before
4289 // inserting them in the result.
4291 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4292 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4293 if ((Elt0 & 1) != 0)
4294 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4295 DAG.getConstant(8, TLI.getShiftAmountTy()));
4297 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4298 DAG.getConstant(0x00FF, MVT::i16));
4299 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4302 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4303 DAG.getIntPtrConstant(i));
4305 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4308 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4309 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4310 /// done when every pair / quad of shuffle mask elements point to elements in
4311 /// the right sequence. e.g.
4312 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4314 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4316 TargetLowering &TLI, DebugLoc dl) {
4317 EVT VT = SVOp->getValueType(0);
4318 SDValue V1 = SVOp->getOperand(0);
4319 SDValue V2 = SVOp->getOperand(1);
4320 unsigned NumElems = VT.getVectorNumElements();
4321 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4322 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4323 EVT MaskEltVT = MaskVT.getVectorElementType();
4325 switch (VT.getSimpleVT().SimpleTy) {
4326 default: assert(false && "Unexpected!");
4327 case MVT::v4f32: NewVT = MVT::v2f64; break;
4328 case MVT::v4i32: NewVT = MVT::v2i64; break;
4329 case MVT::v8i16: NewVT = MVT::v4i32; break;
4330 case MVT::v16i8: NewVT = MVT::v4i32; break;
4333 if (NewWidth == 2) {
4339 int Scale = NumElems / NewWidth;
4340 SmallVector<int, 8> MaskVec;
4341 for (unsigned i = 0; i < NumElems; i += Scale) {
4343 for (int j = 0; j < Scale; ++j) {
4344 int EltIdx = SVOp->getMaskElt(i+j);
4348 StartIdx = EltIdx - (EltIdx % Scale);
4349 if (EltIdx != StartIdx + j)
4353 MaskVec.push_back(-1);
4355 MaskVec.push_back(StartIdx / Scale);
4358 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4359 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4360 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4363 /// getVZextMovL - Return a zero-extending vector move low node.
4365 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4366 SDValue SrcOp, SelectionDAG &DAG,
4367 const X86Subtarget *Subtarget, DebugLoc dl) {
4368 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4369 LoadSDNode *LD = NULL;
4370 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4371 LD = dyn_cast<LoadSDNode>(SrcOp);
4373 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4375 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4376 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4377 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4378 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4379 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4381 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4382 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4383 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4384 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4392 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4393 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4394 DAG.getNode(ISD::BIT_CONVERT, dl,
4398 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4401 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4402 SDValue V1 = SVOp->getOperand(0);
4403 SDValue V2 = SVOp->getOperand(1);
4404 DebugLoc dl = SVOp->getDebugLoc();
4405 EVT VT = SVOp->getValueType(0);
4407 SmallVector<std::pair<int, int>, 8> Locs;
4409 SmallVector<int, 8> Mask1(4U, -1);
4410 SmallVector<int, 8> PermMask;
4411 SVOp->getMask(PermMask);
4415 for (unsigned i = 0; i != 4; ++i) {
4416 int Idx = PermMask[i];
4418 Locs[i] = std::make_pair(-1, -1);
4420 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4422 Locs[i] = std::make_pair(0, NumLo);
4426 Locs[i] = std::make_pair(1, NumHi);
4428 Mask1[2+NumHi] = Idx;
4434 if (NumLo <= 2 && NumHi <= 2) {
4435 // If no more than two elements come from either vector. This can be
4436 // implemented with two shuffles. First shuffle gather the elements.
4437 // The second shuffle, which takes the first shuffle as both of its
4438 // vector operands, put the elements into the right order.
4439 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4441 SmallVector<int, 8> Mask2(4U, -1);
4443 for (unsigned i = 0; i != 4; ++i) {
4444 if (Locs[i].first == -1)
4447 unsigned Idx = (i < 2) ? 0 : 4;
4448 Idx += Locs[i].first * 2 + Locs[i].second;
4453 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4454 } else if (NumLo == 3 || NumHi == 3) {
4455 // Otherwise, we must have three elements from one vector, call it X, and
4456 // one element from the other, call it Y. First, use a shufps to build an
4457 // intermediate vector with the one element from Y and the element from X
4458 // that will be in the same half in the final destination (the indexes don't
4459 // matter). Then, use a shufps to build the final vector, taking the half
4460 // containing the element from Y from the intermediate, and the other half
4463 // Normalize it so the 3 elements come from V1.
4464 CommuteVectorShuffleMask(PermMask, VT);
4468 // Find the element from V2.
4470 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4471 int Val = PermMask[HiIndex];
4478 Mask1[0] = PermMask[HiIndex];
4480 Mask1[2] = PermMask[HiIndex^1];
4482 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4485 Mask1[0] = PermMask[0];
4486 Mask1[1] = PermMask[1];
4487 Mask1[2] = HiIndex & 1 ? 6 : 4;
4488 Mask1[3] = HiIndex & 1 ? 4 : 6;
4489 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4491 Mask1[0] = HiIndex & 1 ? 2 : 0;
4492 Mask1[1] = HiIndex & 1 ? 0 : 2;
4493 Mask1[2] = PermMask[2];
4494 Mask1[3] = PermMask[3];
4499 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4503 // Break it into (shuffle shuffle_hi, shuffle_lo).
4505 SmallVector<int,8> LoMask(4U, -1);
4506 SmallVector<int,8> HiMask(4U, -1);
4508 SmallVector<int,8> *MaskPtr = &LoMask;
4509 unsigned MaskIdx = 0;
4512 for (unsigned i = 0; i != 4; ++i) {
4519 int Idx = PermMask[i];
4521 Locs[i] = std::make_pair(-1, -1);
4522 } else if (Idx < 4) {
4523 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4524 (*MaskPtr)[LoIdx] = Idx;
4527 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4528 (*MaskPtr)[HiIdx] = Idx;
4533 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4534 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4535 SmallVector<int, 8> MaskOps;
4536 for (unsigned i = 0; i != 4; ++i) {
4537 if (Locs[i].first == -1) {
4538 MaskOps.push_back(-1);
4540 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4541 MaskOps.push_back(Idx);
4544 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4548 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4549 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4550 SDValue V1 = Op.getOperand(0);
4551 SDValue V2 = Op.getOperand(1);
4552 EVT VT = Op.getValueType();
4553 DebugLoc dl = Op.getDebugLoc();
4554 unsigned NumElems = VT.getVectorNumElements();
4555 bool isMMX = VT.getSizeInBits() == 64;
4556 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4557 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4558 bool V1IsSplat = false;
4559 bool V2IsSplat = false;
4561 if (isZeroShuffle(SVOp))
4562 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4564 // Promote splats to v4f32.
4565 if (SVOp->isSplat()) {
4566 if (isMMX || NumElems < 4)
4568 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4571 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4573 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4574 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4575 if (NewOp.getNode())
4576 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4577 LowerVECTOR_SHUFFLE(NewOp, DAG));
4578 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4579 // FIXME: Figure out a cleaner way to do this.
4580 // Try to make use of movq to zero out the top part.
4581 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4582 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4583 if (NewOp.getNode()) {
4584 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4585 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4586 DAG, Subtarget, dl);
4588 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4589 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4590 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4591 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4592 DAG, Subtarget, dl);
4596 if (X86::isPSHUFDMask(SVOp))
4599 // Check if this can be converted into a logical shift.
4600 bool isLeft = false;
4603 bool isShift = getSubtarget()->hasSSE2() &&
4604 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4605 if (isShift && ShVal.hasOneUse()) {
4606 // If the shifted value has multiple uses, it may be cheaper to use
4607 // v_set0 + movlhps or movhlps, etc.
4608 EVT EltVT = VT.getVectorElementType();
4609 ShAmt *= EltVT.getSizeInBits();
4610 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4613 if (X86::isMOVLMask(SVOp)) {
4616 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4617 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4622 // FIXME: fold these into legal mask.
4623 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4624 X86::isMOVSLDUPMask(SVOp) ||
4625 X86::isMOVHLPSMask(SVOp) ||
4626 X86::isMOVLHPSMask(SVOp) ||
4627 X86::isMOVLPMask(SVOp)))
4630 if (ShouldXformToMOVHLPS(SVOp) ||
4631 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4632 return CommuteVectorShuffle(SVOp, DAG);
4635 // No better options. Use a vshl / vsrl.
4636 EVT EltVT = VT.getVectorElementType();
4637 ShAmt *= EltVT.getSizeInBits();
4638 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4641 bool Commuted = false;
4642 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4643 // 1,1,1,1 -> v8i16 though.
4644 V1IsSplat = isSplatVector(V1.getNode());
4645 V2IsSplat = isSplatVector(V2.getNode());
4647 // Canonicalize the splat or undef, if present, to be on the RHS.
4648 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4649 Op = CommuteVectorShuffle(SVOp, DAG);
4650 SVOp = cast<ShuffleVectorSDNode>(Op);
4651 V1 = SVOp->getOperand(0);
4652 V2 = SVOp->getOperand(1);
4653 std::swap(V1IsSplat, V2IsSplat);
4654 std::swap(V1IsUndef, V2IsUndef);
4658 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4659 // Shuffling low element of v1 into undef, just return v1.
4662 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4663 // the instruction selector will not match, so get a canonical MOVL with
4664 // swapped operands to undo the commute.
4665 return getMOVL(DAG, dl, VT, V2, V1);
4668 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4669 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4670 X86::isUNPCKLMask(SVOp) ||
4671 X86::isUNPCKHMask(SVOp))
4675 // Normalize mask so all entries that point to V2 points to its first
4676 // element then try to match unpck{h|l} again. If match, return a
4677 // new vector_shuffle with the corrected mask.
4678 SDValue NewMask = NormalizeMask(SVOp, DAG);
4679 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4680 if (NSVOp != SVOp) {
4681 if (X86::isUNPCKLMask(NSVOp, true)) {
4683 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4690 // Commute is back and try unpck* again.
4691 // FIXME: this seems wrong.
4692 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4693 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4694 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4695 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4696 X86::isUNPCKLMask(NewSVOp) ||
4697 X86::isUNPCKHMask(NewSVOp))
4701 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4703 // Normalize the node to match x86 shuffle ops if needed
4704 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4705 return CommuteVectorShuffle(SVOp, DAG);
4707 // Check for legal shuffle and return?
4708 SmallVector<int, 16> PermMask;
4709 SVOp->getMask(PermMask);
4710 if (isShuffleMaskLegal(PermMask, VT))
4713 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4714 if (VT == MVT::v8i16) {
4715 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4716 if (NewOp.getNode())
4720 if (VT == MVT::v16i8) {
4721 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4722 if (NewOp.getNode())
4726 // Handle all 4 wide cases with a number of shuffles except for MMX.
4727 if (NumElems == 4 && !isMMX)
4728 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4734 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4735 SelectionDAG &DAG) {
4736 EVT VT = Op.getValueType();
4737 DebugLoc dl = Op.getDebugLoc();
4738 if (VT.getSizeInBits() == 8) {
4739 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4740 Op.getOperand(0), Op.getOperand(1));
4741 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4742 DAG.getValueType(VT));
4743 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4744 } else if (VT.getSizeInBits() == 16) {
4745 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4746 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4748 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4749 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4750 DAG.getNode(ISD::BIT_CONVERT, dl,
4754 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4755 Op.getOperand(0), Op.getOperand(1));
4756 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4757 DAG.getValueType(VT));
4758 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4759 } else if (VT == MVT::f32) {
4760 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4761 // the result back to FR32 register. It's only worth matching if the
4762 // result has a single use which is a store or a bitcast to i32. And in
4763 // the case of a store, it's not worth it if the index is a constant 0,
4764 // because a MOVSSmr can be used instead, which is smaller and faster.
4765 if (!Op.hasOneUse())
4767 SDNode *User = *Op.getNode()->use_begin();
4768 if ((User->getOpcode() != ISD::STORE ||
4769 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4770 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4771 (User->getOpcode() != ISD::BIT_CONVERT ||
4772 User->getValueType(0) != MVT::i32))
4774 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4775 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4778 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4779 } else if (VT == MVT::i32) {
4780 // ExtractPS works with constant index.
4781 if (isa<ConstantSDNode>(Op.getOperand(1)))
4789 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4790 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4793 if (Subtarget->hasSSE41()) {
4794 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4799 EVT VT = Op.getValueType();
4800 DebugLoc dl = Op.getDebugLoc();
4801 // TODO: handle v16i8.
4802 if (VT.getSizeInBits() == 16) {
4803 SDValue Vec = Op.getOperand(0);
4804 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4806 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4807 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4808 DAG.getNode(ISD::BIT_CONVERT, dl,
4811 // Transform it so it match pextrw which produces a 32-bit result.
4812 EVT EltVT = MVT::i32;
4813 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4814 Op.getOperand(0), Op.getOperand(1));
4815 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4816 DAG.getValueType(VT));
4817 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4818 } else if (VT.getSizeInBits() == 32) {
4819 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4823 // SHUFPS the element to the lowest double word, then movss.
4824 int Mask[4] = { Idx, -1, -1, -1 };
4825 EVT VVT = Op.getOperand(0).getValueType();
4826 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4827 DAG.getUNDEF(VVT), Mask);
4828 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4829 DAG.getIntPtrConstant(0));
4830 } else if (VT.getSizeInBits() == 64) {
4831 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4832 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4833 // to match extract_elt for f64.
4834 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4838 // UNPCKHPD the element to the lowest double word, then movsd.
4839 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4840 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4841 int Mask[2] = { 1, -1 };
4842 EVT VVT = Op.getOperand(0).getValueType();
4843 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4844 DAG.getUNDEF(VVT), Mask);
4845 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4846 DAG.getIntPtrConstant(0));
4853 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4854 EVT VT = Op.getValueType();
4855 EVT EltVT = VT.getVectorElementType();
4856 DebugLoc dl = Op.getDebugLoc();
4858 SDValue N0 = Op.getOperand(0);
4859 SDValue N1 = Op.getOperand(1);
4860 SDValue N2 = Op.getOperand(2);
4862 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4863 isa<ConstantSDNode>(N2)) {
4865 if (VT == MVT::v8i16)
4866 Opc = X86ISD::PINSRW;
4867 else if (VT == MVT::v4i16)
4868 Opc = X86ISD::MMX_PINSRW;
4869 else if (VT == MVT::v16i8)
4870 Opc = X86ISD::PINSRB;
4872 Opc = X86ISD::PINSRB;
4874 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4876 if (N1.getValueType() != MVT::i32)
4877 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4878 if (N2.getValueType() != MVT::i32)
4879 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4880 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4881 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4882 // Bits [7:6] of the constant are the source select. This will always be
4883 // zero here. The DAG Combiner may combine an extract_elt index into these
4884 // bits. For example (insert (extract, 3), 2) could be matched by putting
4885 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4886 // Bits [5:4] of the constant are the destination select. This is the
4887 // value of the incoming immediate.
4888 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4889 // combine either bitwise AND or insert of float 0.0 to set these bits.
4890 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4891 // Create this as a scalar to vector..
4892 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4893 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4894 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4895 // PINSR* works with constant index.
4902 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4903 EVT VT = Op.getValueType();
4904 EVT EltVT = VT.getVectorElementType();
4906 if (Subtarget->hasSSE41())
4907 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4909 if (EltVT == MVT::i8)
4912 DebugLoc dl = Op.getDebugLoc();
4913 SDValue N0 = Op.getOperand(0);
4914 SDValue N1 = Op.getOperand(1);
4915 SDValue N2 = Op.getOperand(2);
4917 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4918 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4919 // as its second argument.
4920 if (N1.getValueType() != MVT::i32)
4921 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4922 if (N2.getValueType() != MVT::i32)
4923 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4924 return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
4925 dl, VT, N0, N1, N2);
4931 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4932 DebugLoc dl = Op.getDebugLoc();
4933 if (Op.getValueType() == MVT::v2f32)
4934 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4935 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4936 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4937 Op.getOperand(0))));
4939 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4940 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4942 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4943 EVT VT = MVT::v2i32;
4944 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4951 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4952 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4955 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4956 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4957 // one of the above mentioned nodes. It has to be wrapped because otherwise
4958 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4959 // be used to form addressing mode. These wrapped nodes will be selected
4962 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4963 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4965 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4967 unsigned char OpFlag = 0;
4968 unsigned WrapperKind = X86ISD::Wrapper;
4969 CodeModel::Model M = getTargetMachine().getCodeModel();
4971 if (Subtarget->isPICStyleRIPRel() &&
4972 (M == CodeModel::Small || M == CodeModel::Kernel))
4973 WrapperKind = X86ISD::WrapperRIP;
4974 else if (Subtarget->isPICStyleGOT())
4975 OpFlag = X86II::MO_GOTOFF;
4976 else if (Subtarget->isPICStyleStubPIC())
4977 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4979 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4981 CP->getOffset(), OpFlag);
4982 DebugLoc DL = CP->getDebugLoc();
4983 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4984 // With PIC, the address is actually $g + Offset.
4986 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4987 DAG.getNode(X86ISD::GlobalBaseReg,
4988 DebugLoc::getUnknownLoc(), getPointerTy()),
4995 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4996 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4998 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5000 unsigned char OpFlag = 0;
5001 unsigned WrapperKind = X86ISD::Wrapper;
5002 CodeModel::Model M = getTargetMachine().getCodeModel();
5004 if (Subtarget->isPICStyleRIPRel() &&
5005 (M == CodeModel::Small || M == CodeModel::Kernel))
5006 WrapperKind = X86ISD::WrapperRIP;
5007 else if (Subtarget->isPICStyleGOT())
5008 OpFlag = X86II::MO_GOTOFF;
5009 else if (Subtarget->isPICStyleStubPIC())
5010 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5012 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5014 DebugLoc DL = JT->getDebugLoc();
5015 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5017 // With PIC, the address is actually $g + Offset.
5019 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5020 DAG.getNode(X86ISD::GlobalBaseReg,
5021 DebugLoc::getUnknownLoc(), getPointerTy()),
5029 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
5030 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5032 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5034 unsigned char OpFlag = 0;
5035 unsigned WrapperKind = X86ISD::Wrapper;
5036 CodeModel::Model M = getTargetMachine().getCodeModel();
5038 if (Subtarget->isPICStyleRIPRel() &&
5039 (M == CodeModel::Small || M == CodeModel::Kernel))
5040 WrapperKind = X86ISD::WrapperRIP;
5041 else if (Subtarget->isPICStyleGOT())
5042 OpFlag = X86II::MO_GOTOFF;
5043 else if (Subtarget->isPICStyleStubPIC())
5044 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5046 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5048 DebugLoc DL = Op.getDebugLoc();
5049 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5052 // With PIC, the address is actually $g + Offset.
5053 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5054 !Subtarget->is64Bit()) {
5055 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5056 DAG.getNode(X86ISD::GlobalBaseReg,
5057 DebugLoc::getUnknownLoc(),
5066 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
5067 // Create the TargetBlockAddressAddress node.
5068 unsigned char OpFlags =
5069 Subtarget->ClassifyBlockAddressReference();
5070 CodeModel::Model M = getTargetMachine().getCodeModel();
5071 BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5072 DebugLoc dl = Op.getDebugLoc();
5073 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5074 /*isTarget=*/true, OpFlags);
5076 if (Subtarget->isPICStyleRIPRel() &&
5077 (M == CodeModel::Small || M == CodeModel::Kernel))
5078 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5080 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5082 // With PIC, the address is actually $g + Offset.
5083 if (isGlobalRelativeToPICBase(OpFlags)) {
5084 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5085 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5093 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5095 SelectionDAG &DAG) const {
5096 // Create the TargetGlobalAddress node, folding in the constant
5097 // offset if it is legal.
5098 unsigned char OpFlags =
5099 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5100 CodeModel::Model M = getTargetMachine().getCodeModel();
5102 if (OpFlags == X86II::MO_NO_FLAG &&
5103 X86::isOffsetSuitableForCodeModel(Offset, M)) {
5104 // A direct static reference to a global.
5105 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5108 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5111 if (Subtarget->isPICStyleRIPRel() &&
5112 (M == CodeModel::Small || M == CodeModel::Kernel))
5113 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5115 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5117 // With PIC, the address is actually $g + Offset.
5118 if (isGlobalRelativeToPICBase(OpFlags)) {
5119 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5120 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5124 // For globals that require a load from a stub to get the address, emit the
5126 if (isGlobalStubReference(OpFlags))
5127 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5128 PseudoSourceValue::getGOT(), 0, false, false, 0);
5130 // If there was a non-zero offset that we didn't fold, create an explicit
5133 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5134 DAG.getConstant(Offset, getPointerTy()));
5140 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
5141 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5142 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5143 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5147 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5148 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5149 unsigned char OperandFlags) {
5150 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5151 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5152 DebugLoc dl = GA->getDebugLoc();
5153 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5154 GA->getValueType(0),
5158 SDValue Ops[] = { Chain, TGA, *InFlag };
5159 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5161 SDValue Ops[] = { Chain, TGA };
5162 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5165 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5166 MFI->setHasCalls(true);
5168 SDValue Flag = Chain.getValue(1);
5169 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5172 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5174 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5177 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
5178 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5179 DAG.getNode(X86ISD::GlobalBaseReg,
5180 DebugLoc::getUnknownLoc(),
5182 InFlag = Chain.getValue(1);
5184 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5187 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5189 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5191 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5192 X86::RAX, X86II::MO_TLSGD);
5195 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5196 // "local exec" model.
5197 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5198 const EVT PtrVT, TLSModel::Model model,
5200 DebugLoc dl = GA->getDebugLoc();
5201 // Get the Thread Pointer
5202 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5203 DebugLoc::getUnknownLoc(), PtrVT,
5204 DAG.getRegister(is64Bit? X86::FS : X86::GS,
5207 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5208 NULL, 0, false, false, 0);
5210 unsigned char OperandFlags = 0;
5211 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
5213 unsigned WrapperKind = X86ISD::Wrapper;
5214 if (model == TLSModel::LocalExec) {
5215 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5216 } else if (is64Bit) {
5217 assert(model == TLSModel::InitialExec);
5218 OperandFlags = X86II::MO_GOTTPOFF;
5219 WrapperKind = X86ISD::WrapperRIP;
5221 assert(model == TLSModel::InitialExec);
5222 OperandFlags = X86II::MO_INDNTPOFF;
5225 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5227 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5228 GA->getOffset(), OperandFlags);
5229 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5231 if (model == TLSModel::InitialExec)
5232 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5233 PseudoSourceValue::getGOT(), 0, false, false, 0);
5235 // The address of the thread local variable is the add of the thread
5236 // pointer with the offset of the variable.
5237 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5241 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
5242 // TODO: implement the "local dynamic" model
5243 // TODO: implement the "initial exec"model for pic executables
5244 assert(Subtarget->isTargetELF() &&
5245 "TLS not implemented for non-ELF targets");
5246 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5247 const GlobalValue *GV = GA->getGlobal();
5249 // If GV is an alias then use the aliasee for determining
5250 // thread-localness.
5251 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5252 GV = GA->resolveAliasedGlobal(false);
5254 TLSModel::Model model = getTLSModel(GV,
5255 getTargetMachine().getRelocationModel());
5258 case TLSModel::GeneralDynamic:
5259 case TLSModel::LocalDynamic: // not implemented
5260 if (Subtarget->is64Bit())
5261 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5262 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5264 case TLSModel::InitialExec:
5265 case TLSModel::LocalExec:
5266 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5267 Subtarget->is64Bit());
5270 llvm_unreachable("Unreachable");
5275 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5276 /// take a 2 x i32 value to shift plus a shift amount.
5277 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
5278 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5279 EVT VT = Op.getValueType();
5280 unsigned VTBits = VT.getSizeInBits();
5281 DebugLoc dl = Op.getDebugLoc();
5282 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5283 SDValue ShOpLo = Op.getOperand(0);
5284 SDValue ShOpHi = Op.getOperand(1);
5285 SDValue ShAmt = Op.getOperand(2);
5286 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5287 DAG.getConstant(VTBits - 1, MVT::i8))
5288 : DAG.getConstant(0, VT);
5291 if (Op.getOpcode() == ISD::SHL_PARTS) {
5292 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5293 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5295 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5296 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5299 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5300 DAG.getConstant(VTBits, MVT::i8));
5301 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5302 AndNode, DAG.getConstant(0, MVT::i8));
5305 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5306 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5307 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5309 if (Op.getOpcode() == ISD::SHL_PARTS) {
5310 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5311 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5313 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5314 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5317 SDValue Ops[2] = { Lo, Hi };
5318 return DAG.getMergeValues(Ops, 2, dl);
5321 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5322 EVT SrcVT = Op.getOperand(0).getValueType();
5324 if (SrcVT.isVector()) {
5325 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5331 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5332 "Unknown SINT_TO_FP to lower!");
5334 // These are really Legal; return the operand so the caller accepts it as
5336 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5338 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5339 Subtarget->is64Bit()) {
5343 DebugLoc dl = Op.getDebugLoc();
5344 unsigned Size = SrcVT.getSizeInBits()/8;
5345 MachineFunction &MF = DAG.getMachineFunction();
5346 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5347 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5348 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5350 PseudoSourceValue::getFixedStack(SSFI), 0,
5352 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5355 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5357 SelectionDAG &DAG) {
5359 DebugLoc dl = Op.getDebugLoc();
5361 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5363 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5365 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5366 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5367 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5368 Tys, Ops, array_lengthof(Ops));
5371 Chain = Result.getValue(1);
5372 SDValue InFlag = Result.getValue(2);
5374 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5375 // shouldn't be necessary except that RFP cannot be live across
5376 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5377 MachineFunction &MF = DAG.getMachineFunction();
5378 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5379 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5380 Tys = DAG.getVTList(MVT::Other);
5382 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5384 Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5385 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5386 PseudoSourceValue::getFixedStack(SSFI), 0,
5393 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5394 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5395 // This algorithm is not obvious. Here it is in C code, more or less:
5397 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5398 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5399 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5401 // Copy ints to xmm registers.
5402 __m128i xh = _mm_cvtsi32_si128( hi );
5403 __m128i xl = _mm_cvtsi32_si128( lo );
5405 // Combine into low half of a single xmm register.
5406 __m128i x = _mm_unpacklo_epi32( xh, xl );
5410 // Merge in appropriate exponents to give the integer bits the right
5412 x = _mm_unpacklo_epi32( x, exp );
5414 // Subtract away the biases to deal with the IEEE-754 double precision
5416 d = _mm_sub_pd( (__m128d) x, bias );
5418 // All conversions up to here are exact. The correctly rounded result is
5419 // calculated using the current rounding mode using the following
5421 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5422 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5423 // store doesn't really need to be here (except
5424 // maybe to zero the other double)
5429 DebugLoc dl = Op.getDebugLoc();
5430 LLVMContext *Context = DAG.getContext();
5432 // Build some magic constants.
5433 std::vector<Constant*> CV0;
5434 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5435 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5436 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5437 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5438 Constant *C0 = ConstantVector::get(CV0);
5439 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5441 std::vector<Constant*> CV1;
5443 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5445 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5446 Constant *C1 = ConstantVector::get(CV1);
5447 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5449 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5450 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5452 DAG.getIntPtrConstant(1)));
5453 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5454 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5456 DAG.getIntPtrConstant(0)));
5457 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5458 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5459 PseudoSourceValue::getConstantPool(), 0,
5461 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5462 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5463 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5464 PseudoSourceValue::getConstantPool(), 0,
5466 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5468 // Add the halves; easiest way is to swap them into another reg first.
5469 int ShufMask[2] = { 1, -1 };
5470 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5471 DAG.getUNDEF(MVT::v2f64), ShufMask);
5472 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5473 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5474 DAG.getIntPtrConstant(0));
5477 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5478 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5479 DebugLoc dl = Op.getDebugLoc();
5480 // FP constant to bias correct the final result.
5481 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5484 // Load the 32-bit value into an XMM register.
5485 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5486 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5488 DAG.getIntPtrConstant(0)));
5490 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5491 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5492 DAG.getIntPtrConstant(0));
5494 // Or the load with the bias.
5495 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5496 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5497 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5499 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5500 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5501 MVT::v2f64, Bias)));
5502 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5503 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5504 DAG.getIntPtrConstant(0));
5506 // Subtract the bias.
5507 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5509 // Handle final rounding.
5510 EVT DestVT = Op.getValueType();
5512 if (DestVT.bitsLT(MVT::f64)) {
5513 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5514 DAG.getIntPtrConstant(0));
5515 } else if (DestVT.bitsGT(MVT::f64)) {
5516 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5519 // Handle final rounding.
5523 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5524 SDValue N0 = Op.getOperand(0);
5525 DebugLoc dl = Op.getDebugLoc();
5527 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5528 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5529 // the optimization here.
5530 if (DAG.SignBitIsZero(N0))
5531 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5533 EVT SrcVT = N0.getValueType();
5534 if (SrcVT == MVT::i64) {
5535 // We only handle SSE2 f64 target here; caller can expand the rest.
5536 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5539 return LowerUINT_TO_FP_i64(Op, DAG);
5540 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5541 return LowerUINT_TO_FP_i32(Op, DAG);
5544 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5546 // Make a 64-bit buffer, and use it to build an FILD.
5547 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5548 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5549 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5550 getPointerTy(), StackSlot, WordOff);
5551 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5552 StackSlot, NULL, 0, false, false, 0);
5553 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5554 OffsetSlot, NULL, 0, false, false, 0);
5555 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5558 std::pair<SDValue,SDValue> X86TargetLowering::
5559 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5560 DebugLoc dl = Op.getDebugLoc();
5562 EVT DstTy = Op.getValueType();
5565 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5569 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5570 DstTy.getSimpleVT() >= MVT::i16 &&
5571 "Unknown FP_TO_SINT to lower!");
5573 // These are really Legal.
5574 if (DstTy == MVT::i32 &&
5575 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5576 return std::make_pair(SDValue(), SDValue());
5577 if (Subtarget->is64Bit() &&
5578 DstTy == MVT::i64 &&
5579 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5580 return std::make_pair(SDValue(), SDValue());
5582 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5584 MachineFunction &MF = DAG.getMachineFunction();
5585 unsigned MemSize = DstTy.getSizeInBits()/8;
5586 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5587 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5590 switch (DstTy.getSimpleVT().SimpleTy) {
5591 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5592 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5593 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5594 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5597 SDValue Chain = DAG.getEntryNode();
5598 SDValue Value = Op.getOperand(0);
5599 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5600 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5601 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5602 PseudoSourceValue::getFixedStack(SSFI), 0,
5604 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5606 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5608 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5609 Chain = Value.getValue(1);
5610 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5611 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5614 // Build the FP_TO_INT*_IN_MEM
5615 SDValue Ops[] = { Chain, Value, StackSlot };
5616 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5618 return std::make_pair(FIST, StackSlot);
5621 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5622 if (Op.getValueType().isVector()) {
5623 if (Op.getValueType() == MVT::v2i32 &&
5624 Op.getOperand(0).getValueType() == MVT::v2f64) {
5630 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5631 SDValue FIST = Vals.first, StackSlot = Vals.second;
5632 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5633 if (FIST.getNode() == 0) return Op;
5636 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5637 FIST, StackSlot, NULL, 0, false, false, 0);
5640 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5641 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5642 SDValue FIST = Vals.first, StackSlot = Vals.second;
5643 assert(FIST.getNode() && "Unexpected failure");
5646 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5647 FIST, StackSlot, NULL, 0, false, false, 0);
5650 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5651 LLVMContext *Context = DAG.getContext();
5652 DebugLoc dl = Op.getDebugLoc();
5653 EVT VT = Op.getValueType();
5656 EltVT = VT.getVectorElementType();
5657 std::vector<Constant*> CV;
5658 if (EltVT == MVT::f64) {
5659 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5663 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5669 Constant *C = ConstantVector::get(CV);
5670 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5671 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5672 PseudoSourceValue::getConstantPool(), 0,
5674 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5677 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5678 LLVMContext *Context = DAG.getContext();
5679 DebugLoc dl = Op.getDebugLoc();
5680 EVT VT = Op.getValueType();
5683 EltVT = VT.getVectorElementType();
5684 std::vector<Constant*> CV;
5685 if (EltVT == MVT::f64) {
5686 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5690 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5696 Constant *C = ConstantVector::get(CV);
5697 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5698 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5699 PseudoSourceValue::getConstantPool(), 0,
5701 if (VT.isVector()) {
5702 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5703 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5704 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5706 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5708 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5712 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5713 LLVMContext *Context = DAG.getContext();
5714 SDValue Op0 = Op.getOperand(0);
5715 SDValue Op1 = Op.getOperand(1);
5716 DebugLoc dl = Op.getDebugLoc();
5717 EVT VT = Op.getValueType();
5718 EVT SrcVT = Op1.getValueType();
5720 // If second operand is smaller, extend it first.
5721 if (SrcVT.bitsLT(VT)) {
5722 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5725 // And if it is bigger, shrink it first.
5726 if (SrcVT.bitsGT(VT)) {
5727 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5731 // At this point the operands and the result should have the same
5732 // type, and that won't be f80 since that is not custom lowered.
5734 // First get the sign bit of second operand.
5735 std::vector<Constant*> CV;
5736 if (SrcVT == MVT::f64) {
5737 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5738 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5740 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5741 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5742 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5743 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5745 Constant *C = ConstantVector::get(CV);
5746 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5747 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5748 PseudoSourceValue::getConstantPool(), 0,
5750 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5752 // Shift sign bit right or left if the two operands have different types.
5753 if (SrcVT.bitsGT(VT)) {
5754 // Op0 is MVT::f32, Op1 is MVT::f64.
5755 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5756 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5757 DAG.getConstant(32, MVT::i32));
5758 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5759 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5760 DAG.getIntPtrConstant(0));
5763 // Clear first operand sign bit.
5765 if (VT == MVT::f64) {
5766 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5767 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5769 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5770 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5771 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5772 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5774 C = ConstantVector::get(CV);
5775 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5776 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5777 PseudoSourceValue::getConstantPool(), 0,
5779 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5781 // Or the value with the sign bit.
5782 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5785 /// Emit nodes that will be selected as "test Op0,Op0", or something
5787 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5788 SelectionDAG &DAG) {
5789 DebugLoc dl = Op.getDebugLoc();
5791 // CF and OF aren't always set the way we want. Determine which
5792 // of these we need.
5793 bool NeedCF = false;
5794 bool NeedOF = false;
5796 case X86::COND_A: case X86::COND_AE:
5797 case X86::COND_B: case X86::COND_BE:
5800 case X86::COND_G: case X86::COND_GE:
5801 case X86::COND_L: case X86::COND_LE:
5802 case X86::COND_O: case X86::COND_NO:
5808 // See if we can use the EFLAGS value from the operand instead of
5809 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5810 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5811 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5812 unsigned Opcode = 0;
5813 unsigned NumOperands = 0;
5814 switch (Op.getNode()->getOpcode()) {
5816 // Due to an isel shortcoming, be conservative if this add is likely to
5817 // be selected as part of a load-modify-store instruction. When the root
5818 // node in a match is a store, isel doesn't know how to remap non-chain
5819 // non-flag uses of other nodes in the match, such as the ADD in this
5820 // case. This leads to the ADD being left around and reselected, with
5821 // the result being two adds in the output.
5822 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5823 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5824 if (UI->getOpcode() == ISD::STORE)
5826 if (ConstantSDNode *C =
5827 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5828 // An add of one will be selected as an INC.
5829 if (C->getAPIntValue() == 1) {
5830 Opcode = X86ISD::INC;
5834 // An add of negative one (subtract of one) will be selected as a DEC.
5835 if (C->getAPIntValue().isAllOnesValue()) {
5836 Opcode = X86ISD::DEC;
5841 // Otherwise use a regular EFLAGS-setting add.
5842 Opcode = X86ISD::ADD;
5846 // If the primary and result isn't used, don't bother using X86ISD::AND,
5847 // because a TEST instruction will be better.
5848 bool NonFlagUse = false;
5849 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5850 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5852 unsigned UOpNo = UI.getOperandNo();
5853 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5854 // Look pass truncate.
5855 UOpNo = User->use_begin().getOperandNo();
5856 User = *User->use_begin();
5858 if (User->getOpcode() != ISD::BRCOND &&
5859 User->getOpcode() != ISD::SETCC &&
5860 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5872 // Due to the ISEL shortcoming noted above, be conservative if this op is
5873 // likely to be selected as part of a load-modify-store instruction.
5874 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5875 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5876 if (UI->getOpcode() == ISD::STORE)
5878 // Otherwise use a regular EFLAGS-setting instruction.
5879 switch (Op.getNode()->getOpcode()) {
5880 case ISD::SUB: Opcode = X86ISD::SUB; break;
5881 case ISD::OR: Opcode = X86ISD::OR; break;
5882 case ISD::XOR: Opcode = X86ISD::XOR; break;
5883 case ISD::AND: Opcode = X86ISD::AND; break;
5884 default: llvm_unreachable("unexpected operator!");
5895 return SDValue(Op.getNode(), 1);
5901 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5902 SmallVector<SDValue, 4> Ops;
5903 for (unsigned i = 0; i != NumOperands; ++i)
5904 Ops.push_back(Op.getOperand(i));
5905 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5906 DAG.ReplaceAllUsesWith(Op, New);
5907 return SDValue(New.getNode(), 1);
5911 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5912 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5913 DAG.getConstant(0, Op.getValueType()));
5916 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5918 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5919 SelectionDAG &DAG) {
5920 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5921 if (C->getAPIntValue() == 0)
5922 return EmitTest(Op0, X86CC, DAG);
5924 DebugLoc dl = Op0.getDebugLoc();
5925 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5928 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
5929 /// if it's possible.
5930 static SDValue LowerToBT(SDValue And, ISD::CondCode CC,
5931 DebugLoc dl, SelectionDAG &DAG) {
5932 SDValue Op0 = And.getOperand(0);
5933 SDValue Op1 = And.getOperand(1);
5934 if (Op0.getOpcode() == ISD::TRUNCATE)
5935 Op0 = Op0.getOperand(0);
5936 if (Op1.getOpcode() == ISD::TRUNCATE)
5937 Op1 = Op1.getOperand(0);
5940 if (Op1.getOpcode() == ISD::SHL) {
5941 if (ConstantSDNode *And10C = dyn_cast<ConstantSDNode>(Op1.getOperand(0)))
5942 if (And10C->getZExtValue() == 1) {
5944 RHS = Op1.getOperand(1);
5946 } else if (Op0.getOpcode() == ISD::SHL) {
5947 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
5948 if (And00C->getZExtValue() == 1) {
5950 RHS = Op0.getOperand(1);
5952 } else if (Op1.getOpcode() == ISD::Constant) {
5953 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
5954 SDValue AndLHS = Op0;
5955 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5956 LHS = AndLHS.getOperand(0);
5957 RHS = AndLHS.getOperand(1);
5961 if (LHS.getNode()) {
5962 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5963 // instruction. Since the shift amount is in-range-or-undefined, we know
5964 // that doing a bittest on the i16 value is ok. We extend to i32 because
5965 // the encoding for the i16 version is larger than the i32 version.
5966 if (LHS.getValueType() == MVT::i8)
5967 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5969 // If the operand types disagree, extend the shift amount to match. Since
5970 // BT ignores high bits (like shifts) we can use anyextend.
5971 if (LHS.getValueType() != RHS.getValueType())
5972 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5974 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5975 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5976 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5977 DAG.getConstant(Cond, MVT::i8), BT);
5983 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5984 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5985 SDValue Op0 = Op.getOperand(0);
5986 SDValue Op1 = Op.getOperand(1);
5987 DebugLoc dl = Op.getDebugLoc();
5988 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5990 // Optimize to BT if possible.
5991 // Lower (X & (1 << N)) == 0 to BT(X, N).
5992 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5993 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5994 if (Op0.getOpcode() == ISD::AND &&
5996 Op1.getOpcode() == ISD::Constant &&
5997 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5998 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5999 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6000 if (NewSetCC.getNode())
6004 // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6005 if (Op0.getOpcode() == X86ISD::SETCC &&
6006 Op1.getOpcode() == ISD::Constant &&
6007 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6008 cast<ConstantSDNode>(Op1)->isNullValue()) &&
6009 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6010 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6011 bool Invert = (CC == ISD::SETNE) ^
6012 cast<ConstantSDNode>(Op1)->isNullValue();
6014 CCode = X86::GetOppositeBranchCondition(CCode);
6015 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6016 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6019 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6020 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6021 if (X86CC == X86::COND_INVALID)
6024 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6026 // Use sbb x, x to materialize carry bit into a GPR.
6027 if (X86CC == X86::COND_B)
6028 return DAG.getNode(ISD::AND, dl, MVT::i8,
6029 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6030 DAG.getConstant(X86CC, MVT::i8), Cond),
6031 DAG.getConstant(1, MVT::i8));
6033 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6034 DAG.getConstant(X86CC, MVT::i8), Cond);
6037 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
6039 SDValue Op0 = Op.getOperand(0);
6040 SDValue Op1 = Op.getOperand(1);
6041 SDValue CC = Op.getOperand(2);
6042 EVT VT = Op.getValueType();
6043 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6044 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6045 DebugLoc dl = Op.getDebugLoc();
6049 EVT VT0 = Op0.getValueType();
6050 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6051 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6054 switch (SetCCOpcode) {
6057 case ISD::SETEQ: SSECC = 0; break;
6059 case ISD::SETGT: Swap = true; // Fallthrough
6061 case ISD::SETOLT: SSECC = 1; break;
6063 case ISD::SETGE: Swap = true; // Fallthrough
6065 case ISD::SETOLE: SSECC = 2; break;
6066 case ISD::SETUO: SSECC = 3; break;
6068 case ISD::SETNE: SSECC = 4; break;
6069 case ISD::SETULE: Swap = true;
6070 case ISD::SETUGE: SSECC = 5; break;
6071 case ISD::SETULT: Swap = true;
6072 case ISD::SETUGT: SSECC = 6; break;
6073 case ISD::SETO: SSECC = 7; break;
6076 std::swap(Op0, Op1);
6078 // In the two special cases we can't handle, emit two comparisons.
6080 if (SetCCOpcode == ISD::SETUEQ) {
6082 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6083 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6084 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6086 else if (SetCCOpcode == ISD::SETONE) {
6088 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6089 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6090 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6092 llvm_unreachable("Illegal FP comparison");
6094 // Handle all other FP comparisons here.
6095 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6098 // We are handling one of the integer comparisons here. Since SSE only has
6099 // GT and EQ comparisons for integer, swapping operands and multiple
6100 // operations may be required for some comparisons.
6101 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6102 bool Swap = false, Invert = false, FlipSigns = false;
6104 switch (VT.getSimpleVT().SimpleTy) {
6107 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6109 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6111 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6112 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6115 switch (SetCCOpcode) {
6117 case ISD::SETNE: Invert = true;
6118 case ISD::SETEQ: Opc = EQOpc; break;
6119 case ISD::SETLT: Swap = true;
6120 case ISD::SETGT: Opc = GTOpc; break;
6121 case ISD::SETGE: Swap = true;
6122 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
6123 case ISD::SETULT: Swap = true;
6124 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6125 case ISD::SETUGE: Swap = true;
6126 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6129 std::swap(Op0, Op1);
6131 // Since SSE has no unsigned integer comparisons, we need to flip the sign
6132 // bits of the inputs before performing those operations.
6134 EVT EltVT = VT.getVectorElementType();
6135 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6137 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6138 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6140 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6141 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6144 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6146 // If the logical-not of the result is required, perform that now.
6148 Result = DAG.getNOT(dl, Result, VT);
6153 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6154 static bool isX86LogicalCmp(SDValue Op) {
6155 unsigned Opc = Op.getNode()->getOpcode();
6156 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6158 if (Op.getResNo() == 1 &&
6159 (Opc == X86ISD::ADD ||
6160 Opc == X86ISD::SUB ||
6161 Opc == X86ISD::SMUL ||
6162 Opc == X86ISD::UMUL ||
6163 Opc == X86ISD::INC ||
6164 Opc == X86ISD::DEC ||
6165 Opc == X86ISD::OR ||
6166 Opc == X86ISD::XOR ||
6167 Opc == X86ISD::AND))
6173 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
6174 bool addTest = true;
6175 SDValue Cond = Op.getOperand(0);
6176 DebugLoc dl = Op.getDebugLoc();
6179 if (Cond.getOpcode() == ISD::SETCC) {
6180 SDValue NewCond = LowerSETCC(Cond, DAG);
6181 if (NewCond.getNode())
6185 // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6186 SDValue Op1 = Op.getOperand(1);
6187 SDValue Op2 = Op.getOperand(2);
6188 if (Cond.getOpcode() == X86ISD::SETCC &&
6189 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6190 SDValue Cmp = Cond.getOperand(1);
6191 if (Cmp.getOpcode() == X86ISD::CMP) {
6192 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6193 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6194 ConstantSDNode *RHSC =
6195 dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6196 if (N1C && N1C->isAllOnesValue() &&
6197 N2C && N2C->isNullValue() &&
6198 RHSC && RHSC->isNullValue()) {
6199 SDValue CmpOp0 = Cmp.getOperand(0);
6200 Cmp = DAG.getNode(X86ISD::CMP, dl, CmpOp0.getValueType(),
6201 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6202 return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6203 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6208 // Look pass (and (setcc_carry (cmp ...)), 1).
6209 if (Cond.getOpcode() == ISD::AND &&
6210 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6211 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6212 if (C && C->getAPIntValue() == 1)
6213 Cond = Cond.getOperand(0);
6216 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6217 // setting operand in place of the X86ISD::SETCC.
6218 if (Cond.getOpcode() == X86ISD::SETCC ||
6219 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6220 CC = Cond.getOperand(0);
6222 SDValue Cmp = Cond.getOperand(1);
6223 unsigned Opc = Cmp.getOpcode();
6224 EVT VT = Op.getValueType();
6226 bool IllegalFPCMov = false;
6227 if (VT.isFloatingPoint() && !VT.isVector() &&
6228 !isScalarFPTypeInSSEReg(VT)) // FPStack?
6229 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6231 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6232 Opc == X86ISD::BT) { // FIXME
6239 // Look pass the truncate.
6240 if (Cond.getOpcode() == ISD::TRUNCATE)
6241 Cond = Cond.getOperand(0);
6243 // We know the result of AND is compared against zero. Try to match
6245 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6246 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6247 if (NewSetCC.getNode()) {
6248 CC = NewSetCC.getOperand(0);
6249 Cond = NewSetCC.getOperand(1);
6256 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6257 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6260 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6261 // condition is true.
6262 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6263 SDValue Ops[] = { Op2, Op1, CC, Cond };
6264 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6267 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6268 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6269 // from the AND / OR.
6270 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6271 Opc = Op.getOpcode();
6272 if (Opc != ISD::OR && Opc != ISD::AND)
6274 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6275 Op.getOperand(0).hasOneUse() &&
6276 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6277 Op.getOperand(1).hasOneUse());
6280 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6281 // 1 and that the SETCC node has a single use.
6282 static bool isXor1OfSetCC(SDValue Op) {
6283 if (Op.getOpcode() != ISD::XOR)
6285 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6286 if (N1C && N1C->getAPIntValue() == 1) {
6287 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6288 Op.getOperand(0).hasOneUse();
6293 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
6294 bool addTest = true;
6295 SDValue Chain = Op.getOperand(0);
6296 SDValue Cond = Op.getOperand(1);
6297 SDValue Dest = Op.getOperand(2);
6298 DebugLoc dl = Op.getDebugLoc();
6301 if (Cond.getOpcode() == ISD::SETCC) {
6302 SDValue NewCond = LowerSETCC(Cond, DAG);
6303 if (NewCond.getNode())
6307 // FIXME: LowerXALUO doesn't handle these!!
6308 else if (Cond.getOpcode() == X86ISD::ADD ||
6309 Cond.getOpcode() == X86ISD::SUB ||
6310 Cond.getOpcode() == X86ISD::SMUL ||
6311 Cond.getOpcode() == X86ISD::UMUL)
6312 Cond = LowerXALUO(Cond, DAG);
6315 // Look pass (and (setcc_carry (cmp ...)), 1).
6316 if (Cond.getOpcode() == ISD::AND &&
6317 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6318 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6319 if (C && C->getAPIntValue() == 1)
6320 Cond = Cond.getOperand(0);
6323 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6324 // setting operand in place of the X86ISD::SETCC.
6325 if (Cond.getOpcode() == X86ISD::SETCC ||
6326 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6327 CC = Cond.getOperand(0);
6329 SDValue Cmp = Cond.getOperand(1);
6330 unsigned Opc = Cmp.getOpcode();
6331 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6332 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6336 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6340 // These can only come from an arithmetic instruction with overflow,
6341 // e.g. SADDO, UADDO.
6342 Cond = Cond.getNode()->getOperand(1);
6349 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6350 SDValue Cmp = Cond.getOperand(0).getOperand(1);
6351 if (CondOpc == ISD::OR) {
6352 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6353 // two branches instead of an explicit OR instruction with a
6355 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6356 isX86LogicalCmp(Cmp)) {
6357 CC = Cond.getOperand(0).getOperand(0);
6358 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6359 Chain, Dest, CC, Cmp);
6360 CC = Cond.getOperand(1).getOperand(0);
6364 } else { // ISD::AND
6365 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6366 // two branches instead of an explicit AND instruction with a
6367 // separate test. However, we only do this if this block doesn't
6368 // have a fall-through edge, because this requires an explicit
6369 // jmp when the condition is false.
6370 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6371 isX86LogicalCmp(Cmp) &&
6372 Op.getNode()->hasOneUse()) {
6373 X86::CondCode CCode =
6374 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6375 CCode = X86::GetOppositeBranchCondition(CCode);
6376 CC = DAG.getConstant(CCode, MVT::i8);
6377 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6378 // Look for an unconditional branch following this conditional branch.
6379 // We need this because we need to reverse the successors in order
6380 // to implement FCMP_OEQ.
6381 if (User.getOpcode() == ISD::BR) {
6382 SDValue FalseBB = User.getOperand(1);
6384 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6385 assert(NewBR == User);
6388 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6389 Chain, Dest, CC, Cmp);
6390 X86::CondCode CCode =
6391 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6392 CCode = X86::GetOppositeBranchCondition(CCode);
6393 CC = DAG.getConstant(CCode, MVT::i8);
6399 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6400 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6401 // It should be transformed during dag combiner except when the condition
6402 // is set by a arithmetics with overflow node.
6403 X86::CondCode CCode =
6404 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6405 CCode = X86::GetOppositeBranchCondition(CCode);
6406 CC = DAG.getConstant(CCode, MVT::i8);
6407 Cond = Cond.getOperand(0).getOperand(1);
6413 // Look pass the truncate.
6414 if (Cond.getOpcode() == ISD::TRUNCATE)
6415 Cond = Cond.getOperand(0);
6417 // We know the result of AND is compared against zero. Try to match
6419 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6420 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6421 if (NewSetCC.getNode()) {
6422 CC = NewSetCC.getOperand(0);
6423 Cond = NewSetCC.getOperand(1);
6430 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6431 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6433 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6434 Chain, Dest, CC, Cond);
6438 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6439 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6440 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6441 // that the guard pages used by the OS virtual memory manager are allocated in
6442 // correct sequence.
6444 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6445 SelectionDAG &DAG) {
6446 assert(Subtarget->isTargetCygMing() &&
6447 "This should be used only on Cygwin/Mingw targets");
6448 DebugLoc dl = Op.getDebugLoc();
6451 SDValue Chain = Op.getOperand(0);
6452 SDValue Size = Op.getOperand(1);
6453 // FIXME: Ensure alignment here
6457 EVT IntPtr = getPointerTy();
6458 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6460 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6461 Flag = Chain.getValue(1);
6463 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6465 Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6466 Flag = Chain.getValue(1);
6468 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6470 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6471 return DAG.getMergeValues(Ops1, 2, dl);
6475 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6477 SDValue Dst, SDValue Src,
6478 SDValue Size, unsigned Align,
6480 uint64_t DstSVOff) {
6481 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6483 // If not DWORD aligned or size is more than the threshold, call the library.
6484 // The libc version is likely to be faster for these cases. It can use the
6485 // address value and run time information about the CPU.
6486 if ((Align & 3) != 0 ||
6488 ConstantSize->getZExtValue() >
6489 getSubtarget()->getMaxInlineSizeThreshold()) {
6490 SDValue InFlag(0, 0);
6492 // Check to see if there is a specialized entry-point for memory zeroing.
6493 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6495 if (const char *bzeroEntry = V &&
6496 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6497 EVT IntPtr = getPointerTy();
6498 const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6499 TargetLowering::ArgListTy Args;
6500 TargetLowering::ArgListEntry Entry;
6502 Entry.Ty = IntPtrTy;
6503 Args.push_back(Entry);
6505 Args.push_back(Entry);
6506 std::pair<SDValue,SDValue> CallResult =
6507 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6508 false, false, false, false,
6509 0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6510 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
6511 return CallResult.second;
6514 // Otherwise have the target-independent code call memset.
6518 uint64_t SizeVal = ConstantSize->getZExtValue();
6519 SDValue InFlag(0, 0);
6522 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6523 unsigned BytesLeft = 0;
6524 bool TwoRepStos = false;
6527 uint64_t Val = ValC->getZExtValue() & 255;
6529 // If the value is a constant, then we can potentially use larger sets.
6530 switch (Align & 3) {
6531 case 2: // WORD aligned
6534 Val = (Val << 8) | Val;
6536 case 0: // DWORD aligned
6539 Val = (Val << 8) | Val;
6540 Val = (Val << 16) | Val;
6541 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
6544 Val = (Val << 32) | Val;
6547 default: // Byte aligned
6550 Count = DAG.getIntPtrConstant(SizeVal);
6554 if (AVT.bitsGT(MVT::i8)) {
6555 unsigned UBytes = AVT.getSizeInBits() / 8;
6556 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6557 BytesLeft = SizeVal % UBytes;
6560 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6562 InFlag = Chain.getValue(1);
6565 Count = DAG.getIntPtrConstant(SizeVal);
6566 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6567 InFlag = Chain.getValue(1);
6570 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6573 InFlag = Chain.getValue(1);
6574 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6577 InFlag = Chain.getValue(1);
6579 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6580 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6581 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6584 InFlag = Chain.getValue(1);
6586 EVT CVT = Count.getValueType();
6587 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6588 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6589 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6592 InFlag = Chain.getValue(1);
6593 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6594 SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6595 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6596 } else if (BytesLeft) {
6597 // Handle the last 1 - 7 bytes.
6598 unsigned Offset = SizeVal - BytesLeft;
6599 EVT AddrVT = Dst.getValueType();
6600 EVT SizeVT = Size.getValueType();
6602 Chain = DAG.getMemset(Chain, dl,
6603 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6604 DAG.getConstant(Offset, AddrVT)),
6606 DAG.getConstant(BytesLeft, SizeVT),
6607 Align, DstSV, DstSVOff + Offset);
6610 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6615 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6616 SDValue Chain, SDValue Dst, SDValue Src,
6617 SDValue Size, unsigned Align,
6619 const Value *DstSV, uint64_t DstSVOff,
6620 const Value *SrcSV, uint64_t SrcSVOff) {
6621 // This requires the copy size to be a constant, preferrably
6622 // within a subtarget-specific limit.
6623 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6626 uint64_t SizeVal = ConstantSize->getZExtValue();
6627 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6630 /// If not DWORD aligned, call the library.
6631 if ((Align & 3) != 0)
6636 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
6639 unsigned UBytes = AVT.getSizeInBits() / 8;
6640 unsigned CountVal = SizeVal / UBytes;
6641 SDValue Count = DAG.getIntPtrConstant(CountVal);
6642 unsigned BytesLeft = SizeVal % UBytes;
6644 SDValue InFlag(0, 0);
6645 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6648 InFlag = Chain.getValue(1);
6649 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6652 InFlag = Chain.getValue(1);
6653 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6656 InFlag = Chain.getValue(1);
6658 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6659 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6660 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6661 array_lengthof(Ops));
6663 SmallVector<SDValue, 4> Results;
6664 Results.push_back(RepMovs);
6666 // Handle the last 1 - 7 bytes.
6667 unsigned Offset = SizeVal - BytesLeft;
6668 EVT DstVT = Dst.getValueType();
6669 EVT SrcVT = Src.getValueType();
6670 EVT SizeVT = Size.getValueType();
6671 Results.push_back(DAG.getMemcpy(Chain, dl,
6672 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6673 DAG.getConstant(Offset, DstVT)),
6674 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6675 DAG.getConstant(Offset, SrcVT)),
6676 DAG.getConstant(BytesLeft, SizeVT),
6677 Align, AlwaysInline,
6678 DstSV, DstSVOff + Offset,
6679 SrcSV, SrcSVOff + Offset));
6682 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6683 &Results[0], Results.size());
6686 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6687 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6688 DebugLoc dl = Op.getDebugLoc();
6690 if (!Subtarget->is64Bit()) {
6691 // vastart just stores the address of the VarArgsFrameIndex slot into the
6692 // memory location argument.
6693 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6694 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6699 // gp_offset (0 - 6 * 8)
6700 // fp_offset (48 - 48 + 8 * 16)
6701 // overflow_arg_area (point to parameters coming in memory).
6703 SmallVector<SDValue, 8> MemOps;
6704 SDValue FIN = Op.getOperand(1);
6706 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6707 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6708 FIN, SV, 0, false, false, 0);
6709 MemOps.push_back(Store);
6712 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6713 FIN, DAG.getIntPtrConstant(4));
6714 Store = DAG.getStore(Op.getOperand(0), dl,
6715 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6716 FIN, SV, 0, false, false, 0);
6717 MemOps.push_back(Store);
6719 // Store ptr to overflow_arg_area
6720 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6721 FIN, DAG.getIntPtrConstant(4));
6722 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6723 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6725 MemOps.push_back(Store);
6727 // Store ptr to reg_save_area.
6728 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6729 FIN, DAG.getIntPtrConstant(8));
6730 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6731 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6733 MemOps.push_back(Store);
6734 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6735 &MemOps[0], MemOps.size());
6738 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6739 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6740 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6741 SDValue Chain = Op.getOperand(0);
6742 SDValue SrcPtr = Op.getOperand(1);
6743 SDValue SrcSV = Op.getOperand(2);
6745 llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6749 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6750 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6751 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6752 SDValue Chain = Op.getOperand(0);
6753 SDValue DstPtr = Op.getOperand(1);
6754 SDValue SrcPtr = Op.getOperand(2);
6755 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6756 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6757 DebugLoc dl = Op.getDebugLoc();
6759 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6760 DAG.getIntPtrConstant(24), 8, false,
6761 DstSV, 0, SrcSV, 0);
6765 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6766 DebugLoc dl = Op.getDebugLoc();
6767 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6769 default: return SDValue(); // Don't custom lower most intrinsics.
6770 // Comparison intrinsics.
6771 case Intrinsic::x86_sse_comieq_ss:
6772 case Intrinsic::x86_sse_comilt_ss:
6773 case Intrinsic::x86_sse_comile_ss:
6774 case Intrinsic::x86_sse_comigt_ss:
6775 case Intrinsic::x86_sse_comige_ss:
6776 case Intrinsic::x86_sse_comineq_ss:
6777 case Intrinsic::x86_sse_ucomieq_ss:
6778 case Intrinsic::x86_sse_ucomilt_ss:
6779 case Intrinsic::x86_sse_ucomile_ss:
6780 case Intrinsic::x86_sse_ucomigt_ss:
6781 case Intrinsic::x86_sse_ucomige_ss:
6782 case Intrinsic::x86_sse_ucomineq_ss:
6783 case Intrinsic::x86_sse2_comieq_sd:
6784 case Intrinsic::x86_sse2_comilt_sd:
6785 case Intrinsic::x86_sse2_comile_sd:
6786 case Intrinsic::x86_sse2_comigt_sd:
6787 case Intrinsic::x86_sse2_comige_sd:
6788 case Intrinsic::x86_sse2_comineq_sd:
6789 case Intrinsic::x86_sse2_ucomieq_sd:
6790 case Intrinsic::x86_sse2_ucomilt_sd:
6791 case Intrinsic::x86_sse2_ucomile_sd:
6792 case Intrinsic::x86_sse2_ucomigt_sd:
6793 case Intrinsic::x86_sse2_ucomige_sd:
6794 case Intrinsic::x86_sse2_ucomineq_sd: {
6796 ISD::CondCode CC = ISD::SETCC_INVALID;
6799 case Intrinsic::x86_sse_comieq_ss:
6800 case Intrinsic::x86_sse2_comieq_sd:
6804 case Intrinsic::x86_sse_comilt_ss:
6805 case Intrinsic::x86_sse2_comilt_sd:
6809 case Intrinsic::x86_sse_comile_ss:
6810 case Intrinsic::x86_sse2_comile_sd:
6814 case Intrinsic::x86_sse_comigt_ss:
6815 case Intrinsic::x86_sse2_comigt_sd:
6819 case Intrinsic::x86_sse_comige_ss:
6820 case Intrinsic::x86_sse2_comige_sd:
6824 case Intrinsic::x86_sse_comineq_ss:
6825 case Intrinsic::x86_sse2_comineq_sd:
6829 case Intrinsic::x86_sse_ucomieq_ss:
6830 case Intrinsic::x86_sse2_ucomieq_sd:
6831 Opc = X86ISD::UCOMI;
6834 case Intrinsic::x86_sse_ucomilt_ss:
6835 case Intrinsic::x86_sse2_ucomilt_sd:
6836 Opc = X86ISD::UCOMI;
6839 case Intrinsic::x86_sse_ucomile_ss:
6840 case Intrinsic::x86_sse2_ucomile_sd:
6841 Opc = X86ISD::UCOMI;
6844 case Intrinsic::x86_sse_ucomigt_ss:
6845 case Intrinsic::x86_sse2_ucomigt_sd:
6846 Opc = X86ISD::UCOMI;
6849 case Intrinsic::x86_sse_ucomige_ss:
6850 case Intrinsic::x86_sse2_ucomige_sd:
6851 Opc = X86ISD::UCOMI;
6854 case Intrinsic::x86_sse_ucomineq_ss:
6855 case Intrinsic::x86_sse2_ucomineq_sd:
6856 Opc = X86ISD::UCOMI;
6861 SDValue LHS = Op.getOperand(1);
6862 SDValue RHS = Op.getOperand(2);
6863 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6864 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6865 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6866 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6867 DAG.getConstant(X86CC, MVT::i8), Cond);
6868 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6870 // ptest intrinsics. The intrinsic these come from are designed to return
6871 // an integer value, not just an instruction so lower it to the ptest
6872 // pattern and a setcc for the result.
6873 case Intrinsic::x86_sse41_ptestz:
6874 case Intrinsic::x86_sse41_ptestc:
6875 case Intrinsic::x86_sse41_ptestnzc:{
6878 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6879 case Intrinsic::x86_sse41_ptestz:
6881 X86CC = X86::COND_E;
6883 case Intrinsic::x86_sse41_ptestc:
6885 X86CC = X86::COND_B;
6887 case Intrinsic::x86_sse41_ptestnzc:
6889 X86CC = X86::COND_A;
6893 SDValue LHS = Op.getOperand(1);
6894 SDValue RHS = Op.getOperand(2);
6895 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6896 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6897 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6898 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6901 // Fix vector shift instructions where the last operand is a non-immediate
6903 case Intrinsic::x86_sse2_pslli_w:
6904 case Intrinsic::x86_sse2_pslli_d:
6905 case Intrinsic::x86_sse2_pslli_q:
6906 case Intrinsic::x86_sse2_psrli_w:
6907 case Intrinsic::x86_sse2_psrli_d:
6908 case Intrinsic::x86_sse2_psrli_q:
6909 case Intrinsic::x86_sse2_psrai_w:
6910 case Intrinsic::x86_sse2_psrai_d:
6911 case Intrinsic::x86_mmx_pslli_w:
6912 case Intrinsic::x86_mmx_pslli_d:
6913 case Intrinsic::x86_mmx_pslli_q:
6914 case Intrinsic::x86_mmx_psrli_w:
6915 case Intrinsic::x86_mmx_psrli_d:
6916 case Intrinsic::x86_mmx_psrli_q:
6917 case Intrinsic::x86_mmx_psrai_w:
6918 case Intrinsic::x86_mmx_psrai_d: {
6919 SDValue ShAmt = Op.getOperand(2);
6920 if (isa<ConstantSDNode>(ShAmt))
6923 unsigned NewIntNo = 0;
6924 EVT ShAmtVT = MVT::v4i32;
6926 case Intrinsic::x86_sse2_pslli_w:
6927 NewIntNo = Intrinsic::x86_sse2_psll_w;
6929 case Intrinsic::x86_sse2_pslli_d:
6930 NewIntNo = Intrinsic::x86_sse2_psll_d;
6932 case Intrinsic::x86_sse2_pslli_q:
6933 NewIntNo = Intrinsic::x86_sse2_psll_q;
6935 case Intrinsic::x86_sse2_psrli_w:
6936 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6938 case Intrinsic::x86_sse2_psrli_d:
6939 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6941 case Intrinsic::x86_sse2_psrli_q:
6942 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6944 case Intrinsic::x86_sse2_psrai_w:
6945 NewIntNo = Intrinsic::x86_sse2_psra_w;
6947 case Intrinsic::x86_sse2_psrai_d:
6948 NewIntNo = Intrinsic::x86_sse2_psra_d;
6951 ShAmtVT = MVT::v2i32;
6953 case Intrinsic::x86_mmx_pslli_w:
6954 NewIntNo = Intrinsic::x86_mmx_psll_w;
6956 case Intrinsic::x86_mmx_pslli_d:
6957 NewIntNo = Intrinsic::x86_mmx_psll_d;
6959 case Intrinsic::x86_mmx_pslli_q:
6960 NewIntNo = Intrinsic::x86_mmx_psll_q;
6962 case Intrinsic::x86_mmx_psrli_w:
6963 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6965 case Intrinsic::x86_mmx_psrli_d:
6966 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6968 case Intrinsic::x86_mmx_psrli_q:
6969 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6971 case Intrinsic::x86_mmx_psrai_w:
6972 NewIntNo = Intrinsic::x86_mmx_psra_w;
6974 case Intrinsic::x86_mmx_psrai_d:
6975 NewIntNo = Intrinsic::x86_mmx_psra_d;
6977 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6983 // The vector shift intrinsics with scalars uses 32b shift amounts but
6984 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6988 ShOps[1] = DAG.getConstant(0, MVT::i32);
6989 if (ShAmtVT == MVT::v4i32) {
6990 ShOps[2] = DAG.getUNDEF(MVT::i32);
6991 ShOps[3] = DAG.getUNDEF(MVT::i32);
6992 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6994 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6997 EVT VT = Op.getValueType();
6998 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6999 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7000 DAG.getConstant(NewIntNo, MVT::i32),
7001 Op.getOperand(1), ShAmt);
7006 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
7007 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7008 DebugLoc dl = Op.getDebugLoc();
7011 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7013 DAG.getConstant(TD->getPointerSize(),
7014 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7015 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7016 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7018 NULL, 0, false, false, 0);
7021 // Just load the return address.
7022 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7023 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7024 RetAddrFI, NULL, 0, false, false, 0);
7027 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
7028 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7029 MFI->setFrameAddressIsTaken(true);
7030 EVT VT = Op.getValueType();
7031 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
7032 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7033 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7034 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7036 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7041 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7042 SelectionDAG &DAG) {
7043 return DAG.getIntPtrConstant(2*TD->getPointerSize());
7046 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
7048 MachineFunction &MF = DAG.getMachineFunction();
7049 SDValue Chain = Op.getOperand(0);
7050 SDValue Offset = Op.getOperand(1);
7051 SDValue Handler = Op.getOperand(2);
7052 DebugLoc dl = Op.getDebugLoc();
7054 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7056 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7058 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7059 DAG.getIntPtrConstant(-TD->getPointerSize()));
7060 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7061 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7062 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7063 MF.getRegInfo().addLiveOut(StoreAddrReg);
7065 return DAG.getNode(X86ISD::EH_RETURN, dl,
7067 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7070 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7071 SelectionDAG &DAG) {
7072 SDValue Root = Op.getOperand(0);
7073 SDValue Trmp = Op.getOperand(1); // trampoline
7074 SDValue FPtr = Op.getOperand(2); // nested function
7075 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7076 DebugLoc dl = Op.getDebugLoc();
7078 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7080 if (Subtarget->is64Bit()) {
7081 SDValue OutChains[6];
7083 // Large code-model.
7084 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
7085 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7087 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7088 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7090 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7092 // Load the pointer to the nested function into R11.
7093 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7094 SDValue Addr = Trmp;
7095 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7096 Addr, TrmpAddr, 0, false, false, 0);
7098 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7099 DAG.getConstant(2, MVT::i64));
7100 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7103 // Load the 'nest' parameter value into R10.
7104 // R10 is specified in X86CallingConv.td
7105 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7106 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7107 DAG.getConstant(10, MVT::i64));
7108 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7109 Addr, TrmpAddr, 10, false, false, 0);
7111 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7112 DAG.getConstant(12, MVT::i64));
7113 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7116 // Jump to the nested function.
7117 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7118 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7119 DAG.getConstant(20, MVT::i64));
7120 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7121 Addr, TrmpAddr, 20, false, false, 0);
7123 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7124 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7125 DAG.getConstant(22, MVT::i64));
7126 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7127 TrmpAddr, 22, false, false, 0);
7130 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7131 return DAG.getMergeValues(Ops, 2, dl);
7133 const Function *Func =
7134 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7135 CallingConv::ID CC = Func->getCallingConv();
7140 llvm_unreachable("Unsupported calling convention");
7141 case CallingConv::C:
7142 case CallingConv::X86_StdCall: {
7143 // Pass 'nest' parameter in ECX.
7144 // Must be kept in sync with X86CallingConv.td
7147 // Check that ECX wasn't needed by an 'inreg' parameter.
7148 const FunctionType *FTy = Func->getFunctionType();
7149 const AttrListPtr &Attrs = Func->getAttributes();
7151 if (!Attrs.isEmpty() && !Func->isVarArg()) {
7152 unsigned InRegCount = 0;
7155 for (FunctionType::param_iterator I = FTy->param_begin(),
7156 E = FTy->param_end(); I != E; ++I, ++Idx)
7157 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7158 // FIXME: should only count parameters that are lowered to integers.
7159 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7161 if (InRegCount > 2) {
7162 llvm_report_error("Nest register in use - reduce number of inreg parameters!");
7167 case CallingConv::X86_FastCall:
7168 case CallingConv::Fast:
7169 // Pass 'nest' parameter in EAX.
7170 // Must be kept in sync with X86CallingConv.td
7175 SDValue OutChains[4];
7178 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7179 DAG.getConstant(10, MVT::i32));
7180 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7182 // This is storing the opcode for MOV32ri.
7183 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7184 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7185 OutChains[0] = DAG.getStore(Root, dl,
7186 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7187 Trmp, TrmpAddr, 0, false, false, 0);
7189 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7190 DAG.getConstant(1, MVT::i32));
7191 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7194 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7195 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7196 DAG.getConstant(5, MVT::i32));
7197 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7198 TrmpAddr, 5, false, false, 1);
7200 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7201 DAG.getConstant(6, MVT::i32));
7202 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7206 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7207 return DAG.getMergeValues(Ops, 2, dl);
7211 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
7213 The rounding mode is in bits 11:10 of FPSR, and has the following
7220 FLT_ROUNDS, on the other hand, expects the following:
7227 To perform the conversion, we do:
7228 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7231 MachineFunction &MF = DAG.getMachineFunction();
7232 const TargetMachine &TM = MF.getTarget();
7233 const TargetFrameInfo &TFI = *TM.getFrameInfo();
7234 unsigned StackAlignment = TFI.getStackAlignment();
7235 EVT VT = Op.getValueType();
7236 DebugLoc dl = Op.getDebugLoc();
7238 // Save FP Control Word to stack slot
7239 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7240 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7242 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7243 DAG.getEntryNode(), StackSlot);
7245 // Load FP Control Word from stack slot
7246 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7249 // Transform as necessary
7251 DAG.getNode(ISD::SRL, dl, MVT::i16,
7252 DAG.getNode(ISD::AND, dl, MVT::i16,
7253 CWD, DAG.getConstant(0x800, MVT::i16)),
7254 DAG.getConstant(11, MVT::i8));
7256 DAG.getNode(ISD::SRL, dl, MVT::i16,
7257 DAG.getNode(ISD::AND, dl, MVT::i16,
7258 CWD, DAG.getConstant(0x400, MVT::i16)),
7259 DAG.getConstant(9, MVT::i8));
7262 DAG.getNode(ISD::AND, dl, MVT::i16,
7263 DAG.getNode(ISD::ADD, dl, MVT::i16,
7264 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7265 DAG.getConstant(1, MVT::i16)),
7266 DAG.getConstant(3, MVT::i16));
7269 return DAG.getNode((VT.getSizeInBits() < 16 ?
7270 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7273 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
7274 EVT VT = Op.getValueType();
7276 unsigned NumBits = VT.getSizeInBits();
7277 DebugLoc dl = Op.getDebugLoc();
7279 Op = Op.getOperand(0);
7280 if (VT == MVT::i8) {
7281 // Zero extend to i32 since there is not an i8 bsr.
7283 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7286 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7287 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7288 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7290 // If src is zero (i.e. bsr sets ZF), returns NumBits.
7293 DAG.getConstant(NumBits+NumBits-1, OpVT),
7294 DAG.getConstant(X86::COND_E, MVT::i8),
7297 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7299 // Finally xor with NumBits-1.
7300 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7303 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7307 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
7308 EVT VT = Op.getValueType();
7310 unsigned NumBits = VT.getSizeInBits();
7311 DebugLoc dl = Op.getDebugLoc();
7313 Op = Op.getOperand(0);
7314 if (VT == MVT::i8) {
7316 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7319 // Issue a bsf (scan bits forward) which also sets EFLAGS.
7320 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7321 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7323 // If src is zero (i.e. bsf sets ZF), returns NumBits.
7326 DAG.getConstant(NumBits, OpVT),
7327 DAG.getConstant(X86::COND_E, MVT::i8),
7330 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7333 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7337 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
7338 EVT VT = Op.getValueType();
7339 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7340 DebugLoc dl = Op.getDebugLoc();
7342 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7343 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7344 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7345 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7346 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7348 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7349 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7350 // return AloBlo + AloBhi + AhiBlo;
7352 SDValue A = Op.getOperand(0);
7353 SDValue B = Op.getOperand(1);
7355 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7356 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7357 A, DAG.getConstant(32, MVT::i32));
7358 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7359 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7360 B, DAG.getConstant(32, MVT::i32));
7361 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7362 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7364 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7365 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7367 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7368 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7370 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7371 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7372 AloBhi, DAG.getConstant(32, MVT::i32));
7373 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7374 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7375 AhiBlo, DAG.getConstant(32, MVT::i32));
7376 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7377 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7382 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
7383 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7384 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7385 // looks for this combo and may remove the "setcc" instruction if the "setcc"
7386 // has only one use.
7387 SDNode *N = Op.getNode();
7388 SDValue LHS = N->getOperand(0);
7389 SDValue RHS = N->getOperand(1);
7390 unsigned BaseOp = 0;
7392 DebugLoc dl = Op.getDebugLoc();
7394 switch (Op.getOpcode()) {
7395 default: llvm_unreachable("Unknown ovf instruction!");
7397 // A subtract of one will be selected as a INC. Note that INC doesn't
7398 // set CF, so we can't do this for UADDO.
7399 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7400 if (C->getAPIntValue() == 1) {
7401 BaseOp = X86ISD::INC;
7405 BaseOp = X86ISD::ADD;
7409 BaseOp = X86ISD::ADD;
7413 // A subtract of one will be selected as a DEC. Note that DEC doesn't
7414 // set CF, so we can't do this for USUBO.
7415 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7416 if (C->getAPIntValue() == 1) {
7417 BaseOp = X86ISD::DEC;
7421 BaseOp = X86ISD::SUB;
7425 BaseOp = X86ISD::SUB;
7429 BaseOp = X86ISD::SMUL;
7433 BaseOp = X86ISD::UMUL;
7438 // Also sets EFLAGS.
7439 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7440 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7443 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7444 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7446 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7450 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7451 EVT T = Op.getValueType();
7452 DebugLoc dl = Op.getDebugLoc();
7455 switch(T.getSimpleVT().SimpleTy) {
7457 assert(false && "Invalid value type!");
7458 case MVT::i8: Reg = X86::AL; size = 1; break;
7459 case MVT::i16: Reg = X86::AX; size = 2; break;
7460 case MVT::i32: Reg = X86::EAX; size = 4; break;
7462 assert(Subtarget->is64Bit() && "Node not type legal!");
7463 Reg = X86::RAX; size = 8;
7466 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7467 Op.getOperand(2), SDValue());
7468 SDValue Ops[] = { cpIn.getValue(0),
7471 DAG.getTargetConstant(size, MVT::i8),
7473 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7474 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7476 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7480 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7481 SelectionDAG &DAG) {
7482 assert(Subtarget->is64Bit() && "Result not type legalized?");
7483 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7484 SDValue TheChain = Op.getOperand(0);
7485 DebugLoc dl = Op.getDebugLoc();
7486 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7487 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7488 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7490 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7491 DAG.getConstant(32, MVT::i8));
7493 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7496 return DAG.getMergeValues(Ops, 2, dl);
7499 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7500 SDNode *Node = Op.getNode();
7501 DebugLoc dl = Node->getDebugLoc();
7502 EVT T = Node->getValueType(0);
7503 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7504 DAG.getConstant(0, T), Node->getOperand(2));
7505 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7506 cast<AtomicSDNode>(Node)->getMemoryVT(),
7507 Node->getOperand(0),
7508 Node->getOperand(1), negOp,
7509 cast<AtomicSDNode>(Node)->getSrcValue(),
7510 cast<AtomicSDNode>(Node)->getAlignment());
7513 /// LowerOperation - Provide custom lowering hooks for some operations.
7515 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7516 switch (Op.getOpcode()) {
7517 default: llvm_unreachable("Should not custom lower this!");
7518 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7519 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7520 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7521 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7522 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7523 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7524 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7525 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7526 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7527 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7528 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7529 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7530 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7531 case ISD::SHL_PARTS:
7532 case ISD::SRA_PARTS:
7533 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7534 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7535 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7536 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7537 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7538 case ISD::FABS: return LowerFABS(Op, DAG);
7539 case ISD::FNEG: return LowerFNEG(Op, DAG);
7540 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7541 case ISD::SETCC: return LowerSETCC(Op, DAG);
7542 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7543 case ISD::SELECT: return LowerSELECT(Op, DAG);
7544 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7545 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7546 case ISD::VASTART: return LowerVASTART(Op, DAG);
7547 case ISD::VAARG: return LowerVAARG(Op, DAG);
7548 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7549 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7550 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7551 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7552 case ISD::FRAME_TO_ARGS_OFFSET:
7553 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7554 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7555 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7556 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7557 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7558 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7559 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7560 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7566 case ISD::UMULO: return LowerXALUO(Op, DAG);
7567 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7571 void X86TargetLowering::
7572 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7573 SelectionDAG &DAG, unsigned NewOp) {
7574 EVT T = Node->getValueType(0);
7575 DebugLoc dl = Node->getDebugLoc();
7576 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7578 SDValue Chain = Node->getOperand(0);
7579 SDValue In1 = Node->getOperand(1);
7580 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7581 Node->getOperand(2), DAG.getIntPtrConstant(0));
7582 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7583 Node->getOperand(2), DAG.getIntPtrConstant(1));
7584 SDValue Ops[] = { Chain, In1, In2L, In2H };
7585 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7587 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7588 cast<MemSDNode>(Node)->getMemOperand());
7589 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7590 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7591 Results.push_back(Result.getValue(2));
7594 /// ReplaceNodeResults - Replace a node with an illegal result type
7595 /// with a new node built out of custom code.
7596 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7597 SmallVectorImpl<SDValue>&Results,
7598 SelectionDAG &DAG) {
7599 DebugLoc dl = N->getDebugLoc();
7600 switch (N->getOpcode()) {
7602 assert(false && "Do not know how to custom type legalize this operation!");
7604 case ISD::FP_TO_SINT: {
7605 std::pair<SDValue,SDValue> Vals =
7606 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7607 SDValue FIST = Vals.first, StackSlot = Vals.second;
7608 if (FIST.getNode() != 0) {
7609 EVT VT = N->getValueType(0);
7610 // Return a load from the stack slot.
7611 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7616 case ISD::READCYCLECOUNTER: {
7617 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7618 SDValue TheChain = N->getOperand(0);
7619 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7620 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7622 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7624 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7625 SDValue Ops[] = { eax, edx };
7626 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7627 Results.push_back(edx.getValue(1));
7630 case ISD::ATOMIC_CMP_SWAP: {
7631 EVT T = N->getValueType(0);
7632 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7633 SDValue cpInL, cpInH;
7634 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7635 DAG.getConstant(0, MVT::i32));
7636 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7637 DAG.getConstant(1, MVT::i32));
7638 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7639 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7641 SDValue swapInL, swapInH;
7642 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7643 DAG.getConstant(0, MVT::i32));
7644 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7645 DAG.getConstant(1, MVT::i32));
7646 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7648 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7649 swapInL.getValue(1));
7650 SDValue Ops[] = { swapInH.getValue(0),
7652 swapInH.getValue(1) };
7653 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7654 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7655 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7656 MVT::i32, Result.getValue(1));
7657 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7658 MVT::i32, cpOutL.getValue(2));
7659 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7660 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7661 Results.push_back(cpOutH.getValue(1));
7664 case ISD::ATOMIC_LOAD_ADD:
7665 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7667 case ISD::ATOMIC_LOAD_AND:
7668 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7670 case ISD::ATOMIC_LOAD_NAND:
7671 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7673 case ISD::ATOMIC_LOAD_OR:
7674 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7676 case ISD::ATOMIC_LOAD_SUB:
7677 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7679 case ISD::ATOMIC_LOAD_XOR:
7680 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7682 case ISD::ATOMIC_SWAP:
7683 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7688 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7690 default: return NULL;
7691 case X86ISD::BSF: return "X86ISD::BSF";
7692 case X86ISD::BSR: return "X86ISD::BSR";
7693 case X86ISD::SHLD: return "X86ISD::SHLD";
7694 case X86ISD::SHRD: return "X86ISD::SHRD";
7695 case X86ISD::FAND: return "X86ISD::FAND";
7696 case X86ISD::FOR: return "X86ISD::FOR";
7697 case X86ISD::FXOR: return "X86ISD::FXOR";
7698 case X86ISD::FSRL: return "X86ISD::FSRL";
7699 case X86ISD::FILD: return "X86ISD::FILD";
7700 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7701 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7702 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7703 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7704 case X86ISD::FLD: return "X86ISD::FLD";
7705 case X86ISD::FST: return "X86ISD::FST";
7706 case X86ISD::CALL: return "X86ISD::CALL";
7707 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7708 case X86ISD::BT: return "X86ISD::BT";
7709 case X86ISD::CMP: return "X86ISD::CMP";
7710 case X86ISD::COMI: return "X86ISD::COMI";
7711 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7712 case X86ISD::SETCC: return "X86ISD::SETCC";
7713 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
7714 case X86ISD::CMOV: return "X86ISD::CMOV";
7715 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7716 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7717 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7718 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7719 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7720 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7721 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7722 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7723 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7724 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7725 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7726 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7727 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
7728 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7729 case X86ISD::FMAX: return "X86ISD::FMAX";
7730 case X86ISD::FMIN: return "X86ISD::FMIN";
7731 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7732 case X86ISD::FRCP: return "X86ISD::FRCP";
7733 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7734 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7735 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7736 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7737 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7738 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7739 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7740 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7741 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7742 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7743 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7744 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7745 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7746 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7747 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7748 case X86ISD::VSHL: return "X86ISD::VSHL";
7749 case X86ISD::VSRL: return "X86ISD::VSRL";
7750 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7751 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7752 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7753 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7754 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7755 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7756 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7757 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7758 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7759 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7760 case X86ISD::ADD: return "X86ISD::ADD";
7761 case X86ISD::SUB: return "X86ISD::SUB";
7762 case X86ISD::SMUL: return "X86ISD::SMUL";
7763 case X86ISD::UMUL: return "X86ISD::UMUL";
7764 case X86ISD::INC: return "X86ISD::INC";
7765 case X86ISD::DEC: return "X86ISD::DEC";
7766 case X86ISD::OR: return "X86ISD::OR";
7767 case X86ISD::XOR: return "X86ISD::XOR";
7768 case X86ISD::AND: return "X86ISD::AND";
7769 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7770 case X86ISD::PTEST: return "X86ISD::PTEST";
7771 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7772 case X86ISD::MINGW_ALLOCA: return "X86ISD::MINGW_ALLOCA";
7776 // isLegalAddressingMode - Return true if the addressing mode represented
7777 // by AM is legal for this target, for a load/store of the specified type.
7778 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7779 const Type *Ty) const {
7780 // X86 supports extremely general addressing modes.
7781 CodeModel::Model M = getTargetMachine().getCodeModel();
7783 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7784 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7789 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7791 // If a reference to this global requires an extra load, we can't fold it.
7792 if (isGlobalStubReference(GVFlags))
7795 // If BaseGV requires a register for the PIC base, we cannot also have a
7796 // BaseReg specified.
7797 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7800 // If lower 4G is not available, then we must use rip-relative addressing.
7801 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7811 // These scales always work.
7816 // These scales are formed with basereg+scalereg. Only accept if there is
7821 default: // Other stuff never works.
7829 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7830 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7832 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7833 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7834 if (NumBits1 <= NumBits2)
7839 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7840 if (!VT1.isInteger() || !VT2.isInteger())
7842 unsigned NumBits1 = VT1.getSizeInBits();
7843 unsigned NumBits2 = VT2.getSizeInBits();
7844 if (NumBits1 <= NumBits2)
7849 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7850 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7851 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7854 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7855 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7856 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7859 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7860 // i16 instructions are longer (0x66 prefix) and potentially slower.
7861 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7864 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7865 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7866 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7867 /// are assumed to be legal.
7869 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7871 // Only do shuffles on 128-bit vector types for now.
7872 if (VT.getSizeInBits() == 64)
7875 // FIXME: pshufb, blends, shifts.
7876 return (VT.getVectorNumElements() == 2 ||
7877 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7878 isMOVLMask(M, VT) ||
7879 isSHUFPMask(M, VT) ||
7880 isPSHUFDMask(M, VT) ||
7881 isPSHUFHWMask(M, VT) ||
7882 isPSHUFLWMask(M, VT) ||
7883 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7884 isUNPCKLMask(M, VT) ||
7885 isUNPCKHMask(M, VT) ||
7886 isUNPCKL_v_undef_Mask(M, VT) ||
7887 isUNPCKH_v_undef_Mask(M, VT));
7891 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7893 unsigned NumElts = VT.getVectorNumElements();
7894 // FIXME: This collection of masks seems suspect.
7897 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7898 return (isMOVLMask(Mask, VT) ||
7899 isCommutedMOVLMask(Mask, VT, true) ||
7900 isSHUFPMask(Mask, VT) ||
7901 isCommutedSHUFPMask(Mask, VT));
7906 //===----------------------------------------------------------------------===//
7907 // X86 Scheduler Hooks
7908 //===----------------------------------------------------------------------===//
7910 // private utility function
7912 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7913 MachineBasicBlock *MBB,
7921 TargetRegisterClass *RC,
7922 bool invSrc) const {
7923 // For the atomic bitwise operator, we generate
7926 // ld t1 = [bitinstr.addr]
7927 // op t2 = t1, [bitinstr.val]
7929 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7931 // fallthrough -->nextMBB
7932 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7933 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7934 MachineFunction::iterator MBBIter = MBB;
7937 /// First build the CFG
7938 MachineFunction *F = MBB->getParent();
7939 MachineBasicBlock *thisMBB = MBB;
7940 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7941 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7942 F->insert(MBBIter, newMBB);
7943 F->insert(MBBIter, nextMBB);
7945 // Move all successors to thisMBB to nextMBB
7946 nextMBB->transferSuccessors(thisMBB);
7948 // Update thisMBB to fall through to newMBB
7949 thisMBB->addSuccessor(newMBB);
7951 // newMBB jumps to itself and fall through to nextMBB
7952 newMBB->addSuccessor(nextMBB);
7953 newMBB->addSuccessor(newMBB);
7955 // Insert instructions into newMBB based on incoming instruction
7956 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7957 "unexpected number of operands");
7958 DebugLoc dl = bInstr->getDebugLoc();
7959 MachineOperand& destOper = bInstr->getOperand(0);
7960 MachineOperand* argOpers[2 + X86AddrNumOperands];
7961 int numArgs = bInstr->getNumOperands() - 1;
7962 for (int i=0; i < numArgs; ++i)
7963 argOpers[i] = &bInstr->getOperand(i+1);
7965 // x86 address has 4 operands: base, index, scale, and displacement
7966 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7967 int valArgIndx = lastAddrIndx + 1;
7969 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7970 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7971 for (int i=0; i <= lastAddrIndx; ++i)
7972 (*MIB).addOperand(*argOpers[i]);
7974 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7976 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7981 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7982 assert((argOpers[valArgIndx]->isReg() ||
7983 argOpers[valArgIndx]->isImm()) &&
7985 if (argOpers[valArgIndx]->isReg())
7986 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7988 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7990 (*MIB).addOperand(*argOpers[valArgIndx]);
7992 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7995 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7996 for (int i=0; i <= lastAddrIndx; ++i)
7997 (*MIB).addOperand(*argOpers[i]);
7999 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8000 (*MIB).setMemRefs(bInstr->memoperands_begin(),
8001 bInstr->memoperands_end());
8003 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
8007 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8009 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
8013 // private utility function: 64 bit atomics on 32 bit host.
8015 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
8016 MachineBasicBlock *MBB,
8021 bool invSrc) const {
8022 // For the atomic bitwise operator, we generate
8023 // thisMBB (instructions are in pairs, except cmpxchg8b)
8024 // ld t1,t2 = [bitinstr.addr]
8026 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
8027 // op t5, t6 <- out1, out2, [bitinstr.val]
8028 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
8029 // mov ECX, EBX <- t5, t6
8030 // mov EAX, EDX <- t1, t2
8031 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
8032 // mov t3, t4 <- EAX, EDX
8034 // result in out1, out2
8035 // fallthrough -->nextMBB
8037 const TargetRegisterClass *RC = X86::GR32RegisterClass;
8038 const unsigned LoadOpc = X86::MOV32rm;
8039 const unsigned copyOpc = X86::MOV32rr;
8040 const unsigned NotOpc = X86::NOT32r;
8041 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8042 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8043 MachineFunction::iterator MBBIter = MBB;
8046 /// First build the CFG
8047 MachineFunction *F = MBB->getParent();
8048 MachineBasicBlock *thisMBB = MBB;
8049 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8050 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8051 F->insert(MBBIter, newMBB);
8052 F->insert(MBBIter, nextMBB);
8054 // Move all successors to thisMBB to nextMBB
8055 nextMBB->transferSuccessors(thisMBB);
8057 // Update thisMBB to fall through to newMBB
8058 thisMBB->addSuccessor(newMBB);
8060 // newMBB jumps to itself and fall through to nextMBB
8061 newMBB->addSuccessor(nextMBB);
8062 newMBB->addSuccessor(newMBB);
8064 DebugLoc dl = bInstr->getDebugLoc();
8065 // Insert instructions into newMBB based on incoming instruction
8066 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8067 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8068 "unexpected number of operands");
8069 MachineOperand& dest1Oper = bInstr->getOperand(0);
8070 MachineOperand& dest2Oper = bInstr->getOperand(1);
8071 MachineOperand* argOpers[2 + X86AddrNumOperands];
8072 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
8073 argOpers[i] = &bInstr->getOperand(i+2);
8075 // x86 address has 5 operands: base, index, scale, displacement, and segment.
8076 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8078 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8079 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8080 for (int i=0; i <= lastAddrIndx; ++i)
8081 (*MIB).addOperand(*argOpers[i]);
8082 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8083 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8084 // add 4 to displacement.
8085 for (int i=0; i <= lastAddrIndx-2; ++i)
8086 (*MIB).addOperand(*argOpers[i]);
8087 MachineOperand newOp3 = *(argOpers[3]);
8089 newOp3.setImm(newOp3.getImm()+4);
8091 newOp3.setOffset(newOp3.getOffset()+4);
8092 (*MIB).addOperand(newOp3);
8093 (*MIB).addOperand(*argOpers[lastAddrIndx]);
8095 // t3/4 are defined later, at the bottom of the loop
8096 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8097 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8098 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8099 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8100 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8101 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8103 // The subsequent operations should be using the destination registers of
8104 //the PHI instructions.
8106 t1 = F->getRegInfo().createVirtualRegister(RC);
8107 t2 = F->getRegInfo().createVirtualRegister(RC);
8108 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8109 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8111 t1 = dest1Oper.getReg();
8112 t2 = dest2Oper.getReg();
8115 int valArgIndx = lastAddrIndx + 1;
8116 assert((argOpers[valArgIndx]->isReg() ||
8117 argOpers[valArgIndx]->isImm()) &&
8119 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8120 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8121 if (argOpers[valArgIndx]->isReg())
8122 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8124 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8125 if (regOpcL != X86::MOV32rr)
8127 (*MIB).addOperand(*argOpers[valArgIndx]);
8128 assert(argOpers[valArgIndx + 1]->isReg() ==
8129 argOpers[valArgIndx]->isReg());
8130 assert(argOpers[valArgIndx + 1]->isImm() ==
8131 argOpers[valArgIndx]->isImm());
8132 if (argOpers[valArgIndx + 1]->isReg())
8133 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8135 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8136 if (regOpcH != X86::MOV32rr)
8138 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8140 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8142 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8145 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8147 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8150 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8151 for (int i=0; i <= lastAddrIndx; ++i)
8152 (*MIB).addOperand(*argOpers[i]);
8154 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8155 (*MIB).setMemRefs(bInstr->memoperands_begin(),
8156 bInstr->memoperands_end());
8158 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8159 MIB.addReg(X86::EAX);
8160 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8161 MIB.addReg(X86::EDX);
8164 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8166 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
8170 // private utility function
8172 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8173 MachineBasicBlock *MBB,
8174 unsigned cmovOpc) const {
8175 // For the atomic min/max operator, we generate
8178 // ld t1 = [min/max.addr]
8179 // mov t2 = [min/max.val]
8181 // cmov[cond] t2 = t1
8183 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
8185 // fallthrough -->nextMBB
8187 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8188 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8189 MachineFunction::iterator MBBIter = MBB;
8192 /// First build the CFG
8193 MachineFunction *F = MBB->getParent();
8194 MachineBasicBlock *thisMBB = MBB;
8195 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8196 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8197 F->insert(MBBIter, newMBB);
8198 F->insert(MBBIter, nextMBB);
8200 // Move all successors of thisMBB to nextMBB
8201 nextMBB->transferSuccessors(thisMBB);
8203 // Update thisMBB to fall through to newMBB
8204 thisMBB->addSuccessor(newMBB);
8206 // newMBB jumps to newMBB and fall through to nextMBB
8207 newMBB->addSuccessor(nextMBB);
8208 newMBB->addSuccessor(newMBB);
8210 DebugLoc dl = mInstr->getDebugLoc();
8211 // Insert instructions into newMBB based on incoming instruction
8212 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8213 "unexpected number of operands");
8214 MachineOperand& destOper = mInstr->getOperand(0);
8215 MachineOperand* argOpers[2 + X86AddrNumOperands];
8216 int numArgs = mInstr->getNumOperands() - 1;
8217 for (int i=0; i < numArgs; ++i)
8218 argOpers[i] = &mInstr->getOperand(i+1);
8220 // x86 address has 4 operands: base, index, scale, and displacement
8221 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8222 int valArgIndx = lastAddrIndx + 1;
8224 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8225 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8226 for (int i=0; i <= lastAddrIndx; ++i)
8227 (*MIB).addOperand(*argOpers[i]);
8229 // We only support register and immediate values
8230 assert((argOpers[valArgIndx]->isReg() ||
8231 argOpers[valArgIndx]->isImm()) &&
8234 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8235 if (argOpers[valArgIndx]->isReg())
8236 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8238 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8239 (*MIB).addOperand(*argOpers[valArgIndx]);
8241 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8244 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8249 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8250 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8254 // Cmp and exchange if none has modified the memory location
8255 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8256 for (int i=0; i <= lastAddrIndx; ++i)
8257 (*MIB).addOperand(*argOpers[i]);
8259 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8260 (*MIB).setMemRefs(mInstr->memoperands_begin(),
8261 mInstr->memoperands_end());
8263 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8264 MIB.addReg(X86::EAX);
8267 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8269 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
8273 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8274 // all of this code can be replaced with that in the .td file.
8276 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8277 unsigned numArgs, bool memArg) const {
8279 MachineFunction *F = BB->getParent();
8280 DebugLoc dl = MI->getDebugLoc();
8281 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8285 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8287 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8289 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8291 for (unsigned i = 0; i < numArgs; ++i) {
8292 MachineOperand &Op = MI->getOperand(i+1);
8294 if (!(Op.isReg() && Op.isImplicit()))
8298 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8301 F->DeleteMachineInstr(MI);
8307 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8309 MachineBasicBlock *MBB) const {
8310 // Emit code to save XMM registers to the stack. The ABI says that the
8311 // number of registers to save is given in %al, so it's theoretically
8312 // possible to do an indirect jump trick to avoid saving all of them,
8313 // however this code takes a simpler approach and just executes all
8314 // of the stores if %al is non-zero. It's less code, and it's probably
8315 // easier on the hardware branch predictor, and stores aren't all that
8316 // expensive anyway.
8318 // Create the new basic blocks. One block contains all the XMM stores,
8319 // and one block is the final destination regardless of whether any
8320 // stores were performed.
8321 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8322 MachineFunction *F = MBB->getParent();
8323 MachineFunction::iterator MBBIter = MBB;
8325 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8326 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8327 F->insert(MBBIter, XMMSaveMBB);
8328 F->insert(MBBIter, EndMBB);
8331 // Move any original successors of MBB to the end block.
8332 EndMBB->transferSuccessors(MBB);
8333 // The original block will now fall through to the XMM save block.
8334 MBB->addSuccessor(XMMSaveMBB);
8335 // The XMMSaveMBB will fall through to the end block.
8336 XMMSaveMBB->addSuccessor(EndMBB);
8338 // Now add the instructions.
8339 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8340 DebugLoc DL = MI->getDebugLoc();
8342 unsigned CountReg = MI->getOperand(0).getReg();
8343 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8344 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8346 if (!Subtarget->isTargetWin64()) {
8347 // If %al is 0, branch around the XMM save block.
8348 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8349 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8350 MBB->addSuccessor(EndMBB);
8353 // In the XMM save block, save all the XMM argument registers.
8354 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8355 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8356 MachineMemOperand *MMO =
8357 F->getMachineMemOperand(
8358 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8359 MachineMemOperand::MOStore, Offset,
8360 /*Size=*/16, /*Align=*/16);
8361 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8362 .addFrameIndex(RegSaveFrameIndex)
8363 .addImm(/*Scale=*/1)
8364 .addReg(/*IndexReg=*/0)
8365 .addImm(/*Disp=*/Offset)
8366 .addReg(/*Segment=*/0)
8367 .addReg(MI->getOperand(i).getReg())
8368 .addMemOperand(MMO);
8371 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8377 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8378 MachineBasicBlock *BB,
8379 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8380 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8381 DebugLoc DL = MI->getDebugLoc();
8383 // To "insert" a SELECT_CC instruction, we actually have to insert the
8384 // diamond control-flow pattern. The incoming instruction knows the
8385 // destination vreg to set, the condition code register to branch on, the
8386 // true/false values to select between, and a branch opcode to use.
8387 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8388 MachineFunction::iterator It = BB;
8394 // cmpTY ccX, r1, r2
8396 // fallthrough --> copy0MBB
8397 MachineBasicBlock *thisMBB = BB;
8398 MachineFunction *F = BB->getParent();
8399 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8400 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8402 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8403 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8404 F->insert(It, copy0MBB);
8405 F->insert(It, sinkMBB);
8406 // Update machine-CFG edges by first adding all successors of the current
8407 // block to the new block which will contain the Phi node for the select.
8408 // Also inform sdisel of the edge changes.
8409 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8410 E = BB->succ_end(); I != E; ++I) {
8411 EM->insert(std::make_pair(*I, sinkMBB));
8412 sinkMBB->addSuccessor(*I);
8414 // Next, remove all successors of the current block, and add the true
8415 // and fallthrough blocks as its successors.
8416 while (!BB->succ_empty())
8417 BB->removeSuccessor(BB->succ_begin());
8418 // Add the true and fallthrough blocks as its successors.
8419 BB->addSuccessor(copy0MBB);
8420 BB->addSuccessor(sinkMBB);
8423 // %FalseValue = ...
8424 // # fallthrough to sinkMBB
8427 // Update machine-CFG edges
8428 BB->addSuccessor(sinkMBB);
8431 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8434 BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8435 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8436 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8438 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8443 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8444 MachineBasicBlock *BB,
8445 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8446 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8447 DebugLoc DL = MI->getDebugLoc();
8448 MachineFunction *F = BB->getParent();
8450 // The lowering is pretty easy: we're just emitting the call to _alloca. The
8451 // non-trivial part is impdef of ESP.
8452 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8455 BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8456 .addExternalSymbol("_alloca")
8457 .addReg(X86::EAX, RegState::Implicit)
8458 .addReg(X86::ESP, RegState::Implicit)
8459 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8460 .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8462 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8467 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8468 MachineBasicBlock *BB,
8469 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8470 switch (MI->getOpcode()) {
8471 default: assert(false && "Unexpected instr type to insert");
8472 case X86::MINGW_ALLOCA:
8473 return EmitLoweredMingwAlloca(MI, BB, EM);
8475 case X86::CMOV_V1I64:
8476 case X86::CMOV_FR32:
8477 case X86::CMOV_FR64:
8478 case X86::CMOV_V4F32:
8479 case X86::CMOV_V2F64:
8480 case X86::CMOV_V2I64:
8481 return EmitLoweredSelect(MI, BB, EM);
8483 case X86::FP32_TO_INT16_IN_MEM:
8484 case X86::FP32_TO_INT32_IN_MEM:
8485 case X86::FP32_TO_INT64_IN_MEM:
8486 case X86::FP64_TO_INT16_IN_MEM:
8487 case X86::FP64_TO_INT32_IN_MEM:
8488 case X86::FP64_TO_INT64_IN_MEM:
8489 case X86::FP80_TO_INT16_IN_MEM:
8490 case X86::FP80_TO_INT32_IN_MEM:
8491 case X86::FP80_TO_INT64_IN_MEM: {
8492 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8493 DebugLoc DL = MI->getDebugLoc();
8495 // Change the floating point control register to use "round towards zero"
8496 // mode when truncating to an integer value.
8497 MachineFunction *F = BB->getParent();
8498 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8499 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8501 // Load the old value of the high byte of the control word...
8503 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8504 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8507 // Set the high part to be round to zero...
8508 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8511 // Reload the modified control word now...
8512 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8514 // Restore the memory image of control word to original value
8515 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8518 // Get the X86 opcode to use.
8520 switch (MI->getOpcode()) {
8521 default: llvm_unreachable("illegal opcode!");
8522 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8523 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8524 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8525 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8526 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8527 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8528 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8529 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8530 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8534 MachineOperand &Op = MI->getOperand(0);
8536 AM.BaseType = X86AddressMode::RegBase;
8537 AM.Base.Reg = Op.getReg();
8539 AM.BaseType = X86AddressMode::FrameIndexBase;
8540 AM.Base.FrameIndex = Op.getIndex();
8542 Op = MI->getOperand(1);
8544 AM.Scale = Op.getImm();
8545 Op = MI->getOperand(2);
8547 AM.IndexReg = Op.getImm();
8548 Op = MI->getOperand(3);
8549 if (Op.isGlobal()) {
8550 AM.GV = Op.getGlobal();
8552 AM.Disp = Op.getImm();
8554 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8555 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8557 // Reload the original control word now.
8558 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8560 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8563 // DBG_VALUE. Only the frame index case is done here.
8564 case X86::DBG_VALUE: {
8565 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8566 DebugLoc DL = MI->getDebugLoc();
8568 MachineFunction *F = BB->getParent();
8569 AM.BaseType = X86AddressMode::FrameIndexBase;
8570 AM.Base.FrameIndex = MI->getOperand(0).getImm();
8571 addFullAddress(BuildMI(BB, DL, TII->get(X86::DBG_VALUE)), AM).
8572 addImm(MI->getOperand(1).getImm()).
8573 addMetadata(MI->getOperand(2).getMetadata());
8574 F->DeleteMachineInstr(MI); // Remove pseudo.
8578 // String/text processing lowering.
8579 case X86::PCMPISTRM128REG:
8580 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8581 case X86::PCMPISTRM128MEM:
8582 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8583 case X86::PCMPESTRM128REG:
8584 return EmitPCMP(MI, BB, 5, false /* in mem */);
8585 case X86::PCMPESTRM128MEM:
8586 return EmitPCMP(MI, BB, 5, true /* in mem */);
8589 case X86::ATOMAND32:
8590 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8591 X86::AND32ri, X86::MOV32rm,
8592 X86::LCMPXCHG32, X86::MOV32rr,
8593 X86::NOT32r, X86::EAX,
8594 X86::GR32RegisterClass);
8596 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8597 X86::OR32ri, X86::MOV32rm,
8598 X86::LCMPXCHG32, X86::MOV32rr,
8599 X86::NOT32r, X86::EAX,
8600 X86::GR32RegisterClass);
8601 case X86::ATOMXOR32:
8602 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8603 X86::XOR32ri, X86::MOV32rm,
8604 X86::LCMPXCHG32, X86::MOV32rr,
8605 X86::NOT32r, X86::EAX,
8606 X86::GR32RegisterClass);
8607 case X86::ATOMNAND32:
8608 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8609 X86::AND32ri, X86::MOV32rm,
8610 X86::LCMPXCHG32, X86::MOV32rr,
8611 X86::NOT32r, X86::EAX,
8612 X86::GR32RegisterClass, true);
8613 case X86::ATOMMIN32:
8614 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8615 case X86::ATOMMAX32:
8616 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8617 case X86::ATOMUMIN32:
8618 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8619 case X86::ATOMUMAX32:
8620 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8622 case X86::ATOMAND16:
8623 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8624 X86::AND16ri, X86::MOV16rm,
8625 X86::LCMPXCHG16, X86::MOV16rr,
8626 X86::NOT16r, X86::AX,
8627 X86::GR16RegisterClass);
8629 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8630 X86::OR16ri, X86::MOV16rm,
8631 X86::LCMPXCHG16, X86::MOV16rr,
8632 X86::NOT16r, X86::AX,
8633 X86::GR16RegisterClass);
8634 case X86::ATOMXOR16:
8635 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8636 X86::XOR16ri, X86::MOV16rm,
8637 X86::LCMPXCHG16, X86::MOV16rr,
8638 X86::NOT16r, X86::AX,
8639 X86::GR16RegisterClass);
8640 case X86::ATOMNAND16:
8641 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8642 X86::AND16ri, X86::MOV16rm,
8643 X86::LCMPXCHG16, X86::MOV16rr,
8644 X86::NOT16r, X86::AX,
8645 X86::GR16RegisterClass, true);
8646 case X86::ATOMMIN16:
8647 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8648 case X86::ATOMMAX16:
8649 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8650 case X86::ATOMUMIN16:
8651 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8652 case X86::ATOMUMAX16:
8653 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8656 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8657 X86::AND8ri, X86::MOV8rm,
8658 X86::LCMPXCHG8, X86::MOV8rr,
8659 X86::NOT8r, X86::AL,
8660 X86::GR8RegisterClass);
8662 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8663 X86::OR8ri, X86::MOV8rm,
8664 X86::LCMPXCHG8, X86::MOV8rr,
8665 X86::NOT8r, X86::AL,
8666 X86::GR8RegisterClass);
8668 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8669 X86::XOR8ri, X86::MOV8rm,
8670 X86::LCMPXCHG8, X86::MOV8rr,
8671 X86::NOT8r, X86::AL,
8672 X86::GR8RegisterClass);
8673 case X86::ATOMNAND8:
8674 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8675 X86::AND8ri, X86::MOV8rm,
8676 X86::LCMPXCHG8, X86::MOV8rr,
8677 X86::NOT8r, X86::AL,
8678 X86::GR8RegisterClass, true);
8679 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8680 // This group is for 64-bit host.
8681 case X86::ATOMAND64:
8682 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8683 X86::AND64ri32, X86::MOV64rm,
8684 X86::LCMPXCHG64, X86::MOV64rr,
8685 X86::NOT64r, X86::RAX,
8686 X86::GR64RegisterClass);
8688 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8689 X86::OR64ri32, X86::MOV64rm,
8690 X86::LCMPXCHG64, X86::MOV64rr,
8691 X86::NOT64r, X86::RAX,
8692 X86::GR64RegisterClass);
8693 case X86::ATOMXOR64:
8694 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8695 X86::XOR64ri32, X86::MOV64rm,
8696 X86::LCMPXCHG64, X86::MOV64rr,
8697 X86::NOT64r, X86::RAX,
8698 X86::GR64RegisterClass);
8699 case X86::ATOMNAND64:
8700 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8701 X86::AND64ri32, X86::MOV64rm,
8702 X86::LCMPXCHG64, X86::MOV64rr,
8703 X86::NOT64r, X86::RAX,
8704 X86::GR64RegisterClass, true);
8705 case X86::ATOMMIN64:
8706 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8707 case X86::ATOMMAX64:
8708 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8709 case X86::ATOMUMIN64:
8710 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8711 case X86::ATOMUMAX64:
8712 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8714 // This group does 64-bit operations on a 32-bit host.
8715 case X86::ATOMAND6432:
8716 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8717 X86::AND32rr, X86::AND32rr,
8718 X86::AND32ri, X86::AND32ri,
8720 case X86::ATOMOR6432:
8721 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8722 X86::OR32rr, X86::OR32rr,
8723 X86::OR32ri, X86::OR32ri,
8725 case X86::ATOMXOR6432:
8726 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8727 X86::XOR32rr, X86::XOR32rr,
8728 X86::XOR32ri, X86::XOR32ri,
8730 case X86::ATOMNAND6432:
8731 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8732 X86::AND32rr, X86::AND32rr,
8733 X86::AND32ri, X86::AND32ri,
8735 case X86::ATOMADD6432:
8736 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8737 X86::ADD32rr, X86::ADC32rr,
8738 X86::ADD32ri, X86::ADC32ri,
8740 case X86::ATOMSUB6432:
8741 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8742 X86::SUB32rr, X86::SBB32rr,
8743 X86::SUB32ri, X86::SBB32ri,
8745 case X86::ATOMSWAP6432:
8746 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8747 X86::MOV32rr, X86::MOV32rr,
8748 X86::MOV32ri, X86::MOV32ri,
8750 case X86::VASTART_SAVE_XMM_REGS:
8751 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8755 //===----------------------------------------------------------------------===//
8756 // X86 Optimization Hooks
8757 //===----------------------------------------------------------------------===//
8759 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8763 const SelectionDAG &DAG,
8764 unsigned Depth) const {
8765 unsigned Opc = Op.getOpcode();
8766 assert((Opc >= ISD::BUILTIN_OP_END ||
8767 Opc == ISD::INTRINSIC_WO_CHAIN ||
8768 Opc == ISD::INTRINSIC_W_CHAIN ||
8769 Opc == ISD::INTRINSIC_VOID) &&
8770 "Should use MaskedValueIsZero if you don't know whether Op"
8771 " is a target node!");
8773 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8785 // These nodes' second result is a boolean.
8786 if (Op.getResNo() == 0)
8790 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8791 Mask.getBitWidth() - 1);
8796 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8797 /// node is a GlobalAddress + offset.
8798 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8799 GlobalValue* &GA, int64_t &Offset) const{
8800 if (N->getOpcode() == X86ISD::Wrapper) {
8801 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8802 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8803 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8807 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8810 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8811 EVT EltVT, LoadSDNode *&LDBase,
8812 unsigned &LastLoadedElt,
8813 SelectionDAG &DAG, MachineFrameInfo *MFI,
8814 const TargetLowering &TLI) {
8816 LastLoadedElt = -1U;
8817 for (unsigned i = 0; i < NumElems; ++i) {
8818 if (N->getMaskElt(i) < 0) {
8824 SDValue Elt = DAG.getShuffleScalarElt(N, i);
8825 if (!Elt.getNode() ||
8826 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8829 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8831 LDBase = cast<LoadSDNode>(Elt.getNode());
8835 if (Elt.getOpcode() == ISD::UNDEF)
8838 LoadSDNode *LD = cast<LoadSDNode>(Elt);
8839 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
8846 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8847 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8848 /// if the load addresses are consecutive, non-overlapping, and in the right
8849 /// order. In the case of v2i64, it will see if it can rewrite the
8850 /// shuffle to be an appropriate build vector so it can take advantage of
8851 // performBuildVectorCombine.
8852 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8853 const TargetLowering &TLI) {
8854 DebugLoc dl = N->getDebugLoc();
8855 EVT VT = N->getValueType(0);
8856 EVT EltVT = VT.getVectorElementType();
8857 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8858 unsigned NumElems = VT.getVectorNumElements();
8860 if (VT.getSizeInBits() != 128)
8863 // Try to combine a vector_shuffle into a 128-bit load.
8864 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8865 LoadSDNode *LD = NULL;
8866 unsigned LastLoadedElt;
8867 if (!EltsFromConsecutiveLoads(SVN, NumElems, EltVT, LD, LastLoadedElt, DAG,
8871 if (LastLoadedElt == NumElems - 1) {
8872 if (DAG.InferPtrAlignment(LD->getBasePtr()) >= 16)
8873 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8874 LD->getSrcValue(), LD->getSrcValueOffset(),
8875 LD->isVolatile(), LD->isNonTemporal(), 0);
8876 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8877 LD->getSrcValue(), LD->getSrcValueOffset(),
8878 LD->isVolatile(), LD->isNonTemporal(),
8879 LD->getAlignment());
8880 } else if (NumElems == 4 && LastLoadedElt == 1) {
8881 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8882 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8883 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8884 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8889 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8890 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8891 const X86Subtarget *Subtarget) {
8892 DebugLoc DL = N->getDebugLoc();
8893 SDValue Cond = N->getOperand(0);
8894 // Get the LHS/RHS of the select.
8895 SDValue LHS = N->getOperand(1);
8896 SDValue RHS = N->getOperand(2);
8898 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8899 // instructions match the semantics of the common C idiom x<y?x:y but not
8900 // x<=y?x:y, because of how they handle negative zero (which can be
8901 // ignored in unsafe-math mode).
8902 if (Subtarget->hasSSE2() &&
8903 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8904 Cond.getOpcode() == ISD::SETCC) {
8905 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8907 unsigned Opcode = 0;
8908 // Check for x CC y ? x : y.
8909 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
8910 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
8914 // Converting this to a min would handle NaNs incorrectly, and swapping
8915 // the operands would cause it to handle comparisons between positive
8916 // and negative zero incorrectly.
8917 if (!FiniteOnlyFPMath() &&
8918 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8919 if (!UnsafeFPMath &&
8920 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8922 std::swap(LHS, RHS);
8924 Opcode = X86ISD::FMIN;
8927 // Converting this to a min would handle comparisons between positive
8928 // and negative zero incorrectly.
8929 if (!UnsafeFPMath &&
8930 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
8932 Opcode = X86ISD::FMIN;
8935 // Converting this to a min would handle both negative zeros and NaNs
8936 // incorrectly, but we can swap the operands to fix both.
8937 std::swap(LHS, RHS);
8941 Opcode = X86ISD::FMIN;
8945 // Converting this to a max would handle comparisons between positive
8946 // and negative zero incorrectly.
8947 if (!UnsafeFPMath &&
8948 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
8950 Opcode = X86ISD::FMAX;
8953 // Converting this to a max would handle NaNs incorrectly, and swapping
8954 // the operands would cause it to handle comparisons between positive
8955 // and negative zero incorrectly.
8956 if (!FiniteOnlyFPMath() &&
8957 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8958 if (!UnsafeFPMath &&
8959 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8961 std::swap(LHS, RHS);
8963 Opcode = X86ISD::FMAX;
8966 // Converting this to a max would handle both negative zeros and NaNs
8967 // incorrectly, but we can swap the operands to fix both.
8968 std::swap(LHS, RHS);
8972 Opcode = X86ISD::FMAX;
8975 // Check for x CC y ? y : x -- a min/max with reversed arms.
8976 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
8977 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
8981 // Converting this to a min would handle comparisons between positive
8982 // and negative zero incorrectly, and swapping the operands would
8983 // cause it to handle NaNs incorrectly.
8984 if (!UnsafeFPMath &&
8985 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
8986 if (!FiniteOnlyFPMath() &&
8987 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8989 std::swap(LHS, RHS);
8991 Opcode = X86ISD::FMIN;
8994 // Converting this to a min would handle NaNs incorrectly.
8995 if (!UnsafeFPMath &&
8996 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8998 Opcode = X86ISD::FMIN;
9001 // Converting this to a min would handle both negative zeros and NaNs
9002 // incorrectly, but we can swap the operands to fix both.
9003 std::swap(LHS, RHS);
9007 Opcode = X86ISD::FMIN;
9011 // Converting this to a max would handle NaNs incorrectly.
9012 if (!FiniteOnlyFPMath() &&
9013 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9015 Opcode = X86ISD::FMAX;
9018 // Converting this to a max would handle comparisons between positive
9019 // and negative zero incorrectly, and swapping the operands would
9020 // cause it to handle NaNs incorrectly.
9021 if (!UnsafeFPMath &&
9022 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
9023 if (!FiniteOnlyFPMath() &&
9024 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9026 std::swap(LHS, RHS);
9028 Opcode = X86ISD::FMAX;
9031 // Converting this to a max would handle both negative zeros and NaNs
9032 // incorrectly, but we can swap the operands to fix both.
9033 std::swap(LHS, RHS);
9037 Opcode = X86ISD::FMAX;
9043 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9046 // If this is a select between two integer constants, try to do some
9048 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9049 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9050 // Don't do this for crazy integer types.
9051 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9052 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9053 // so that TrueC (the true value) is larger than FalseC.
9054 bool NeedsCondInvert = false;
9056 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9057 // Efficiently invertible.
9058 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
9059 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
9060 isa<ConstantSDNode>(Cond.getOperand(1))))) {
9061 NeedsCondInvert = true;
9062 std::swap(TrueC, FalseC);
9065 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
9066 if (FalseC->getAPIntValue() == 0 &&
9067 TrueC->getAPIntValue().isPowerOf2()) {
9068 if (NeedsCondInvert) // Invert the condition if needed.
9069 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9070 DAG.getConstant(1, Cond.getValueType()));
9072 // Zero extend the condition if needed.
9073 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9075 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9076 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9077 DAG.getConstant(ShAmt, MVT::i8));
9080 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9081 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9082 if (NeedsCondInvert) // Invert the condition if needed.
9083 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9084 DAG.getConstant(1, Cond.getValueType()));
9086 // Zero extend the condition if needed.
9087 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9088 FalseC->getValueType(0), Cond);
9089 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9090 SDValue(FalseC, 0));
9093 // Optimize cases that will turn into an LEA instruction. This requires
9094 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9095 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9096 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9097 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9099 bool isFastMultiplier = false;
9101 switch ((unsigned char)Diff) {
9103 case 1: // result = add base, cond
9104 case 2: // result = lea base( , cond*2)
9105 case 3: // result = lea base(cond, cond*2)
9106 case 4: // result = lea base( , cond*4)
9107 case 5: // result = lea base(cond, cond*4)
9108 case 8: // result = lea base( , cond*8)
9109 case 9: // result = lea base(cond, cond*8)
9110 isFastMultiplier = true;
9115 if (isFastMultiplier) {
9116 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9117 if (NeedsCondInvert) // Invert the condition if needed.
9118 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9119 DAG.getConstant(1, Cond.getValueType()));
9121 // Zero extend the condition if needed.
9122 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9124 // Scale the condition by the difference.
9126 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9127 DAG.getConstant(Diff, Cond.getValueType()));
9129 // Add the base if non-zero.
9130 if (FalseC->getAPIntValue() != 0)
9131 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9132 SDValue(FalseC, 0));
9142 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9143 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9144 TargetLowering::DAGCombinerInfo &DCI) {
9145 DebugLoc DL = N->getDebugLoc();
9147 // If the flag operand isn't dead, don't touch this CMOV.
9148 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9151 // If this is a select between two integer constants, try to do some
9152 // optimizations. Note that the operands are ordered the opposite of SELECT
9154 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9155 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9156 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9157 // larger than FalseC (the false value).
9158 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9160 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9161 CC = X86::GetOppositeBranchCondition(CC);
9162 std::swap(TrueC, FalseC);
9165 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
9166 // This is efficient for any integer data type (including i8/i16) and
9168 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9169 SDValue Cond = N->getOperand(3);
9170 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9171 DAG.getConstant(CC, MVT::i8), Cond);
9173 // Zero extend the condition if needed.
9174 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9176 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9177 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9178 DAG.getConstant(ShAmt, MVT::i8));
9179 if (N->getNumValues() == 2) // Dead flag value?
9180 return DCI.CombineTo(N, Cond, SDValue());
9184 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
9185 // for any integer data type, including i8/i16.
9186 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9187 SDValue Cond = N->getOperand(3);
9188 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9189 DAG.getConstant(CC, MVT::i8), Cond);
9191 // Zero extend the condition if needed.
9192 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9193 FalseC->getValueType(0), Cond);
9194 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9195 SDValue(FalseC, 0));
9197 if (N->getNumValues() == 2) // Dead flag value?
9198 return DCI.CombineTo(N, Cond, SDValue());
9202 // Optimize cases that will turn into an LEA instruction. This requires
9203 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9204 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9205 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9206 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9208 bool isFastMultiplier = false;
9210 switch ((unsigned char)Diff) {
9212 case 1: // result = add base, cond
9213 case 2: // result = lea base( , cond*2)
9214 case 3: // result = lea base(cond, cond*2)
9215 case 4: // result = lea base( , cond*4)
9216 case 5: // result = lea base(cond, cond*4)
9217 case 8: // result = lea base( , cond*8)
9218 case 9: // result = lea base(cond, cond*8)
9219 isFastMultiplier = true;
9224 if (isFastMultiplier) {
9225 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9226 SDValue Cond = N->getOperand(3);
9227 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9228 DAG.getConstant(CC, MVT::i8), Cond);
9229 // Zero extend the condition if needed.
9230 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9232 // Scale the condition by the difference.
9234 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9235 DAG.getConstant(Diff, Cond.getValueType()));
9237 // Add the base if non-zero.
9238 if (FalseC->getAPIntValue() != 0)
9239 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9240 SDValue(FalseC, 0));
9241 if (N->getNumValues() == 2) // Dead flag value?
9242 return DCI.CombineTo(N, Cond, SDValue());
9252 /// PerformMulCombine - Optimize a single multiply with constant into two
9253 /// in order to implement it with two cheaper instructions, e.g.
9254 /// LEA + SHL, LEA + LEA.
9255 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9256 TargetLowering::DAGCombinerInfo &DCI) {
9257 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9260 EVT VT = N->getValueType(0);
9264 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9267 uint64_t MulAmt = C->getZExtValue();
9268 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9271 uint64_t MulAmt1 = 0;
9272 uint64_t MulAmt2 = 0;
9273 if ((MulAmt % 9) == 0) {
9275 MulAmt2 = MulAmt / 9;
9276 } else if ((MulAmt % 5) == 0) {
9278 MulAmt2 = MulAmt / 5;
9279 } else if ((MulAmt % 3) == 0) {
9281 MulAmt2 = MulAmt / 3;
9284 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9285 DebugLoc DL = N->getDebugLoc();
9287 if (isPowerOf2_64(MulAmt2) &&
9288 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9289 // If second multiplifer is pow2, issue it first. We want the multiply by
9290 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9292 std::swap(MulAmt1, MulAmt2);
9295 if (isPowerOf2_64(MulAmt1))
9296 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9297 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9299 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9300 DAG.getConstant(MulAmt1, VT));
9302 if (isPowerOf2_64(MulAmt2))
9303 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9304 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9306 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9307 DAG.getConstant(MulAmt2, VT));
9309 // Do not add new nodes to DAG combiner worklist.
9310 DCI.CombineTo(N, NewMul, false);
9315 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9316 SDValue N0 = N->getOperand(0);
9317 SDValue N1 = N->getOperand(1);
9318 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9319 EVT VT = N0.getValueType();
9321 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9322 // since the result of setcc_c is all zero's or all ones.
9323 if (N1C && N0.getOpcode() == ISD::AND &&
9324 N0.getOperand(1).getOpcode() == ISD::Constant) {
9325 SDValue N00 = N0.getOperand(0);
9326 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9327 ((N00.getOpcode() == ISD::ANY_EXTEND ||
9328 N00.getOpcode() == ISD::ZERO_EXTEND) &&
9329 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9330 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9331 APInt ShAmt = N1C->getAPIntValue();
9332 Mask = Mask.shl(ShAmt);
9334 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9335 N00, DAG.getConstant(Mask, VT));
9342 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9344 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9345 const X86Subtarget *Subtarget) {
9346 EVT VT = N->getValueType(0);
9347 if (!VT.isVector() && VT.isInteger() &&
9348 N->getOpcode() == ISD::SHL)
9349 return PerformSHLCombine(N, DAG);
9351 // On X86 with SSE2 support, we can transform this to a vector shift if
9352 // all elements are shifted by the same amount. We can't do this in legalize
9353 // because the a constant vector is typically transformed to a constant pool
9354 // so we have no knowledge of the shift amount.
9355 if (!Subtarget->hasSSE2())
9358 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9361 SDValue ShAmtOp = N->getOperand(1);
9362 EVT EltVT = VT.getVectorElementType();
9363 DebugLoc DL = N->getDebugLoc();
9364 SDValue BaseShAmt = SDValue();
9365 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9366 unsigned NumElts = VT.getVectorNumElements();
9368 for (; i != NumElts; ++i) {
9369 SDValue Arg = ShAmtOp.getOperand(i);
9370 if (Arg.getOpcode() == ISD::UNDEF) continue;
9374 for (; i != NumElts; ++i) {
9375 SDValue Arg = ShAmtOp.getOperand(i);
9376 if (Arg.getOpcode() == ISD::UNDEF) continue;
9377 if (Arg != BaseShAmt) {
9381 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9382 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9383 SDValue InVec = ShAmtOp.getOperand(0);
9384 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9385 unsigned NumElts = InVec.getValueType().getVectorNumElements();
9387 for (; i != NumElts; ++i) {
9388 SDValue Arg = InVec.getOperand(i);
9389 if (Arg.getOpcode() == ISD::UNDEF) continue;
9393 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9394 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9395 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9396 if (C->getZExtValue() == SplatIdx)
9397 BaseShAmt = InVec.getOperand(1);
9400 if (BaseShAmt.getNode() == 0)
9401 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9402 DAG.getIntPtrConstant(0));
9406 // The shift amount is an i32.
9407 if (EltVT.bitsGT(MVT::i32))
9408 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9409 else if (EltVT.bitsLT(MVT::i32))
9410 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9412 // The shift amount is identical so we can do a vector shift.
9413 SDValue ValOp = N->getOperand(0);
9414 switch (N->getOpcode()) {
9416 llvm_unreachable("Unknown shift opcode!");
9419 if (VT == MVT::v2i64)
9420 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9421 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9423 if (VT == MVT::v4i32)
9424 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9425 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9427 if (VT == MVT::v8i16)
9428 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9429 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9433 if (VT == MVT::v4i32)
9434 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9435 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9437 if (VT == MVT::v8i16)
9438 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9439 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9443 if (VT == MVT::v2i64)
9444 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9445 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9447 if (VT == MVT::v4i32)
9448 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9449 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9451 if (VT == MVT::v8i16)
9452 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9453 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9460 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9461 const X86Subtarget *Subtarget) {
9462 EVT VT = N->getValueType(0);
9463 if (VT != MVT::i64 || !Subtarget->is64Bit())
9466 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9467 SDValue N0 = N->getOperand(0);
9468 SDValue N1 = N->getOperand(1);
9469 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9471 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9474 SDValue ShAmt0 = N0.getOperand(1);
9475 if (ShAmt0.getValueType() != MVT::i8)
9477 SDValue ShAmt1 = N1.getOperand(1);
9478 if (ShAmt1.getValueType() != MVT::i8)
9480 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9481 ShAmt0 = ShAmt0.getOperand(0);
9482 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9483 ShAmt1 = ShAmt1.getOperand(0);
9485 DebugLoc DL = N->getDebugLoc();
9486 unsigned Opc = X86ISD::SHLD;
9487 SDValue Op0 = N0.getOperand(0);
9488 SDValue Op1 = N1.getOperand(0);
9489 if (ShAmt0.getOpcode() == ISD::SUB) {
9491 std::swap(Op0, Op1);
9492 std::swap(ShAmt0, ShAmt1);
9495 if (ShAmt1.getOpcode() == ISD::SUB) {
9496 SDValue Sum = ShAmt1.getOperand(0);
9497 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9498 if (SumC->getSExtValue() == 64 &&
9499 ShAmt1.getOperand(1) == ShAmt0)
9500 return DAG.getNode(Opc, DL, VT,
9502 DAG.getNode(ISD::TRUNCATE, DL,
9505 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9506 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9508 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == 64)
9509 return DAG.getNode(Opc, DL, VT,
9510 N0.getOperand(0), N1.getOperand(0),
9511 DAG.getNode(ISD::TRUNCATE, DL,
9518 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9519 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9520 const X86Subtarget *Subtarget) {
9521 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
9522 // the FP state in cases where an emms may be missing.
9523 // A preferable solution to the general problem is to figure out the right
9524 // places to insert EMMS. This qualifies as a quick hack.
9526 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9527 StoreSDNode *St = cast<StoreSDNode>(N);
9528 EVT VT = St->getValue().getValueType();
9529 if (VT.getSizeInBits() != 64)
9532 const Function *F = DAG.getMachineFunction().getFunction();
9533 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9534 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9535 && Subtarget->hasSSE2();
9536 if ((VT.isVector() ||
9537 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9538 isa<LoadSDNode>(St->getValue()) &&
9539 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9540 St->getChain().hasOneUse() && !St->isVolatile()) {
9541 SDNode* LdVal = St->getValue().getNode();
9543 int TokenFactorIndex = -1;
9544 SmallVector<SDValue, 8> Ops;
9545 SDNode* ChainVal = St->getChain().getNode();
9546 // Must be a store of a load. We currently handle two cases: the load
9547 // is a direct child, and it's under an intervening TokenFactor. It is
9548 // possible to dig deeper under nested TokenFactors.
9549 if (ChainVal == LdVal)
9550 Ld = cast<LoadSDNode>(St->getChain());
9551 else if (St->getValue().hasOneUse() &&
9552 ChainVal->getOpcode() == ISD::TokenFactor) {
9553 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9554 if (ChainVal->getOperand(i).getNode() == LdVal) {
9555 TokenFactorIndex = i;
9556 Ld = cast<LoadSDNode>(St->getValue());
9558 Ops.push_back(ChainVal->getOperand(i));
9562 if (!Ld || !ISD::isNormalLoad(Ld))
9565 // If this is not the MMX case, i.e. we are just turning i64 load/store
9566 // into f64 load/store, avoid the transformation if there are multiple
9567 // uses of the loaded value.
9568 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9571 DebugLoc LdDL = Ld->getDebugLoc();
9572 DebugLoc StDL = N->getDebugLoc();
9573 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9574 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9576 if (Subtarget->is64Bit() || F64IsLegal) {
9577 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9578 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9579 Ld->getBasePtr(), Ld->getSrcValue(),
9580 Ld->getSrcValueOffset(), Ld->isVolatile(),
9581 Ld->isNonTemporal(), Ld->getAlignment());
9582 SDValue NewChain = NewLd.getValue(1);
9583 if (TokenFactorIndex != -1) {
9584 Ops.push_back(NewChain);
9585 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9588 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9589 St->getSrcValue(), St->getSrcValueOffset(),
9590 St->isVolatile(), St->isNonTemporal(),
9591 St->getAlignment());
9594 // Otherwise, lower to two pairs of 32-bit loads / stores.
9595 SDValue LoAddr = Ld->getBasePtr();
9596 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9597 DAG.getConstant(4, MVT::i32));
9599 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9600 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9601 Ld->isVolatile(), Ld->isNonTemporal(),
9602 Ld->getAlignment());
9603 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9604 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9605 Ld->isVolatile(), Ld->isNonTemporal(),
9606 MinAlign(Ld->getAlignment(), 4));
9608 SDValue NewChain = LoLd.getValue(1);
9609 if (TokenFactorIndex != -1) {
9610 Ops.push_back(LoLd);
9611 Ops.push_back(HiLd);
9612 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9616 LoAddr = St->getBasePtr();
9617 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9618 DAG.getConstant(4, MVT::i32));
9620 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9621 St->getSrcValue(), St->getSrcValueOffset(),
9622 St->isVolatile(), St->isNonTemporal(),
9623 St->getAlignment());
9624 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9626 St->getSrcValueOffset() + 4,
9628 St->isNonTemporal(),
9629 MinAlign(St->getAlignment(), 4));
9630 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9635 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9636 /// X86ISD::FXOR nodes.
9637 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9638 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9639 // F[X]OR(0.0, x) -> x
9640 // F[X]OR(x, 0.0) -> x
9641 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9642 if (C->getValueAPF().isPosZero())
9643 return N->getOperand(1);
9644 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9645 if (C->getValueAPF().isPosZero())
9646 return N->getOperand(0);
9650 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9651 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9652 // FAND(0.0, x) -> 0.0
9653 // FAND(x, 0.0) -> 0.0
9654 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9655 if (C->getValueAPF().isPosZero())
9656 return N->getOperand(0);
9657 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9658 if (C->getValueAPF().isPosZero())
9659 return N->getOperand(1);
9663 static SDValue PerformBTCombine(SDNode *N,
9665 TargetLowering::DAGCombinerInfo &DCI) {
9666 // BT ignores high bits in the bit index operand.
9667 SDValue Op1 = N->getOperand(1);
9668 if (Op1.hasOneUse()) {
9669 unsigned BitWidth = Op1.getValueSizeInBits();
9670 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9671 APInt KnownZero, KnownOne;
9672 TargetLowering::TargetLoweringOpt TLO(DAG);
9673 TargetLowering &TLI = DAG.getTargetLoweringInfo();
9674 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9675 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9676 DCI.CommitTargetLoweringOpt(TLO);
9681 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9682 SDValue Op = N->getOperand(0);
9683 if (Op.getOpcode() == ISD::BIT_CONVERT)
9684 Op = Op.getOperand(0);
9685 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9686 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9687 VT.getVectorElementType().getSizeInBits() ==
9688 OpVT.getVectorElementType().getSizeInBits()) {
9689 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9694 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9695 // Locked instructions, in turn, have implicit fence semantics (all memory
9696 // operations are flushed before issuing the locked instruction, and the
9697 // are not buffered), so we can fold away the common pattern of
9698 // fence-atomic-fence.
9699 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9700 SDValue atomic = N->getOperand(0);
9701 switch (atomic.getOpcode()) {
9702 case ISD::ATOMIC_CMP_SWAP:
9703 case ISD::ATOMIC_SWAP:
9704 case ISD::ATOMIC_LOAD_ADD:
9705 case ISD::ATOMIC_LOAD_SUB:
9706 case ISD::ATOMIC_LOAD_AND:
9707 case ISD::ATOMIC_LOAD_OR:
9708 case ISD::ATOMIC_LOAD_XOR:
9709 case ISD::ATOMIC_LOAD_NAND:
9710 case ISD::ATOMIC_LOAD_MIN:
9711 case ISD::ATOMIC_LOAD_MAX:
9712 case ISD::ATOMIC_LOAD_UMIN:
9713 case ISD::ATOMIC_LOAD_UMAX:
9719 SDValue fence = atomic.getOperand(0);
9720 if (fence.getOpcode() != ISD::MEMBARRIER)
9723 switch (atomic.getOpcode()) {
9724 case ISD::ATOMIC_CMP_SWAP:
9725 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9726 atomic.getOperand(1), atomic.getOperand(2),
9727 atomic.getOperand(3));
9728 case ISD::ATOMIC_SWAP:
9729 case ISD::ATOMIC_LOAD_ADD:
9730 case ISD::ATOMIC_LOAD_SUB:
9731 case ISD::ATOMIC_LOAD_AND:
9732 case ISD::ATOMIC_LOAD_OR:
9733 case ISD::ATOMIC_LOAD_XOR:
9734 case ISD::ATOMIC_LOAD_NAND:
9735 case ISD::ATOMIC_LOAD_MIN:
9736 case ISD::ATOMIC_LOAD_MAX:
9737 case ISD::ATOMIC_LOAD_UMIN:
9738 case ISD::ATOMIC_LOAD_UMAX:
9739 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9740 atomic.getOperand(1), atomic.getOperand(2));
9746 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9747 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
9748 // (and (i32 x86isd::setcc_carry), 1)
9749 // This eliminates the zext. This transformation is necessary because
9750 // ISD::SETCC is always legalized to i8.
9751 DebugLoc dl = N->getDebugLoc();
9752 SDValue N0 = N->getOperand(0);
9753 EVT VT = N->getValueType(0);
9754 if (N0.getOpcode() == ISD::AND &&
9756 N0.getOperand(0).hasOneUse()) {
9757 SDValue N00 = N0.getOperand(0);
9758 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9760 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9761 if (!C || C->getZExtValue() != 1)
9763 return DAG.getNode(ISD::AND, dl, VT,
9764 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9765 N00.getOperand(0), N00.getOperand(1)),
9766 DAG.getConstant(1, VT));
9772 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9773 DAGCombinerInfo &DCI) const {
9774 SelectionDAG &DAG = DCI.DAG;
9775 switch (N->getOpcode()) {
9777 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9778 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9779 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9780 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9783 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9784 case ISD::OR: return PerformOrCombine(N, DAG, Subtarget);
9785 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9787 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9788 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9789 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9790 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9791 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
9792 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
9798 //===----------------------------------------------------------------------===//
9799 // X86 Inline Assembly Support
9800 //===----------------------------------------------------------------------===//
9802 static bool LowerToBSwap(CallInst *CI) {
9803 // FIXME: this should verify that we are targetting a 486 or better. If not,
9804 // we will turn this bswap into something that will be lowered to logical ops
9805 // instead of emitting the bswap asm. For now, we don't support 486 or lower
9806 // so don't worry about this.
9808 // Verify this is a simple bswap.
9809 if (CI->getNumOperands() != 2 ||
9810 CI->getType() != CI->getOperand(1)->getType() ||
9811 !CI->getType()->isIntegerTy())
9814 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9815 if (!Ty || Ty->getBitWidth() % 16 != 0)
9818 // Okay, we can do this xform, do so now.
9819 const Type *Tys[] = { Ty };
9820 Module *M = CI->getParent()->getParent()->getParent();
9821 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9823 Value *Op = CI->getOperand(1);
9824 Op = CallInst::Create(Int, Op, CI->getName(), CI);
9826 CI->replaceAllUsesWith(Op);
9827 CI->eraseFromParent();
9831 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9832 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9833 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9835 std::string AsmStr = IA->getAsmString();
9837 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9838 SmallVector<StringRef, 4> AsmPieces;
9839 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
9841 switch (AsmPieces.size()) {
9842 default: return false;
9844 AsmStr = AsmPieces[0];
9846 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
9849 if (AsmPieces.size() == 2 &&
9850 (AsmPieces[0] == "bswap" ||
9851 AsmPieces[0] == "bswapq" ||
9852 AsmPieces[0] == "bswapl") &&
9853 (AsmPieces[1] == "$0" ||
9854 AsmPieces[1] == "${0:q}")) {
9855 // No need to check constraints, nothing other than the equivalent of
9856 // "=r,0" would be valid here.
9857 return LowerToBSwap(CI);
9859 // rorw $$8, ${0:w} --> llvm.bswap.i16
9860 if (CI->getType()->isIntegerTy(16) &&
9861 AsmPieces.size() == 3 &&
9862 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
9863 AsmPieces[1] == "$$8," &&
9864 AsmPieces[2] == "${0:w}" &&
9865 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
9867 const std::string &Constraints = IA->getConstraintString();
9868 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
9869 std::sort(AsmPieces.begin(), AsmPieces.end());
9870 if (AsmPieces.size() == 4 &&
9871 AsmPieces[0] == "~{cc}" &&
9872 AsmPieces[1] == "~{dirflag}" &&
9873 AsmPieces[2] == "~{flags}" &&
9874 AsmPieces[3] == "~{fpsr}") {
9875 return LowerToBSwap(CI);
9880 if (CI->getType()->isIntegerTy(64) &&
9881 Constraints.size() >= 2 &&
9882 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9883 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9884 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
9885 SmallVector<StringRef, 4> Words;
9886 SplitString(AsmPieces[0], Words, " \t");
9887 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9889 SplitString(AsmPieces[1], Words, " \t");
9890 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9892 SplitString(AsmPieces[2], Words, " \t,");
9893 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9894 Words[2] == "%edx") {
9895 return LowerToBSwap(CI);
9907 /// getConstraintType - Given a constraint letter, return the type of
9908 /// constraint it is for this target.
9909 X86TargetLowering::ConstraintType
9910 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9911 if (Constraint.size() == 1) {
9912 switch (Constraint[0]) {
9924 return C_RegisterClass;
9932 return TargetLowering::getConstraintType(Constraint);
9935 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9936 /// with another that has more specific requirements based on the type of the
9937 /// corresponding operand.
9938 const char *X86TargetLowering::
9939 LowerXConstraint(EVT ConstraintVT) const {
9940 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9941 // 'f' like normal targets.
9942 if (ConstraintVT.isFloatingPoint()) {
9943 if (Subtarget->hasSSE2())
9945 if (Subtarget->hasSSE1())
9949 return TargetLowering::LowerXConstraint(ConstraintVT);
9952 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9953 /// vector. If it is invalid, don't add anything to Ops.
9954 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9957 std::vector<SDValue>&Ops,
9958 SelectionDAG &DAG) const {
9959 SDValue Result(0, 0);
9961 switch (Constraint) {
9964 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9965 if (C->getZExtValue() <= 31) {
9966 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9972 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9973 if (C->getZExtValue() <= 63) {
9974 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9980 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9981 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
9982 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9988 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9989 if (C->getZExtValue() <= 255) {
9990 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9996 // 32-bit signed value
9997 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9998 const ConstantInt *CI = C->getConstantIntValue();
9999 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10000 C->getSExtValue())) {
10001 // Widen to 64 bits here to get it sign extended.
10002 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10005 // FIXME gcc accepts some relocatable values here too, but only in certain
10006 // memory models; it's complicated.
10011 // 32-bit unsigned value
10012 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10013 const ConstantInt *CI = C->getConstantIntValue();
10014 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10015 C->getZExtValue())) {
10016 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10020 // FIXME gcc accepts some relocatable values here too, but only in certain
10021 // memory models; it's complicated.
10025 // Literal immediates are always ok.
10026 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10027 // Widen to 64 bits here to get it sign extended.
10028 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10032 // If we are in non-pic codegen mode, we allow the address of a global (with
10033 // an optional displacement) to be used with 'i'.
10034 GlobalAddressSDNode *GA = 0;
10035 int64_t Offset = 0;
10037 // Match either (GA), (GA+C), (GA+C1+C2), etc.
10039 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10040 Offset += GA->getOffset();
10042 } else if (Op.getOpcode() == ISD::ADD) {
10043 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10044 Offset += C->getZExtValue();
10045 Op = Op.getOperand(0);
10048 } else if (Op.getOpcode() == ISD::SUB) {
10049 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10050 Offset += -C->getZExtValue();
10051 Op = Op.getOperand(0);
10056 // Otherwise, this isn't something we can handle, reject it.
10060 GlobalValue *GV = GA->getGlobal();
10061 // If we require an extra load to get this address, as in PIC mode, we
10062 // can't accept it.
10063 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10064 getTargetMachine())))
10068 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
10070 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10076 if (Result.getNode()) {
10077 Ops.push_back(Result);
10080 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
10084 std::vector<unsigned> X86TargetLowering::
10085 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10087 if (Constraint.size() == 1) {
10088 // FIXME: not handling fp-stack yet!
10089 switch (Constraint[0]) { // GCC X86 Constraint Letters
10090 default: break; // Unknown constraint letter
10091 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10092 if (Subtarget->is64Bit()) {
10093 if (VT == MVT::i32)
10094 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10095 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10096 X86::R10D,X86::R11D,X86::R12D,
10097 X86::R13D,X86::R14D,X86::R15D,
10098 X86::EBP, X86::ESP, 0);
10099 else if (VT == MVT::i16)
10100 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
10101 X86::SI, X86::DI, X86::R8W,X86::R9W,
10102 X86::R10W,X86::R11W,X86::R12W,
10103 X86::R13W,X86::R14W,X86::R15W,
10104 X86::BP, X86::SP, 0);
10105 else if (VT == MVT::i8)
10106 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
10107 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10108 X86::R10B,X86::R11B,X86::R12B,
10109 X86::R13B,X86::R14B,X86::R15B,
10110 X86::BPL, X86::SPL, 0);
10112 else if (VT == MVT::i64)
10113 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10114 X86::RSI, X86::RDI, X86::R8, X86::R9,
10115 X86::R10, X86::R11, X86::R12,
10116 X86::R13, X86::R14, X86::R15,
10117 X86::RBP, X86::RSP, 0);
10121 // 32-bit fallthrough
10122 case 'Q': // Q_REGS
10123 if (VT == MVT::i32)
10124 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10125 else if (VT == MVT::i16)
10126 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10127 else if (VT == MVT::i8)
10128 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10129 else if (VT == MVT::i64)
10130 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10135 return std::vector<unsigned>();
10138 std::pair<unsigned, const TargetRegisterClass*>
10139 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10141 // First, see if this is a constraint that directly corresponds to an LLVM
10143 if (Constraint.size() == 1) {
10144 // GCC Constraint Letters
10145 switch (Constraint[0]) {
10147 case 'r': // GENERAL_REGS
10148 case 'l': // INDEX_REGS
10150 return std::make_pair(0U, X86::GR8RegisterClass);
10151 if (VT == MVT::i16)
10152 return std::make_pair(0U, X86::GR16RegisterClass);
10153 if (VT == MVT::i32 || !Subtarget->is64Bit())
10154 return std::make_pair(0U, X86::GR32RegisterClass);
10155 return std::make_pair(0U, X86::GR64RegisterClass);
10156 case 'R': // LEGACY_REGS
10158 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10159 if (VT == MVT::i16)
10160 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10161 if (VT == MVT::i32 || !Subtarget->is64Bit())
10162 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10163 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10164 case 'f': // FP Stack registers.
10165 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10166 // value to the correct fpstack register class.
10167 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10168 return std::make_pair(0U, X86::RFP32RegisterClass);
10169 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10170 return std::make_pair(0U, X86::RFP64RegisterClass);
10171 return std::make_pair(0U, X86::RFP80RegisterClass);
10172 case 'y': // MMX_REGS if MMX allowed.
10173 if (!Subtarget->hasMMX()) break;
10174 return std::make_pair(0U, X86::VR64RegisterClass);
10175 case 'Y': // SSE_REGS if SSE2 allowed
10176 if (!Subtarget->hasSSE2()) break;
10178 case 'x': // SSE_REGS if SSE1 allowed
10179 if (!Subtarget->hasSSE1()) break;
10181 switch (VT.getSimpleVT().SimpleTy) {
10183 // Scalar SSE types.
10186 return std::make_pair(0U, X86::FR32RegisterClass);
10189 return std::make_pair(0U, X86::FR64RegisterClass);
10197 return std::make_pair(0U, X86::VR128RegisterClass);
10203 // Use the default implementation in TargetLowering to convert the register
10204 // constraint into a member of a register class.
10205 std::pair<unsigned, const TargetRegisterClass*> Res;
10206 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10208 // Not found as a standard register?
10209 if (Res.second == 0) {
10210 // Map st(0) -> st(7) -> ST0
10211 if (Constraint.size() == 7 && Constraint[0] == '{' &&
10212 tolower(Constraint[1]) == 's' &&
10213 tolower(Constraint[2]) == 't' &&
10214 Constraint[3] == '(' &&
10215 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10216 Constraint[5] == ')' &&
10217 Constraint[6] == '}') {
10219 Res.first = X86::ST0+Constraint[4]-'0';
10220 Res.second = X86::RFP80RegisterClass;
10224 // GCC allows "st(0)" to be called just plain "st".
10225 if (StringRef("{st}").equals_lower(Constraint)) {
10226 Res.first = X86::ST0;
10227 Res.second = X86::RFP80RegisterClass;
10232 if (StringRef("{flags}").equals_lower(Constraint)) {
10233 Res.first = X86::EFLAGS;
10234 Res.second = X86::CCRRegisterClass;
10238 // 'A' means EAX + EDX.
10239 if (Constraint == "A") {
10240 Res.first = X86::EAX;
10241 Res.second = X86::GR32_ADRegisterClass;
10247 // Otherwise, check to see if this is a register class of the wrong value
10248 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10249 // turn into {ax},{dx}.
10250 if (Res.second->hasType(VT))
10251 return Res; // Correct type already, nothing to do.
10253 // All of the single-register GCC register classes map their values onto
10254 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
10255 // really want an 8-bit or 32-bit register, map to the appropriate register
10256 // class and return the appropriate register.
10257 if (Res.second == X86::GR16RegisterClass) {
10258 if (VT == MVT::i8) {
10259 unsigned DestReg = 0;
10260 switch (Res.first) {
10262 case X86::AX: DestReg = X86::AL; break;
10263 case X86::DX: DestReg = X86::DL; break;
10264 case X86::CX: DestReg = X86::CL; break;
10265 case X86::BX: DestReg = X86::BL; break;
10268 Res.first = DestReg;
10269 Res.second = X86::GR8RegisterClass;
10271 } else if (VT == MVT::i32) {
10272 unsigned DestReg = 0;
10273 switch (Res.first) {
10275 case X86::AX: DestReg = X86::EAX; break;
10276 case X86::DX: DestReg = X86::EDX; break;
10277 case X86::CX: DestReg = X86::ECX; break;
10278 case X86::BX: DestReg = X86::EBX; break;
10279 case X86::SI: DestReg = X86::ESI; break;
10280 case X86::DI: DestReg = X86::EDI; break;
10281 case X86::BP: DestReg = X86::EBP; break;
10282 case X86::SP: DestReg = X86::ESP; break;
10285 Res.first = DestReg;
10286 Res.second = X86::GR32RegisterClass;
10288 } else if (VT == MVT::i64) {
10289 unsigned DestReg = 0;
10290 switch (Res.first) {
10292 case X86::AX: DestReg = X86::RAX; break;
10293 case X86::DX: DestReg = X86::RDX; break;
10294 case X86::CX: DestReg = X86::RCX; break;
10295 case X86::BX: DestReg = X86::RBX; break;
10296 case X86::SI: DestReg = X86::RSI; break;
10297 case X86::DI: DestReg = X86::RDI; break;
10298 case X86::BP: DestReg = X86::RBP; break;
10299 case X86::SP: DestReg = X86::RSP; break;
10302 Res.first = DestReg;
10303 Res.second = X86::GR64RegisterClass;
10306 } else if (Res.second == X86::FR32RegisterClass ||
10307 Res.second == X86::FR64RegisterClass ||
10308 Res.second == X86::VR128RegisterClass) {
10309 // Handle references to XMM physical registers that got mapped into the
10310 // wrong class. This can happen with constraints like {xmm0} where the
10311 // target independent register mapper will just pick the first match it can
10312 // find, ignoring the required type.
10313 if (VT == MVT::f32)
10314 Res.second = X86::FR32RegisterClass;
10315 else if (VT == MVT::f64)
10316 Res.second = X86::FR64RegisterClass;
10317 else if (X86::VR128RegisterClass->hasType(VT))
10318 Res.second = X86::VR128RegisterClass;