1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/ADT/VectorExtras.h"
26 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/SelectionDAG.h"
32 #include "llvm/CodeGen/SSARegMap.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/ADT/StringExtras.h"
38 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
39 : TargetLowering(TM) {
40 Subtarget = &TM.getSubtarget<X86Subtarget>();
41 X86ScalarSSE = Subtarget->hasSSE2();
42 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
44 // Set up the TargetLowering object.
46 // X86 is weird, it always uses i8 for shift amounts and setcc results.
47 setShiftAmountType(MVT::i8);
48 setSetCCResultType(MVT::i8);
49 setSetCCResultContents(ZeroOrOneSetCCResult);
50 setSchedulingPreference(SchedulingForRegPressure);
51 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
52 setStackPointerRegisterToSaveRestore(X86StackPtr);
54 if (Subtarget->isTargetDarwin()) {
55 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
56 setUseUnderscoreSetJmp(false);
57 setUseUnderscoreLongJmp(false);
58 } else if (Subtarget->isTargetMingw()) {
59 // MS runtime is weird: it exports _setjmp, but longjmp!
60 setUseUnderscoreSetJmp(true);
61 setUseUnderscoreLongJmp(false);
63 setUseUnderscoreSetJmp(true);
64 setUseUnderscoreLongJmp(true);
67 // Set up the register classes.
68 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
69 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
70 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
71 if (Subtarget->is64Bit())
72 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
74 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Expand);
76 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
78 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
79 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
80 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
82 if (Subtarget->is64Bit()) {
83 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
84 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
87 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
88 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
90 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
93 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
95 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
96 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
97 // SSE has no i16 to fp conversion, only i32
99 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
101 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
102 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
105 if (!Subtarget->is64Bit()) {
106 // Custom lower SINT_TO_FP and FP_TO_SINT from/to i64 in 32-bit mode.
107 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
108 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
111 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
113 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
114 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
117 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
119 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
120 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
123 // Handle FP_TO_UINT by promoting the destination to a larger signed
125 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
126 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
127 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
129 if (Subtarget->is64Bit()) {
130 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
131 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
133 if (X86ScalarSSE && !Subtarget->hasSSE3())
134 // Expand FP_TO_UINT into a select.
135 // FIXME: We would like to use a Custom expander here eventually to do
136 // the optimal thing for SSE vs. the default expansion in the legalizer.
137 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
139 // With SSE3 we can use fisttpll to convert to a signed i64.
140 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
143 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
145 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
146 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
149 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
150 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
151 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
152 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
153 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
154 if (Subtarget->is64Bit())
155 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Expand);
156 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Expand);
157 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
158 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
159 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
160 setOperationAction(ISD::FREM , MVT::f64 , Expand);
162 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
163 setOperationAction(ISD::CTTZ , MVT::i8 , Expand);
164 setOperationAction(ISD::CTLZ , MVT::i8 , Expand);
165 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
166 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
167 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
168 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
169 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
170 setOperationAction(ISD::CTLZ , MVT::i32 , Expand);
171 if (Subtarget->is64Bit()) {
172 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
173 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
174 setOperationAction(ISD::CTLZ , MVT::i64 , Expand);
177 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
178 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
180 // These should be promoted to a larger select which is supported.
181 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
182 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
183 // X86 wants to expand cmov itself.
184 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
185 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
186 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
187 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
188 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
189 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
190 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
191 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
192 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
193 if (Subtarget->is64Bit()) {
194 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
195 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
197 // X86 ret instruction may pop stack.
198 setOperationAction(ISD::RET , MVT::Other, Custom);
200 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
201 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
202 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
203 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
204 if (Subtarget->is64Bit()) {
205 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
206 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
207 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
208 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
210 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
211 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
212 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
213 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
214 // X86 wants to expand memset / memcpy itself.
215 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
216 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
218 // We don't have line number support yet.
219 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
220 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
221 // FIXME - use subtarget debug flags
222 if (!Subtarget->isTargetDarwin() &&
223 !Subtarget->isTargetELF() &&
224 !Subtarget->isTargetCygMing())
225 setOperationAction(ISD::LABEL, MVT::Other, Expand);
227 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
228 setOperationAction(ISD::VASTART , MVT::Other, Custom);
229 setOperationAction(ISD::VAARG , MVT::Other, Expand);
230 setOperationAction(ISD::VAEND , MVT::Other, Expand);
231 if (Subtarget->is64Bit())
232 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
234 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
236 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
237 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
238 if (Subtarget->is64Bit())
239 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
240 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Expand);
243 // Set up the FP register classes.
244 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
245 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
247 // Use ANDPD to simulate FABS.
248 setOperationAction(ISD::FABS , MVT::f64, Custom);
249 setOperationAction(ISD::FABS , MVT::f32, Custom);
251 // Use XORP to simulate FNEG.
252 setOperationAction(ISD::FNEG , MVT::f64, Custom);
253 setOperationAction(ISD::FNEG , MVT::f32, Custom);
255 // Use ANDPD and ORPD to simulate FCOPYSIGN.
256 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
257 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
259 // We don't support sin/cos/fmod
260 setOperationAction(ISD::FSIN , MVT::f64, Expand);
261 setOperationAction(ISD::FCOS , MVT::f64, Expand);
262 setOperationAction(ISD::FREM , MVT::f64, Expand);
263 setOperationAction(ISD::FSIN , MVT::f32, Expand);
264 setOperationAction(ISD::FCOS , MVT::f32, Expand);
265 setOperationAction(ISD::FREM , MVT::f32, Expand);
267 // Expand FP immediates into loads from the stack, except for the special
269 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
270 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
271 addLegalFPImmediate(+0.0); // xorps / xorpd
273 // Set up the FP register classes.
274 addRegisterClass(MVT::f64, X86::RFPRegisterClass);
276 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
277 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
278 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
281 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
282 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
285 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
286 addLegalFPImmediate(+0.0); // FLD0
287 addLegalFPImmediate(+1.0); // FLD1
288 addLegalFPImmediate(-0.0); // FLD0/FCHS
289 addLegalFPImmediate(-1.0); // FLD1/FCHS
292 // First set operation action for all vector types to expand. Then we
293 // will selectively turn on ones that can be effectively codegen'd.
294 for (unsigned VT = (unsigned)MVT::Vector + 1;
295 VT != (unsigned)MVT::LAST_VALUETYPE; VT++) {
296 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
297 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
298 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
299 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
300 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
301 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
302 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
303 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
304 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
305 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
306 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
307 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
308 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
309 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
310 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
313 if (Subtarget->hasMMX()) {
314 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
315 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
316 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
318 // FIXME: add MMX packed arithmetics
320 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
321 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
322 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
324 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
325 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
326 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
328 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
329 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v2i32);
330 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
331 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v2i32);
332 setOperationAction(ISD::LOAD, MVT::v2i32, Legal);
334 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Expand);
335 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Expand);
336 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Expand);
339 if (Subtarget->hasSSE1()) {
340 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
342 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
343 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
344 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
345 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
346 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
347 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
348 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
349 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
350 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
353 if (Subtarget->hasSSE2()) {
354 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
355 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
356 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
357 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
358 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
360 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
361 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
362 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
363 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
364 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
365 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
366 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
367 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
368 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
369 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
370 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
371 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
372 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
374 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
375 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
376 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
377 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
378 // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
379 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
381 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
382 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
383 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
384 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
385 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
387 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
388 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
389 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
390 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
391 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
392 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
394 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
395 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
396 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
397 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
398 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
399 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
400 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
401 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
402 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
403 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
404 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
405 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
408 // Custom lower v2i64 and v2f64 selects.
409 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
410 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
411 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
412 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
415 // We want to custom lower some of our intrinsics.
416 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
418 // We have target-specific dag combine patterns for the following nodes:
419 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
420 setTargetDAGCombine(ISD::SELECT);
422 computeRegisterProperties();
424 // FIXME: These should be based on subtarget info. Plus, the values should
425 // be smaller when we are in optimizing for size mode.
426 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
427 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
428 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
429 allowUnalignedMemoryAccesses = true; // x86 supports it!
433 //===----------------------------------------------------------------------===//
434 // Return Value Calling Convention Implementation
435 //===----------------------------------------------------------------------===//
437 #include "X86GenCallingConv.inc"
439 /// LowerRET - Lower an ISD::RET node.
440 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
441 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
443 SmallVector<CCValAssign, 16> RVLocs;
444 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
445 CCState CCInfo(CC, getTargetMachine(), RVLocs);
446 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
449 // If this is the first return lowered for this function, add the regs to the
450 // liveout set for the function.
451 if (DAG.getMachineFunction().liveout_empty()) {
452 for (unsigned i = 0; i != RVLocs.size(); ++i)
453 if (RVLocs[i].isRegLoc())
454 DAG.getMachineFunction().addLiveOut(RVLocs[i].getLocReg());
457 SDOperand Chain = Op.getOperand(0);
460 // Copy the result values into the output registers.
461 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
462 RVLocs[0].getLocReg() != X86::ST0) {
463 for (unsigned i = 0; i != RVLocs.size(); ++i) {
464 CCValAssign &VA = RVLocs[i];
465 assert(VA.isRegLoc() && "Can only return in registers!");
466 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
468 Flag = Chain.getValue(1);
471 // We need to handle a destination of ST0 specially, because it isn't really
473 SDOperand Value = Op.getOperand(1);
475 // If this is an FP return with ScalarSSE, we need to move the value from
476 // an XMM register onto the fp-stack.
480 // If this is a load into a scalarsse value, don't store the loaded value
481 // back to the stack, only to reload it: just replace the scalar-sse load.
482 if (ISD::isNON_EXTLoad(Value.Val) &&
483 (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
484 Chain = Value.getOperand(0);
485 MemLoc = Value.getOperand(1);
487 // Spill the value to memory and reload it into top of stack.
488 unsigned Size = MVT::getSizeInBits(RVLocs[0].getValVT())/8;
489 MachineFunction &MF = DAG.getMachineFunction();
490 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
491 MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
492 Chain = DAG.getStore(Op.getOperand(0), Value, MemLoc, NULL, 0);
494 SDVTList Tys = DAG.getVTList(MVT::f64, MVT::Other);
495 SDOperand Ops[] = {Chain, MemLoc, DAG.getValueType(RVLocs[0].getValVT())};
496 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
497 Chain = Value.getValue(1);
500 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
501 SDOperand Ops[] = { Chain, Value };
502 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
503 Flag = Chain.getValue(1);
506 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
508 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
510 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
514 /// LowerCallResult - Lower the result values of an ISD::CALL into the
515 /// appropriate copies out of appropriate physical registers. This assumes that
516 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
517 /// being lowered. The returns a SDNode with the same number of values as the
519 SDNode *X86TargetLowering::
520 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
521 unsigned CallingConv, SelectionDAG &DAG) {
523 // Assign locations to each value returned by this call.
524 SmallVector<CCValAssign, 16> RVLocs;
525 CCState CCInfo(CallingConv, getTargetMachine(), RVLocs);
526 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
529 SmallVector<SDOperand, 8> ResultVals;
531 // Copy all of the result registers out of their specified physreg.
532 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
533 for (unsigned i = 0; i != RVLocs.size(); ++i) {
534 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
535 RVLocs[i].getValVT(), InFlag).getValue(1);
536 InFlag = Chain.getValue(2);
537 ResultVals.push_back(Chain.getValue(0));
540 // Copies from the FP stack are special, as ST0 isn't a valid register
541 // before the fp stackifier runs.
543 // Copy ST0 into an RFP register with FP_GET_RESULT.
544 SDVTList Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
545 SDOperand GROps[] = { Chain, InFlag };
546 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
547 Chain = RetVal.getValue(1);
548 InFlag = RetVal.getValue(2);
550 // If we are using ScalarSSE, store ST(0) to the stack and reload it into
553 // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
554 // shouldn't be necessary except that RFP cannot be live across
555 // multiple blocks. When stackifier is fixed, they can be uncoupled.
556 MachineFunction &MF = DAG.getMachineFunction();
557 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
558 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
560 Chain, RetVal, StackSlot, DAG.getValueType(RVLocs[0].getValVT()), InFlag
562 Chain = DAG.getNode(X86ISD::FST, MVT::Other, Ops, 5);
563 RetVal = DAG.getLoad(RVLocs[0].getValVT(), Chain, StackSlot, NULL, 0);
564 Chain = RetVal.getValue(1);
567 if (RVLocs[0].getValVT() == MVT::f32 && !X86ScalarSSE)
568 // FIXME: we would really like to remember that this FP_ROUND
569 // operation is okay to eliminate if we allow excess FP precision.
570 RetVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, RetVal);
571 ResultVals.push_back(RetVal);
574 // Merge everything together with a MERGE_VALUES node.
575 ResultVals.push_back(Chain);
576 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
577 &ResultVals[0], ResultVals.size()).Val;
581 //===----------------------------------------------------------------------===//
582 // C & StdCall Calling Convention implementation
583 //===----------------------------------------------------------------------===//
584 // StdCall calling convention seems to be standard for many Windows' API
585 // routines and around. It differs from C calling convention just a little:
586 // callee should clean up the stack, not caller. Symbols should be also
587 // decorated in some fancy way :) It doesn't support any vector arguments.
589 /// AddLiveIn - This helper function adds the specified physical register to the
590 /// MachineFunction as a live in value. It also creates a corresponding virtual
592 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
593 const TargetRegisterClass *RC) {
594 assert(RC->contains(PReg) && "Not the correct regclass!");
595 unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
596 MF.addLiveIn(PReg, VReg);
600 SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG,
602 unsigned NumArgs = Op.Val->getNumValues() - 1;
603 MachineFunction &MF = DAG.getMachineFunction();
604 MachineFrameInfo *MFI = MF.getFrameInfo();
605 SDOperand Root = Op.getOperand(0);
606 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
608 // Assign locations to all of the incoming arguments.
609 SmallVector<CCValAssign, 16> ArgLocs;
610 CCState CCInfo(MF.getFunction()->getCallingConv(), getTargetMachine(),
612 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_C);
614 SmallVector<SDOperand, 8> ArgValues;
615 unsigned LastVal = ~0U;
616 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
617 CCValAssign &VA = ArgLocs[i];
618 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
620 assert(VA.getValNo() != LastVal &&
621 "Don't support value assigned to multiple locs yet");
622 LastVal = VA.getValNo();
625 MVT::ValueType RegVT = VA.getLocVT();
626 TargetRegisterClass *RC;
627 if (RegVT == MVT::i32)
628 RC = X86::GR32RegisterClass;
630 assert(MVT::isVector(RegVT));
631 RC = X86::VR128RegisterClass;
634 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
635 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
637 // If this is an 8 or 16-bit value, it is really passed promoted to 32
638 // bits. Insert an assert[sz]ext to capture this, then truncate to the
640 if (VA.getLocInfo() == CCValAssign::SExt)
641 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
642 DAG.getValueType(VA.getValVT()));
643 else if (VA.getLocInfo() == CCValAssign::ZExt)
644 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
645 DAG.getValueType(VA.getValVT()));
647 if (VA.getLocInfo() != CCValAssign::Full)
648 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
650 ArgValues.push_back(ArgValue);
652 assert(VA.isMemLoc());
654 // Create the nodes corresponding to a load from this parameter slot.
655 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
656 VA.getLocMemOffset());
657 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
658 ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
662 unsigned StackSize = CCInfo.getNextStackOffset();
664 ArgValues.push_back(Root);
666 // If the function takes variable number of arguments, make a frame index for
667 // the start of the first vararg value... for expansion of llvm.va_start.
669 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
671 if (isStdCall && !isVarArg) {
672 BytesToPopOnReturn = StackSize; // Callee pops everything..
673 BytesCallerReserves = 0;
675 BytesToPopOnReturn = 0; // Callee pops nothing.
677 // If this is an sret function, the return should pop the hidden pointer.
679 (cast<ConstantSDNode>(Op.getOperand(3))->getValue() &
680 ISD::ParamFlags::StructReturn))
681 BytesToPopOnReturn = 4;
683 BytesCallerReserves = StackSize;
686 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
687 ReturnAddrIndex = 0; // No return address slot generated yet.
689 MF.getInfo<X86FunctionInfo>()->setBytesToPopOnReturn(BytesToPopOnReturn);
691 // Return the new list of results.
692 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
693 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
696 SDOperand X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG,
698 SDOperand Chain = Op.getOperand(0);
699 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
700 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
701 SDOperand Callee = Op.getOperand(4);
702 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
704 // Analyze operands of the call, assigning locations to each operand.
705 SmallVector<CCValAssign, 16> ArgLocs;
706 CCState CCInfo(CC, getTargetMachine(), ArgLocs);
707 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_C);
709 // Get a count of how many bytes are to be pushed on the stack.
710 unsigned NumBytes = CCInfo.getNextStackOffset();
712 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
714 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
715 SmallVector<SDOperand, 8> MemOpChains;
719 // Walk the register/memloc assignments, inserting copies/loads.
720 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
721 CCValAssign &VA = ArgLocs[i];
722 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
724 // Promote the value if needed.
725 switch (VA.getLocInfo()) {
726 default: assert(0 && "Unknown loc info!");
727 case CCValAssign::Full: break;
728 case CCValAssign::SExt:
729 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
731 case CCValAssign::ZExt:
732 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
734 case CCValAssign::AExt:
735 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
740 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
742 assert(VA.isMemLoc());
743 if (StackPtr.Val == 0)
744 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
745 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
746 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
747 MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
751 // If the first argument is an sret pointer, remember it.
752 bool isSRet = NumOps &&
753 (cast<ConstantSDNode>(Op.getOperand(6))->getValue() &
754 ISD::ParamFlags::StructReturn);
756 if (!MemOpChains.empty())
757 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
758 &MemOpChains[0], MemOpChains.size());
760 // Build a sequence of copy-to-reg nodes chained together with token chain
761 // and flag operands which copy the outgoing args into registers.
763 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
764 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
766 InFlag = Chain.getValue(1);
769 // ELF / PIC requires GOT in the EBX register before function calls via PLT
771 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
772 Subtarget->isPICStyleGOT()) {
773 Chain = DAG.getCopyToReg(Chain, X86::EBX,
774 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
776 InFlag = Chain.getValue(1);
779 // If the callee is a GlobalAddress node (quite common, every direct call is)
780 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
781 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
782 // We should use extra load for direct calls to dllimported functions in
784 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
785 getTargetMachine(), true))
786 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
787 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
788 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
790 // Returns a chain & a flag for retval copy to use.
791 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
792 SmallVector<SDOperand, 8> Ops;
793 Ops.push_back(Chain);
794 Ops.push_back(Callee);
796 // Add argument registers to the end of the list so that they are known live
798 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
799 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
800 RegsToPass[i].second.getValueType()));
802 // Add an implicit use GOT pointer in EBX.
803 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
804 Subtarget->isPICStyleGOT())
805 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
808 Ops.push_back(InFlag);
810 Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
811 NodeTys, &Ops[0], Ops.size());
812 InFlag = Chain.getValue(1);
814 // Create the CALLSEQ_END node.
815 unsigned NumBytesForCalleeToPush = 0;
817 if (CC == CallingConv::X86_StdCall) {
819 NumBytesForCalleeToPush = isSRet ? 4 : 0;
821 NumBytesForCalleeToPush = NumBytes;
823 // If this is is a call to a struct-return function, the callee
824 // pops the hidden struct pointer, so we have to push it back.
825 // This is common for Darwin/X86, Linux & Mingw32 targets.
826 NumBytesForCalleeToPush = isSRet ? 4 : 0;
829 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
831 Ops.push_back(Chain);
832 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
833 Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
834 Ops.push_back(InFlag);
835 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
836 InFlag = Chain.getValue(1);
838 // Handle result values, copying them out of physregs into vregs that we
840 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
844 //===----------------------------------------------------------------------===//
845 // FastCall Calling Convention implementation
846 //===----------------------------------------------------------------------===//
848 // The X86 'fastcall' calling convention passes up to two integer arguments in
849 // registers (an appropriate portion of ECX/EDX), passes arguments in C order,
850 // and requires that the callee pop its arguments off the stack (allowing proper
851 // tail calls), and has the same return value conventions as C calling convs.
853 // This calling convention always arranges for the callee pop value to be 8n+4
854 // bytes, which is needed for tail recursion elimination and stack alignment
857 X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
858 MachineFunction &MF = DAG.getMachineFunction();
859 MachineFrameInfo *MFI = MF.getFrameInfo();
860 SDOperand Root = Op.getOperand(0);
862 // Assign locations to all of the incoming arguments.
863 SmallVector<CCValAssign, 16> ArgLocs;
864 CCState CCInfo(MF.getFunction()->getCallingConv(), getTargetMachine(),
866 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_FastCall);
868 SmallVector<SDOperand, 8> ArgValues;
869 unsigned LastVal = ~0U;
870 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
871 CCValAssign &VA = ArgLocs[i];
872 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
874 assert(VA.getValNo() != LastVal &&
875 "Don't support value assigned to multiple locs yet");
876 LastVal = VA.getValNo();
879 MVT::ValueType RegVT = VA.getLocVT();
880 TargetRegisterClass *RC;
881 if (RegVT == MVT::i32)
882 RC = X86::GR32RegisterClass;
884 assert(MVT::isVector(RegVT));
885 RC = X86::VR128RegisterClass;
888 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
889 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
891 // If this is an 8 or 16-bit value, it is really passed promoted to 32
892 // bits. Insert an assert[sz]ext to capture this, then truncate to the
894 if (VA.getLocInfo() == CCValAssign::SExt)
895 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
896 DAG.getValueType(VA.getValVT()));
897 else if (VA.getLocInfo() == CCValAssign::ZExt)
898 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
899 DAG.getValueType(VA.getValVT()));
901 if (VA.getLocInfo() != CCValAssign::Full)
902 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
904 ArgValues.push_back(ArgValue);
906 assert(VA.isMemLoc());
908 // Create the nodes corresponding to a load from this parameter slot.
909 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
910 VA.getLocMemOffset());
911 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
912 ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
916 ArgValues.push_back(Root);
918 unsigned StackSize = CCInfo.getNextStackOffset();
920 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
921 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
922 // arguments and the arguments after the retaddr has been pushed are aligned.
923 if ((StackSize & 7) == 0)
927 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
928 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
929 ReturnAddrIndex = 0; // No return address slot generated yet.
930 BytesToPopOnReturn = StackSize; // Callee pops all stack arguments.
931 BytesCallerReserves = 0;
933 MF.getInfo<X86FunctionInfo>()->setBytesToPopOnReturn(BytesToPopOnReturn);
935 // Return the new list of results.
936 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
937 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
940 SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG,
942 SDOperand Chain = Op.getOperand(0);
943 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
944 SDOperand Callee = Op.getOperand(4);
946 // Analyze operands of the call, assigning locations to each operand.
947 SmallVector<CCValAssign, 16> ArgLocs;
948 CCState CCInfo(CC, getTargetMachine(), ArgLocs);
949 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_FastCall);
951 // Get a count of how many bytes are to be pushed on the stack.
952 unsigned NumBytes = CCInfo.getNextStackOffset();
954 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
955 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
956 // arguments and the arguments after the retaddr has been pushed are aligned.
957 if ((NumBytes & 7) == 0)
961 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
963 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
964 SmallVector<SDOperand, 8> MemOpChains;
968 // Walk the register/memloc assignments, inserting copies/loads.
969 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
970 CCValAssign &VA = ArgLocs[i];
971 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
973 // Promote the value if needed.
974 switch (VA.getLocInfo()) {
975 default: assert(0 && "Unknown loc info!");
976 case CCValAssign::Full: break;
977 case CCValAssign::SExt:
978 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
980 case CCValAssign::ZExt:
981 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
983 case CCValAssign::AExt:
984 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
989 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
991 assert(VA.isMemLoc());
992 if (StackPtr.Val == 0)
993 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
994 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
995 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
996 MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
1000 if (!MemOpChains.empty())
1001 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1002 &MemOpChains[0], MemOpChains.size());
1004 // Build a sequence of copy-to-reg nodes chained together with token chain
1005 // and flag operands which copy the outgoing args into registers.
1007 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1008 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1010 InFlag = Chain.getValue(1);
1013 // If the callee is a GlobalAddress node (quite common, every direct call is)
1014 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1015 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1016 // We should use extra load for direct calls to dllimported functions in
1018 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1019 getTargetMachine(), true))
1020 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1021 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1022 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1024 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1026 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1027 Subtarget->isPICStyleGOT()) {
1028 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1029 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1031 InFlag = Chain.getValue(1);
1034 // Returns a chain & a flag for retval copy to use.
1035 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1036 SmallVector<SDOperand, 8> Ops;
1037 Ops.push_back(Chain);
1038 Ops.push_back(Callee);
1040 // Add argument registers to the end of the list so that they are known live
1042 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1043 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1044 RegsToPass[i].second.getValueType()));
1046 // Add an implicit use GOT pointer in EBX.
1047 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1048 Subtarget->isPICStyleGOT())
1049 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1052 Ops.push_back(InFlag);
1054 // FIXME: Do not generate X86ISD::TAILCALL for now.
1055 Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
1056 NodeTys, &Ops[0], Ops.size());
1057 InFlag = Chain.getValue(1);
1059 // Returns a flag for retval copy to use.
1060 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1062 Ops.push_back(Chain);
1063 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1064 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1065 Ops.push_back(InFlag);
1066 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1067 InFlag = Chain.getValue(1);
1069 // Handle result values, copying them out of physregs into vregs that we
1071 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1075 //===----------------------------------------------------------------------===//
1076 // X86-64 C Calling Convention implementation
1077 //===----------------------------------------------------------------------===//
1080 X86TargetLowering::LowerX86_64CCCArguments(SDOperand Op, SelectionDAG &DAG) {
1081 MachineFunction &MF = DAG.getMachineFunction();
1082 MachineFrameInfo *MFI = MF.getFrameInfo();
1083 SDOperand Root = Op.getOperand(0);
1084 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1086 static const unsigned GPR64ArgRegs[] = {
1087 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1089 static const unsigned XMMArgRegs[] = {
1090 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1091 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1095 // Assign locations to all of the incoming arguments.
1096 SmallVector<CCValAssign, 16> ArgLocs;
1097 CCState CCInfo(MF.getFunction()->getCallingConv(), getTargetMachine(),
1099 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_C);
1101 SmallVector<SDOperand, 8> ArgValues;
1102 unsigned LastVal = ~0U;
1103 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1104 CCValAssign &VA = ArgLocs[i];
1105 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1107 assert(VA.getValNo() != LastVal &&
1108 "Don't support value assigned to multiple locs yet");
1109 LastVal = VA.getValNo();
1111 if (VA.isRegLoc()) {
1112 MVT::ValueType RegVT = VA.getLocVT();
1113 TargetRegisterClass *RC;
1114 if (RegVT == MVT::i32)
1115 RC = X86::GR32RegisterClass;
1116 else if (RegVT == MVT::i64)
1117 RC = X86::GR64RegisterClass;
1118 else if (RegVT == MVT::f32)
1119 RC = X86::FR32RegisterClass;
1120 else if (RegVT == MVT::f64)
1121 RC = X86::FR64RegisterClass;
1123 assert(MVT::isVector(RegVT));
1124 RC = X86::VR128RegisterClass;
1127 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1128 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1130 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1131 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1133 if (VA.getLocInfo() == CCValAssign::SExt)
1134 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1135 DAG.getValueType(VA.getValVT()));
1136 else if (VA.getLocInfo() == CCValAssign::ZExt)
1137 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1138 DAG.getValueType(VA.getValVT()));
1140 if (VA.getLocInfo() != CCValAssign::Full)
1141 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1143 ArgValues.push_back(ArgValue);
1145 assert(VA.isMemLoc());
1147 // Create the nodes corresponding to a load from this parameter slot.
1148 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1149 VA.getLocMemOffset());
1150 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1151 ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
1155 unsigned StackSize = CCInfo.getNextStackOffset();
1157 // If the function takes variable number of arguments, make a frame index for
1158 // the start of the first vararg value... for expansion of llvm.va_start.
1160 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1161 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1163 // For X86-64, if there are vararg parameters that are passed via
1164 // registers, then we must store them to their spots on the stack so they
1165 // may be loaded by deferencing the result of va_next.
1166 VarArgsGPOffset = NumIntRegs * 8;
1167 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1168 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1169 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1171 // Store the integer parameter registers.
1172 SmallVector<SDOperand, 8> MemOps;
1173 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1174 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1175 DAG.getConstant(VarArgsGPOffset, getPointerTy()));
1176 for (; NumIntRegs != 6; ++NumIntRegs) {
1177 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1178 X86::GR64RegisterClass);
1179 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1180 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1181 MemOps.push_back(Store);
1182 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1183 DAG.getConstant(8, getPointerTy()));
1186 // Now store the XMM (fp + vector) parameter registers.
1187 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1188 DAG.getConstant(VarArgsFPOffset, getPointerTy()));
1189 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1190 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1191 X86::VR128RegisterClass);
1192 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1193 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1194 MemOps.push_back(Store);
1195 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1196 DAG.getConstant(16, getPointerTy()));
1198 if (!MemOps.empty())
1199 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1200 &MemOps[0], MemOps.size());
1203 ArgValues.push_back(Root);
1205 ReturnAddrIndex = 0; // No return address slot generated yet.
1206 BytesToPopOnReturn = 0; // Callee pops nothing.
1207 BytesCallerReserves = StackSize;
1209 // Return the new list of results.
1210 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1211 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1215 X86TargetLowering::LowerX86_64CCCCallTo(SDOperand Op, SelectionDAG &DAG,
1217 SDOperand Chain = Op.getOperand(0);
1218 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1219 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1220 SDOperand Callee = Op.getOperand(4);
1222 // Analyze operands of the call, assigning locations to each operand.
1223 SmallVector<CCValAssign, 16> ArgLocs;
1224 CCState CCInfo(CC, getTargetMachine(), ArgLocs);
1225 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_C);
1227 // Get a count of how many bytes are to be pushed on the stack.
1228 unsigned NumBytes = CCInfo.getNextStackOffset();
1229 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1231 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1232 SmallVector<SDOperand, 8> MemOpChains;
1236 // Walk the register/memloc assignments, inserting copies/loads.
1237 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1238 CCValAssign &VA = ArgLocs[i];
1239 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1241 // Promote the value if needed.
1242 switch (VA.getLocInfo()) {
1243 default: assert(0 && "Unknown loc info!");
1244 case CCValAssign::Full: break;
1245 case CCValAssign::SExt:
1246 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1248 case CCValAssign::ZExt:
1249 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1251 case CCValAssign::AExt:
1252 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1256 if (VA.isRegLoc()) {
1257 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1259 assert(VA.isMemLoc());
1260 if (StackPtr.Val == 0)
1261 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1262 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1263 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1264 MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
1268 if (!MemOpChains.empty())
1269 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1270 &MemOpChains[0], MemOpChains.size());
1272 // Build a sequence of copy-to-reg nodes chained together with token chain
1273 // and flag operands which copy the outgoing args into registers.
1275 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1276 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1278 InFlag = Chain.getValue(1);
1282 // From AMD64 ABI document:
1283 // For calls that may call functions that use varargs or stdargs
1284 // (prototype-less calls or calls to functions containing ellipsis (...) in
1285 // the declaration) %al is used as hidden argument to specify the number
1286 // of SSE registers used. The contents of %al do not need to match exactly
1287 // the number of registers, but must be an ubound on the number of SSE
1288 // registers used and is in the range 0 - 8 inclusive.
1290 // Count the number of XMM registers allocated.
1291 static const unsigned XMMArgRegs[] = {
1292 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1293 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1295 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1297 Chain = DAG.getCopyToReg(Chain, X86::AL,
1298 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1299 InFlag = Chain.getValue(1);
1302 // If the callee is a GlobalAddress node (quite common, every direct call is)
1303 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1304 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1305 // We should use extra load for direct calls to dllimported functions in
1307 if (getTargetMachine().getCodeModel() != CodeModel::Large
1308 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1309 getTargetMachine(), true))
1310 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1311 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1312 if (getTargetMachine().getCodeModel() != CodeModel::Large)
1313 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1315 // Returns a chain & a flag for retval copy to use.
1316 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1317 SmallVector<SDOperand, 8> Ops;
1318 Ops.push_back(Chain);
1319 Ops.push_back(Callee);
1321 // Add argument registers to the end of the list so that they are known live
1323 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1324 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1325 RegsToPass[i].second.getValueType()));
1328 Ops.push_back(InFlag);
1330 // FIXME: Do not generate X86ISD::TAILCALL for now.
1331 Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
1332 NodeTys, &Ops[0], Ops.size());
1333 InFlag = Chain.getValue(1);
1335 // Returns a flag for retval copy to use.
1336 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1338 Ops.push_back(Chain);
1339 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1340 Ops.push_back(DAG.getConstant(0, getPointerTy()));
1341 Ops.push_back(InFlag);
1342 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1343 InFlag = Chain.getValue(1);
1345 // Handle result values, copying them out of physregs into vregs that we
1347 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1351 //===----------------------------------------------------------------------===//
1352 // Other Lowering Hooks
1353 //===----------------------------------------------------------------------===//
1356 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1357 if (ReturnAddrIndex == 0) {
1358 // Set up a frame object for the return address.
1359 MachineFunction &MF = DAG.getMachineFunction();
1360 if (Subtarget->is64Bit())
1361 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1363 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1366 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1371 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1372 /// specific condition code. It returns a false if it cannot do a direct
1373 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1375 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1376 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1377 SelectionDAG &DAG) {
1378 X86CC = X86::COND_INVALID;
1380 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1381 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1382 // X > -1 -> X == 0, jump !sign.
1383 RHS = DAG.getConstant(0, RHS.getValueType());
1384 X86CC = X86::COND_NS;
1386 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1387 // X < 0 -> X == 0, jump on sign.
1388 X86CC = X86::COND_S;
1393 switch (SetCCOpcode) {
1395 case ISD::SETEQ: X86CC = X86::COND_E; break;
1396 case ISD::SETGT: X86CC = X86::COND_G; break;
1397 case ISD::SETGE: X86CC = X86::COND_GE; break;
1398 case ISD::SETLT: X86CC = X86::COND_L; break;
1399 case ISD::SETLE: X86CC = X86::COND_LE; break;
1400 case ISD::SETNE: X86CC = X86::COND_NE; break;
1401 case ISD::SETULT: X86CC = X86::COND_B; break;
1402 case ISD::SETUGT: X86CC = X86::COND_A; break;
1403 case ISD::SETULE: X86CC = X86::COND_BE; break;
1404 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1407 // On a floating point condition, the flags are set as follows:
1409 // 0 | 0 | 0 | X > Y
1410 // 0 | 0 | 1 | X < Y
1411 // 1 | 0 | 0 | X == Y
1412 // 1 | 1 | 1 | unordered
1414 switch (SetCCOpcode) {
1417 case ISD::SETEQ: X86CC = X86::COND_E; break;
1418 case ISD::SETOLT: Flip = true; // Fallthrough
1420 case ISD::SETGT: X86CC = X86::COND_A; break;
1421 case ISD::SETOLE: Flip = true; // Fallthrough
1423 case ISD::SETGE: X86CC = X86::COND_AE; break;
1424 case ISD::SETUGT: Flip = true; // Fallthrough
1426 case ISD::SETLT: X86CC = X86::COND_B; break;
1427 case ISD::SETUGE: Flip = true; // Fallthrough
1429 case ISD::SETLE: X86CC = X86::COND_BE; break;
1431 case ISD::SETNE: X86CC = X86::COND_NE; break;
1432 case ISD::SETUO: X86CC = X86::COND_P; break;
1433 case ISD::SETO: X86CC = X86::COND_NP; break;
1436 std::swap(LHS, RHS);
1439 return X86CC != X86::COND_INVALID;
1442 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1443 /// code. Current x86 isa includes the following FP cmov instructions:
1444 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1445 static bool hasFPCMov(unsigned X86CC) {
1461 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
1462 /// true if Op is undef or if its value falls within the specified range (L, H].
1463 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1464 if (Op.getOpcode() == ISD::UNDEF)
1467 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1468 return (Val >= Low && Val < Hi);
1471 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
1472 /// true if Op is undef or if its value equal to the specified value.
1473 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1474 if (Op.getOpcode() == ISD::UNDEF)
1476 return cast<ConstantSDNode>(Op)->getValue() == Val;
1479 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
1480 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
1481 bool X86::isPSHUFDMask(SDNode *N) {
1482 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1484 if (N->getNumOperands() != 4)
1487 // Check if the value doesn't reference the second vector.
1488 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1489 SDOperand Arg = N->getOperand(i);
1490 if (Arg.getOpcode() == ISD::UNDEF) continue;
1491 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1492 if (cast<ConstantSDNode>(Arg)->getValue() >= 4)
1499 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
1500 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
1501 bool X86::isPSHUFHWMask(SDNode *N) {
1502 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1504 if (N->getNumOperands() != 8)
1507 // Lower quadword copied in order.
1508 for (unsigned i = 0; i != 4; ++i) {
1509 SDOperand Arg = N->getOperand(i);
1510 if (Arg.getOpcode() == ISD::UNDEF) continue;
1511 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1512 if (cast<ConstantSDNode>(Arg)->getValue() != i)
1516 // Upper quadword shuffled.
1517 for (unsigned i = 4; i != 8; ++i) {
1518 SDOperand Arg = N->getOperand(i);
1519 if (Arg.getOpcode() == ISD::UNDEF) continue;
1520 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1521 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1522 if (Val < 4 || Val > 7)
1529 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
1530 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
1531 bool X86::isPSHUFLWMask(SDNode *N) {
1532 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1534 if (N->getNumOperands() != 8)
1537 // Upper quadword copied in order.
1538 for (unsigned i = 4; i != 8; ++i)
1539 if (!isUndefOrEqual(N->getOperand(i), i))
1542 // Lower quadword shuffled.
1543 for (unsigned i = 0; i != 4; ++i)
1544 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
1550 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
1551 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
1552 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
1553 if (NumElems != 2 && NumElems != 4) return false;
1555 unsigned Half = NumElems / 2;
1556 for (unsigned i = 0; i < Half; ++i)
1557 if (!isUndefOrInRange(Elems[i], 0, NumElems))
1559 for (unsigned i = Half; i < NumElems; ++i)
1560 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
1566 bool X86::isSHUFPMask(SDNode *N) {
1567 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1568 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
1571 /// isCommutedSHUFP - Returns true if the shuffle mask is except
1572 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
1573 /// half elements to come from vector 1 (which would equal the dest.) and
1574 /// the upper half to come from vector 2.
1575 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
1576 if (NumOps != 2 && NumOps != 4) return false;
1578 unsigned Half = NumOps / 2;
1579 for (unsigned i = 0; i < Half; ++i)
1580 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
1582 for (unsigned i = Half; i < NumOps; ++i)
1583 if (!isUndefOrInRange(Ops[i], 0, NumOps))
1588 static bool isCommutedSHUFP(SDNode *N) {
1589 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1590 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
1593 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
1594 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
1595 bool X86::isMOVHLPSMask(SDNode *N) {
1596 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1598 if (N->getNumOperands() != 4)
1601 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
1602 return isUndefOrEqual(N->getOperand(0), 6) &&
1603 isUndefOrEqual(N->getOperand(1), 7) &&
1604 isUndefOrEqual(N->getOperand(2), 2) &&
1605 isUndefOrEqual(N->getOperand(3), 3);
1608 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
1609 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
1611 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
1612 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1614 if (N->getNumOperands() != 4)
1617 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
1618 return isUndefOrEqual(N->getOperand(0), 2) &&
1619 isUndefOrEqual(N->getOperand(1), 3) &&
1620 isUndefOrEqual(N->getOperand(2), 2) &&
1621 isUndefOrEqual(N->getOperand(3), 3);
1624 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
1625 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
1626 bool X86::isMOVLPMask(SDNode *N) {
1627 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1629 unsigned NumElems = N->getNumOperands();
1630 if (NumElems != 2 && NumElems != 4)
1633 for (unsigned i = 0; i < NumElems/2; ++i)
1634 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
1637 for (unsigned i = NumElems/2; i < NumElems; ++i)
1638 if (!isUndefOrEqual(N->getOperand(i), i))
1644 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
1645 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
1647 bool X86::isMOVHPMask(SDNode *N) {
1648 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1650 unsigned NumElems = N->getNumOperands();
1651 if (NumElems != 2 && NumElems != 4)
1654 for (unsigned i = 0; i < NumElems/2; ++i)
1655 if (!isUndefOrEqual(N->getOperand(i), i))
1658 for (unsigned i = 0; i < NumElems/2; ++i) {
1659 SDOperand Arg = N->getOperand(i + NumElems/2);
1660 if (!isUndefOrEqual(Arg, i + NumElems))
1667 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
1668 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
1669 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
1670 bool V2IsSplat = false) {
1671 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
1674 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
1675 SDOperand BitI = Elts[i];
1676 SDOperand BitI1 = Elts[i+1];
1677 if (!isUndefOrEqual(BitI, j))
1680 if (isUndefOrEqual(BitI1, NumElts))
1683 if (!isUndefOrEqual(BitI1, j + NumElts))
1691 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
1692 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1693 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
1696 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
1697 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
1698 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
1699 bool V2IsSplat = false) {
1700 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
1703 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
1704 SDOperand BitI = Elts[i];
1705 SDOperand BitI1 = Elts[i+1];
1706 if (!isUndefOrEqual(BitI, j + NumElts/2))
1709 if (isUndefOrEqual(BitI1, NumElts))
1712 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
1720 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
1721 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1722 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
1725 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
1726 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
1728 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
1729 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1731 unsigned NumElems = N->getNumOperands();
1732 if (NumElems != 4 && NumElems != 8 && NumElems != 16)
1735 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
1736 SDOperand BitI = N->getOperand(i);
1737 SDOperand BitI1 = N->getOperand(i+1);
1739 if (!isUndefOrEqual(BitI, j))
1741 if (!isUndefOrEqual(BitI1, j))
1748 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
1749 /// specifies a shuffle of elements that is suitable for input to MOVSS,
1750 /// MOVSD, and MOVD, i.e. setting the lowest element.
1751 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
1752 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
1755 if (!isUndefOrEqual(Elts[0], NumElts))
1758 for (unsigned i = 1; i < NumElts; ++i) {
1759 if (!isUndefOrEqual(Elts[i], i))
1766 bool X86::isMOVLMask(SDNode *N) {
1767 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1768 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
1771 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
1772 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
1773 /// element of vector 2 and the other elements to come from vector 1 in order.
1774 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
1775 bool V2IsSplat = false,
1776 bool V2IsUndef = false) {
1777 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
1780 if (!isUndefOrEqual(Ops[0], 0))
1783 for (unsigned i = 1; i < NumOps; ++i) {
1784 SDOperand Arg = Ops[i];
1785 if (!(isUndefOrEqual(Arg, i+NumOps) ||
1786 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
1787 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
1794 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
1795 bool V2IsUndef = false) {
1796 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1797 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
1798 V2IsSplat, V2IsUndef);
1801 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
1802 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
1803 bool X86::isMOVSHDUPMask(SDNode *N) {
1804 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1806 if (N->getNumOperands() != 4)
1809 // Expect 1, 1, 3, 3
1810 for (unsigned i = 0; i < 2; ++i) {
1811 SDOperand Arg = N->getOperand(i);
1812 if (Arg.getOpcode() == ISD::UNDEF) continue;
1813 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1814 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1815 if (Val != 1) return false;
1819 for (unsigned i = 2; i < 4; ++i) {
1820 SDOperand Arg = N->getOperand(i);
1821 if (Arg.getOpcode() == ISD::UNDEF) continue;
1822 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1823 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1824 if (Val != 3) return false;
1828 // Don't use movshdup if it can be done with a shufps.
1832 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
1833 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
1834 bool X86::isMOVSLDUPMask(SDNode *N) {
1835 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1837 if (N->getNumOperands() != 4)
1840 // Expect 0, 0, 2, 2
1841 for (unsigned i = 0; i < 2; ++i) {
1842 SDOperand Arg = N->getOperand(i);
1843 if (Arg.getOpcode() == ISD::UNDEF) continue;
1844 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1845 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1846 if (Val != 0) return false;
1850 for (unsigned i = 2; i < 4; ++i) {
1851 SDOperand Arg = N->getOperand(i);
1852 if (Arg.getOpcode() == ISD::UNDEF) continue;
1853 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1854 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1855 if (Val != 2) return false;
1859 // Don't use movshdup if it can be done with a shufps.
1863 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
1864 /// a splat of a single element.
1865 static bool isSplatMask(SDNode *N) {
1866 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1868 // This is a splat operation if each element of the permute is the same, and
1869 // if the value doesn't reference the second vector.
1870 unsigned NumElems = N->getNumOperands();
1871 SDOperand ElementBase;
1873 for (; i != NumElems; ++i) {
1874 SDOperand Elt = N->getOperand(i);
1875 if (isa<ConstantSDNode>(Elt)) {
1881 if (!ElementBase.Val)
1884 for (; i != NumElems; ++i) {
1885 SDOperand Arg = N->getOperand(i);
1886 if (Arg.getOpcode() == ISD::UNDEF) continue;
1887 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1888 if (Arg != ElementBase) return false;
1891 // Make sure it is a splat of the first vector operand.
1892 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
1895 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
1896 /// a splat of a single element and it's a 2 or 4 element mask.
1897 bool X86::isSplatMask(SDNode *N) {
1898 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1900 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
1901 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
1903 return ::isSplatMask(N);
1906 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
1907 /// specifies a splat of zero element.
1908 bool X86::isSplatLoMask(SDNode *N) {
1909 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1911 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
1912 if (!isUndefOrEqual(N->getOperand(i), 0))
1917 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
1918 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
1920 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
1921 unsigned NumOperands = N->getNumOperands();
1922 unsigned Shift = (NumOperands == 4) ? 2 : 1;
1924 for (unsigned i = 0; i < NumOperands; ++i) {
1926 SDOperand Arg = N->getOperand(NumOperands-i-1);
1927 if (Arg.getOpcode() != ISD::UNDEF)
1928 Val = cast<ConstantSDNode>(Arg)->getValue();
1929 if (Val >= NumOperands) Val -= NumOperands;
1931 if (i != NumOperands - 1)
1938 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
1939 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
1941 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
1943 // 8 nodes, but we only care about the last 4.
1944 for (unsigned i = 7; i >= 4; --i) {
1946 SDOperand Arg = N->getOperand(i);
1947 if (Arg.getOpcode() != ISD::UNDEF)
1948 Val = cast<ConstantSDNode>(Arg)->getValue();
1957 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
1958 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
1960 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
1962 // 8 nodes, but we only care about the first 4.
1963 for (int i = 3; i >= 0; --i) {
1965 SDOperand Arg = N->getOperand(i);
1966 if (Arg.getOpcode() != ISD::UNDEF)
1967 Val = cast<ConstantSDNode>(Arg)->getValue();
1976 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
1977 /// specifies a 8 element shuffle that can be broken into a pair of
1978 /// PSHUFHW and PSHUFLW.
1979 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
1980 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1982 if (N->getNumOperands() != 8)
1985 // Lower quadword shuffled.
1986 for (unsigned i = 0; i != 4; ++i) {
1987 SDOperand Arg = N->getOperand(i);
1988 if (Arg.getOpcode() == ISD::UNDEF) continue;
1989 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1990 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1995 // Upper quadword shuffled.
1996 for (unsigned i = 4; i != 8; ++i) {
1997 SDOperand Arg = N->getOperand(i);
1998 if (Arg.getOpcode() == ISD::UNDEF) continue;
1999 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2000 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2001 if (Val < 4 || Val > 7)
2008 /// CommuteVectorShuffle - Swap vector_shuffle operandsas well as
2009 /// values in ther permute mask.
2010 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2011 SDOperand &V2, SDOperand &Mask,
2012 SelectionDAG &DAG) {
2013 MVT::ValueType VT = Op.getValueType();
2014 MVT::ValueType MaskVT = Mask.getValueType();
2015 MVT::ValueType EltVT = MVT::getVectorBaseType(MaskVT);
2016 unsigned NumElems = Mask.getNumOperands();
2017 SmallVector<SDOperand, 8> MaskVec;
2019 for (unsigned i = 0; i != NumElems; ++i) {
2020 SDOperand Arg = Mask.getOperand(i);
2021 if (Arg.getOpcode() == ISD::UNDEF) {
2022 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2025 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2026 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2028 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2030 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2034 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2035 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2038 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2039 /// match movhlps. The lower half elements should come from upper half of
2040 /// V1 (and in order), and the upper half elements should come from the upper
2041 /// half of V2 (and in order).
2042 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2043 unsigned NumElems = Mask->getNumOperands();
2046 for (unsigned i = 0, e = 2; i != e; ++i)
2047 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2049 for (unsigned i = 2; i != 4; ++i)
2050 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2055 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2056 /// is promoted to a vector.
2057 static inline bool isScalarLoadToVector(SDNode *N) {
2058 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2059 N = N->getOperand(0).Val;
2060 return ISD::isNON_EXTLoad(N);
2065 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2066 /// match movlp{s|d}. The lower half elements should come from lower half of
2067 /// V1 (and in order), and the upper half elements should come from the upper
2068 /// half of V2 (and in order). And since V1 will become the source of the
2069 /// MOVLP, it must be either a vector load or a scalar load to vector.
2070 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2071 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2073 // Is V2 is a vector load, don't do this transformation. We will try to use
2074 // load folding shufps op.
2075 if (ISD::isNON_EXTLoad(V2))
2078 unsigned NumElems = Mask->getNumOperands();
2079 if (NumElems != 2 && NumElems != 4)
2081 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2082 if (!isUndefOrEqual(Mask->getOperand(i), i))
2084 for (unsigned i = NumElems/2; i != NumElems; ++i)
2085 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2090 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2092 static bool isSplatVector(SDNode *N) {
2093 if (N->getOpcode() != ISD::BUILD_VECTOR)
2096 SDOperand SplatValue = N->getOperand(0);
2097 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2098 if (N->getOperand(i) != SplatValue)
2103 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2105 static bool isUndefShuffle(SDNode *N) {
2106 if (N->getOpcode() != ISD::BUILD_VECTOR)
2109 SDOperand V1 = N->getOperand(0);
2110 SDOperand V2 = N->getOperand(1);
2111 SDOperand Mask = N->getOperand(2);
2112 unsigned NumElems = Mask.getNumOperands();
2113 for (unsigned i = 0; i != NumElems; ++i) {
2114 SDOperand Arg = Mask.getOperand(i);
2115 if (Arg.getOpcode() != ISD::UNDEF) {
2116 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2117 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2119 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2126 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2127 /// that point to V2 points to its first element.
2128 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2129 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2131 bool Changed = false;
2132 SmallVector<SDOperand, 8> MaskVec;
2133 unsigned NumElems = Mask.getNumOperands();
2134 for (unsigned i = 0; i != NumElems; ++i) {
2135 SDOperand Arg = Mask.getOperand(i);
2136 if (Arg.getOpcode() != ISD::UNDEF) {
2137 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2138 if (Val > NumElems) {
2139 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2143 MaskVec.push_back(Arg);
2147 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2148 &MaskVec[0], MaskVec.size());
2152 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2153 /// operation of specified width.
2154 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2155 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2156 MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2158 SmallVector<SDOperand, 8> MaskVec;
2159 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2160 for (unsigned i = 1; i != NumElems; ++i)
2161 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2162 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2165 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2166 /// of specified width.
2167 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2168 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2169 MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2170 SmallVector<SDOperand, 8> MaskVec;
2171 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2172 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2173 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2175 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2178 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2179 /// of specified width.
2180 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2181 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2182 MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2183 unsigned Half = NumElems/2;
2184 SmallVector<SDOperand, 8> MaskVec;
2185 for (unsigned i = 0; i != Half; ++i) {
2186 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2187 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2189 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2192 /// getZeroVector - Returns a vector of specified type with all zero elements.
2194 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2195 assert(MVT::isVector(VT) && "Expected a vector type");
2196 unsigned NumElems = getVectorNumElements(VT);
2197 MVT::ValueType EVT = MVT::getVectorBaseType(VT);
2198 bool isFP = MVT::isFloatingPoint(EVT);
2199 SDOperand Zero = isFP ? DAG.getConstantFP(0.0, EVT) : DAG.getConstant(0, EVT);
2200 SmallVector<SDOperand, 8> ZeroVec(NumElems, Zero);
2201 return DAG.getNode(ISD::BUILD_VECTOR, VT, &ZeroVec[0], ZeroVec.size());
2204 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2206 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2207 SDOperand V1 = Op.getOperand(0);
2208 SDOperand Mask = Op.getOperand(2);
2209 MVT::ValueType VT = Op.getValueType();
2210 unsigned NumElems = Mask.getNumOperands();
2211 Mask = getUnpacklMask(NumElems, DAG);
2212 while (NumElems != 4) {
2213 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2216 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2218 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2219 Mask = getZeroVector(MaskVT, DAG);
2220 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2221 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2222 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2225 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2227 static inline bool isZeroNode(SDOperand Elt) {
2228 return ((isa<ConstantSDNode>(Elt) &&
2229 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2230 (isa<ConstantFPSDNode>(Elt) &&
2231 cast<ConstantFPSDNode>(Elt)->isExactlyValue(0.0)));
2234 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2235 /// vector and zero or undef vector.
2236 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
2237 unsigned NumElems, unsigned Idx,
2238 bool isZero, SelectionDAG &DAG) {
2239 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2240 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2241 MVT::ValueType EVT = MVT::getVectorBaseType(MaskVT);
2242 SDOperand Zero = DAG.getConstant(0, EVT);
2243 SmallVector<SDOperand, 8> MaskVec(NumElems, Zero);
2244 MaskVec[Idx] = DAG.getConstant(NumElems, EVT);
2245 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2246 &MaskVec[0], MaskVec.size());
2247 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2250 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2252 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2253 unsigned NumNonZero, unsigned NumZero,
2254 SelectionDAG &DAG, TargetLowering &TLI) {
2260 for (unsigned i = 0; i < 16; ++i) {
2261 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2262 if (ThisIsNonZero && First) {
2264 V = getZeroVector(MVT::v8i16, DAG);
2266 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2271 SDOperand ThisElt(0, 0), LastElt(0, 0);
2272 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2273 if (LastIsNonZero) {
2274 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2276 if (ThisIsNonZero) {
2277 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2278 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2279 ThisElt, DAG.getConstant(8, MVT::i8));
2281 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2286 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2287 DAG.getConstant(i/2, TLI.getPointerTy()));
2291 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2294 /// LowerBuildVectorv16i8 - Custom lower build_vector of v8i16.
2296 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2297 unsigned NumNonZero, unsigned NumZero,
2298 SelectionDAG &DAG, TargetLowering &TLI) {
2304 for (unsigned i = 0; i < 8; ++i) {
2305 bool isNonZero = (NonZeros & (1 << i)) != 0;
2309 V = getZeroVector(MVT::v8i16, DAG);
2311 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2314 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2315 DAG.getConstant(i, TLI.getPointerTy()));
2323 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2324 // All zero's are handled with pxor.
2325 if (ISD::isBuildVectorAllZeros(Op.Val))
2328 // All one's are handled with pcmpeqd.
2329 if (ISD::isBuildVectorAllOnes(Op.Val))
2332 MVT::ValueType VT = Op.getValueType();
2333 MVT::ValueType EVT = MVT::getVectorBaseType(VT);
2334 unsigned EVTBits = MVT::getSizeInBits(EVT);
2336 unsigned NumElems = Op.getNumOperands();
2337 unsigned NumZero = 0;
2338 unsigned NumNonZero = 0;
2339 unsigned NonZeros = 0;
2340 std::set<SDOperand> Values;
2341 for (unsigned i = 0; i < NumElems; ++i) {
2342 SDOperand Elt = Op.getOperand(i);
2343 if (Elt.getOpcode() != ISD::UNDEF) {
2345 if (isZeroNode(Elt))
2348 NonZeros |= (1 << i);
2354 if (NumNonZero == 0)
2355 // Must be a mix of zero and undef. Return a zero vector.
2356 return getZeroVector(VT, DAG);
2358 // Splat is obviously ok. Let legalizer expand it to a shuffle.
2359 if (Values.size() == 1)
2362 // Special case for single non-zero element.
2363 if (NumNonZero == 1) {
2364 unsigned Idx = CountTrailingZeros_32(NonZeros);
2365 SDOperand Item = Op.getOperand(Idx);
2366 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
2368 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
2369 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
2372 if (EVTBits == 32) {
2373 // Turn it into a shuffle of zero and zero-extended scalar to vector.
2374 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
2376 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2377 MVT::ValueType MaskEVT = MVT::getVectorBaseType(MaskVT);
2378 SmallVector<SDOperand, 8> MaskVec;
2379 for (unsigned i = 0; i < NumElems; i++)
2380 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
2381 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2382 &MaskVec[0], MaskVec.size());
2383 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
2384 DAG.getNode(ISD::UNDEF, VT), Mask);
2388 // Let legalizer expand 2-wide build_vector's.
2392 // If element VT is < 32 bits, convert it to inserts into a zero vector.
2394 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
2396 if (V.Val) return V;
2399 if (EVTBits == 16) {
2400 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
2402 if (V.Val) return V;
2405 // If element VT is == 32 bits, turn it into a number of shuffles.
2406 SmallVector<SDOperand, 8> V;
2408 if (NumElems == 4 && NumZero > 0) {
2409 for (unsigned i = 0; i < 4; ++i) {
2410 bool isZero = !(NonZeros & (1 << i));
2412 V[i] = getZeroVector(VT, DAG);
2414 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
2417 for (unsigned i = 0; i < 2; ++i) {
2418 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
2421 V[i] = V[i*2]; // Must be a zero vector.
2424 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
2425 getMOVLMask(NumElems, DAG));
2428 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
2429 getMOVLMask(NumElems, DAG));
2432 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
2433 getUnpacklMask(NumElems, DAG));
2438 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
2439 // clears the upper bits.
2440 // FIXME: we can do the same for v4f32 case when we know both parts of
2441 // the lower half come from scalar_to_vector (loadf32). We should do
2442 // that in post legalizer dag combiner with target specific hooks.
2443 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
2445 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2446 MVT::ValueType EVT = MVT::getVectorBaseType(MaskVT);
2447 SmallVector<SDOperand, 8> MaskVec;
2448 bool Reverse = (NonZeros & 0x3) == 2;
2449 for (unsigned i = 0; i < 2; ++i)
2451 MaskVec.push_back(DAG.getConstant(1-i, EVT));
2453 MaskVec.push_back(DAG.getConstant(i, EVT));
2454 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
2455 for (unsigned i = 0; i < 2; ++i)
2457 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
2459 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
2460 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2461 &MaskVec[0], MaskVec.size());
2462 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
2465 if (Values.size() > 2) {
2466 // Expand into a number of unpckl*.
2468 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
2469 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
2470 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
2471 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
2472 for (unsigned i = 0; i < NumElems; ++i)
2473 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
2475 while (NumElems != 0) {
2476 for (unsigned i = 0; i < NumElems; ++i)
2477 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
2488 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
2489 SDOperand V1 = Op.getOperand(0);
2490 SDOperand V2 = Op.getOperand(1);
2491 SDOperand PermMask = Op.getOperand(2);
2492 MVT::ValueType VT = Op.getValueType();
2493 unsigned NumElems = PermMask.getNumOperands();
2494 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
2495 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
2496 bool V1IsSplat = false;
2497 bool V2IsSplat = false;
2499 if (isUndefShuffle(Op.Val))
2500 return DAG.getNode(ISD::UNDEF, VT);
2502 if (isSplatMask(PermMask.Val)) {
2503 if (NumElems <= 4) return Op;
2504 // Promote it to a v4i32 splat.
2505 return PromoteSplat(Op, DAG);
2508 if (X86::isMOVLMask(PermMask.Val))
2509 return (V1IsUndef) ? V2 : Op;
2511 if (X86::isMOVSHDUPMask(PermMask.Val) ||
2512 X86::isMOVSLDUPMask(PermMask.Val) ||
2513 X86::isMOVHLPSMask(PermMask.Val) ||
2514 X86::isMOVHPMask(PermMask.Val) ||
2515 X86::isMOVLPMask(PermMask.Val))
2518 if (ShouldXformToMOVHLPS(PermMask.Val) ||
2519 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
2520 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2522 bool Commuted = false;
2523 V1IsSplat = isSplatVector(V1.Val);
2524 V2IsSplat = isSplatVector(V2.Val);
2525 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
2526 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2527 std::swap(V1IsSplat, V2IsSplat);
2528 std::swap(V1IsUndef, V2IsUndef);
2532 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
2533 if (V2IsUndef) return V1;
2534 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2536 // V2 is a splat, so the mask may be malformed. That is, it may point
2537 // to any V2 element. The instruction selectior won't like this. Get
2538 // a corrected mask and commute to form a proper MOVS{S|D}.
2539 SDOperand NewMask = getMOVLMask(NumElems, DAG);
2540 if (NewMask.Val != PermMask.Val)
2541 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2546 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
2547 X86::isUNPCKLMask(PermMask.Val) ||
2548 X86::isUNPCKHMask(PermMask.Val))
2552 // Normalize mask so all entries that point to V2 points to its first
2553 // element then try to match unpck{h|l} again. If match, return a
2554 // new vector_shuffle with the corrected mask.
2555 SDOperand NewMask = NormalizeMask(PermMask, DAG);
2556 if (NewMask.Val != PermMask.Val) {
2557 if (X86::isUNPCKLMask(PermMask.Val, true)) {
2558 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
2559 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2560 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
2561 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
2562 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2567 // Normalize the node to match x86 shuffle ops if needed
2568 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
2569 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2572 // Commute is back and try unpck* again.
2573 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
2574 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
2575 X86::isUNPCKLMask(PermMask.Val) ||
2576 X86::isUNPCKHMask(PermMask.Val))
2580 // If VT is integer, try PSHUF* first, then SHUFP*.
2581 if (MVT::isInteger(VT)) {
2582 if (X86::isPSHUFDMask(PermMask.Val) ||
2583 X86::isPSHUFHWMask(PermMask.Val) ||
2584 X86::isPSHUFLWMask(PermMask.Val)) {
2585 if (V2.getOpcode() != ISD::UNDEF)
2586 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
2587 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
2591 if (X86::isSHUFPMask(PermMask.Val))
2594 // Handle v8i16 shuffle high / low shuffle node pair.
2595 if (VT == MVT::v8i16 && isPSHUFHW_PSHUFLWMask(PermMask.Val)) {
2596 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2597 MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2598 SmallVector<SDOperand, 8> MaskVec;
2599 for (unsigned i = 0; i != 4; ++i)
2600 MaskVec.push_back(PermMask.getOperand(i));
2601 for (unsigned i = 4; i != 8; ++i)
2602 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2603 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2604 &MaskVec[0], MaskVec.size());
2605 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2607 for (unsigned i = 0; i != 4; ++i)
2608 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2609 for (unsigned i = 4; i != 8; ++i)
2610 MaskVec.push_back(PermMask.getOperand(i));
2611 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0],MaskVec.size());
2612 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2615 // Floating point cases in the other order.
2616 if (X86::isSHUFPMask(PermMask.Val))
2618 if (X86::isPSHUFDMask(PermMask.Val) ||
2619 X86::isPSHUFHWMask(PermMask.Val) ||
2620 X86::isPSHUFLWMask(PermMask.Val)) {
2621 if (V2.getOpcode() != ISD::UNDEF)
2622 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
2623 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
2628 if (NumElems == 4) {
2629 MVT::ValueType MaskVT = PermMask.getValueType();
2630 MVT::ValueType MaskEVT = MVT::getVectorBaseType(MaskVT);
2631 SmallVector<std::pair<int, int>, 8> Locs;
2632 Locs.reserve(NumElems);
2633 SmallVector<SDOperand, 8> Mask1(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2634 SmallVector<SDOperand, 8> Mask2(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2637 // If no more than two elements come from either vector. This can be
2638 // implemented with two shuffles. First shuffle gather the elements.
2639 // The second shuffle, which takes the first shuffle as both of its
2640 // vector operands, put the elements into the right order.
2641 for (unsigned i = 0; i != NumElems; ++i) {
2642 SDOperand Elt = PermMask.getOperand(i);
2643 if (Elt.getOpcode() == ISD::UNDEF) {
2644 Locs[i] = std::make_pair(-1, -1);
2646 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
2647 if (Val < NumElems) {
2648 Locs[i] = std::make_pair(0, NumLo);
2652 Locs[i] = std::make_pair(1, NumHi);
2653 if (2+NumHi < NumElems)
2654 Mask1[2+NumHi] = Elt;
2659 if (NumLo <= 2 && NumHi <= 2) {
2660 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2661 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2662 &Mask1[0], Mask1.size()));
2663 for (unsigned i = 0; i != NumElems; ++i) {
2664 if (Locs[i].first == -1)
2667 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
2668 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
2669 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
2673 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
2674 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2675 &Mask2[0], Mask2.size()));
2678 // Break it into (shuffle shuffle_hi, shuffle_lo).
2680 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2681 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2682 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
2683 unsigned MaskIdx = 0;
2685 unsigned HiIdx = NumElems/2;
2686 for (unsigned i = 0; i != NumElems; ++i) {
2687 if (i == NumElems/2) {
2693 SDOperand Elt = PermMask.getOperand(i);
2694 if (Elt.getOpcode() == ISD::UNDEF) {
2695 Locs[i] = std::make_pair(-1, -1);
2696 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
2697 Locs[i] = std::make_pair(MaskIdx, LoIdx);
2698 (*MaskPtr)[LoIdx] = Elt;
2701 Locs[i] = std::make_pair(MaskIdx, HiIdx);
2702 (*MaskPtr)[HiIdx] = Elt;
2707 SDOperand LoShuffle =
2708 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2709 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2710 &LoMask[0], LoMask.size()));
2711 SDOperand HiShuffle =
2712 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2713 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2714 &HiMask[0], HiMask.size()));
2715 SmallVector<SDOperand, 8> MaskOps;
2716 for (unsigned i = 0; i != NumElems; ++i) {
2717 if (Locs[i].first == -1) {
2718 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
2720 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
2721 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
2724 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
2725 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2726 &MaskOps[0], MaskOps.size()));
2733 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
2734 if (!isa<ConstantSDNode>(Op.getOperand(1)))
2737 MVT::ValueType VT = Op.getValueType();
2738 // TODO: handle v16i8.
2739 if (MVT::getSizeInBits(VT) == 16) {
2740 // Transform it so it match pextrw which produces a 32-bit result.
2741 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
2742 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
2743 Op.getOperand(0), Op.getOperand(1));
2744 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
2745 DAG.getValueType(VT));
2746 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
2747 } else if (MVT::getSizeInBits(VT) == 32) {
2748 SDOperand Vec = Op.getOperand(0);
2749 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
2752 // SHUFPS the element to the lowest double word, then movss.
2753 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2754 SmallVector<SDOperand, 8> IdxVec;
2755 IdxVec.push_back(DAG.getConstant(Idx, MVT::getVectorBaseType(MaskVT)));
2756 IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2757 IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2758 IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2759 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2760 &IdxVec[0], IdxVec.size());
2761 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
2762 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
2763 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
2764 DAG.getConstant(0, getPointerTy()));
2765 } else if (MVT::getSizeInBits(VT) == 64) {
2766 SDOperand Vec = Op.getOperand(0);
2767 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
2771 // UNPCKHPD the element to the lowest double word, then movsd.
2772 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
2773 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
2774 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2775 SmallVector<SDOperand, 8> IdxVec;
2776 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorBaseType(MaskVT)));
2777 IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2778 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2779 &IdxVec[0], IdxVec.size());
2780 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
2781 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
2782 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
2783 DAG.getConstant(0, getPointerTy()));
2790 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
2791 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
2792 // as its second argument.
2793 MVT::ValueType VT = Op.getValueType();
2794 MVT::ValueType BaseVT = MVT::getVectorBaseType(VT);
2795 SDOperand N0 = Op.getOperand(0);
2796 SDOperand N1 = Op.getOperand(1);
2797 SDOperand N2 = Op.getOperand(2);
2798 if (MVT::getSizeInBits(BaseVT) == 16) {
2799 if (N1.getValueType() != MVT::i32)
2800 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
2801 if (N2.getValueType() != MVT::i32)
2802 N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(), MVT::i32);
2803 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
2804 } else if (MVT::getSizeInBits(BaseVT) == 32) {
2805 unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
2808 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
2809 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2810 MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2811 SmallVector<SDOperand, 8> MaskVec;
2812 MaskVec.push_back(DAG.getConstant(4, BaseVT));
2813 for (unsigned i = 1; i <= 3; ++i)
2814 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2815 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
2816 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2817 &MaskVec[0], MaskVec.size()));
2819 // Use two pinsrw instructions to insert a 32 bit value.
2821 if (MVT::isFloatingPoint(N1.getValueType())) {
2822 if (ISD::isNON_EXTLoad(N1.Val)) {
2823 // Just load directly from f32mem to GR32.
2824 LoadSDNode *LD = cast<LoadSDNode>(N1);
2825 N1 = DAG.getLoad(MVT::i32, LD->getChain(), LD->getBasePtr(),
2826 LD->getSrcValue(), LD->getSrcValueOffset());
2828 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4f32, N1);
2829 N1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, N1);
2830 N1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32, N1,
2831 DAG.getConstant(0, getPointerTy()));
2834 N0 = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, N0);
2835 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
2836 DAG.getConstant(Idx, getPointerTy()));
2837 N1 = DAG.getNode(ISD::SRL, MVT::i32, N1, DAG.getConstant(16, MVT::i8));
2838 N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
2839 DAG.getConstant(Idx+1, getPointerTy()));
2840 return DAG.getNode(ISD::BIT_CONVERT, VT, N0);
2848 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2849 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
2850 return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
2853 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2854 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
2855 // one of the above mentioned nodes. It has to be wrapped because otherwise
2856 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2857 // be used to form addressing mode. These wrapped nodes will be selected
2860 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
2861 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2862 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
2864 CP->getAlignment());
2865 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
2866 // With PIC, the address is actually $g + Offset.
2867 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2868 !Subtarget->isPICStyleRIPRel()) {
2869 Result = DAG.getNode(ISD::ADD, getPointerTy(),
2870 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
2878 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
2879 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2880 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
2881 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
2882 // With PIC, the address is actually $g + Offset.
2883 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2884 !Subtarget->isPICStyleRIPRel()) {
2885 Result = DAG.getNode(ISD::ADD, getPointerTy(),
2886 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
2890 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
2891 // load the value at address GV, not the value of GV itself. This means that
2892 // the GlobalAddress must be in the base or index register of the address, not
2893 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
2894 // The same applies for external symbols during PIC codegen
2895 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
2896 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result, NULL, 0);
2902 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
2903 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
2904 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
2905 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
2906 // With PIC, the address is actually $g + Offset.
2907 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2908 !Subtarget->isPICStyleRIPRel()) {
2909 Result = DAG.getNode(ISD::ADD, getPointerTy(),
2910 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
2917 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
2918 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2919 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
2920 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
2921 // With PIC, the address is actually $g + Offset.
2922 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2923 !Subtarget->isPICStyleRIPRel()) {
2924 Result = DAG.getNode(ISD::ADD, getPointerTy(),
2925 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
2932 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
2933 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
2934 "Not an i64 shift!");
2935 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
2936 SDOperand ShOpLo = Op.getOperand(0);
2937 SDOperand ShOpHi = Op.getOperand(1);
2938 SDOperand ShAmt = Op.getOperand(2);
2939 SDOperand Tmp1 = isSRA ?
2940 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
2941 DAG.getConstant(0, MVT::i32);
2943 SDOperand Tmp2, Tmp3;
2944 if (Op.getOpcode() == ISD::SHL_PARTS) {
2945 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
2946 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
2948 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
2949 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
2952 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
2953 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
2954 DAG.getConstant(32, MVT::i8));
2955 SDOperand COps[]={DAG.getEntryNode(), AndNode, DAG.getConstant(0, MVT::i8)};
2956 SDOperand InFlag = DAG.getNode(X86ISD::CMP, VTs, 2, COps, 3).getValue(1);
2959 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
2961 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
2962 SmallVector<SDOperand, 4> Ops;
2963 if (Op.getOpcode() == ISD::SHL_PARTS) {
2964 Ops.push_back(Tmp2);
2965 Ops.push_back(Tmp3);
2967 Ops.push_back(InFlag);
2968 Hi = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
2969 InFlag = Hi.getValue(1);
2972 Ops.push_back(Tmp3);
2973 Ops.push_back(Tmp1);
2975 Ops.push_back(InFlag);
2976 Lo = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
2978 Ops.push_back(Tmp2);
2979 Ops.push_back(Tmp3);
2981 Ops.push_back(InFlag);
2982 Lo = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
2983 InFlag = Lo.getValue(1);
2986 Ops.push_back(Tmp3);
2987 Ops.push_back(Tmp1);
2989 Ops.push_back(InFlag);
2990 Hi = DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
2993 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
2997 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
3000 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
3001 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
3002 Op.getOperand(0).getValueType() >= MVT::i16 &&
3003 "Unknown SINT_TO_FP to lower!");
3006 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
3007 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
3008 MachineFunction &MF = DAG.getMachineFunction();
3009 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
3010 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3011 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
3012 StackSlot, NULL, 0);
3017 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
3019 Tys = DAG.getVTList(MVT::f64, MVT::Other);
3020 SmallVector<SDOperand, 8> Ops;
3021 Ops.push_back(Chain);
3022 Ops.push_back(StackSlot);
3023 Ops.push_back(DAG.getValueType(SrcVT));
3024 Result = DAG.getNode(X86ScalarSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
3025 Tys, &Ops[0], Ops.size());
3028 Chain = Result.getValue(1);
3029 SDOperand InFlag = Result.getValue(2);
3031 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
3032 // shouldn't be necessary except that RFP cannot be live across
3033 // multiple blocks. When stackifier is fixed, they can be uncoupled.
3034 MachineFunction &MF = DAG.getMachineFunction();
3035 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3036 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3037 Tys = DAG.getVTList(MVT::Other);
3038 SmallVector<SDOperand, 8> Ops;
3039 Ops.push_back(Chain);
3040 Ops.push_back(Result);
3041 Ops.push_back(StackSlot);
3042 Ops.push_back(DAG.getValueType(Op.getValueType()));
3043 Ops.push_back(InFlag);
3044 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
3045 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, NULL, 0);
3051 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
3052 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
3053 "Unknown FP_TO_SINT to lower!");
3054 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
3056 MachineFunction &MF = DAG.getMachineFunction();
3057 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
3058 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3059 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3062 switch (Op.getValueType()) {
3063 default: assert(0 && "Invalid FP_TO_SINT to lower!");
3064 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
3065 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
3066 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
3069 SDOperand Chain = DAG.getEntryNode();
3070 SDOperand Value = Op.getOperand(0);
3072 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
3073 Chain = DAG.getStore(Chain, Value, StackSlot, NULL, 0);
3074 SDVTList Tys = DAG.getVTList(MVT::f64, MVT::Other);
3076 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
3078 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
3079 Chain = Value.getValue(1);
3080 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
3081 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
3084 // Build the FP_TO_INT*_IN_MEM
3085 SDOperand Ops[] = { Chain, Value, StackSlot };
3086 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
3089 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
3092 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
3093 MVT::ValueType VT = Op.getValueType();
3094 const Type *OpNTy = MVT::getTypeForValueType(VT);
3095 std::vector<Constant*> CV;
3096 if (VT == MVT::f64) {
3097 CV.push_back(ConstantFP::get(OpNTy, BitsToDouble(~(1ULL << 63))));
3098 CV.push_back(ConstantFP::get(OpNTy, 0.0));
3100 CV.push_back(ConstantFP::get(OpNTy, BitsToFloat(~(1U << 31))));
3101 CV.push_back(ConstantFP::get(OpNTy, 0.0));
3102 CV.push_back(ConstantFP::get(OpNTy, 0.0));
3103 CV.push_back(ConstantFP::get(OpNTy, 0.0));
3105 Constant *CS = ConstantStruct::get(CV);
3106 SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3107 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
3108 SmallVector<SDOperand, 3> Ops;
3109 Ops.push_back(DAG.getEntryNode());
3110 Ops.push_back(CPIdx);
3111 Ops.push_back(DAG.getSrcValue(NULL));
3112 SDOperand Mask = DAG.getNode(X86ISD::LOAD_PACK, Tys, &Ops[0], Ops.size());
3113 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
3116 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
3117 MVT::ValueType VT = Op.getValueType();
3118 const Type *OpNTy = MVT::getTypeForValueType(VT);
3119 std::vector<Constant*> CV;
3120 if (VT == MVT::f64) {
3121 CV.push_back(ConstantFP::get(OpNTy, BitsToDouble(1ULL << 63)));
3122 CV.push_back(ConstantFP::get(OpNTy, 0.0));
3124 CV.push_back(ConstantFP::get(OpNTy, BitsToFloat(1U << 31)));
3125 CV.push_back(ConstantFP::get(OpNTy, 0.0));
3126 CV.push_back(ConstantFP::get(OpNTy, 0.0));
3127 CV.push_back(ConstantFP::get(OpNTy, 0.0));
3129 Constant *CS = ConstantStruct::get(CV);
3130 SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3131 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
3132 SmallVector<SDOperand, 3> Ops;
3133 Ops.push_back(DAG.getEntryNode());
3134 Ops.push_back(CPIdx);
3135 Ops.push_back(DAG.getSrcValue(NULL));
3136 SDOperand Mask = DAG.getNode(X86ISD::LOAD_PACK, Tys, &Ops[0], Ops.size());
3137 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
3140 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
3141 SDOperand Op0 = Op.getOperand(0);
3142 SDOperand Op1 = Op.getOperand(1);
3143 MVT::ValueType VT = Op.getValueType();
3144 MVT::ValueType SrcVT = Op1.getValueType();
3145 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
3147 // If second operand is smaller, extend it first.
3148 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
3149 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
3153 // First get the sign bit of second operand.
3154 std::vector<Constant*> CV;
3155 if (SrcVT == MVT::f64) {
3156 CV.push_back(ConstantFP::get(SrcTy, BitsToDouble(1ULL << 63)));
3157 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3159 CV.push_back(ConstantFP::get(SrcTy, BitsToFloat(1U << 31)));
3160 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3161 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3162 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3164 Constant *CS = ConstantStruct::get(CV);
3165 SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3166 SDVTList Tys = DAG.getVTList(SrcVT, MVT::Other);
3167 SmallVector<SDOperand, 3> Ops;
3168 Ops.push_back(DAG.getEntryNode());
3169 Ops.push_back(CPIdx);
3170 Ops.push_back(DAG.getSrcValue(NULL));
3171 SDOperand Mask1 = DAG.getNode(X86ISD::LOAD_PACK, Tys, &Ops[0], Ops.size());
3172 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
3174 // Shift sign bit right or left if the two operands have different types.
3175 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
3176 // Op0 is MVT::f32, Op1 is MVT::f64.
3177 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
3178 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
3179 DAG.getConstant(32, MVT::i32));
3180 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
3181 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
3182 DAG.getConstant(0, getPointerTy()));
3185 // Clear first operand sign bit.
3187 if (VT == MVT::f64) {
3188 CV.push_back(ConstantFP::get(SrcTy, BitsToDouble(~(1ULL << 63))));
3189 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3191 CV.push_back(ConstantFP::get(SrcTy, BitsToFloat(~(1U << 31))));
3192 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3193 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3194 CV.push_back(ConstantFP::get(SrcTy, 0.0));
3196 CS = ConstantStruct::get(CV);
3197 CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3198 Tys = DAG.getVTList(VT, MVT::Other);
3200 Ops.push_back(DAG.getEntryNode());
3201 Ops.push_back(CPIdx);
3202 Ops.push_back(DAG.getSrcValue(NULL));
3203 SDOperand Mask2 = DAG.getNode(X86ISD::LOAD_PACK, Tys, &Ops[0], Ops.size());
3204 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
3206 // Or the value with the sign bit.
3207 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
3210 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG,
3212 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
3214 SDOperand Op0 = Op.getOperand(0);
3215 SDOperand Op1 = Op.getOperand(1);
3216 SDOperand CC = Op.getOperand(2);
3217 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3218 const MVT::ValueType *VTs1 = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3219 const MVT::ValueType *VTs2 = DAG.getNodeValueTypes(MVT::i8, MVT::Flag);
3220 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
3223 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
3225 SDOperand Ops1[] = { Chain, Op0, Op1 };
3226 Cond = DAG.getNode(X86ISD::CMP, VTs1, 2, Ops1, 3).getValue(1);
3227 SDOperand Ops2[] = { DAG.getConstant(X86CC, MVT::i8), Cond };
3228 return DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops2, 2);
3231 assert(isFP && "Illegal integer SetCC!");
3233 SDOperand COps[] = { Chain, Op0, Op1 };
3234 Cond = DAG.getNode(X86ISD::CMP, VTs1, 2, COps, 3).getValue(1);
3236 switch (SetCCOpcode) {
3237 default: assert(false && "Illegal floating point SetCC!");
3238 case ISD::SETOEQ: { // !PF & ZF
3239 SDOperand Ops1[] = { DAG.getConstant(X86::COND_NP, MVT::i8), Cond };
3240 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops1, 2);
3241 SDOperand Ops2[] = { DAG.getConstant(X86::COND_E, MVT::i8),
3243 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops2, 2);
3244 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
3246 case ISD::SETUNE: { // PF | !ZF
3247 SDOperand Ops1[] = { DAG.getConstant(X86::COND_P, MVT::i8), Cond };
3248 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops1, 2);
3249 SDOperand Ops2[] = { DAG.getConstant(X86::COND_NE, MVT::i8),
3251 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, VTs2, 2, Ops2, 2);
3252 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
3257 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
3258 bool addTest = true;
3259 SDOperand Chain = DAG.getEntryNode();
3260 SDOperand Cond = Op.getOperand(0);
3262 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3264 if (Cond.getOpcode() == ISD::SETCC)
3265 Cond = LowerSETCC(Cond, DAG, Chain);
3267 if (Cond.getOpcode() == X86ISD::SETCC) {
3268 CC = Cond.getOperand(0);
3270 // If condition flag is set by a X86ISD::CMP, then make a copy of it
3271 // (since flag operand cannot be shared). Use it as the condition setting
3272 // operand in place of the X86ISD::SETCC.
3273 // If the X86ISD::SETCC has more than one use, then perhaps it's better
3274 // to use a test instead of duplicating the X86ISD::CMP (for register
3275 // pressure reason)?
3276 SDOperand Cmp = Cond.getOperand(1);
3277 unsigned Opc = Cmp.getOpcode();
3278 bool IllegalFPCMov = !X86ScalarSSE &&
3279 MVT::isFloatingPoint(Op.getValueType()) &&
3280 !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
3281 if ((Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI) &&
3283 SDOperand Ops[] = { Chain, Cmp.getOperand(1), Cmp.getOperand(2) };
3284 Cond = DAG.getNode(Opc, VTs, 2, Ops, 3);
3290 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3291 SDOperand Ops[] = { Chain, Cond, DAG.getConstant(0, MVT::i8) };
3292 Cond = DAG.getNode(X86ISD::CMP, VTs, 2, Ops, 3);
3295 VTs = DAG.getNodeValueTypes(Op.getValueType(), MVT::Flag);
3296 SmallVector<SDOperand, 4> Ops;
3297 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
3298 // condition is true.
3299 Ops.push_back(Op.getOperand(2));
3300 Ops.push_back(Op.getOperand(1));
3302 Ops.push_back(Cond.getValue(1));
3303 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
3306 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
3307 bool addTest = true;
3308 SDOperand Chain = Op.getOperand(0);
3309 SDOperand Cond = Op.getOperand(1);
3310 SDOperand Dest = Op.getOperand(2);
3312 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3314 if (Cond.getOpcode() == ISD::SETCC)
3315 Cond = LowerSETCC(Cond, DAG, Chain);
3317 if (Cond.getOpcode() == X86ISD::SETCC) {
3318 CC = Cond.getOperand(0);
3320 // If condition flag is set by a X86ISD::CMP, then make a copy of it
3321 // (since flag operand cannot be shared). Use it as the condition setting
3322 // operand in place of the X86ISD::SETCC.
3323 // If the X86ISD::SETCC has more than one use, then perhaps it's better
3324 // to use a test instead of duplicating the X86ISD::CMP (for register
3325 // pressure reason)?
3326 SDOperand Cmp = Cond.getOperand(1);
3327 unsigned Opc = Cmp.getOpcode();
3328 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI) {
3329 SDOperand Ops[] = { Chain, Cmp.getOperand(1), Cmp.getOperand(2) };
3330 Cond = DAG.getNode(Opc, VTs, 2, Ops, 3);
3336 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3337 SDOperand Ops[] = { Chain, Cond, DAG.getConstant(0, MVT::i8) };
3338 Cond = DAG.getNode(X86ISD::CMP, VTs, 2, Ops, 3);
3340 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
3341 Cond, Op.getOperand(2), CC, Cond.getValue(1));
3344 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
3345 unsigned CallingConv= cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3347 if (Subtarget->is64Bit())
3348 return LowerX86_64CCCCallTo(Op, DAG, CallingConv);
3350 switch (CallingConv) {
3352 assert(0 && "Unsupported calling convention");
3353 case CallingConv::Fast:
3354 // TODO: Implement fastcc
3356 case CallingConv::C:
3357 case CallingConv::X86_StdCall:
3358 return LowerCCCCallTo(Op, DAG, CallingConv);
3359 case CallingConv::X86_FastCall:
3360 return LowerFastCCCallTo(Op, DAG, CallingConv);
3365 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
3366 MachineFunction &MF = DAG.getMachineFunction();
3367 const Function* Fn = MF.getFunction();
3368 if (Fn->hasExternalLinkage() &&
3369 Subtarget->isTargetCygMing() &&
3370 Fn->getName() == "main")
3371 MF.getInfo<X86FunctionInfo>()->setForceFramePointer(true);
3373 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3374 if (Subtarget->is64Bit())
3375 return LowerX86_64CCCArguments(Op, DAG);
3379 assert(0 && "Unsupported calling convention");
3380 case CallingConv::Fast:
3381 // TODO: implement fastcc.
3384 case CallingConv::C:
3385 return LowerCCCArguments(Op, DAG);
3386 case CallingConv::X86_StdCall:
3387 MF.getInfo<X86FunctionInfo>()->setDecorationStyle(StdCall);
3388 return LowerCCCArguments(Op, DAG, true);
3389 case CallingConv::X86_FastCall:
3390 MF.getInfo<X86FunctionInfo>()->setDecorationStyle(FastCall);
3391 return LowerFastCCArguments(Op, DAG);
3395 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
3396 SDOperand InFlag(0, 0);
3397 SDOperand Chain = Op.getOperand(0);
3399 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
3400 if (Align == 0) Align = 1;
3402 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3403 // If not DWORD aligned, call memset if size is less than the threshold.
3404 // It knows how to align to the right boundary first.
3405 if ((Align & 3) != 0 ||
3406 (I && I->getValue() < Subtarget->getMinRepStrSizeThreshold())) {
3407 MVT::ValueType IntPtr = getPointerTy();
3408 const Type *IntPtrTy = getTargetData()->getIntPtrType();
3409 TargetLowering::ArgListTy Args;
3410 TargetLowering::ArgListEntry Entry;
3411 Entry.Node = Op.getOperand(1);
3412 Entry.Ty = IntPtrTy;
3413 Args.push_back(Entry);
3414 // Extend the unsigned i8 argument to be an int value for the call.
3415 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
3416 Entry.Ty = IntPtrTy;
3417 Args.push_back(Entry);
3418 Entry.Node = Op.getOperand(3);
3419 Args.push_back(Entry);
3420 std::pair<SDOperand,SDOperand> CallResult =
3421 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
3422 DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
3423 return CallResult.second;
3428 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3429 unsigned BytesLeft = 0;
3430 bool TwoRepStos = false;
3433 uint64_t Val = ValC->getValue() & 255;
3435 // If the value is a constant, then we can potentially use larger sets.
3436 switch (Align & 3) {
3437 case 2: // WORD aligned
3440 Val = (Val << 8) | Val;
3442 case 0: // DWORD aligned
3445 Val = (Val << 8) | Val;
3446 Val = (Val << 16) | Val;
3447 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
3450 Val = (Val << 32) | Val;
3453 default: // Byte aligned
3456 Count = Op.getOperand(3);
3460 if (AVT > MVT::i8) {
3462 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
3463 Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
3464 BytesLeft = I->getValue() % UBytes;
3466 assert(AVT >= MVT::i32 &&
3467 "Do not use rep;stos if not at least DWORD aligned");
3468 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
3469 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
3474 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
3476 InFlag = Chain.getValue(1);
3479 Count = Op.getOperand(3);
3480 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
3481 InFlag = Chain.getValue(1);
3484 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
3486 InFlag = Chain.getValue(1);
3487 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
3488 Op.getOperand(1), InFlag);
3489 InFlag = Chain.getValue(1);
3491 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3492 SmallVector<SDOperand, 8> Ops;
3493 Ops.push_back(Chain);
3494 Ops.push_back(DAG.getValueType(AVT));
3495 Ops.push_back(InFlag);
3496 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
3499 InFlag = Chain.getValue(1);
3500 Count = Op.getOperand(3);
3501 MVT::ValueType CVT = Count.getValueType();
3502 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
3503 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
3504 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
3506 InFlag = Chain.getValue(1);
3507 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3509 Ops.push_back(Chain);
3510 Ops.push_back(DAG.getValueType(MVT::i8));
3511 Ops.push_back(InFlag);
3512 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
3513 } else if (BytesLeft) {
3514 // Issue stores for the last 1 - 7 bytes.
3516 unsigned Val = ValC->getValue() & 255;
3517 unsigned Offset = I->getValue() - BytesLeft;
3518 SDOperand DstAddr = Op.getOperand(1);
3519 MVT::ValueType AddrVT = DstAddr.getValueType();
3520 if (BytesLeft >= 4) {
3521 Val = (Val << 8) | Val;
3522 Val = (Val << 16) | Val;
3523 Value = DAG.getConstant(Val, MVT::i32);
3524 Chain = DAG.getStore(Chain, Value,
3525 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3526 DAG.getConstant(Offset, AddrVT)),
3531 if (BytesLeft >= 2) {
3532 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
3533 Chain = DAG.getStore(Chain, Value,
3534 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3535 DAG.getConstant(Offset, AddrVT)),
3540 if (BytesLeft == 1) {
3541 Value = DAG.getConstant(Val, MVT::i8);
3542 Chain = DAG.getStore(Chain, Value,
3543 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3544 DAG.getConstant(Offset, AddrVT)),
3552 SDOperand X86TargetLowering::LowerMEMCPY(SDOperand Op, SelectionDAG &DAG) {
3553 SDOperand Chain = Op.getOperand(0);
3555 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
3556 if (Align == 0) Align = 1;
3558 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3559 // If not DWORD aligned, call memcpy if size is less than the threshold.
3560 // It knows how to align to the right boundary first.
3561 if ((Align & 3) != 0 ||
3562 (I && I->getValue() < Subtarget->getMinRepStrSizeThreshold())) {
3563 MVT::ValueType IntPtr = getPointerTy();
3564 TargetLowering::ArgListTy Args;
3565 TargetLowering::ArgListEntry Entry;
3566 Entry.Ty = getTargetData()->getIntPtrType();
3567 Entry.Node = Op.getOperand(1); Args.push_back(Entry);
3568 Entry.Node = Op.getOperand(2); Args.push_back(Entry);
3569 Entry.Node = Op.getOperand(3); Args.push_back(Entry);
3570 std::pair<SDOperand,SDOperand> CallResult =
3571 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
3572 DAG.getExternalSymbol("memcpy", IntPtr), Args, DAG);
3573 return CallResult.second;
3578 unsigned BytesLeft = 0;
3579 bool TwoRepMovs = false;
3580 switch (Align & 3) {
3581 case 2: // WORD aligned
3584 case 0: // DWORD aligned
3586 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
3589 default: // Byte aligned
3591 Count = Op.getOperand(3);
3595 if (AVT > MVT::i8) {
3597 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
3598 Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
3599 BytesLeft = I->getValue() % UBytes;
3601 assert(AVT >= MVT::i32 &&
3602 "Do not use rep;movs if not at least DWORD aligned");
3603 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
3604 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
3609 SDOperand InFlag(0, 0);
3610 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
3612 InFlag = Chain.getValue(1);
3613 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
3614 Op.getOperand(1), InFlag);
3615 InFlag = Chain.getValue(1);
3616 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
3617 Op.getOperand(2), InFlag);
3618 InFlag = Chain.getValue(1);
3620 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3621 SmallVector<SDOperand, 8> Ops;
3622 Ops.push_back(Chain);
3623 Ops.push_back(DAG.getValueType(AVT));
3624 Ops.push_back(InFlag);
3625 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
3628 InFlag = Chain.getValue(1);
3629 Count = Op.getOperand(3);
3630 MVT::ValueType CVT = Count.getValueType();
3631 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
3632 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
3633 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
3635 InFlag = Chain.getValue(1);
3636 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3638 Ops.push_back(Chain);
3639 Ops.push_back(DAG.getValueType(MVT::i8));
3640 Ops.push_back(InFlag);
3641 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
3642 } else if (BytesLeft) {
3643 // Issue loads and stores for the last 1 - 7 bytes.
3644 unsigned Offset = I->getValue() - BytesLeft;
3645 SDOperand DstAddr = Op.getOperand(1);
3646 MVT::ValueType DstVT = DstAddr.getValueType();
3647 SDOperand SrcAddr = Op.getOperand(2);
3648 MVT::ValueType SrcVT = SrcAddr.getValueType();
3650 if (BytesLeft >= 4) {
3651 Value = DAG.getLoad(MVT::i32, Chain,
3652 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3653 DAG.getConstant(Offset, SrcVT)),
3655 Chain = Value.getValue(1);
3656 Chain = DAG.getStore(Chain, Value,
3657 DAG.getNode(ISD::ADD, DstVT, DstAddr,
3658 DAG.getConstant(Offset, DstVT)),
3663 if (BytesLeft >= 2) {
3664 Value = DAG.getLoad(MVT::i16, Chain,
3665 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3666 DAG.getConstant(Offset, SrcVT)),
3668 Chain = Value.getValue(1);
3669 Chain = DAG.getStore(Chain, Value,
3670 DAG.getNode(ISD::ADD, DstVT, DstAddr,
3671 DAG.getConstant(Offset, DstVT)),
3677 if (BytesLeft == 1) {
3678 Value = DAG.getLoad(MVT::i8, Chain,
3679 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3680 DAG.getConstant(Offset, SrcVT)),
3682 Chain = Value.getValue(1);
3683 Chain = DAG.getStore(Chain, Value,
3684 DAG.getNode(ISD::ADD, DstVT, DstAddr,
3685 DAG.getConstant(Offset, DstVT)),
3694 X86TargetLowering::LowerREADCYCLCECOUNTER(SDOperand Op, SelectionDAG &DAG) {
3695 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
3696 SDOperand TheOp = Op.getOperand(0);
3697 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheOp, 1);
3698 if (Subtarget->is64Bit()) {
3699 SDOperand Copy1 = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
3700 SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::RDX,
3701 MVT::i64, Copy1.getValue(2));
3702 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, Copy2,
3703 DAG.getConstant(32, MVT::i8));
3705 DAG.getNode(ISD::OR, MVT::i64, Copy1, Tmp), Copy2.getValue(1)
3708 Tys = DAG.getVTList(MVT::i64, MVT::Other);
3709 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2);
3712 SDOperand Copy1 = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
3713 SDOperand Copy2 = DAG.getCopyFromReg(Copy1.getValue(1), X86::EDX,
3714 MVT::i32, Copy1.getValue(2));
3715 SDOperand Ops[] = { Copy1, Copy2, Copy2.getValue(1) };
3716 Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
3717 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 3);
3720 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
3721 SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
3723 if (!Subtarget->is64Bit()) {
3724 // vastart just stores the address of the VarArgsFrameIndex slot into the
3725 // memory location argument.
3726 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
3727 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV->getValue(),
3732 // gp_offset (0 - 6 * 8)
3733 // fp_offset (48 - 48 + 8 * 16)
3734 // overflow_arg_area (point to parameters coming in memory).
3736 SmallVector<SDOperand, 8> MemOps;
3737 SDOperand FIN = Op.getOperand(1);
3739 SDOperand Store = DAG.getStore(Op.getOperand(0),
3740 DAG.getConstant(VarArgsGPOffset, MVT::i32),
3741 FIN, SV->getValue(), SV->getOffset());
3742 MemOps.push_back(Store);
3745 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
3746 DAG.getConstant(4, getPointerTy()));
3747 Store = DAG.getStore(Op.getOperand(0),
3748 DAG.getConstant(VarArgsFPOffset, MVT::i32),
3749 FIN, SV->getValue(), SV->getOffset());
3750 MemOps.push_back(Store);
3752 // Store ptr to overflow_arg_area
3753 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
3754 DAG.getConstant(4, getPointerTy()));
3755 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
3756 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV->getValue(),
3758 MemOps.push_back(Store);
3760 // Store ptr to reg_save_area.
3761 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
3762 DAG.getConstant(8, getPointerTy()));
3763 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
3764 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV->getValue(),
3766 MemOps.push_back(Store);
3767 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
3770 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
3771 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
3772 SDOperand Chain = Op.getOperand(0);
3773 SDOperand DstPtr = Op.getOperand(1);
3774 SDOperand SrcPtr = Op.getOperand(2);
3775 SrcValueSDNode *DstSV = cast<SrcValueSDNode>(Op.getOperand(3));
3776 SrcValueSDNode *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4));
3778 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr,
3779 SrcSV->getValue(), SrcSV->getOffset());
3780 Chain = SrcPtr.getValue(1);
3781 for (unsigned i = 0; i < 3; ++i) {
3782 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr,
3783 SrcSV->getValue(), SrcSV->getOffset());
3784 Chain = Val.getValue(1);
3785 Chain = DAG.getStore(Chain, Val, DstPtr,
3786 DstSV->getValue(), DstSV->getOffset());
3789 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
3790 DAG.getConstant(8, getPointerTy()));
3791 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
3792 DAG.getConstant(8, getPointerTy()));
3798 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
3799 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
3801 default: return SDOperand(); // Don't custom lower most intrinsics.
3802 // Comparison intrinsics.
3803 case Intrinsic::x86_sse_comieq_ss:
3804 case Intrinsic::x86_sse_comilt_ss:
3805 case Intrinsic::x86_sse_comile_ss:
3806 case Intrinsic::x86_sse_comigt_ss:
3807 case Intrinsic::x86_sse_comige_ss:
3808 case Intrinsic::x86_sse_comineq_ss:
3809 case Intrinsic::x86_sse_ucomieq_ss:
3810 case Intrinsic::x86_sse_ucomilt_ss:
3811 case Intrinsic::x86_sse_ucomile_ss:
3812 case Intrinsic::x86_sse_ucomigt_ss:
3813 case Intrinsic::x86_sse_ucomige_ss:
3814 case Intrinsic::x86_sse_ucomineq_ss:
3815 case Intrinsic::x86_sse2_comieq_sd:
3816 case Intrinsic::x86_sse2_comilt_sd:
3817 case Intrinsic::x86_sse2_comile_sd:
3818 case Intrinsic::x86_sse2_comigt_sd:
3819 case Intrinsic::x86_sse2_comige_sd:
3820 case Intrinsic::x86_sse2_comineq_sd:
3821 case Intrinsic::x86_sse2_ucomieq_sd:
3822 case Intrinsic::x86_sse2_ucomilt_sd:
3823 case Intrinsic::x86_sse2_ucomile_sd:
3824 case Intrinsic::x86_sse2_ucomigt_sd:
3825 case Intrinsic::x86_sse2_ucomige_sd:
3826 case Intrinsic::x86_sse2_ucomineq_sd: {
3828 ISD::CondCode CC = ISD::SETCC_INVALID;
3831 case Intrinsic::x86_sse_comieq_ss:
3832 case Intrinsic::x86_sse2_comieq_sd:
3836 case Intrinsic::x86_sse_comilt_ss:
3837 case Intrinsic::x86_sse2_comilt_sd:
3841 case Intrinsic::x86_sse_comile_ss:
3842 case Intrinsic::x86_sse2_comile_sd:
3846 case Intrinsic::x86_sse_comigt_ss:
3847 case Intrinsic::x86_sse2_comigt_sd:
3851 case Intrinsic::x86_sse_comige_ss:
3852 case Intrinsic::x86_sse2_comige_sd:
3856 case Intrinsic::x86_sse_comineq_ss:
3857 case Intrinsic::x86_sse2_comineq_sd:
3861 case Intrinsic::x86_sse_ucomieq_ss:
3862 case Intrinsic::x86_sse2_ucomieq_sd:
3863 Opc = X86ISD::UCOMI;
3866 case Intrinsic::x86_sse_ucomilt_ss:
3867 case Intrinsic::x86_sse2_ucomilt_sd:
3868 Opc = X86ISD::UCOMI;
3871 case Intrinsic::x86_sse_ucomile_ss:
3872 case Intrinsic::x86_sse2_ucomile_sd:
3873 Opc = X86ISD::UCOMI;
3876 case Intrinsic::x86_sse_ucomigt_ss:
3877 case Intrinsic::x86_sse2_ucomigt_sd:
3878 Opc = X86ISD::UCOMI;
3881 case Intrinsic::x86_sse_ucomige_ss:
3882 case Intrinsic::x86_sse2_ucomige_sd:
3883 Opc = X86ISD::UCOMI;
3886 case Intrinsic::x86_sse_ucomineq_ss:
3887 case Intrinsic::x86_sse2_ucomineq_sd:
3888 Opc = X86ISD::UCOMI;
3894 SDOperand LHS = Op.getOperand(1);
3895 SDOperand RHS = Op.getOperand(2);
3896 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
3898 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3899 SDOperand Ops1[] = { DAG.getEntryNode(), LHS, RHS };
3900 SDOperand Cond = DAG.getNode(Opc, VTs, 2, Ops1, 3);
3901 VTs = DAG.getNodeValueTypes(MVT::i8, MVT::Flag);
3902 SDOperand Ops2[] = { DAG.getConstant(X86CC, MVT::i8), Cond };
3903 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, VTs, 2, Ops2, 2);
3904 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
3909 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
3910 // Depths > 0 not supported yet!
3911 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
3914 // Just load the return address
3915 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
3916 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
3919 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
3920 // Depths > 0 not supported yet!
3921 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
3924 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
3925 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
3926 DAG.getConstant(4, getPointerTy()));
3929 /// LowerOperation - Provide custom lowering hooks for some operations.
3931 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
3932 switch (Op.getOpcode()) {
3933 default: assert(0 && "Should not custom lower this!");
3934 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
3935 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
3936 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3937 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
3938 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
3939 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
3940 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
3941 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
3942 case ISD::SHL_PARTS:
3943 case ISD::SRA_PARTS:
3944 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
3945 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
3946 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
3947 case ISD::FABS: return LowerFABS(Op, DAG);
3948 case ISD::FNEG: return LowerFNEG(Op, DAG);
3949 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
3950 case ISD::SETCC: return LowerSETCC(Op, DAG, DAG.getEntryNode());
3951 case ISD::SELECT: return LowerSELECT(Op, DAG);
3952 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3953 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
3954 case ISD::CALL: return LowerCALL(Op, DAG);
3955 case ISD::RET: return LowerRET(Op, DAG);
3956 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
3957 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
3958 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
3959 case ISD::READCYCLECOUNTER: return LowerREADCYCLCECOUNTER(Op, DAG);
3960 case ISD::VASTART: return LowerVASTART(Op, DAG);
3961 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
3962 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3963 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
3964 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
3969 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
3971 default: return NULL;
3972 case X86ISD::SHLD: return "X86ISD::SHLD";
3973 case X86ISD::SHRD: return "X86ISD::SHRD";
3974 case X86ISD::FAND: return "X86ISD::FAND";
3975 case X86ISD::FOR: return "X86ISD::FOR";
3976 case X86ISD::FXOR: return "X86ISD::FXOR";
3977 case X86ISD::FSRL: return "X86ISD::FSRL";
3978 case X86ISD::FILD: return "X86ISD::FILD";
3979 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
3980 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
3981 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
3982 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
3983 case X86ISD::FLD: return "X86ISD::FLD";
3984 case X86ISD::FST: return "X86ISD::FST";
3985 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
3986 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
3987 case X86ISD::CALL: return "X86ISD::CALL";
3988 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
3989 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
3990 case X86ISD::CMP: return "X86ISD::CMP";
3991 case X86ISD::COMI: return "X86ISD::COMI";
3992 case X86ISD::UCOMI: return "X86ISD::UCOMI";
3993 case X86ISD::SETCC: return "X86ISD::SETCC";
3994 case X86ISD::CMOV: return "X86ISD::CMOV";
3995 case X86ISD::BRCOND: return "X86ISD::BRCOND";
3996 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
3997 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
3998 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
3999 case X86ISD::LOAD_PACK: return "X86ISD::LOAD_PACK";
4000 case X86ISD::LOAD_UA: return "X86ISD::LOAD_UA";
4001 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
4002 case X86ISD::Wrapper: return "X86ISD::Wrapper";
4003 case X86ISD::S2VEC: return "X86ISD::S2VEC";
4004 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
4005 case X86ISD::PINSRW: return "X86ISD::PINSRW";
4006 case X86ISD::FMAX: return "X86ISD::FMAX";
4007 case X86ISD::FMIN: return "X86ISD::FMIN";
4011 /// isLegalAddressImmediate - Return true if the integer value can be used
4012 /// as the offset of the target addressing mode for load / store of the
4014 bool X86TargetLowering::isLegalAddressImmediate(int64_t V,const Type *Ty) const{
4015 // X86 allows a sign-extended 32-bit immediate field.
4016 return (V > -(1LL << 32) && V < (1LL << 32)-1);
4019 /// isLegalAddressImmediate - Return true if the GlobalValue can be used as
4020 /// the offset of the target addressing mode.
4021 bool X86TargetLowering::isLegalAddressImmediate(GlobalValue *GV) const {
4022 // In 64-bit mode, GV is 64-bit so it won't fit in the 32-bit displacement
4023 // field unless we are in small code model.
4024 if (Subtarget->is64Bit() &&
4025 getTargetMachine().getCodeModel() != CodeModel::Small)
4028 return (!Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false));
4031 /// isLegalAddressScale - Return true if the integer value can be used as the
4032 /// scale of the target addressing mode for load / store of the given type.
4033 bool X86TargetLowering::isLegalAddressScale(int64_t S, const Type *Ty) const {
4037 case 2: case 4: case 8:
4039 // FIXME: These require both scale + index last and thus more expensive.
4040 // How to tell LSR to try for 2, 4, 8 first?
4041 case 3: case 5: case 9:
4046 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4047 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4048 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4049 /// are assumed to be legal.
4051 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
4052 // Only do shuffles on 128-bit vector types for now.
4053 if (MVT::getSizeInBits(VT) == 64) return false;
4054 return (Mask.Val->getNumOperands() <= 4 ||
4055 isSplatMask(Mask.Val) ||
4056 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
4057 X86::isUNPCKLMask(Mask.Val) ||
4058 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
4059 X86::isUNPCKHMask(Mask.Val));
4062 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
4064 SelectionDAG &DAG) const {
4065 unsigned NumElts = BVOps.size();
4066 // Only do shuffles on 128-bit vector types for now.
4067 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
4068 if (NumElts == 2) return true;
4070 return (isMOVLMask(&BVOps[0], 4) ||
4071 isCommutedMOVL(&BVOps[0], 4, true) ||
4072 isSHUFPMask(&BVOps[0], 4) ||
4073 isCommutedSHUFP(&BVOps[0], 4));
4078 //===----------------------------------------------------------------------===//
4079 // X86 Scheduler Hooks
4080 //===----------------------------------------------------------------------===//
4083 X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
4084 MachineBasicBlock *BB) {
4085 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4086 switch (MI->getOpcode()) {
4087 default: assert(false && "Unexpected instr type to insert");
4088 case X86::CMOV_FR32:
4089 case X86::CMOV_FR64:
4090 case X86::CMOV_V4F32:
4091 case X86::CMOV_V2F64:
4092 case X86::CMOV_V2I64: {
4093 // To "insert" a SELECT_CC instruction, we actually have to insert the
4094 // diamond control-flow pattern. The incoming instruction knows the
4095 // destination vreg to set, the condition code register to branch on, the
4096 // true/false values to select between, and a branch opcode to use.
4097 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4098 ilist<MachineBasicBlock>::iterator It = BB;
4104 // cmpTY ccX, r1, r2
4106 // fallthrough --> copy0MBB
4107 MachineBasicBlock *thisMBB = BB;
4108 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
4109 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
4111 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
4112 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
4113 MachineFunction *F = BB->getParent();
4114 F->getBasicBlockList().insert(It, copy0MBB);
4115 F->getBasicBlockList().insert(It, sinkMBB);
4116 // Update machine-CFG edges by first adding all successors of the current
4117 // block to the new block which will contain the Phi node for the select.
4118 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
4119 e = BB->succ_end(); i != e; ++i)
4120 sinkMBB->addSuccessor(*i);
4121 // Next, remove all successors of the current block, and add the true
4122 // and fallthrough blocks as its successors.
4123 while(!BB->succ_empty())
4124 BB->removeSuccessor(BB->succ_begin());
4125 BB->addSuccessor(copy0MBB);
4126 BB->addSuccessor(sinkMBB);
4129 // %FalseValue = ...
4130 // # fallthrough to sinkMBB
4133 // Update machine-CFG edges
4134 BB->addSuccessor(sinkMBB);
4137 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
4140 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
4141 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
4142 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
4144 delete MI; // The pseudo instruction is gone now.
4148 case X86::FP_TO_INT16_IN_MEM:
4149 case X86::FP_TO_INT32_IN_MEM:
4150 case X86::FP_TO_INT64_IN_MEM: {
4151 // Change the floating point control register to use "round towards zero"
4152 // mode when truncating to an integer value.
4153 MachineFunction *F = BB->getParent();
4154 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
4155 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
4157 // Load the old value of the high byte of the control word...
4159 F->getSSARegMap()->createVirtualRegister(X86::GR16RegisterClass);
4160 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
4162 // Set the high part to be round to zero...
4163 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
4166 // Reload the modified control word now...
4167 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
4169 // Restore the memory image of control word to original value
4170 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
4173 // Get the X86 opcode to use.
4175 switch (MI->getOpcode()) {
4176 default: assert(0 && "illegal opcode!");
4177 case X86::FP_TO_INT16_IN_MEM: Opc = X86::FpIST16m; break;
4178 case X86::FP_TO_INT32_IN_MEM: Opc = X86::FpIST32m; break;
4179 case X86::FP_TO_INT64_IN_MEM: Opc = X86::FpIST64m; break;
4183 MachineOperand &Op = MI->getOperand(0);
4184 if (Op.isRegister()) {
4185 AM.BaseType = X86AddressMode::RegBase;
4186 AM.Base.Reg = Op.getReg();
4188 AM.BaseType = X86AddressMode::FrameIndexBase;
4189 AM.Base.FrameIndex = Op.getFrameIndex();
4191 Op = MI->getOperand(1);
4192 if (Op.isImmediate())
4193 AM.Scale = Op.getImm();
4194 Op = MI->getOperand(2);
4195 if (Op.isImmediate())
4196 AM.IndexReg = Op.getImm();
4197 Op = MI->getOperand(3);
4198 if (Op.isGlobalAddress()) {
4199 AM.GV = Op.getGlobal();
4201 AM.Disp = Op.getImm();
4203 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
4204 .addReg(MI->getOperand(4).getReg());
4206 // Reload the original control word now.
4207 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
4209 delete MI; // The pseudo instruction is gone now.
4215 //===----------------------------------------------------------------------===//
4216 // X86 Optimization Hooks
4217 //===----------------------------------------------------------------------===//
4219 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
4221 uint64_t &KnownZero,
4223 unsigned Depth) const {
4224 unsigned Opc = Op.getOpcode();
4225 assert((Opc >= ISD::BUILTIN_OP_END ||
4226 Opc == ISD::INTRINSIC_WO_CHAIN ||
4227 Opc == ISD::INTRINSIC_W_CHAIN ||
4228 Opc == ISD::INTRINSIC_VOID) &&
4229 "Should use MaskedValueIsZero if you don't know whether Op"
4230 " is a target node!");
4232 KnownZero = KnownOne = 0; // Don't know anything.
4236 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
4241 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4242 /// element of the result of the vector shuffle.
4243 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
4244 MVT::ValueType VT = N->getValueType(0);
4245 SDOperand PermMask = N->getOperand(2);
4246 unsigned NumElems = PermMask.getNumOperands();
4247 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
4249 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4251 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(VT));
4252 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
4253 SDOperand Idx = PermMask.getOperand(i);
4254 if (Idx.getOpcode() == ISD::UNDEF)
4255 return DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(VT));
4256 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
4261 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
4262 /// node is a GlobalAddress + an offset.
4263 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
4264 unsigned Opc = N->getOpcode();
4265 if (Opc == X86ISD::Wrapper) {
4266 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
4267 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
4270 } else if (Opc == ISD::ADD) {
4271 SDOperand N1 = N->getOperand(0);
4272 SDOperand N2 = N->getOperand(1);
4273 if (isGAPlusOffset(N1.Val, GA, Offset)) {
4274 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
4276 Offset += V->getSignExtended();
4279 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
4280 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
4282 Offset += V->getSignExtended();
4290 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
4292 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
4293 MachineFrameInfo *MFI) {
4294 if (N->getOperand(0).Val != Base->getOperand(0).Val)
4297 SDOperand Loc = N->getOperand(1);
4298 SDOperand BaseLoc = Base->getOperand(1);
4299 if (Loc.getOpcode() == ISD::FrameIndex) {
4300 if (BaseLoc.getOpcode() != ISD::FrameIndex)
4302 int FI = dyn_cast<FrameIndexSDNode>(Loc)->getIndex();
4303 int BFI = dyn_cast<FrameIndexSDNode>(BaseLoc)->getIndex();
4304 int FS = MFI->getObjectSize(FI);
4305 int BFS = MFI->getObjectSize(BFI);
4306 if (FS != BFS || FS != Size) return false;
4307 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
4309 GlobalValue *GV1 = NULL;
4310 GlobalValue *GV2 = NULL;
4311 int64_t Offset1 = 0;
4312 int64_t Offset2 = 0;
4313 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
4314 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
4315 if (isGA1 && isGA2 && GV1 == GV2)
4316 return Offset1 == (Offset2 + Dist*Size);
4322 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
4323 const X86Subtarget *Subtarget) {
4326 if (isGAPlusOffset(Base, GV, Offset))
4327 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
4329 assert(Base->getOpcode() == ISD::FrameIndex && "Unexpected base node!");
4330 int BFI = dyn_cast<FrameIndexSDNode>(Base)->getIndex();
4332 // Fixed objects do not specify alignment, however the offsets are known.
4333 return ((Subtarget->getStackAlignment() % 16) == 0 &&
4334 (MFI->getObjectOffset(BFI) % 16) == 0);
4336 return MFI->getObjectAlignment(BFI) >= 16;
4342 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
4343 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
4344 /// if the load addresses are consecutive, non-overlapping, and in the right
4346 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
4347 const X86Subtarget *Subtarget) {
4348 MachineFunction &MF = DAG.getMachineFunction();
4349 MachineFrameInfo *MFI = MF.getFrameInfo();
4350 MVT::ValueType VT = N->getValueType(0);
4351 MVT::ValueType EVT = MVT::getVectorBaseType(VT);
4352 SDOperand PermMask = N->getOperand(2);
4353 int NumElems = (int)PermMask.getNumOperands();
4354 SDNode *Base = NULL;
4355 for (int i = 0; i < NumElems; ++i) {
4356 SDOperand Idx = PermMask.getOperand(i);
4357 if (Idx.getOpcode() == ISD::UNDEF) {
4358 if (!Base) return SDOperand();
4361 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
4362 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
4366 else if (!isConsecutiveLoad(Arg.Val, Base,
4367 i, MVT::getSizeInBits(EVT)/8,MFI))
4372 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
4374 LoadSDNode *LD = cast<LoadSDNode>(Base);
4375 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
4376 LD->getSrcValueOffset());
4378 // Just use movups, it's shorter.
4379 SDVTList Tys = DAG.getVTList(MVT::v4f32, MVT::Other);
4380 SmallVector<SDOperand, 3> Ops;
4381 Ops.push_back(Base->getOperand(0));
4382 Ops.push_back(Base->getOperand(1));
4383 Ops.push_back(Base->getOperand(2));
4384 return DAG.getNode(ISD::BIT_CONVERT, VT,
4385 DAG.getNode(X86ISD::LOAD_UA, Tys, &Ops[0], Ops.size()));
4389 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
4390 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
4391 const X86Subtarget *Subtarget) {
4392 SDOperand Cond = N->getOperand(0);
4394 // If we have SSE[12] support, try to form min/max nodes.
4395 if (Subtarget->hasSSE2() &&
4396 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
4397 if (Cond.getOpcode() == ISD::SETCC) {
4398 // Get the LHS/RHS of the select.
4399 SDOperand LHS = N->getOperand(1);
4400 SDOperand RHS = N->getOperand(2);
4401 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
4403 unsigned Opcode = 0;
4404 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
4407 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
4410 if (!UnsafeFPMath) break;
4412 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
4414 Opcode = X86ISD::FMIN;
4417 case ISD::SETOGT: // (X > Y) ? X : Y -> max
4420 if (!UnsafeFPMath) break;
4422 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
4424 Opcode = X86ISD::FMAX;
4427 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
4430 case ISD::SETOGT: // (X > Y) ? Y : X -> min
4433 if (!UnsafeFPMath) break;
4435 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
4437 Opcode = X86ISD::FMIN;
4440 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
4443 if (!UnsafeFPMath) break;
4445 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
4447 Opcode = X86ISD::FMAX;
4453 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
4462 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
4463 DAGCombinerInfo &DCI) const {
4464 SelectionDAG &DAG = DCI.DAG;
4465 switch (N->getOpcode()) {
4467 case ISD::VECTOR_SHUFFLE:
4468 return PerformShuffleCombine(N, DAG, Subtarget);
4470 return PerformSELECTCombine(N, DAG, Subtarget);
4476 //===----------------------------------------------------------------------===//
4477 // X86 Inline Assembly Support
4478 //===----------------------------------------------------------------------===//
4480 /// getConstraintType - Given a constraint letter, return the type of
4481 /// constraint it is for this target.
4482 X86TargetLowering::ConstraintType
4483 X86TargetLowering::getConstraintType(char ConstraintLetter) const {
4484 switch (ConstraintLetter) {
4493 return C_RegisterClass;
4494 default: return TargetLowering::getConstraintType(ConstraintLetter);
4498 /// isOperandValidForConstraint - Return the specified operand (possibly
4499 /// modified) if the specified SDOperand is valid for the specified target
4500 /// constraint letter, otherwise return null.
4501 SDOperand X86TargetLowering::
4502 isOperandValidForConstraint(SDOperand Op, char Constraint, SelectionDAG &DAG) {
4503 switch (Constraint) {
4506 // Literal immediates are always ok.
4507 if (isa<ConstantSDNode>(Op)) return Op;
4509 // If we are in non-pic codegen mode, we allow the address of a global to
4510 // be used with 'i'.
4511 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
4512 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4513 return SDOperand(0, 0);
4515 if (GA->getOpcode() != ISD::TargetGlobalAddress)
4516 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
4521 // Otherwise, not valid for this mode.
4522 return SDOperand(0, 0);
4524 return TargetLowering::isOperandValidForConstraint(Op, Constraint, DAG);
4528 std::vector<unsigned> X86TargetLowering::
4529 getRegClassForInlineAsmConstraint(const std::string &Constraint,
4530 MVT::ValueType VT) const {
4531 if (Constraint.size() == 1) {
4532 // FIXME: not handling fp-stack yet!
4533 // FIXME: not handling MMX registers yet ('y' constraint).
4534 switch (Constraint[0]) { // GCC X86 Constraint Letters
4535 default: break; // Unknown constraint letter
4536 case 'A': // EAX/EDX
4537 if (VT == MVT::i32 || VT == MVT::i64)
4538 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
4540 case 'r': // GENERAL_REGS
4541 case 'R': // LEGACY_REGS
4542 if (VT == MVT::i64 && Subtarget->is64Bit())
4543 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
4544 X86::RSI, X86::RDI, X86::RBP, X86::RSP,
4545 X86::R8, X86::R9, X86::R10, X86::R11,
4546 X86::R12, X86::R13, X86::R14, X86::R15, 0);
4548 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
4549 X86::ESI, X86::EDI, X86::EBP, X86::ESP, 0);
4550 else if (VT == MVT::i16)
4551 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
4552 X86::SI, X86::DI, X86::BP, X86::SP, 0);
4553 else if (VT == MVT::i8)
4554 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
4556 case 'l': // INDEX_REGS
4558 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
4559 X86::ESI, X86::EDI, X86::EBP, 0);
4560 else if (VT == MVT::i16)
4561 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
4562 X86::SI, X86::DI, X86::BP, 0);
4563 else if (VT == MVT::i8)
4564 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::DL, 0);
4566 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
4569 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
4570 else if (VT == MVT::i16)
4571 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
4572 else if (VT == MVT::i8)
4573 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::DL, 0);
4575 case 'x': // SSE_REGS if SSE1 allowed
4576 if (Subtarget->hasSSE1())
4577 return make_vector<unsigned>(X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
4578 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7,
4580 return std::vector<unsigned>();
4581 case 'Y': // SSE_REGS if SSE2 allowed
4582 if (Subtarget->hasSSE2())
4583 return make_vector<unsigned>(X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
4584 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7,
4586 return std::vector<unsigned>();
4590 return std::vector<unsigned>();
4593 std::pair<unsigned, const TargetRegisterClass*>
4594 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
4595 MVT::ValueType VT) const {
4596 // Use the default implementation in TargetLowering to convert the register
4597 // constraint into a member of a register class.
4598 std::pair<unsigned, const TargetRegisterClass*> Res;
4599 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
4601 // Not found as a standard register?
4602 if (Res.second == 0) {
4603 // GCC calls "st(0)" just plain "st".
4604 if (StringsEqualNoCase("{st}", Constraint)) {
4605 Res.first = X86::ST0;
4606 Res.second = X86::RSTRegisterClass;
4612 // Otherwise, check to see if this is a register class of the wrong value
4613 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
4614 // turn into {ax},{dx}.
4615 if (Res.second->hasType(VT))
4616 return Res; // Correct type already, nothing to do.
4618 // All of the single-register GCC register classes map their values onto
4619 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
4620 // really want an 8-bit or 32-bit register, map to the appropriate register
4621 // class and return the appropriate register.
4622 if (Res.second != X86::GR16RegisterClass)
4625 if (VT == MVT::i8) {
4626 unsigned DestReg = 0;
4627 switch (Res.first) {
4629 case X86::AX: DestReg = X86::AL; break;
4630 case X86::DX: DestReg = X86::DL; break;
4631 case X86::CX: DestReg = X86::CL; break;
4632 case X86::BX: DestReg = X86::BL; break;
4635 Res.first = DestReg;
4636 Res.second = Res.second = X86::GR8RegisterClass;
4638 } else if (VT == MVT::i32) {
4639 unsigned DestReg = 0;
4640 switch (Res.first) {
4642 case X86::AX: DestReg = X86::EAX; break;
4643 case X86::DX: DestReg = X86::EDX; break;
4644 case X86::CX: DestReg = X86::ECX; break;
4645 case X86::BX: DestReg = X86::EBX; break;
4646 case X86::SI: DestReg = X86::ESI; break;
4647 case X86::DI: DestReg = X86::EDI; break;
4648 case X86::BP: DestReg = X86::EBP; break;
4649 case X86::SP: DestReg = X86::ESP; break;
4652 Res.first = DestReg;
4653 Res.second = Res.second = X86::GR32RegisterClass;
4655 } else if (VT == MVT::i64) {
4656 unsigned DestReg = 0;
4657 switch (Res.first) {
4659 case X86::AX: DestReg = X86::RAX; break;
4660 case X86::DX: DestReg = X86::RDX; break;
4661 case X86::CX: DestReg = X86::RCX; break;
4662 case X86::BX: DestReg = X86::RBX; break;
4663 case X86::SI: DestReg = X86::RSI; break;
4664 case X86::DI: DestReg = X86::RDI; break;
4665 case X86::BP: DestReg = X86::RBP; break;
4666 case X86::SP: DestReg = X86::RSP; break;
4669 Res.first = DestReg;
4670 Res.second = Res.second = X86::GR64RegisterClass;