1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
55 STATISTIC(NumTailCalls, "Number of tail calls");
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference. Idx is an index in the 128 bits we
64 /// want. It need not be aligned to a 128-bit bounday. That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67 SelectionDAG &DAG, DebugLoc dl) {
68 EVT VT = Vec.getValueType();
69 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
70 EVT ElVT = VT.getVectorElementType();
71 unsigned Factor = VT.getSizeInBits()/128;
72 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73 VT.getVectorNumElements()/Factor);
75 // Extract from UNDEF is UNDEF.
76 if (Vec.getOpcode() == ISD::UNDEF)
77 return DAG.getUNDEF(ResultVT);
79 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
80 // we can match to VEXTRACTF128.
81 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
83 // This is the index of the first element of the 128-bit chunk
85 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
88 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
89 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
95 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference. Idx is an index in the 128 bits
98 /// we want. It need not be aligned to a 128-bit bounday. That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101 unsigned IdxVal, SelectionDAG &DAG,
103 // Inserting UNDEF is Result
104 if (Vec.getOpcode() == ISD::UNDEF)
107 EVT VT = Vec.getValueType();
108 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
110 EVT ElVT = VT.getVectorElementType();
111 EVT ResultVT = Result.getValueType();
113 // Insert the relevant 128 bits.
114 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
116 // This is the index of the first element of the 128-bit chunk
118 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
121 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
122 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131 unsigned NumElems, SelectionDAG &DAG,
133 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139 bool is64Bit = Subtarget->is64Bit();
141 if (Subtarget->isTargetEnvMacho()) {
143 return new X86_64MachoTargetObjectFile();
144 return new TargetLoweringObjectFileMachO();
147 if (Subtarget->isTargetLinux())
148 return new X86LinuxTargetObjectFile();
149 if (Subtarget->isTargetELF())
150 return new TargetLoweringObjectFileELF();
151 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152 return new TargetLoweringObjectFileCOFF();
153 llvm_unreachable("unknown subtarget type");
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157 : TargetLowering(TM, createTLOF(TM)) {
158 Subtarget = &TM.getSubtarget<X86Subtarget>();
159 X86ScalarSSEf64 = Subtarget->hasSSE2();
160 X86ScalarSSEf32 = Subtarget->hasSSE1();
161 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
163 RegInfo = TM.getRegisterInfo();
164 TD = getTargetData();
166 // Set up the TargetLowering object.
167 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
169 // X86 is weird, it always uses i8 for shift amounts and setcc results.
170 setBooleanContents(ZeroOrOneBooleanContent);
171 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
172 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174 // For 64-bit since we have so many registers use the ILP scheduler, for
175 // 32-bit code use the register pressure specific scheduling.
176 // For Atom, always use ILP scheduling.
177 if (Subtarget->isAtom())
178 setSchedulingPreference(Sched::ILP);
179 else if (Subtarget->is64Bit())
180 setSchedulingPreference(Sched::ILP);
182 setSchedulingPreference(Sched::RegPressure);
183 setStackPointerRegisterToSaveRestore(X86StackPtr);
185 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
186 // Setup Windows compiler runtime calls.
187 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
188 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
189 setLibcallName(RTLIB::SREM_I64, "_allrem");
190 setLibcallName(RTLIB::UREM_I64, "_aullrem");
191 setLibcallName(RTLIB::MUL_I64, "_allmul");
192 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
193 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
194 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
195 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
196 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
198 // The _ftol2 runtime function has an unusual calling conv, which
199 // is modeled by a special pseudo-instruction.
200 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
201 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
202 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
203 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
206 if (Subtarget->isTargetDarwin()) {
207 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
208 setUseUnderscoreSetJmp(false);
209 setUseUnderscoreLongJmp(false);
210 } else if (Subtarget->isTargetMingw()) {
211 // MS runtime is weird: it exports _setjmp, but longjmp!
212 setUseUnderscoreSetJmp(true);
213 setUseUnderscoreLongJmp(false);
215 setUseUnderscoreSetJmp(true);
216 setUseUnderscoreLongJmp(true);
219 // Set up the register classes.
220 addRegisterClass(MVT::i8, &X86::GR8RegClass);
221 addRegisterClass(MVT::i16, &X86::GR16RegClass);
222 addRegisterClass(MVT::i32, &X86::GR32RegClass);
223 if (Subtarget->is64Bit())
224 addRegisterClass(MVT::i64, &X86::GR64RegClass);
226 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
228 // We don't accept any truncstore of integer registers.
229 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
230 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
231 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
232 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
233 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
234 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
236 // SETOEQ and SETUNE require checking two conditions.
237 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
238 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
239 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
240 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
241 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
242 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
244 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
246 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
247 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
248 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
250 if (Subtarget->is64Bit()) {
251 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
252 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
253 } else if (!TM.Options.UseSoftFloat) {
254 // We have an algorithm for SSE2->double, and we turn this into a
255 // 64-bit FILD followed by conditional FADD for other targets.
256 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
257 // We have an algorithm for SSE2, and we turn this into a 64-bit
258 // FILD for other targets.
259 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
262 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
264 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
265 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
267 if (!TM.Options.UseSoftFloat) {
268 // SSE has no i16 to fp conversion, only i32
269 if (X86ScalarSSEf32) {
270 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
271 // f32 and f64 cases are Legal, f80 case is not
272 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
274 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
275 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
278 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
279 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
282 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
283 // are Legal, f80 is custom lowered.
284 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
285 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
287 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
289 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
290 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
292 if (X86ScalarSSEf32) {
293 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
294 // f32 and f64 cases are Legal, f80 case is not
295 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
297 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
298 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
301 // Handle FP_TO_UINT by promoting the destination to a larger signed
303 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
304 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
305 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
307 if (Subtarget->is64Bit()) {
308 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
309 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
310 } else if (!TM.Options.UseSoftFloat) {
311 // Since AVX is a superset of SSE3, only check for SSE here.
312 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
313 // Expand FP_TO_UINT into a select.
314 // FIXME: We would like to use a Custom expander here eventually to do
315 // the optimal thing for SSE vs. the default expansion in the legalizer.
316 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
318 // With SSE3 we can use fisttpll to convert to a signed i64; without
319 // SSE, we're stuck with a fistpll.
320 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
323 if (isTargetFTOL()) {
324 // Use the _ftol2 runtime function, which has a pseudo-instruction
325 // to handle its weird calling convention.
326 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
329 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
330 if (!X86ScalarSSEf64) {
331 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
332 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
333 if (Subtarget->is64Bit()) {
334 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
335 // Without SSE, i64->f64 goes through memory.
336 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
340 // Scalar integer divide and remainder are lowered to use operations that
341 // produce two results, to match the available instructions. This exposes
342 // the two-result form to trivial CSE, which is able to combine x/y and x%y
343 // into a single instruction.
345 // Scalar integer multiply-high is also lowered to use two-result
346 // operations, to match the available instructions. However, plain multiply
347 // (low) operations are left as Legal, as there are single-result
348 // instructions for this in x86. Using the two-result multiply instructions
349 // when both high and low results are needed must be arranged by dagcombine.
350 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
352 setOperationAction(ISD::MULHS, VT, Expand);
353 setOperationAction(ISD::MULHU, VT, Expand);
354 setOperationAction(ISD::SDIV, VT, Expand);
355 setOperationAction(ISD::UDIV, VT, Expand);
356 setOperationAction(ISD::SREM, VT, Expand);
357 setOperationAction(ISD::UREM, VT, Expand);
359 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
360 setOperationAction(ISD::ADDC, VT, Custom);
361 setOperationAction(ISD::ADDE, VT, Custom);
362 setOperationAction(ISD::SUBC, VT, Custom);
363 setOperationAction(ISD::SUBE, VT, Custom);
366 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
367 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
368 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
369 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
370 if (Subtarget->is64Bit())
371 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
372 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
373 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
375 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
376 setOperationAction(ISD::FREM , MVT::f32 , Expand);
377 setOperationAction(ISD::FREM , MVT::f64 , Expand);
378 setOperationAction(ISD::FREM , MVT::f80 , Expand);
379 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
381 // Promote the i8 variants and force them on up to i32 which has a shorter
383 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
384 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
385 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
386 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
387 if (Subtarget->hasBMI()) {
388 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
389 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
390 if (Subtarget->is64Bit())
391 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
393 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
394 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
395 if (Subtarget->is64Bit())
396 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
399 if (Subtarget->hasLZCNT()) {
400 // When promoting the i8 variants, force them to i32 for a shorter
402 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
403 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
404 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
405 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
406 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
407 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
408 if (Subtarget->is64Bit())
409 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
411 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
412 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
413 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
414 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
415 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
416 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
417 if (Subtarget->is64Bit()) {
418 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
419 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
423 if (Subtarget->hasPOPCNT()) {
424 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
426 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
427 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
428 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
429 if (Subtarget->is64Bit())
430 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
433 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
434 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
436 // These should be promoted to a larger select which is supported.
437 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
438 // X86 wants to expand cmov itself.
439 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
440 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
441 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
442 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
443 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
444 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
445 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
446 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
447 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
448 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
449 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
450 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
451 if (Subtarget->is64Bit()) {
452 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
453 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
455 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
458 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
459 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
460 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
461 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
462 if (Subtarget->is64Bit())
463 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
464 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
465 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
466 if (Subtarget->is64Bit()) {
467 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
468 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
469 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
470 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
471 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
473 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
474 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
475 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
476 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
477 if (Subtarget->is64Bit()) {
478 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
479 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
480 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
483 if (Subtarget->hasSSE1())
484 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
486 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
487 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
489 // On X86 and X86-64, atomic operations are lowered to locked instructions.
490 // Locked instructions, in turn, have implicit fence semantics (all memory
491 // operations are flushed before issuing the locked instruction, and they
492 // are not buffered), so we can fold away the common pattern of
493 // fence-atomic-fence.
494 setShouldFoldAtomicFences(true);
496 // Expand certain atomics
497 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
499 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
500 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
501 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
504 if (!Subtarget->is64Bit()) {
505 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
506 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
507 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
508 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
509 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
510 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
511 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
512 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
515 if (Subtarget->hasCmpxchg16b()) {
516 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
519 // FIXME - use subtarget debug flags
520 if (!Subtarget->isTargetDarwin() &&
521 !Subtarget->isTargetELF() &&
522 !Subtarget->isTargetCygMing()) {
523 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
526 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
527 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
528 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
529 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
530 if (Subtarget->is64Bit()) {
531 setExceptionPointerRegister(X86::RAX);
532 setExceptionSelectorRegister(X86::RDX);
534 setExceptionPointerRegister(X86::EAX);
535 setExceptionSelectorRegister(X86::EDX);
537 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
538 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
540 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
541 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
543 setOperationAction(ISD::TRAP, MVT::Other, Legal);
545 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
546 setOperationAction(ISD::VASTART , MVT::Other, Custom);
547 setOperationAction(ISD::VAEND , MVT::Other, Expand);
548 if (Subtarget->is64Bit()) {
549 setOperationAction(ISD::VAARG , MVT::Other, Custom);
550 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
552 setOperationAction(ISD::VAARG , MVT::Other, Expand);
553 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
556 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
557 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
559 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
560 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
561 MVT::i64 : MVT::i32, Custom);
562 else if (TM.Options.EnableSegmentedStacks)
563 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
564 MVT::i64 : MVT::i32, Custom);
566 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
567 MVT::i64 : MVT::i32, Expand);
569 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
570 // f32 and f64 use SSE.
571 // Set up the FP register classes.
572 addRegisterClass(MVT::f32, &X86::FR32RegClass);
573 addRegisterClass(MVT::f64, &X86::FR64RegClass);
575 // Use ANDPD to simulate FABS.
576 setOperationAction(ISD::FABS , MVT::f64, Custom);
577 setOperationAction(ISD::FABS , MVT::f32, Custom);
579 // Use XORP to simulate FNEG.
580 setOperationAction(ISD::FNEG , MVT::f64, Custom);
581 setOperationAction(ISD::FNEG , MVT::f32, Custom);
583 // Use ANDPD and ORPD to simulate FCOPYSIGN.
584 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
585 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
587 // Lower this to FGETSIGNx86 plus an AND.
588 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
589 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
591 // We don't support sin/cos/fmod
592 setOperationAction(ISD::FSIN , MVT::f64, Expand);
593 setOperationAction(ISD::FCOS , MVT::f64, Expand);
594 setOperationAction(ISD::FSIN , MVT::f32, Expand);
595 setOperationAction(ISD::FCOS , MVT::f32, Expand);
597 // Expand FP immediates into loads from the stack, except for the special
599 addLegalFPImmediate(APFloat(+0.0)); // xorpd
600 addLegalFPImmediate(APFloat(+0.0f)); // xorps
601 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
602 // Use SSE for f32, x87 for f64.
603 // Set up the FP register classes.
604 addRegisterClass(MVT::f32, &X86::FR32RegClass);
605 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
607 // Use ANDPS to simulate FABS.
608 setOperationAction(ISD::FABS , MVT::f32, Custom);
610 // Use XORP to simulate FNEG.
611 setOperationAction(ISD::FNEG , MVT::f32, Custom);
613 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
615 // Use ANDPS and ORPS to simulate FCOPYSIGN.
616 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
617 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
619 // We don't support sin/cos/fmod
620 setOperationAction(ISD::FSIN , MVT::f32, Expand);
621 setOperationAction(ISD::FCOS , MVT::f32, Expand);
623 // Special cases we handle for FP constants.
624 addLegalFPImmediate(APFloat(+0.0f)); // xorps
625 addLegalFPImmediate(APFloat(+0.0)); // FLD0
626 addLegalFPImmediate(APFloat(+1.0)); // FLD1
627 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
628 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
630 if (!TM.Options.UnsafeFPMath) {
631 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
632 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
634 } else if (!TM.Options.UseSoftFloat) {
635 // f32 and f64 in x87.
636 // Set up the FP register classes.
637 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
638 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
640 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
641 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
642 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
643 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
645 if (!TM.Options.UnsafeFPMath) {
646 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
647 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
649 addLegalFPImmediate(APFloat(+0.0)); // FLD0
650 addLegalFPImmediate(APFloat(+1.0)); // FLD1
651 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
652 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
653 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
654 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
655 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
656 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
659 // We don't support FMA.
660 setOperationAction(ISD::FMA, MVT::f64, Expand);
661 setOperationAction(ISD::FMA, MVT::f32, Expand);
663 // Long double always uses X87.
664 if (!TM.Options.UseSoftFloat) {
665 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
666 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
667 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
669 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
670 addLegalFPImmediate(TmpFlt); // FLD0
672 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
675 APFloat TmpFlt2(+1.0);
676 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
678 addLegalFPImmediate(TmpFlt2); // FLD1
679 TmpFlt2.changeSign();
680 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
683 if (!TM.Options.UnsafeFPMath) {
684 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
685 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
688 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
689 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
690 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
691 setOperationAction(ISD::FRINT, MVT::f80, Expand);
692 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
693 setOperationAction(ISD::FMA, MVT::f80, Expand);
696 // Always use a library call for pow.
697 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
698 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
699 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
701 setOperationAction(ISD::FLOG, MVT::f80, Expand);
702 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
703 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
704 setOperationAction(ISD::FEXP, MVT::f80, Expand);
705 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
707 // First set operation action for all vector types to either promote
708 // (for widening) or expand (for scalarization). Then we will selectively
709 // turn on ones that can be effectively codegen'd.
710 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
711 VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
712 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
727 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
729 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
730 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::FMA, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
745 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
746 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
747 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
748 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
749 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
751 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
753 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
756 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
757 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
758 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
759 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
760 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
761 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
762 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
763 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
764 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
765 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
766 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
767 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
768 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
769 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
770 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
771 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
772 setTruncStoreAction((MVT::SimpleValueType)VT,
773 (MVT::SimpleValueType)InnerVT, Expand);
774 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
775 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
776 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
779 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
780 // with -msoft-float, disable use of MMX as well.
781 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
782 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
783 // No operations on x86mmx supported, everything uses intrinsics.
786 // MMX-sized vectors (other than x86mmx) are expected to be expanded
787 // into smaller operations.
788 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
789 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
790 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
791 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
792 setOperationAction(ISD::AND, MVT::v8i8, Expand);
793 setOperationAction(ISD::AND, MVT::v4i16, Expand);
794 setOperationAction(ISD::AND, MVT::v2i32, Expand);
795 setOperationAction(ISD::AND, MVT::v1i64, Expand);
796 setOperationAction(ISD::OR, MVT::v8i8, Expand);
797 setOperationAction(ISD::OR, MVT::v4i16, Expand);
798 setOperationAction(ISD::OR, MVT::v2i32, Expand);
799 setOperationAction(ISD::OR, MVT::v1i64, Expand);
800 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
801 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
802 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
803 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
804 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
805 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
806 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
807 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
808 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
809 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
810 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
811 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
812 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
813 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
814 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
815 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
816 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
818 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
819 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
821 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
822 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
823 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
824 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
825 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
826 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
827 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
828 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
829 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
830 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
831 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
832 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
835 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
836 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
838 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
839 // registers cannot be used even for integer operations.
840 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
841 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
842 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
843 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
845 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
846 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
847 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
848 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
849 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
850 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
851 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
852 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
853 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
854 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
855 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
856 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
857 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
858 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
859 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
860 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
862 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
863 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
864 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
865 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
867 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
868 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
869 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
870 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
871 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
873 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
874 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
875 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
876 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
877 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
879 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
880 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
881 EVT VT = (MVT::SimpleValueType)i;
882 // Do not attempt to custom lower non-power-of-2 vectors
883 if (!isPowerOf2_32(VT.getVectorNumElements()))
885 // Do not attempt to custom lower non-128-bit vectors
886 if (!VT.is128BitVector())
888 setOperationAction(ISD::BUILD_VECTOR,
889 VT.getSimpleVT().SimpleTy, Custom);
890 setOperationAction(ISD::VECTOR_SHUFFLE,
891 VT.getSimpleVT().SimpleTy, Custom);
892 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
893 VT.getSimpleVT().SimpleTy, Custom);
896 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
897 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
898 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
899 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
900 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
901 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
903 if (Subtarget->is64Bit()) {
904 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
905 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
908 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
909 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
910 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
913 // Do not attempt to promote non-128-bit vectors
914 if (!VT.is128BitVector())
917 setOperationAction(ISD::AND, SVT, Promote);
918 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
919 setOperationAction(ISD::OR, SVT, Promote);
920 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
921 setOperationAction(ISD::XOR, SVT, Promote);
922 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
923 setOperationAction(ISD::LOAD, SVT, Promote);
924 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
925 setOperationAction(ISD::SELECT, SVT, Promote);
926 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
929 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
931 // Custom lower v2i64 and v2f64 selects.
932 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
933 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
934 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
935 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
937 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
938 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
941 if (Subtarget->hasSSE41()) {
942 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
943 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
944 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
945 setOperationAction(ISD::FRINT, MVT::f32, Legal);
946 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
947 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
948 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
949 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
950 setOperationAction(ISD::FRINT, MVT::f64, Legal);
951 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
953 // FIXME: Do we need to handle scalar-to-vector here?
954 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
956 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
957 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
958 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
959 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
960 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
962 // i8 and i16 vectors are custom , because the source register and source
963 // source memory operand types are not the same width. f32 vectors are
964 // custom since the immediate controlling the insert encodes additional
966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
969 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
971 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
972 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
973 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
974 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
976 // FIXME: these should be Legal but thats only for the case where
977 // the index is constant. For now custom expand to deal with that.
978 if (Subtarget->is64Bit()) {
979 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
980 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
984 if (Subtarget->hasSSE2()) {
985 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
986 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
988 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
989 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
991 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
992 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
994 if (Subtarget->hasAVX2()) {
995 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
996 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
998 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
999 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1001 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1003 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1004 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1006 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1007 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1009 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1013 if (Subtarget->hasSSE42())
1014 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1016 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1017 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1018 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1019 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1020 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1021 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1022 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1024 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1025 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1026 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1028 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1029 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1030 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1031 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1032 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1033 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1035 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1036 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1037 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1038 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1039 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1040 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1042 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1043 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1044 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1046 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1047 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1049 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1050 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1052 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1053 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1055 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1056 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1057 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1058 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1060 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1061 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1062 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1064 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1065 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1066 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1067 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1069 if (Subtarget->hasFMA()) {
1070 setOperationAction(ISD::FMA, MVT::v8f32, Custom);
1071 setOperationAction(ISD::FMA, MVT::v4f64, Custom);
1072 setOperationAction(ISD::FMA, MVT::v4f32, Custom);
1073 setOperationAction(ISD::FMA, MVT::v2f64, Custom);
1074 setOperationAction(ISD::FMA, MVT::f32, Custom);
1075 setOperationAction(ISD::FMA, MVT::f64, Custom);
1078 if (Subtarget->hasAVX2()) {
1079 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1080 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1081 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1082 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1084 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1085 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1086 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1087 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1089 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1090 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1091 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1092 // Don't lower v32i8 because there is no 128-bit byte mul
1094 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1096 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1097 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1099 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1100 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1102 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1104 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1105 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1106 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1107 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1109 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1110 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1111 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1112 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1114 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1115 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1116 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1117 // Don't lower v32i8 because there is no 128-bit byte mul
1119 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1120 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1122 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1123 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1125 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1128 // Custom lower several nodes for 256-bit types.
1129 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1130 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1131 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1134 // Extract subvector is special because the value type
1135 // (result) is 128-bit but the source is 256-bit wide.
1136 if (VT.is128BitVector())
1137 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1139 // Do not attempt to custom lower other non-256-bit vectors
1140 if (!VT.is256BitVector())
1143 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1144 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1145 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1146 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1147 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1148 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1149 setOperationAction(ISD::CONCAT_VECTORS, SVT, Custom);
1152 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1153 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1154 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1157 // Do not attempt to promote non-256-bit vectors
1158 if (!VT.is256BitVector())
1161 setOperationAction(ISD::AND, SVT, Promote);
1162 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1163 setOperationAction(ISD::OR, SVT, Promote);
1164 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1165 setOperationAction(ISD::XOR, SVT, Promote);
1166 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1167 setOperationAction(ISD::LOAD, SVT, Promote);
1168 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1169 setOperationAction(ISD::SELECT, SVT, Promote);
1170 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1174 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1175 // of this type with custom code.
1176 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1177 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1178 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1182 // We want to custom lower some of our intrinsics.
1183 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1184 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1187 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1188 // handle type legalization for these operations here.
1190 // FIXME: We really should do custom legalization for addition and
1191 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1192 // than generic legalization for 64-bit multiplication-with-overflow, though.
1193 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1194 // Add/Sub/Mul with overflow operations are custom lowered.
1196 setOperationAction(ISD::SADDO, VT, Custom);
1197 setOperationAction(ISD::UADDO, VT, Custom);
1198 setOperationAction(ISD::SSUBO, VT, Custom);
1199 setOperationAction(ISD::USUBO, VT, Custom);
1200 setOperationAction(ISD::SMULO, VT, Custom);
1201 setOperationAction(ISD::UMULO, VT, Custom);
1204 // There are no 8-bit 3-address imul/mul instructions
1205 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1206 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1208 if (!Subtarget->is64Bit()) {
1209 // These libcalls are not available in 32-bit.
1210 setLibcallName(RTLIB::SHL_I128, 0);
1211 setLibcallName(RTLIB::SRL_I128, 0);
1212 setLibcallName(RTLIB::SRA_I128, 0);
1215 // We have target-specific dag combine patterns for the following nodes:
1216 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1217 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1218 setTargetDAGCombine(ISD::VSELECT);
1219 setTargetDAGCombine(ISD::SELECT);
1220 setTargetDAGCombine(ISD::SHL);
1221 setTargetDAGCombine(ISD::SRA);
1222 setTargetDAGCombine(ISD::SRL);
1223 setTargetDAGCombine(ISD::OR);
1224 setTargetDAGCombine(ISD::AND);
1225 setTargetDAGCombine(ISD::ADD);
1226 setTargetDAGCombine(ISD::FADD);
1227 setTargetDAGCombine(ISD::FSUB);
1228 setTargetDAGCombine(ISD::FMA);
1229 setTargetDAGCombine(ISD::SUB);
1230 setTargetDAGCombine(ISD::LOAD);
1231 setTargetDAGCombine(ISD::STORE);
1232 setTargetDAGCombine(ISD::ZERO_EXTEND);
1233 setTargetDAGCombine(ISD::ANY_EXTEND);
1234 setTargetDAGCombine(ISD::SIGN_EXTEND);
1235 setTargetDAGCombine(ISD::TRUNCATE);
1236 setTargetDAGCombine(ISD::UINT_TO_FP);
1237 setTargetDAGCombine(ISD::SINT_TO_FP);
1238 setTargetDAGCombine(ISD::SETCC);
1239 setTargetDAGCombine(ISD::FP_TO_SINT);
1240 if (Subtarget->is64Bit())
1241 setTargetDAGCombine(ISD::MUL);
1242 setTargetDAGCombine(ISD::XOR);
1244 computeRegisterProperties();
1246 // On Darwin, -Os means optimize for size without hurting performance,
1247 // do not reduce the limit.
1248 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1249 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1250 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1251 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1252 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1253 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1254 setPrefLoopAlignment(4); // 2^4 bytes.
1255 benefitFromCodePlacementOpt = true;
1257 // Predictable cmov don't hurt on atom because it's in-order.
1258 predictableSelectIsExpensive = !Subtarget->isAtom();
1260 setPrefFunctionAlignment(4); // 2^4 bytes.
1264 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1265 if (!VT.isVector()) return MVT::i8;
1266 return VT.changeVectorElementTypeToInteger();
1270 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1271 /// the desired ByVal argument alignment.
1272 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1275 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1276 if (VTy->getBitWidth() == 128)
1278 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1279 unsigned EltAlign = 0;
1280 getMaxByValAlign(ATy->getElementType(), EltAlign);
1281 if (EltAlign > MaxAlign)
1282 MaxAlign = EltAlign;
1283 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1284 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1285 unsigned EltAlign = 0;
1286 getMaxByValAlign(STy->getElementType(i), EltAlign);
1287 if (EltAlign > MaxAlign)
1288 MaxAlign = EltAlign;
1295 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1296 /// function arguments in the caller parameter area. For X86, aggregates
1297 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1298 /// are at 4-byte boundaries.
1299 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1300 if (Subtarget->is64Bit()) {
1301 // Max of 8 and alignment of type.
1302 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1309 if (Subtarget->hasSSE1())
1310 getMaxByValAlign(Ty, Align);
1314 /// getOptimalMemOpType - Returns the target specific optimal type for load
1315 /// and store operations as a result of memset, memcpy, and memmove
1316 /// lowering. If DstAlign is zero that means it's safe to destination
1317 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1318 /// means there isn't a need to check it against alignment requirement,
1319 /// probably because the source does not need to be loaded. If
1320 /// 'IsZeroVal' is true, that means it's safe to return a
1321 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1322 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1323 /// constant so it does not need to be loaded.
1324 /// It returns EVT::Other if the type should be determined using generic
1325 /// target-independent logic.
1327 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1328 unsigned DstAlign, unsigned SrcAlign,
1331 MachineFunction &MF) const {
1332 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1333 // linux. This is because the stack realignment code can't handle certain
1334 // cases like PR2962. This should be removed when PR2962 is fixed.
1335 const Function *F = MF.getFunction();
1337 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1339 (Subtarget->isUnalignedMemAccessFast() ||
1340 ((DstAlign == 0 || DstAlign >= 16) &&
1341 (SrcAlign == 0 || SrcAlign >= 16))) &&
1342 Subtarget->getStackAlignment() >= 16) {
1343 if (Subtarget->getStackAlignment() >= 32) {
1344 if (Subtarget->hasAVX2())
1346 if (Subtarget->hasAVX())
1349 if (Subtarget->hasSSE2())
1351 if (Subtarget->hasSSE1())
1353 } else if (!MemcpyStrSrc && Size >= 8 &&
1354 !Subtarget->is64Bit() &&
1355 Subtarget->getStackAlignment() >= 8 &&
1356 Subtarget->hasSSE2()) {
1357 // Do not use f64 to lower memcpy if source is string constant. It's
1358 // better to use i32 to avoid the loads.
1362 if (Subtarget->is64Bit() && Size >= 8)
1367 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1368 /// current function. The returned value is a member of the
1369 /// MachineJumpTableInfo::JTEntryKind enum.
1370 unsigned X86TargetLowering::getJumpTableEncoding() const {
1371 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1373 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1374 Subtarget->isPICStyleGOT())
1375 return MachineJumpTableInfo::EK_Custom32;
1377 // Otherwise, use the normal jump table encoding heuristics.
1378 return TargetLowering::getJumpTableEncoding();
1382 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1383 const MachineBasicBlock *MBB,
1384 unsigned uid,MCContext &Ctx) const{
1385 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1386 Subtarget->isPICStyleGOT());
1387 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1389 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1390 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1393 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1395 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1396 SelectionDAG &DAG) const {
1397 if (!Subtarget->is64Bit())
1398 // This doesn't have DebugLoc associated with it, but is not really the
1399 // same as a Register.
1400 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1404 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1405 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1407 const MCExpr *X86TargetLowering::
1408 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1409 MCContext &Ctx) const {
1410 // X86-64 uses RIP relative addressing based on the jump table label.
1411 if (Subtarget->isPICStyleRIPRel())
1412 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1414 // Otherwise, the reference is relative to the PIC base.
1415 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1418 // FIXME: Why this routine is here? Move to RegInfo!
1419 std::pair<const TargetRegisterClass*, uint8_t>
1420 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1421 const TargetRegisterClass *RRC = 0;
1423 switch (VT.getSimpleVT().SimpleTy) {
1425 return TargetLowering::findRepresentativeClass(VT);
1426 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1427 RRC = Subtarget->is64Bit() ?
1428 (const TargetRegisterClass*)&X86::GR64RegClass :
1429 (const TargetRegisterClass*)&X86::GR32RegClass;
1432 RRC = &X86::VR64RegClass;
1434 case MVT::f32: case MVT::f64:
1435 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1436 case MVT::v4f32: case MVT::v2f64:
1437 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1439 RRC = &X86::VR128RegClass;
1442 return std::make_pair(RRC, Cost);
1445 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1446 unsigned &Offset) const {
1447 if (!Subtarget->isTargetLinux())
1450 if (Subtarget->is64Bit()) {
1451 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1453 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1466 //===----------------------------------------------------------------------===//
1467 // Return Value Calling Convention Implementation
1468 //===----------------------------------------------------------------------===//
1470 #include "X86GenCallingConv.inc"
1473 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1474 MachineFunction &MF, bool isVarArg,
1475 const SmallVectorImpl<ISD::OutputArg> &Outs,
1476 LLVMContext &Context) const {
1477 SmallVector<CCValAssign, 16> RVLocs;
1478 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1480 return CCInfo.CheckReturn(Outs, RetCC_X86);
1484 X86TargetLowering::LowerReturn(SDValue Chain,
1485 CallingConv::ID CallConv, bool isVarArg,
1486 const SmallVectorImpl<ISD::OutputArg> &Outs,
1487 const SmallVectorImpl<SDValue> &OutVals,
1488 DebugLoc dl, SelectionDAG &DAG) const {
1489 MachineFunction &MF = DAG.getMachineFunction();
1490 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1492 SmallVector<CCValAssign, 16> RVLocs;
1493 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1494 RVLocs, *DAG.getContext());
1495 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1497 // Add the regs to the liveout set for the function.
1498 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1499 for (unsigned i = 0; i != RVLocs.size(); ++i)
1500 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1501 MRI.addLiveOut(RVLocs[i].getLocReg());
1505 SmallVector<SDValue, 6> RetOps;
1506 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1507 // Operand #1 = Bytes To Pop
1508 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1511 // Copy the result values into the output registers.
1512 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1513 CCValAssign &VA = RVLocs[i];
1514 assert(VA.isRegLoc() && "Can only return in registers!");
1515 SDValue ValToCopy = OutVals[i];
1516 EVT ValVT = ValToCopy.getValueType();
1518 // Promote values to the appropriate types
1519 if (VA.getLocInfo() == CCValAssign::SExt)
1520 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1521 else if (VA.getLocInfo() == CCValAssign::ZExt)
1522 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1523 else if (VA.getLocInfo() == CCValAssign::AExt)
1524 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1525 else if (VA.getLocInfo() == CCValAssign::BCvt)
1526 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1528 // If this is x86-64, and we disabled SSE, we can't return FP values,
1529 // or SSE or MMX vectors.
1530 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1531 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1532 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1533 report_fatal_error("SSE register return with SSE disabled");
1535 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1536 // llvm-gcc has never done it right and no one has noticed, so this
1537 // should be OK for now.
1538 if (ValVT == MVT::f64 &&
1539 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1540 report_fatal_error("SSE2 register return with SSE2 disabled");
1542 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1543 // the RET instruction and handled by the FP Stackifier.
1544 if (VA.getLocReg() == X86::ST0 ||
1545 VA.getLocReg() == X86::ST1) {
1546 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1547 // change the value to the FP stack register class.
1548 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1549 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1550 RetOps.push_back(ValToCopy);
1551 // Don't emit a copytoreg.
1555 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1556 // which is returned in RAX / RDX.
1557 if (Subtarget->is64Bit()) {
1558 if (ValVT == MVT::x86mmx) {
1559 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1560 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1561 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1563 // If we don't have SSE2 available, convert to v4f32 so the generated
1564 // register is legal.
1565 if (!Subtarget->hasSSE2())
1566 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1571 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1572 Flag = Chain.getValue(1);
1575 // The x86-64 ABI for returning structs by value requires that we copy
1576 // the sret argument into %rax for the return. We saved the argument into
1577 // a virtual register in the entry block, so now we copy the value out
1579 if (Subtarget->is64Bit() &&
1580 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1581 MachineFunction &MF = DAG.getMachineFunction();
1582 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1583 unsigned Reg = FuncInfo->getSRetReturnReg();
1585 "SRetReturnReg should have been set in LowerFormalArguments().");
1586 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1588 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1589 Flag = Chain.getValue(1);
1591 // RAX now acts like a return value.
1592 MRI.addLiveOut(X86::RAX);
1595 RetOps[0] = Chain; // Update chain.
1597 // Add the flag if we have it.
1599 RetOps.push_back(Flag);
1601 return DAG.getNode(X86ISD::RET_FLAG, dl,
1602 MVT::Other, &RetOps[0], RetOps.size());
1605 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1606 if (N->getNumValues() != 1)
1608 if (!N->hasNUsesOfValue(1, 0))
1611 SDValue TCChain = Chain;
1612 SDNode *Copy = *N->use_begin();
1613 if (Copy->getOpcode() == ISD::CopyToReg) {
1614 // If the copy has a glue operand, we conservatively assume it isn't safe to
1615 // perform a tail call.
1616 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1618 TCChain = Copy->getOperand(0);
1619 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1622 bool HasRet = false;
1623 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1625 if (UI->getOpcode() != X86ISD::RET_FLAG)
1638 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1639 ISD::NodeType ExtendKind) const {
1641 // TODO: Is this also valid on 32-bit?
1642 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1643 ReturnMVT = MVT::i8;
1645 ReturnMVT = MVT::i32;
1647 EVT MinVT = getRegisterType(Context, ReturnMVT);
1648 return VT.bitsLT(MinVT) ? MinVT : VT;
1651 /// LowerCallResult - Lower the result values of a call into the
1652 /// appropriate copies out of appropriate physical registers.
1655 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1656 CallingConv::ID CallConv, bool isVarArg,
1657 const SmallVectorImpl<ISD::InputArg> &Ins,
1658 DebugLoc dl, SelectionDAG &DAG,
1659 SmallVectorImpl<SDValue> &InVals) const {
1661 // Assign locations to each value returned by this call.
1662 SmallVector<CCValAssign, 16> RVLocs;
1663 bool Is64Bit = Subtarget->is64Bit();
1664 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1665 getTargetMachine(), RVLocs, *DAG.getContext());
1666 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1668 // Copy all of the result registers out of their specified physreg.
1669 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1670 CCValAssign &VA = RVLocs[i];
1671 EVT CopyVT = VA.getValVT();
1673 // If this is x86-64, and we disabled SSE, we can't return FP values
1674 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1675 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1676 report_fatal_error("SSE register return with SSE disabled");
1681 // If this is a call to a function that returns an fp value on the floating
1682 // point stack, we must guarantee the value is popped from the stack, so
1683 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1684 // if the return value is not used. We use the FpPOP_RETVAL instruction
1686 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1687 // If we prefer to use the value in xmm registers, copy it out as f80 and
1688 // use a truncate to move it from fp stack reg to xmm reg.
1689 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1690 SDValue Ops[] = { Chain, InFlag };
1691 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1692 MVT::Other, MVT::Glue, Ops, 2), 1);
1693 Val = Chain.getValue(0);
1695 // Round the f80 to the right size, which also moves it to the appropriate
1697 if (CopyVT != VA.getValVT())
1698 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1699 // This truncation won't change the value.
1700 DAG.getIntPtrConstant(1));
1702 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1703 CopyVT, InFlag).getValue(1);
1704 Val = Chain.getValue(0);
1706 InFlag = Chain.getValue(2);
1707 InVals.push_back(Val);
1714 //===----------------------------------------------------------------------===//
1715 // C & StdCall & Fast Calling Convention implementation
1716 //===----------------------------------------------------------------------===//
1717 // StdCall calling convention seems to be standard for many Windows' API
1718 // routines and around. It differs from C calling convention just a little:
1719 // callee should clean up the stack, not caller. Symbols should be also
1720 // decorated in some fancy way :) It doesn't support any vector arguments.
1721 // For info on fast calling convention see Fast Calling Convention (tail call)
1722 // implementation LowerX86_32FastCCCallTo.
1724 /// CallIsStructReturn - Determines whether a call uses struct return
1726 enum StructReturnType {
1731 static StructReturnType
1732 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1734 return NotStructReturn;
1736 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1737 if (!Flags.isSRet())
1738 return NotStructReturn;
1739 if (Flags.isInReg())
1740 return RegStructReturn;
1741 return StackStructReturn;
1744 /// ArgsAreStructReturn - Determines whether a function uses struct
1745 /// return semantics.
1746 static StructReturnType
1747 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1749 return NotStructReturn;
1751 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1752 if (!Flags.isSRet())
1753 return NotStructReturn;
1754 if (Flags.isInReg())
1755 return RegStructReturn;
1756 return StackStructReturn;
1759 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1760 /// by "Src" to address "Dst" with size and alignment information specified by
1761 /// the specific parameter attribute. The copy will be passed as a byval
1762 /// function parameter.
1764 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1765 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1767 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1769 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1770 /*isVolatile*/false, /*AlwaysInline=*/true,
1771 MachinePointerInfo(), MachinePointerInfo());
1774 /// IsTailCallConvention - Return true if the calling convention is one that
1775 /// supports tail call optimization.
1776 static bool IsTailCallConvention(CallingConv::ID CC) {
1777 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1780 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1781 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1785 CallingConv::ID CalleeCC = CS.getCallingConv();
1786 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1792 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1793 /// a tailcall target by changing its ABI.
1794 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1795 bool GuaranteedTailCallOpt) {
1796 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1800 X86TargetLowering::LowerMemArgument(SDValue Chain,
1801 CallingConv::ID CallConv,
1802 const SmallVectorImpl<ISD::InputArg> &Ins,
1803 DebugLoc dl, SelectionDAG &DAG,
1804 const CCValAssign &VA,
1805 MachineFrameInfo *MFI,
1807 // Create the nodes corresponding to a load from this parameter slot.
1808 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1809 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1810 getTargetMachine().Options.GuaranteedTailCallOpt);
1811 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1814 // If value is passed by pointer we have address passed instead of the value
1816 if (VA.getLocInfo() == CCValAssign::Indirect)
1817 ValVT = VA.getLocVT();
1819 ValVT = VA.getValVT();
1821 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1822 // changed with more analysis.
1823 // In case of tail call optimization mark all arguments mutable. Since they
1824 // could be overwritten by lowering of arguments in case of a tail call.
1825 if (Flags.isByVal()) {
1826 unsigned Bytes = Flags.getByValSize();
1827 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1828 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1829 return DAG.getFrameIndex(FI, getPointerTy());
1831 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1832 VA.getLocMemOffset(), isImmutable);
1833 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1834 return DAG.getLoad(ValVT, dl, Chain, FIN,
1835 MachinePointerInfo::getFixedStack(FI),
1836 false, false, false, 0);
1841 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1842 CallingConv::ID CallConv,
1844 const SmallVectorImpl<ISD::InputArg> &Ins,
1847 SmallVectorImpl<SDValue> &InVals)
1849 MachineFunction &MF = DAG.getMachineFunction();
1850 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1852 const Function* Fn = MF.getFunction();
1853 if (Fn->hasExternalLinkage() &&
1854 Subtarget->isTargetCygMing() &&
1855 Fn->getName() == "main")
1856 FuncInfo->setForceFramePointer(true);
1858 MachineFrameInfo *MFI = MF.getFrameInfo();
1859 bool Is64Bit = Subtarget->is64Bit();
1860 bool IsWindows = Subtarget->isTargetWindows();
1861 bool IsWin64 = Subtarget->isTargetWin64();
1863 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1864 "Var args not supported with calling convention fastcc or ghc");
1866 // Assign locations to all of the incoming arguments.
1867 SmallVector<CCValAssign, 16> ArgLocs;
1868 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1869 ArgLocs, *DAG.getContext());
1871 // Allocate shadow area for Win64
1873 CCInfo.AllocateStack(32, 8);
1876 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1878 unsigned LastVal = ~0U;
1880 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1881 CCValAssign &VA = ArgLocs[i];
1882 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1884 assert(VA.getValNo() != LastVal &&
1885 "Don't support value assigned to multiple locs yet");
1887 LastVal = VA.getValNo();
1889 if (VA.isRegLoc()) {
1890 EVT RegVT = VA.getLocVT();
1891 const TargetRegisterClass *RC;
1892 if (RegVT == MVT::i32)
1893 RC = &X86::GR32RegClass;
1894 else if (Is64Bit && RegVT == MVT::i64)
1895 RC = &X86::GR64RegClass;
1896 else if (RegVT == MVT::f32)
1897 RC = &X86::FR32RegClass;
1898 else if (RegVT == MVT::f64)
1899 RC = &X86::FR64RegClass;
1900 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1901 RC = &X86::VR256RegClass;
1902 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1903 RC = &X86::VR128RegClass;
1904 else if (RegVT == MVT::x86mmx)
1905 RC = &X86::VR64RegClass;
1907 llvm_unreachable("Unknown argument type!");
1909 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1910 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1912 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1913 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1915 if (VA.getLocInfo() == CCValAssign::SExt)
1916 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1917 DAG.getValueType(VA.getValVT()));
1918 else if (VA.getLocInfo() == CCValAssign::ZExt)
1919 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1920 DAG.getValueType(VA.getValVT()));
1921 else if (VA.getLocInfo() == CCValAssign::BCvt)
1922 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1924 if (VA.isExtInLoc()) {
1925 // Handle MMX values passed in XMM regs.
1926 if (RegVT.isVector()) {
1927 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1930 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1933 assert(VA.isMemLoc());
1934 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1937 // If value is passed via pointer - do a load.
1938 if (VA.getLocInfo() == CCValAssign::Indirect)
1939 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1940 MachinePointerInfo(), false, false, false, 0);
1942 InVals.push_back(ArgValue);
1945 // The x86-64 ABI for returning structs by value requires that we copy
1946 // the sret argument into %rax for the return. Save the argument into
1947 // a virtual register so that we can access it from the return points.
1948 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1949 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1950 unsigned Reg = FuncInfo->getSRetReturnReg();
1952 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1953 FuncInfo->setSRetReturnReg(Reg);
1955 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1956 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1959 unsigned StackSize = CCInfo.getNextStackOffset();
1960 // Align stack specially for tail calls.
1961 if (FuncIsMadeTailCallSafe(CallConv,
1962 MF.getTarget().Options.GuaranteedTailCallOpt))
1963 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1965 // If the function takes variable number of arguments, make a frame index for
1966 // the start of the first vararg value... for expansion of llvm.va_start.
1968 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1969 CallConv != CallingConv::X86_ThisCall)) {
1970 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1973 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1975 // FIXME: We should really autogenerate these arrays
1976 static const uint16_t GPR64ArgRegsWin64[] = {
1977 X86::RCX, X86::RDX, X86::R8, X86::R9
1979 static const uint16_t GPR64ArgRegs64Bit[] = {
1980 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1982 static const uint16_t XMMArgRegs64Bit[] = {
1983 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1984 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1986 const uint16_t *GPR64ArgRegs;
1987 unsigned NumXMMRegs = 0;
1990 // The XMM registers which might contain var arg parameters are shadowed
1991 // in their paired GPR. So we only need to save the GPR to their home
1993 TotalNumIntRegs = 4;
1994 GPR64ArgRegs = GPR64ArgRegsWin64;
1996 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1997 GPR64ArgRegs = GPR64ArgRegs64Bit;
1999 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2002 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2005 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
2006 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2007 "SSE register cannot be used when SSE is disabled!");
2008 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2009 NoImplicitFloatOps) &&
2010 "SSE register cannot be used when SSE is disabled!");
2011 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2012 !Subtarget->hasSSE1())
2013 // Kernel mode asks for SSE to be disabled, so don't push them
2015 TotalNumXMMRegs = 0;
2018 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2019 // Get to the caller-allocated home save location. Add 8 to account
2020 // for the return address.
2021 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2022 FuncInfo->setRegSaveFrameIndex(
2023 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2024 // Fixup to set vararg frame on shadow area (4 x i64).
2026 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2028 // For X86-64, if there are vararg parameters that are passed via
2029 // registers, then we must store them to their spots on the stack so
2030 // they may be loaded by deferencing the result of va_next.
2031 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2032 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2033 FuncInfo->setRegSaveFrameIndex(
2034 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2038 // Store the integer parameter registers.
2039 SmallVector<SDValue, 8> MemOps;
2040 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2042 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2043 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2044 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2045 DAG.getIntPtrConstant(Offset));
2046 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2047 &X86::GR64RegClass);
2048 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2050 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2051 MachinePointerInfo::getFixedStack(
2052 FuncInfo->getRegSaveFrameIndex(), Offset),
2054 MemOps.push_back(Store);
2058 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2059 // Now store the XMM (fp + vector) parameter registers.
2060 SmallVector<SDValue, 11> SaveXMMOps;
2061 SaveXMMOps.push_back(Chain);
2063 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2064 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2065 SaveXMMOps.push_back(ALVal);
2067 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2068 FuncInfo->getRegSaveFrameIndex()));
2069 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2070 FuncInfo->getVarArgsFPOffset()));
2072 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2073 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2074 &X86::VR128RegClass);
2075 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2076 SaveXMMOps.push_back(Val);
2078 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2080 &SaveXMMOps[0], SaveXMMOps.size()));
2083 if (!MemOps.empty())
2084 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2085 &MemOps[0], MemOps.size());
2089 // Some CCs need callee pop.
2090 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2091 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2092 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2094 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2095 // If this is an sret function, the return should pop the hidden pointer.
2096 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2097 argsAreStructReturn(Ins) == StackStructReturn)
2098 FuncInfo->setBytesToPopOnReturn(4);
2102 // RegSaveFrameIndex is X86-64 only.
2103 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2104 if (CallConv == CallingConv::X86_FastCall ||
2105 CallConv == CallingConv::X86_ThisCall)
2106 // fastcc functions can't have varargs.
2107 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2110 FuncInfo->setArgumentStackSize(StackSize);
2116 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2117 SDValue StackPtr, SDValue Arg,
2118 DebugLoc dl, SelectionDAG &DAG,
2119 const CCValAssign &VA,
2120 ISD::ArgFlagsTy Flags) const {
2121 unsigned LocMemOffset = VA.getLocMemOffset();
2122 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2123 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2124 if (Flags.isByVal())
2125 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2127 return DAG.getStore(Chain, dl, Arg, PtrOff,
2128 MachinePointerInfo::getStack(LocMemOffset),
2132 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2133 /// optimization is performed and it is required.
2135 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2136 SDValue &OutRetAddr, SDValue Chain,
2137 bool IsTailCall, bool Is64Bit,
2138 int FPDiff, DebugLoc dl) const {
2139 // Adjust the Return address stack slot.
2140 EVT VT = getPointerTy();
2141 OutRetAddr = getReturnAddressFrameIndex(DAG);
2143 // Load the "old" Return address.
2144 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2145 false, false, false, 0);
2146 return SDValue(OutRetAddr.getNode(), 1);
2149 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2150 /// optimization is performed and it is required (FPDiff!=0).
2152 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2153 SDValue Chain, SDValue RetAddrFrIdx,
2154 bool Is64Bit, int FPDiff, DebugLoc dl) {
2155 // Store the return address to the appropriate stack slot.
2156 if (!FPDiff) return Chain;
2157 // Calculate the new stack slot for the return address.
2158 int SlotSize = Is64Bit ? 8 : 4;
2159 int NewReturnAddrFI =
2160 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2161 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2162 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2163 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2164 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2170 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2171 SmallVectorImpl<SDValue> &InVals) const {
2172 SelectionDAG &DAG = CLI.DAG;
2173 DebugLoc &dl = CLI.DL;
2174 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2175 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2176 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2177 SDValue Chain = CLI.Chain;
2178 SDValue Callee = CLI.Callee;
2179 CallingConv::ID CallConv = CLI.CallConv;
2180 bool &isTailCall = CLI.IsTailCall;
2181 bool isVarArg = CLI.IsVarArg;
2183 MachineFunction &MF = DAG.getMachineFunction();
2184 bool Is64Bit = Subtarget->is64Bit();
2185 bool IsWin64 = Subtarget->isTargetWin64();
2186 bool IsWindows = Subtarget->isTargetWindows();
2187 StructReturnType SR = callIsStructReturn(Outs);
2188 bool IsSibcall = false;
2190 if (MF.getTarget().Options.DisableTailCalls)
2194 // Check if it's really possible to do a tail call.
2195 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2196 isVarArg, SR != NotStructReturn,
2197 MF.getFunction()->hasStructRetAttr(),
2198 Outs, OutVals, Ins, DAG);
2200 // Sibcalls are automatically detected tailcalls which do not require
2202 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2209 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2210 "Var args not supported with calling convention fastcc or ghc");
2212 // Analyze operands of the call, assigning locations to each operand.
2213 SmallVector<CCValAssign, 16> ArgLocs;
2214 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2215 ArgLocs, *DAG.getContext());
2217 // Allocate shadow area for Win64
2219 CCInfo.AllocateStack(32, 8);
2222 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2224 // Get a count of how many bytes are to be pushed on the stack.
2225 unsigned NumBytes = CCInfo.getNextStackOffset();
2227 // This is a sibcall. The memory operands are available in caller's
2228 // own caller's stack.
2230 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2231 IsTailCallConvention(CallConv))
2232 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2235 if (isTailCall && !IsSibcall) {
2236 // Lower arguments at fp - stackoffset + fpdiff.
2237 unsigned NumBytesCallerPushed =
2238 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2239 FPDiff = NumBytesCallerPushed - NumBytes;
2241 // Set the delta of movement of the returnaddr stackslot.
2242 // But only set if delta is greater than previous delta.
2243 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2244 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2248 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2250 SDValue RetAddrFrIdx;
2251 // Load return address for tail calls.
2252 if (isTailCall && FPDiff)
2253 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2254 Is64Bit, FPDiff, dl);
2256 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2257 SmallVector<SDValue, 8> MemOpChains;
2260 // Walk the register/memloc assignments, inserting copies/loads. In the case
2261 // of tail call optimization arguments are handle later.
2262 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2263 CCValAssign &VA = ArgLocs[i];
2264 EVT RegVT = VA.getLocVT();
2265 SDValue Arg = OutVals[i];
2266 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2267 bool isByVal = Flags.isByVal();
2269 // Promote the value if needed.
2270 switch (VA.getLocInfo()) {
2271 default: llvm_unreachable("Unknown loc info!");
2272 case CCValAssign::Full: break;
2273 case CCValAssign::SExt:
2274 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2276 case CCValAssign::ZExt:
2277 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2279 case CCValAssign::AExt:
2280 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2281 // Special case: passing MMX values in XMM registers.
2282 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2283 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2284 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2286 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2288 case CCValAssign::BCvt:
2289 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2291 case CCValAssign::Indirect: {
2292 // Store the argument.
2293 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2294 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2295 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2296 MachinePointerInfo::getFixedStack(FI),
2303 if (VA.isRegLoc()) {
2304 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2305 if (isVarArg && IsWin64) {
2306 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2307 // shadow reg if callee is a varargs function.
2308 unsigned ShadowReg = 0;
2309 switch (VA.getLocReg()) {
2310 case X86::XMM0: ShadowReg = X86::RCX; break;
2311 case X86::XMM1: ShadowReg = X86::RDX; break;
2312 case X86::XMM2: ShadowReg = X86::R8; break;
2313 case X86::XMM3: ShadowReg = X86::R9; break;
2316 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2318 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2319 assert(VA.isMemLoc());
2320 if (StackPtr.getNode() == 0)
2321 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2322 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2323 dl, DAG, VA, Flags));
2327 if (!MemOpChains.empty())
2328 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2329 &MemOpChains[0], MemOpChains.size());
2331 if (Subtarget->isPICStyleGOT()) {
2332 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2335 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2336 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2338 // If we are tail calling and generating PIC/GOT style code load the
2339 // address of the callee into ECX. The value in ecx is used as target of
2340 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2341 // for tail calls on PIC/GOT architectures. Normally we would just put the
2342 // address of GOT into ebx and then call target@PLT. But for tail calls
2343 // ebx would be restored (since ebx is callee saved) before jumping to the
2346 // Note: The actual moving to ECX is done further down.
2347 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2348 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2349 !G->getGlobal()->hasProtectedVisibility())
2350 Callee = LowerGlobalAddress(Callee, DAG);
2351 else if (isa<ExternalSymbolSDNode>(Callee))
2352 Callee = LowerExternalSymbol(Callee, DAG);
2356 if (Is64Bit && isVarArg && !IsWin64) {
2357 // From AMD64 ABI document:
2358 // For calls that may call functions that use varargs or stdargs
2359 // (prototype-less calls or calls to functions containing ellipsis (...) in
2360 // the declaration) %al is used as hidden argument to specify the number
2361 // of SSE registers used. The contents of %al do not need to match exactly
2362 // the number of registers, but must be an ubound on the number of SSE
2363 // registers used and is in the range 0 - 8 inclusive.
2365 // Count the number of XMM registers allocated.
2366 static const uint16_t XMMArgRegs[] = {
2367 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2368 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2370 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2371 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2372 && "SSE registers cannot be used when SSE is disabled");
2374 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2375 DAG.getConstant(NumXMMRegs, MVT::i8)));
2378 // For tail calls lower the arguments to the 'real' stack slot.
2380 // Force all the incoming stack arguments to be loaded from the stack
2381 // before any new outgoing arguments are stored to the stack, because the
2382 // outgoing stack slots may alias the incoming argument stack slots, and
2383 // the alias isn't otherwise explicit. This is slightly more conservative
2384 // than necessary, because it means that each store effectively depends
2385 // on every argument instead of just those arguments it would clobber.
2386 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2388 SmallVector<SDValue, 8> MemOpChains2;
2391 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2392 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2393 CCValAssign &VA = ArgLocs[i];
2396 assert(VA.isMemLoc());
2397 SDValue Arg = OutVals[i];
2398 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2399 // Create frame index.
2400 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2401 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2402 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2403 FIN = DAG.getFrameIndex(FI, getPointerTy());
2405 if (Flags.isByVal()) {
2406 // Copy relative to framepointer.
2407 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2408 if (StackPtr.getNode() == 0)
2409 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2411 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2413 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2417 // Store relative to framepointer.
2418 MemOpChains2.push_back(
2419 DAG.getStore(ArgChain, dl, Arg, FIN,
2420 MachinePointerInfo::getFixedStack(FI),
2426 if (!MemOpChains2.empty())
2427 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2428 &MemOpChains2[0], MemOpChains2.size());
2430 // Store the return address to the appropriate stack slot.
2431 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2435 // Build a sequence of copy-to-reg nodes chained together with token chain
2436 // and flag operands which copy the outgoing args into registers.
2438 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2439 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2440 RegsToPass[i].second, InFlag);
2441 InFlag = Chain.getValue(1);
2444 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2445 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2446 // In the 64-bit large code model, we have to make all calls
2447 // through a register, since the call instruction's 32-bit
2448 // pc-relative offset may not be large enough to hold the whole
2450 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2451 // If the callee is a GlobalAddress node (quite common, every direct call
2452 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2455 // We should use extra load for direct calls to dllimported functions in
2457 const GlobalValue *GV = G->getGlobal();
2458 if (!GV->hasDLLImportLinkage()) {
2459 unsigned char OpFlags = 0;
2460 bool ExtraLoad = false;
2461 unsigned WrapperKind = ISD::DELETED_NODE;
2463 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2464 // external symbols most go through the PLT in PIC mode. If the symbol
2465 // has hidden or protected visibility, or if it is static or local, then
2466 // we don't need to use the PLT - we can directly call it.
2467 if (Subtarget->isTargetELF() &&
2468 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2469 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2470 OpFlags = X86II::MO_PLT;
2471 } else if (Subtarget->isPICStyleStubAny() &&
2472 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2473 (!Subtarget->getTargetTriple().isMacOSX() ||
2474 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2475 // PC-relative references to external symbols should go through $stub,
2476 // unless we're building with the leopard linker or later, which
2477 // automatically synthesizes these stubs.
2478 OpFlags = X86II::MO_DARWIN_STUB;
2479 } else if (Subtarget->isPICStyleRIPRel() &&
2480 isa<Function>(GV) &&
2481 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2482 // If the function is marked as non-lazy, generate an indirect call
2483 // which loads from the GOT directly. This avoids runtime overhead
2484 // at the cost of eager binding (and one extra byte of encoding).
2485 OpFlags = X86II::MO_GOTPCREL;
2486 WrapperKind = X86ISD::WrapperRIP;
2490 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2491 G->getOffset(), OpFlags);
2493 // Add a wrapper if needed.
2494 if (WrapperKind != ISD::DELETED_NODE)
2495 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2496 // Add extra indirection if needed.
2498 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2499 MachinePointerInfo::getGOT(),
2500 false, false, false, 0);
2502 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2503 unsigned char OpFlags = 0;
2505 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2506 // external symbols should go through the PLT.
2507 if (Subtarget->isTargetELF() &&
2508 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2509 OpFlags = X86II::MO_PLT;
2510 } else if (Subtarget->isPICStyleStubAny() &&
2511 (!Subtarget->getTargetTriple().isMacOSX() ||
2512 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2513 // PC-relative references to external symbols should go through $stub,
2514 // unless we're building with the leopard linker or later, which
2515 // automatically synthesizes these stubs.
2516 OpFlags = X86II::MO_DARWIN_STUB;
2519 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2523 // Returns a chain & a flag for retval copy to use.
2524 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2525 SmallVector<SDValue, 8> Ops;
2527 if (!IsSibcall && isTailCall) {
2528 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2529 DAG.getIntPtrConstant(0, true), InFlag);
2530 InFlag = Chain.getValue(1);
2533 Ops.push_back(Chain);
2534 Ops.push_back(Callee);
2537 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2539 // Add argument registers to the end of the list so that they are known live
2541 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2542 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2543 RegsToPass[i].second.getValueType()));
2545 // Add a register mask operand representing the call-preserved registers.
2546 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2547 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2548 assert(Mask && "Missing call preserved mask for calling convention");
2549 Ops.push_back(DAG.getRegisterMask(Mask));
2551 if (InFlag.getNode())
2552 Ops.push_back(InFlag);
2556 //// If this is the first return lowered for this function, add the regs
2557 //// to the liveout set for the function.
2558 // This isn't right, although it's probably harmless on x86; liveouts
2559 // should be computed from returns not tail calls. Consider a void
2560 // function making a tail call to a function returning int.
2561 return DAG.getNode(X86ISD::TC_RETURN, dl,
2562 NodeTys, &Ops[0], Ops.size());
2565 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2566 InFlag = Chain.getValue(1);
2568 // Create the CALLSEQ_END node.
2569 unsigned NumBytesForCalleeToPush;
2570 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2571 getTargetMachine().Options.GuaranteedTailCallOpt))
2572 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2573 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2574 SR == StackStructReturn)
2575 // If this is a call to a struct-return function, the callee
2576 // pops the hidden struct pointer, so we have to push it back.
2577 // This is common for Darwin/X86, Linux & Mingw32 targets.
2578 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2579 NumBytesForCalleeToPush = 4;
2581 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2583 // Returns a flag for retval copy to use.
2585 Chain = DAG.getCALLSEQ_END(Chain,
2586 DAG.getIntPtrConstant(NumBytes, true),
2587 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2590 InFlag = Chain.getValue(1);
2593 // Handle result values, copying them out of physregs into vregs that we
2595 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2596 Ins, dl, DAG, InVals);
2600 //===----------------------------------------------------------------------===//
2601 // Fast Calling Convention (tail call) implementation
2602 //===----------------------------------------------------------------------===//
2604 // Like std call, callee cleans arguments, convention except that ECX is
2605 // reserved for storing the tail called function address. Only 2 registers are
2606 // free for argument passing (inreg). Tail call optimization is performed
2608 // * tailcallopt is enabled
2609 // * caller/callee are fastcc
2610 // On X86_64 architecture with GOT-style position independent code only local
2611 // (within module) calls are supported at the moment.
2612 // To keep the stack aligned according to platform abi the function
2613 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2614 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2615 // If a tail called function callee has more arguments than the caller the
2616 // caller needs to make sure that there is room to move the RETADDR to. This is
2617 // achieved by reserving an area the size of the argument delta right after the
2618 // original REtADDR, but before the saved framepointer or the spilled registers
2619 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2631 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2632 /// for a 16 byte align requirement.
2634 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2635 SelectionDAG& DAG) const {
2636 MachineFunction &MF = DAG.getMachineFunction();
2637 const TargetMachine &TM = MF.getTarget();
2638 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2639 unsigned StackAlignment = TFI.getStackAlignment();
2640 uint64_t AlignMask = StackAlignment - 1;
2641 int64_t Offset = StackSize;
2642 uint64_t SlotSize = TD->getPointerSize();
2643 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2644 // Number smaller than 12 so just add the difference.
2645 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2647 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2648 Offset = ((~AlignMask) & Offset) + StackAlignment +
2649 (StackAlignment-SlotSize);
2654 /// MatchingStackOffset - Return true if the given stack call argument is
2655 /// already available in the same position (relatively) of the caller's
2656 /// incoming argument stack.
2658 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2659 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2660 const X86InstrInfo *TII) {
2661 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2663 if (Arg.getOpcode() == ISD::CopyFromReg) {
2664 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2665 if (!TargetRegisterInfo::isVirtualRegister(VR))
2667 MachineInstr *Def = MRI->getVRegDef(VR);
2670 if (!Flags.isByVal()) {
2671 if (!TII->isLoadFromStackSlot(Def, FI))
2674 unsigned Opcode = Def->getOpcode();
2675 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2676 Def->getOperand(1).isFI()) {
2677 FI = Def->getOperand(1).getIndex();
2678 Bytes = Flags.getByValSize();
2682 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2683 if (Flags.isByVal())
2684 // ByVal argument is passed in as a pointer but it's now being
2685 // dereferenced. e.g.
2686 // define @foo(%struct.X* %A) {
2687 // tail call @bar(%struct.X* byval %A)
2690 SDValue Ptr = Ld->getBasePtr();
2691 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2694 FI = FINode->getIndex();
2695 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2696 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2697 FI = FINode->getIndex();
2698 Bytes = Flags.getByValSize();
2702 assert(FI != INT_MAX);
2703 if (!MFI->isFixedObjectIndex(FI))
2705 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2708 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2709 /// for tail call optimization. Targets which want to do tail call
2710 /// optimization should implement this function.
2712 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2713 CallingConv::ID CalleeCC,
2715 bool isCalleeStructRet,
2716 bool isCallerStructRet,
2717 const SmallVectorImpl<ISD::OutputArg> &Outs,
2718 const SmallVectorImpl<SDValue> &OutVals,
2719 const SmallVectorImpl<ISD::InputArg> &Ins,
2720 SelectionDAG& DAG) const {
2721 if (!IsTailCallConvention(CalleeCC) &&
2722 CalleeCC != CallingConv::C)
2725 // If -tailcallopt is specified, make fastcc functions tail-callable.
2726 const MachineFunction &MF = DAG.getMachineFunction();
2727 const Function *CallerF = DAG.getMachineFunction().getFunction();
2728 CallingConv::ID CallerCC = CallerF->getCallingConv();
2729 bool CCMatch = CallerCC == CalleeCC;
2731 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2732 if (IsTailCallConvention(CalleeCC) && CCMatch)
2737 // Look for obvious safe cases to perform tail call optimization that do not
2738 // require ABI changes. This is what gcc calls sibcall.
2740 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2741 // emit a special epilogue.
2742 if (RegInfo->needsStackRealignment(MF))
2745 // Also avoid sibcall optimization if either caller or callee uses struct
2746 // return semantics.
2747 if (isCalleeStructRet || isCallerStructRet)
2750 // An stdcall caller is expected to clean up its arguments; the callee
2751 // isn't going to do that.
2752 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2755 // Do not sibcall optimize vararg calls unless all arguments are passed via
2757 if (isVarArg && !Outs.empty()) {
2759 // Optimizing for varargs on Win64 is unlikely to be safe without
2760 // additional testing.
2761 if (Subtarget->isTargetWin64())
2764 SmallVector<CCValAssign, 16> ArgLocs;
2765 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2766 getTargetMachine(), ArgLocs, *DAG.getContext());
2768 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2769 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2770 if (!ArgLocs[i].isRegLoc())
2774 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2775 // stack. Therefore, if it's not used by the call it is not safe to optimize
2776 // this into a sibcall.
2777 bool Unused = false;
2778 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2785 SmallVector<CCValAssign, 16> RVLocs;
2786 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2787 getTargetMachine(), RVLocs, *DAG.getContext());
2788 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2789 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2790 CCValAssign &VA = RVLocs[i];
2791 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2796 // If the calling conventions do not match, then we'd better make sure the
2797 // results are returned in the same way as what the caller expects.
2799 SmallVector<CCValAssign, 16> RVLocs1;
2800 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2801 getTargetMachine(), RVLocs1, *DAG.getContext());
2802 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2804 SmallVector<CCValAssign, 16> RVLocs2;
2805 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2806 getTargetMachine(), RVLocs2, *DAG.getContext());
2807 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2809 if (RVLocs1.size() != RVLocs2.size())
2811 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2812 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2814 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2816 if (RVLocs1[i].isRegLoc()) {
2817 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2820 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2826 // If the callee takes no arguments then go on to check the results of the
2828 if (!Outs.empty()) {
2829 // Check if stack adjustment is needed. For now, do not do this if any
2830 // argument is passed on the stack.
2831 SmallVector<CCValAssign, 16> ArgLocs;
2832 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2833 getTargetMachine(), ArgLocs, *DAG.getContext());
2835 // Allocate shadow area for Win64
2836 if (Subtarget->isTargetWin64()) {
2837 CCInfo.AllocateStack(32, 8);
2840 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2841 if (CCInfo.getNextStackOffset()) {
2842 MachineFunction &MF = DAG.getMachineFunction();
2843 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2846 // Check if the arguments are already laid out in the right way as
2847 // the caller's fixed stack objects.
2848 MachineFrameInfo *MFI = MF.getFrameInfo();
2849 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2850 const X86InstrInfo *TII =
2851 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2852 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2853 CCValAssign &VA = ArgLocs[i];
2854 SDValue Arg = OutVals[i];
2855 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2856 if (VA.getLocInfo() == CCValAssign::Indirect)
2858 if (!VA.isRegLoc()) {
2859 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2866 // If the tailcall address may be in a register, then make sure it's
2867 // possible to register allocate for it. In 32-bit, the call address can
2868 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2869 // callee-saved registers are restored. These happen to be the same
2870 // registers used to pass 'inreg' arguments so watch out for those.
2871 if (!Subtarget->is64Bit() &&
2872 !isa<GlobalAddressSDNode>(Callee) &&
2873 !isa<ExternalSymbolSDNode>(Callee)) {
2874 unsigned NumInRegs = 0;
2875 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2876 CCValAssign &VA = ArgLocs[i];
2879 unsigned Reg = VA.getLocReg();
2882 case X86::EAX: case X86::EDX: case X86::ECX:
2883 if (++NumInRegs == 3)
2895 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2896 const TargetLibraryInfo *libInfo) const {
2897 return X86::createFastISel(funcInfo, libInfo);
2901 //===----------------------------------------------------------------------===//
2902 // Other Lowering Hooks
2903 //===----------------------------------------------------------------------===//
2905 static bool MayFoldLoad(SDValue Op) {
2906 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2909 static bool MayFoldIntoStore(SDValue Op) {
2910 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2913 static bool isTargetShuffle(unsigned Opcode) {
2915 default: return false;
2916 case X86ISD::PSHUFD:
2917 case X86ISD::PSHUFHW:
2918 case X86ISD::PSHUFLW:
2920 case X86ISD::PALIGN:
2921 case X86ISD::MOVLHPS:
2922 case X86ISD::MOVLHPD:
2923 case X86ISD::MOVHLPS:
2924 case X86ISD::MOVLPS:
2925 case X86ISD::MOVLPD:
2926 case X86ISD::MOVSHDUP:
2927 case X86ISD::MOVSLDUP:
2928 case X86ISD::MOVDDUP:
2931 case X86ISD::UNPCKL:
2932 case X86ISD::UNPCKH:
2933 case X86ISD::VPERMILP:
2934 case X86ISD::VPERM2X128:
2935 case X86ISD::VPERMI:
2940 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2941 SDValue V1, SelectionDAG &DAG) {
2943 default: llvm_unreachable("Unknown x86 shuffle node");
2944 case X86ISD::MOVSHDUP:
2945 case X86ISD::MOVSLDUP:
2946 case X86ISD::MOVDDUP:
2947 return DAG.getNode(Opc, dl, VT, V1);
2951 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2952 SDValue V1, unsigned TargetMask,
2953 SelectionDAG &DAG) {
2955 default: llvm_unreachable("Unknown x86 shuffle node");
2956 case X86ISD::PSHUFD:
2957 case X86ISD::PSHUFHW:
2958 case X86ISD::PSHUFLW:
2959 case X86ISD::VPERMILP:
2960 case X86ISD::VPERMI:
2961 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2965 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2966 SDValue V1, SDValue V2, unsigned TargetMask,
2967 SelectionDAG &DAG) {
2969 default: llvm_unreachable("Unknown x86 shuffle node");
2970 case X86ISD::PALIGN:
2972 case X86ISD::VPERM2X128:
2973 return DAG.getNode(Opc, dl, VT, V1, V2,
2974 DAG.getConstant(TargetMask, MVT::i8));
2978 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2979 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2981 default: llvm_unreachable("Unknown x86 shuffle node");
2982 case X86ISD::MOVLHPS:
2983 case X86ISD::MOVLHPD:
2984 case X86ISD::MOVHLPS:
2985 case X86ISD::MOVLPS:
2986 case X86ISD::MOVLPD:
2989 case X86ISD::UNPCKL:
2990 case X86ISD::UNPCKH:
2991 return DAG.getNode(Opc, dl, VT, V1, V2);
2995 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2996 MachineFunction &MF = DAG.getMachineFunction();
2997 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2998 int ReturnAddrIndex = FuncInfo->getRAIndex();
3000 if (ReturnAddrIndex == 0) {
3001 // Set up a frame object for the return address.
3002 uint64_t SlotSize = TD->getPointerSize();
3003 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3005 FuncInfo->setRAIndex(ReturnAddrIndex);
3008 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3012 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3013 bool hasSymbolicDisplacement) {
3014 // Offset should fit into 32 bit immediate field.
3015 if (!isInt<32>(Offset))
3018 // If we don't have a symbolic displacement - we don't have any extra
3020 if (!hasSymbolicDisplacement)
3023 // FIXME: Some tweaks might be needed for medium code model.
3024 if (M != CodeModel::Small && M != CodeModel::Kernel)
3027 // For small code model we assume that latest object is 16MB before end of 31
3028 // bits boundary. We may also accept pretty large negative constants knowing
3029 // that all objects are in the positive half of address space.
3030 if (M == CodeModel::Small && Offset < 16*1024*1024)
3033 // For kernel code model we know that all object resist in the negative half
3034 // of 32bits address space. We may not accept negative offsets, since they may
3035 // be just off and we may accept pretty large positive ones.
3036 if (M == CodeModel::Kernel && Offset > 0)
3042 /// isCalleePop - Determines whether the callee is required to pop its
3043 /// own arguments. Callee pop is necessary to support tail calls.
3044 bool X86::isCalleePop(CallingConv::ID CallingConv,
3045 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3049 switch (CallingConv) {
3052 case CallingConv::X86_StdCall:
3054 case CallingConv::X86_FastCall:
3056 case CallingConv::X86_ThisCall:
3058 case CallingConv::Fast:
3060 case CallingConv::GHC:
3065 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3066 /// specific condition code, returning the condition code and the LHS/RHS of the
3067 /// comparison to make.
3068 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3069 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3071 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3072 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3073 // X > -1 -> X == 0, jump !sign.
3074 RHS = DAG.getConstant(0, RHS.getValueType());
3075 return X86::COND_NS;
3077 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3078 // X < 0 -> X == 0, jump on sign.
3081 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3083 RHS = DAG.getConstant(0, RHS.getValueType());
3084 return X86::COND_LE;
3088 switch (SetCCOpcode) {
3089 default: llvm_unreachable("Invalid integer condition!");
3090 case ISD::SETEQ: return X86::COND_E;
3091 case ISD::SETGT: return X86::COND_G;
3092 case ISD::SETGE: return X86::COND_GE;
3093 case ISD::SETLT: return X86::COND_L;
3094 case ISD::SETLE: return X86::COND_LE;
3095 case ISD::SETNE: return X86::COND_NE;
3096 case ISD::SETULT: return X86::COND_B;
3097 case ISD::SETUGT: return X86::COND_A;
3098 case ISD::SETULE: return X86::COND_BE;
3099 case ISD::SETUGE: return X86::COND_AE;
3103 // First determine if it is required or is profitable to flip the operands.
3105 // If LHS is a foldable load, but RHS is not, flip the condition.
3106 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3107 !ISD::isNON_EXTLoad(RHS.getNode())) {
3108 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3109 std::swap(LHS, RHS);
3112 switch (SetCCOpcode) {
3118 std::swap(LHS, RHS);
3122 // On a floating point condition, the flags are set as follows:
3124 // 0 | 0 | 0 | X > Y
3125 // 0 | 0 | 1 | X < Y
3126 // 1 | 0 | 0 | X == Y
3127 // 1 | 1 | 1 | unordered
3128 switch (SetCCOpcode) {
3129 default: llvm_unreachable("Condcode should be pre-legalized away");
3131 case ISD::SETEQ: return X86::COND_E;
3132 case ISD::SETOLT: // flipped
3134 case ISD::SETGT: return X86::COND_A;
3135 case ISD::SETOLE: // flipped
3137 case ISD::SETGE: return X86::COND_AE;
3138 case ISD::SETUGT: // flipped
3140 case ISD::SETLT: return X86::COND_B;
3141 case ISD::SETUGE: // flipped
3143 case ISD::SETLE: return X86::COND_BE;
3145 case ISD::SETNE: return X86::COND_NE;
3146 case ISD::SETUO: return X86::COND_P;
3147 case ISD::SETO: return X86::COND_NP;
3149 case ISD::SETUNE: return X86::COND_INVALID;
3153 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3154 /// code. Current x86 isa includes the following FP cmov instructions:
3155 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3156 static bool hasFPCMov(unsigned X86CC) {
3172 /// isFPImmLegal - Returns true if the target can instruction select the
3173 /// specified FP immediate natively. If false, the legalizer will
3174 /// materialize the FP immediate as a load from a constant pool.
3175 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3176 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3177 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3183 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3184 /// the specified range (L, H].
3185 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3186 return (Val < 0) || (Val >= Low && Val < Hi);
3189 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3190 /// specified value.
3191 static bool isUndefOrEqual(int Val, int CmpVal) {
3192 if (Val < 0 || Val == CmpVal)
3197 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3198 /// from position Pos and ending in Pos+Size, falls within the specified
3199 /// sequential range (L, L+Pos]. or is undef.
3200 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3201 unsigned Pos, unsigned Size, int Low) {
3202 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3203 if (!isUndefOrEqual(Mask[i], Low))
3208 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3209 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3210 /// the second operand.
3211 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3212 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3213 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3214 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3215 return (Mask[0] < 2 && Mask[1] < 2);
3219 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3220 /// is suitable for input to PSHUFHW.
3221 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3222 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3225 // Lower quadword copied in order or undef.
3226 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3229 // Upper quadword shuffled.
3230 for (unsigned i = 4; i != 8; ++i)
3231 if (!isUndefOrInRange(Mask[i], 4, 8))
3234 if (VT == MVT::v16i16) {
3235 // Lower quadword copied in order or undef.
3236 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3239 // Upper quadword shuffled.
3240 for (unsigned i = 12; i != 16; ++i)
3241 if (!isUndefOrInRange(Mask[i], 12, 16))
3248 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3249 /// is suitable for input to PSHUFLW.
3250 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3251 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3254 // Upper quadword copied in order.
3255 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3258 // Lower quadword shuffled.
3259 for (unsigned i = 0; i != 4; ++i)
3260 if (!isUndefOrInRange(Mask[i], 0, 4))
3263 if (VT == MVT::v16i16) {
3264 // Upper quadword copied in order.
3265 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3268 // Lower quadword shuffled.
3269 for (unsigned i = 8; i != 12; ++i)
3270 if (!isUndefOrInRange(Mask[i], 8, 12))
3277 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3278 /// is suitable for input to PALIGNR.
3279 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3280 const X86Subtarget *Subtarget) {
3281 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3282 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3285 unsigned NumElts = VT.getVectorNumElements();
3286 unsigned NumLanes = VT.getSizeInBits()/128;
3287 unsigned NumLaneElts = NumElts/NumLanes;
3289 // Do not handle 64-bit element shuffles with palignr.
3290 if (NumLaneElts == 2)
3293 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3295 for (i = 0; i != NumLaneElts; ++i) {
3300 // Lane is all undef, go to next lane
3301 if (i == NumLaneElts)
3304 int Start = Mask[i+l];
3306 // Make sure its in this lane in one of the sources
3307 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3308 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3311 // If not lane 0, then we must match lane 0
3312 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3315 // Correct second source to be contiguous with first source
3316 if (Start >= (int)NumElts)
3317 Start -= NumElts - NumLaneElts;
3319 // Make sure we're shifting in the right direction.
3320 if (Start <= (int)(i+l))
3325 // Check the rest of the elements to see if they are consecutive.
3326 for (++i; i != NumLaneElts; ++i) {
3327 int Idx = Mask[i+l];
3329 // Make sure its in this lane
3330 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3331 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3334 // If not lane 0, then we must match lane 0
3335 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3338 if (Idx >= (int)NumElts)
3339 Idx -= NumElts - NumLaneElts;
3341 if (!isUndefOrEqual(Idx, Start+i))
3350 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3351 /// the two vector operands have swapped position.
3352 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3353 unsigned NumElems) {
3354 for (unsigned i = 0; i != NumElems; ++i) {
3358 else if (idx < (int)NumElems)
3359 Mask[i] = idx + NumElems;
3361 Mask[i] = idx - NumElems;
3365 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3366 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3367 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3368 /// reverse of what x86 shuffles want.
3369 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3370 bool Commuted = false) {
3371 if (!HasAVX && VT.getSizeInBits() == 256)
3374 unsigned NumElems = VT.getVectorNumElements();
3375 unsigned NumLanes = VT.getSizeInBits()/128;
3376 unsigned NumLaneElems = NumElems/NumLanes;
3378 if (NumLaneElems != 2 && NumLaneElems != 4)
3381 // VSHUFPSY divides the resulting vector into 4 chunks.
3382 // The sources are also splitted into 4 chunks, and each destination
3383 // chunk must come from a different source chunk.
3385 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3386 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3388 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3389 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3391 // VSHUFPDY divides the resulting vector into 4 chunks.
3392 // The sources are also splitted into 4 chunks, and each destination
3393 // chunk must come from a different source chunk.
3395 // SRC1 => X3 X2 X1 X0
3396 // SRC2 => Y3 Y2 Y1 Y0
3398 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3400 unsigned HalfLaneElems = NumLaneElems/2;
3401 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3402 for (unsigned i = 0; i != NumLaneElems; ++i) {
3403 int Idx = Mask[i+l];
3404 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3405 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3407 // For VSHUFPSY, the mask of the second half must be the same as the
3408 // first but with the appropriate offsets. This works in the same way as
3409 // VPERMILPS works with masks.
3410 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3412 if (!isUndefOrEqual(Idx, Mask[i]+l))
3420 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3421 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3422 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3423 unsigned NumElems = VT.getVectorNumElements();
3425 if (VT.getSizeInBits() != 128)
3431 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3432 return isUndefOrEqual(Mask[0], 6) &&
3433 isUndefOrEqual(Mask[1], 7) &&
3434 isUndefOrEqual(Mask[2], 2) &&
3435 isUndefOrEqual(Mask[3], 3);
3438 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3439 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3441 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3442 unsigned NumElems = VT.getVectorNumElements();
3444 if (VT.getSizeInBits() != 128)
3450 return isUndefOrEqual(Mask[0], 2) &&
3451 isUndefOrEqual(Mask[1], 3) &&
3452 isUndefOrEqual(Mask[2], 2) &&
3453 isUndefOrEqual(Mask[3], 3);
3456 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3457 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3458 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3459 if (VT.getSizeInBits() != 128)
3462 unsigned NumElems = VT.getVectorNumElements();
3464 if (NumElems != 2 && NumElems != 4)
3467 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3468 if (!isUndefOrEqual(Mask[i], i + NumElems))
3471 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3472 if (!isUndefOrEqual(Mask[i], i))
3478 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3479 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3480 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3481 unsigned NumElems = VT.getVectorNumElements();
3483 if ((NumElems != 2 && NumElems != 4)
3484 || VT.getSizeInBits() > 128)
3487 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3488 if (!isUndefOrEqual(Mask[i], i))
3491 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3492 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3499 // Some special combinations that can be optimized.
3502 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3503 SelectionDAG &DAG) {
3504 EVT VT = SVOp->getValueType(0);
3505 DebugLoc dl = SVOp->getDebugLoc();
3507 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3510 ArrayRef<int> Mask = SVOp->getMask();
3512 // These are the special masks that may be optimized.
3513 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3514 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3515 bool MatchEvenMask = true;
3516 bool MatchOddMask = true;
3517 for (int i=0; i<8; ++i) {
3518 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3519 MatchEvenMask = false;
3520 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3521 MatchOddMask = false;
3523 static const int CompactionMaskEven[] = {0, 2, -1, -1, 4, 6, -1, -1};
3524 static const int CompactionMaskOdd [] = {1, 3, -1, -1, 5, 7, -1, -1};
3526 const int *CompactionMask;
3528 CompactionMask = CompactionMaskEven;
3529 else if (MatchOddMask)
3530 CompactionMask = CompactionMaskOdd;
3534 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3536 SDValue Op0 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(0),
3537 UndefNode, CompactionMask);
3538 SDValue Op1 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(1),
3539 UndefNode, CompactionMask);
3540 static const int UnpackMask[] = {0, 8, 1, 9, 4, 12, 5, 13};
3541 return DAG.getVectorShuffle(VT, dl, Op0, Op1, UnpackMask);
3544 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3545 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3546 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3547 bool HasAVX2, bool V2IsSplat = false) {
3548 unsigned NumElts = VT.getVectorNumElements();
3550 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3551 "Unsupported vector type for unpckh");
3553 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3554 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3557 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3558 // independently on 128-bit lanes.
3559 unsigned NumLanes = VT.getSizeInBits()/128;
3560 unsigned NumLaneElts = NumElts/NumLanes;
3562 for (unsigned l = 0; l != NumLanes; ++l) {
3563 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3564 i != (l+1)*NumLaneElts;
3567 int BitI1 = Mask[i+1];
3568 if (!isUndefOrEqual(BitI, j))
3571 if (!isUndefOrEqual(BitI1, NumElts))
3574 if (!isUndefOrEqual(BitI1, j + NumElts))
3583 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3584 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3585 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3586 bool HasAVX2, bool V2IsSplat = false) {
3587 unsigned NumElts = VT.getVectorNumElements();
3589 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3590 "Unsupported vector type for unpckh");
3592 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3593 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3596 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3597 // independently on 128-bit lanes.
3598 unsigned NumLanes = VT.getSizeInBits()/128;
3599 unsigned NumLaneElts = NumElts/NumLanes;
3601 for (unsigned l = 0; l != NumLanes; ++l) {
3602 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3603 i != (l+1)*NumLaneElts; i += 2, ++j) {
3605 int BitI1 = Mask[i+1];
3606 if (!isUndefOrEqual(BitI, j))
3609 if (isUndefOrEqual(BitI1, NumElts))
3612 if (!isUndefOrEqual(BitI1, j+NumElts))
3620 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3621 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3623 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3625 unsigned NumElts = VT.getVectorNumElements();
3627 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3628 "Unsupported vector type for unpckh");
3630 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3631 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3634 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3635 // FIXME: Need a better way to get rid of this, there's no latency difference
3636 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3637 // the former later. We should also remove the "_undef" special mask.
3638 if (NumElts == 4 && VT.getSizeInBits() == 256)
3641 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3642 // independently on 128-bit lanes.
3643 unsigned NumLanes = VT.getSizeInBits()/128;
3644 unsigned NumLaneElts = NumElts/NumLanes;
3646 for (unsigned l = 0; l != NumLanes; ++l) {
3647 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3648 i != (l+1)*NumLaneElts;
3651 int BitI1 = Mask[i+1];
3653 if (!isUndefOrEqual(BitI, j))
3655 if (!isUndefOrEqual(BitI1, j))
3663 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3664 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3666 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3667 unsigned NumElts = VT.getVectorNumElements();
3669 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3670 "Unsupported vector type for unpckh");
3672 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3673 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3676 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3677 // independently on 128-bit lanes.
3678 unsigned NumLanes = VT.getSizeInBits()/128;
3679 unsigned NumLaneElts = NumElts/NumLanes;
3681 for (unsigned l = 0; l != NumLanes; ++l) {
3682 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3683 i != (l+1)*NumLaneElts; i += 2, ++j) {
3685 int BitI1 = Mask[i+1];
3686 if (!isUndefOrEqual(BitI, j))
3688 if (!isUndefOrEqual(BitI1, j))
3695 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3696 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3697 /// MOVSD, and MOVD, i.e. setting the lowest element.
3698 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3699 if (VT.getVectorElementType().getSizeInBits() < 32)
3701 if (VT.getSizeInBits() == 256)
3704 unsigned NumElts = VT.getVectorNumElements();
3706 if (!isUndefOrEqual(Mask[0], NumElts))
3709 for (unsigned i = 1; i != NumElts; ++i)
3710 if (!isUndefOrEqual(Mask[i], i))
3716 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3717 /// as permutations between 128-bit chunks or halves. As an example: this
3719 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3720 /// The first half comes from the second half of V1 and the second half from the
3721 /// the second half of V2.
3722 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3723 if (!HasAVX || VT.getSizeInBits() != 256)
3726 // The shuffle result is divided into half A and half B. In total the two
3727 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3728 // B must come from C, D, E or F.
3729 unsigned HalfSize = VT.getVectorNumElements()/2;
3730 bool MatchA = false, MatchB = false;
3732 // Check if A comes from one of C, D, E, F.
3733 for (unsigned Half = 0; Half != 4; ++Half) {
3734 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3740 // Check if B comes from one of C, D, E, F.
3741 for (unsigned Half = 0; Half != 4; ++Half) {
3742 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3748 return MatchA && MatchB;
3751 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3752 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3753 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3754 EVT VT = SVOp->getValueType(0);
3756 unsigned HalfSize = VT.getVectorNumElements()/2;
3758 unsigned FstHalf = 0, SndHalf = 0;
3759 for (unsigned i = 0; i < HalfSize; ++i) {
3760 if (SVOp->getMaskElt(i) > 0) {
3761 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3765 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3766 if (SVOp->getMaskElt(i) > 0) {
3767 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3772 return (FstHalf | (SndHalf << 4));
3775 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3776 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3777 /// Note that VPERMIL mask matching is different depending whether theunderlying
3778 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3779 /// to the same elements of the low, but to the higher half of the source.
3780 /// In VPERMILPD the two lanes could be shuffled independently of each other
3781 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3782 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3786 unsigned NumElts = VT.getVectorNumElements();
3787 // Only match 256-bit with 32/64-bit types
3788 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3791 unsigned NumLanes = VT.getSizeInBits()/128;
3792 unsigned LaneSize = NumElts/NumLanes;
3793 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3794 for (unsigned i = 0; i != LaneSize; ++i) {
3795 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3797 if (NumElts != 8 || l == 0)
3799 // VPERMILPS handling
3802 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3810 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3811 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3812 /// element of vector 2 and the other elements to come from vector 1 in order.
3813 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3814 bool V2IsSplat = false, bool V2IsUndef = false) {
3815 unsigned NumOps = VT.getVectorNumElements();
3816 if (VT.getSizeInBits() == 256)
3818 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3821 if (!isUndefOrEqual(Mask[0], 0))
3824 for (unsigned i = 1; i != NumOps; ++i)
3825 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3826 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3827 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3833 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3834 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3835 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3836 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3837 const X86Subtarget *Subtarget) {
3838 if (!Subtarget->hasSSE3())
3841 unsigned NumElems = VT.getVectorNumElements();
3843 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3844 (VT.getSizeInBits() == 256 && NumElems != 8))
3847 // "i+1" is the value the indexed mask element must have
3848 for (unsigned i = 0; i != NumElems; i += 2)
3849 if (!isUndefOrEqual(Mask[i], i+1) ||
3850 !isUndefOrEqual(Mask[i+1], i+1))
3856 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3857 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3858 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3859 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3860 const X86Subtarget *Subtarget) {
3861 if (!Subtarget->hasSSE3())
3864 unsigned NumElems = VT.getVectorNumElements();
3866 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3867 (VT.getSizeInBits() == 256 && NumElems != 8))
3870 // "i" is the value the indexed mask element must have
3871 for (unsigned i = 0; i != NumElems; i += 2)
3872 if (!isUndefOrEqual(Mask[i], i) ||
3873 !isUndefOrEqual(Mask[i+1], i))
3879 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3880 /// specifies a shuffle of elements that is suitable for input to 256-bit
3881 /// version of MOVDDUP.
3882 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3883 unsigned NumElts = VT.getVectorNumElements();
3885 if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3888 for (unsigned i = 0; i != NumElts/2; ++i)
3889 if (!isUndefOrEqual(Mask[i], 0))
3891 for (unsigned i = NumElts/2; i != NumElts; ++i)
3892 if (!isUndefOrEqual(Mask[i], NumElts/2))
3897 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3898 /// specifies a shuffle of elements that is suitable for input to 128-bit
3899 /// version of MOVDDUP.
3900 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3901 if (VT.getSizeInBits() != 128)
3904 unsigned e = VT.getVectorNumElements() / 2;
3905 for (unsigned i = 0; i != e; ++i)
3906 if (!isUndefOrEqual(Mask[i], i))
3908 for (unsigned i = 0; i != e; ++i)
3909 if (!isUndefOrEqual(Mask[e+i], i))
3914 /// isVEXTRACTF128Index - Return true if the specified
3915 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3916 /// suitable for input to VEXTRACTF128.
3917 bool X86::isVEXTRACTF128Index(SDNode *N) {
3918 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3921 // The index should be aligned on a 128-bit boundary.
3923 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3925 unsigned VL = N->getValueType(0).getVectorNumElements();
3926 unsigned VBits = N->getValueType(0).getSizeInBits();
3927 unsigned ElSize = VBits / VL;
3928 bool Result = (Index * ElSize) % 128 == 0;
3933 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3934 /// operand specifies a subvector insert that is suitable for input to
3936 bool X86::isVINSERTF128Index(SDNode *N) {
3937 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3940 // The index should be aligned on a 128-bit boundary.
3942 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3944 unsigned VL = N->getValueType(0).getVectorNumElements();
3945 unsigned VBits = N->getValueType(0).getSizeInBits();
3946 unsigned ElSize = VBits / VL;
3947 bool Result = (Index * ElSize) % 128 == 0;
3952 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3953 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3954 /// Handles 128-bit and 256-bit.
3955 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3956 EVT VT = N->getValueType(0);
3958 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3959 "Unsupported vector type for PSHUF/SHUFP");
3961 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3962 // independently on 128-bit lanes.
3963 unsigned NumElts = VT.getVectorNumElements();
3964 unsigned NumLanes = VT.getSizeInBits()/128;
3965 unsigned NumLaneElts = NumElts/NumLanes;
3967 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3968 "Only supports 2 or 4 elements per lane");
3970 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3972 for (unsigned i = 0; i != NumElts; ++i) {
3973 int Elt = N->getMaskElt(i);
3974 if (Elt < 0) continue;
3975 Elt &= NumLaneElts - 1;
3976 unsigned ShAmt = (i << Shift) % 8;
3977 Mask |= Elt << ShAmt;
3983 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3984 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3985 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3986 EVT VT = N->getValueType(0);
3988 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3989 "Unsupported vector type for PSHUFHW");
3991 unsigned NumElts = VT.getVectorNumElements();
3994 for (unsigned l = 0; l != NumElts; l += 8) {
3995 // 8 nodes per lane, but we only care about the last 4.
3996 for (unsigned i = 0; i < 4; ++i) {
3997 int Elt = N->getMaskElt(l+i+4);
3998 if (Elt < 0) continue;
3999 Elt &= 0x3; // only 2-bits.
4000 Mask |= Elt << (i * 2);
4007 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4008 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4009 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4010 EVT VT = N->getValueType(0);
4012 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4013 "Unsupported vector type for PSHUFHW");
4015 unsigned NumElts = VT.getVectorNumElements();
4018 for (unsigned l = 0; l != NumElts; l += 8) {
4019 // 8 nodes per lane, but we only care about the first 4.
4020 for (unsigned i = 0; i < 4; ++i) {
4021 int Elt = N->getMaskElt(l+i);
4022 if (Elt < 0) continue;
4023 Elt &= 0x3; // only 2-bits
4024 Mask |= Elt << (i * 2);
4031 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4032 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4033 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4034 EVT VT = SVOp->getValueType(0);
4035 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4037 unsigned NumElts = VT.getVectorNumElements();
4038 unsigned NumLanes = VT.getSizeInBits()/128;
4039 unsigned NumLaneElts = NumElts/NumLanes;
4043 for (i = 0; i != NumElts; ++i) {
4044 Val = SVOp->getMaskElt(i);
4048 if (Val >= (int)NumElts)
4049 Val -= NumElts - NumLaneElts;
4051 assert(Val - i > 0 && "PALIGNR imm should be positive");
4052 return (Val - i) * EltSize;
4055 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4056 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4058 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4059 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4060 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4063 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4065 EVT VecVT = N->getOperand(0).getValueType();
4066 EVT ElVT = VecVT.getVectorElementType();
4068 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4069 return Index / NumElemsPerChunk;
4072 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4073 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4075 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4076 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4077 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4080 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4082 EVT VecVT = N->getValueType(0);
4083 EVT ElVT = VecVT.getVectorElementType();
4085 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4086 return Index / NumElemsPerChunk;
4089 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4090 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4091 /// Handles 256-bit.
4092 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4093 EVT VT = N->getValueType(0);
4095 unsigned NumElts = VT.getVectorNumElements();
4097 assert((VT.is256BitVector() && NumElts == 4) &&
4098 "Unsupported vector type for VPERMQ/VPERMPD");
4101 for (unsigned i = 0; i != NumElts; ++i) {
4102 int Elt = N->getMaskElt(i);
4105 Mask |= Elt << (i*2);
4110 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4112 bool X86::isZeroNode(SDValue Elt) {
4113 return ((isa<ConstantSDNode>(Elt) &&
4114 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4115 (isa<ConstantFPSDNode>(Elt) &&
4116 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4119 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4120 /// their permute mask.
4121 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4122 SelectionDAG &DAG) {
4123 EVT VT = SVOp->getValueType(0);
4124 unsigned NumElems = VT.getVectorNumElements();
4125 SmallVector<int, 8> MaskVec;
4127 for (unsigned i = 0; i != NumElems; ++i) {
4128 int Idx = SVOp->getMaskElt(i);
4130 if (Idx < (int)NumElems)
4135 MaskVec.push_back(Idx);
4137 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4138 SVOp->getOperand(0), &MaskVec[0]);
4141 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4142 /// match movhlps. The lower half elements should come from upper half of
4143 /// V1 (and in order), and the upper half elements should come from the upper
4144 /// half of V2 (and in order).
4145 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4146 if (VT.getSizeInBits() != 128)
4148 if (VT.getVectorNumElements() != 4)
4150 for (unsigned i = 0, e = 2; i != e; ++i)
4151 if (!isUndefOrEqual(Mask[i], i+2))
4153 for (unsigned i = 2; i != 4; ++i)
4154 if (!isUndefOrEqual(Mask[i], i+4))
4159 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4160 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4162 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4163 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4165 N = N->getOperand(0).getNode();
4166 if (!ISD::isNON_EXTLoad(N))
4169 *LD = cast<LoadSDNode>(N);
4173 // Test whether the given value is a vector value which will be legalized
4175 static bool WillBeConstantPoolLoad(SDNode *N) {
4176 if (N->getOpcode() != ISD::BUILD_VECTOR)
4179 // Check for any non-constant elements.
4180 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4181 switch (N->getOperand(i).getNode()->getOpcode()) {
4183 case ISD::ConstantFP:
4190 // Vectors of all-zeros and all-ones are materialized with special
4191 // instructions rather than being loaded.
4192 return !ISD::isBuildVectorAllZeros(N) &&
4193 !ISD::isBuildVectorAllOnes(N);
4196 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4197 /// match movlp{s|d}. The lower half elements should come from lower half of
4198 /// V1 (and in order), and the upper half elements should come from the upper
4199 /// half of V2 (and in order). And since V1 will become the source of the
4200 /// MOVLP, it must be either a vector load or a scalar load to vector.
4201 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4202 ArrayRef<int> Mask, EVT VT) {
4203 if (VT.getSizeInBits() != 128)
4206 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4208 // Is V2 is a vector load, don't do this transformation. We will try to use
4209 // load folding shufps op.
4210 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4213 unsigned NumElems = VT.getVectorNumElements();
4215 if (NumElems != 2 && NumElems != 4)
4217 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4218 if (!isUndefOrEqual(Mask[i], i))
4220 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4221 if (!isUndefOrEqual(Mask[i], i+NumElems))
4226 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4228 static bool isSplatVector(SDNode *N) {
4229 if (N->getOpcode() != ISD::BUILD_VECTOR)
4232 SDValue SplatValue = N->getOperand(0);
4233 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4234 if (N->getOperand(i) != SplatValue)
4239 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4240 /// to an zero vector.
4241 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4242 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4243 SDValue V1 = N->getOperand(0);
4244 SDValue V2 = N->getOperand(1);
4245 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4246 for (unsigned i = 0; i != NumElems; ++i) {
4247 int Idx = N->getMaskElt(i);
4248 if (Idx >= (int)NumElems) {
4249 unsigned Opc = V2.getOpcode();
4250 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4252 if (Opc != ISD::BUILD_VECTOR ||
4253 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4255 } else if (Idx >= 0) {
4256 unsigned Opc = V1.getOpcode();
4257 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4259 if (Opc != ISD::BUILD_VECTOR ||
4260 !X86::isZeroNode(V1.getOperand(Idx)))
4267 /// getZeroVector - Returns a vector of specified type with all zero elements.
4269 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4270 SelectionDAG &DAG, DebugLoc dl) {
4271 assert(VT.isVector() && "Expected a vector type");
4272 unsigned Size = VT.getSizeInBits();
4274 // Always build SSE zero vectors as <4 x i32> bitcasted
4275 // to their dest type. This ensures they get CSE'd.
4277 if (Size == 128) { // SSE
4278 if (Subtarget->hasSSE2()) { // SSE2
4279 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4280 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4282 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4283 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4285 } else if (Size == 256) { // AVX
4286 if (Subtarget->hasAVX2()) { // AVX2
4287 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4288 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4289 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4291 // 256-bit logic and arithmetic instructions in AVX are all
4292 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4293 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4294 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4295 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4298 llvm_unreachable("Unexpected vector type");
4300 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4303 /// getOnesVector - Returns a vector of specified type with all bits set.
4304 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4305 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4306 /// Then bitcast to their original type, ensuring they get CSE'd.
4307 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4309 assert(VT.isVector() && "Expected a vector type");
4310 unsigned Size = VT.getSizeInBits();
4312 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4315 if (HasAVX2) { // AVX2
4316 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4317 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4319 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4320 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4322 } else if (Size == 128) {
4323 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4325 llvm_unreachable("Unexpected vector type");
4327 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4330 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4331 /// that point to V2 points to its first element.
4332 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4333 for (unsigned i = 0; i != NumElems; ++i) {
4334 if (Mask[i] > (int)NumElems) {
4340 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4341 /// operation of specified width.
4342 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4344 unsigned NumElems = VT.getVectorNumElements();
4345 SmallVector<int, 8> Mask;
4346 Mask.push_back(NumElems);
4347 for (unsigned i = 1; i != NumElems; ++i)
4349 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4352 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4353 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4355 unsigned NumElems = VT.getVectorNumElements();
4356 SmallVector<int, 8> Mask;
4357 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4359 Mask.push_back(i + NumElems);
4361 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4364 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4365 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4367 unsigned NumElems = VT.getVectorNumElements();
4368 SmallVector<int, 8> Mask;
4369 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4370 Mask.push_back(i + Half);
4371 Mask.push_back(i + NumElems + Half);
4373 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4376 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4377 // a generic shuffle instruction because the target has no such instructions.
4378 // Generate shuffles which repeat i16 and i8 several times until they can be
4379 // represented by v4f32 and then be manipulated by target suported shuffles.
4380 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4381 EVT VT = V.getValueType();
4382 int NumElems = VT.getVectorNumElements();
4383 DebugLoc dl = V.getDebugLoc();
4385 while (NumElems > 4) {
4386 if (EltNo < NumElems/2) {
4387 V = getUnpackl(DAG, dl, VT, V, V);
4389 V = getUnpackh(DAG, dl, VT, V, V);
4390 EltNo -= NumElems/2;
4397 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4398 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4399 EVT VT = V.getValueType();
4400 DebugLoc dl = V.getDebugLoc();
4401 unsigned Size = VT.getSizeInBits();
4404 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4405 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4406 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4408 } else if (Size == 256) {
4409 // To use VPERMILPS to splat scalars, the second half of indicies must
4410 // refer to the higher part, which is a duplication of the lower one,
4411 // because VPERMILPS can only handle in-lane permutations.
4412 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4413 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4415 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4416 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4419 llvm_unreachable("Vector size not supported");
4421 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4424 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4425 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4426 EVT SrcVT = SV->getValueType(0);
4427 SDValue V1 = SV->getOperand(0);
4428 DebugLoc dl = SV->getDebugLoc();
4430 int EltNo = SV->getSplatIndex();
4431 int NumElems = SrcVT.getVectorNumElements();
4432 unsigned Size = SrcVT.getSizeInBits();
4434 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4435 "Unknown how to promote splat for type");
4437 // Extract the 128-bit part containing the splat element and update
4438 // the splat element index when it refers to the higher register.
4440 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4441 if (EltNo >= NumElems/2)
4442 EltNo -= NumElems/2;
4445 // All i16 and i8 vector types can't be used directly by a generic shuffle
4446 // instruction because the target has no such instruction. Generate shuffles
4447 // which repeat i16 and i8 several times until they fit in i32, and then can
4448 // be manipulated by target suported shuffles.
4449 EVT EltVT = SrcVT.getVectorElementType();
4450 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4451 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4453 // Recreate the 256-bit vector and place the same 128-bit vector
4454 // into the low and high part. This is necessary because we want
4455 // to use VPERM* to shuffle the vectors
4457 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4460 return getLegalSplat(DAG, V1, EltNo);
4463 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4464 /// vector of zero or undef vector. This produces a shuffle where the low
4465 /// element of V2 is swizzled into the zero/undef vector, landing at element
4466 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4467 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4469 const X86Subtarget *Subtarget,
4470 SelectionDAG &DAG) {
4471 EVT VT = V2.getValueType();
4473 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4474 unsigned NumElems = VT.getVectorNumElements();
4475 SmallVector<int, 16> MaskVec;
4476 for (unsigned i = 0; i != NumElems; ++i)
4477 // If this is the insertion idx, put the low elt of V2 here.
4478 MaskVec.push_back(i == Idx ? NumElems : i);
4479 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4482 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4483 /// target specific opcode. Returns true if the Mask could be calculated.
4484 /// Sets IsUnary to true if only uses one source.
4485 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4486 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4487 unsigned NumElems = VT.getVectorNumElements();
4491 switch(N->getOpcode()) {
4493 ImmN = N->getOperand(N->getNumOperands()-1);
4494 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4496 case X86ISD::UNPCKH:
4497 DecodeUNPCKHMask(VT, Mask);
4499 case X86ISD::UNPCKL:
4500 DecodeUNPCKLMask(VT, Mask);
4502 case X86ISD::MOVHLPS:
4503 DecodeMOVHLPSMask(NumElems, Mask);
4505 case X86ISD::MOVLHPS:
4506 DecodeMOVLHPSMask(NumElems, Mask);
4508 case X86ISD::PSHUFD:
4509 case X86ISD::VPERMILP:
4510 ImmN = N->getOperand(N->getNumOperands()-1);
4511 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4514 case X86ISD::PSHUFHW:
4515 ImmN = N->getOperand(N->getNumOperands()-1);
4516 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4519 case X86ISD::PSHUFLW:
4520 ImmN = N->getOperand(N->getNumOperands()-1);
4521 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4524 case X86ISD::VPERMI:
4525 ImmN = N->getOperand(N->getNumOperands()-1);
4526 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4530 case X86ISD::MOVSD: {
4531 // The index 0 always comes from the first element of the second source,
4532 // this is why MOVSS and MOVSD are used in the first place. The other
4533 // elements come from the other positions of the first source vector
4534 Mask.push_back(NumElems);
4535 for (unsigned i = 1; i != NumElems; ++i) {
4540 case X86ISD::VPERM2X128:
4541 ImmN = N->getOperand(N->getNumOperands()-1);
4542 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4543 if (Mask.empty()) return false;
4545 case X86ISD::MOVDDUP:
4546 case X86ISD::MOVLHPD:
4547 case X86ISD::MOVLPD:
4548 case X86ISD::MOVLPS:
4549 case X86ISD::MOVSHDUP:
4550 case X86ISD::MOVSLDUP:
4551 case X86ISD::PALIGN:
4552 // Not yet implemented
4554 default: llvm_unreachable("unknown target shuffle node");
4560 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4561 /// element of the result of the vector shuffle.
4562 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4565 return SDValue(); // Limit search depth.
4567 SDValue V = SDValue(N, 0);
4568 EVT VT = V.getValueType();
4569 unsigned Opcode = V.getOpcode();
4571 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4572 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4573 int Elt = SV->getMaskElt(Index);
4576 return DAG.getUNDEF(VT.getVectorElementType());
4578 unsigned NumElems = VT.getVectorNumElements();
4579 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4580 : SV->getOperand(1);
4581 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4584 // Recurse into target specific vector shuffles to find scalars.
4585 if (isTargetShuffle(Opcode)) {
4586 MVT ShufVT = V.getValueType().getSimpleVT();
4587 unsigned NumElems = ShufVT.getVectorNumElements();
4588 SmallVector<int, 16> ShuffleMask;
4592 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4595 int Elt = ShuffleMask[Index];
4597 return DAG.getUNDEF(ShufVT.getVectorElementType());
4599 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4601 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4605 // Actual nodes that may contain scalar elements
4606 if (Opcode == ISD::BITCAST) {
4607 V = V.getOperand(0);
4608 EVT SrcVT = V.getValueType();
4609 unsigned NumElems = VT.getVectorNumElements();
4611 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4615 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4616 return (Index == 0) ? V.getOperand(0)
4617 : DAG.getUNDEF(VT.getVectorElementType());
4619 if (V.getOpcode() == ISD::BUILD_VECTOR)
4620 return V.getOperand(Index);
4625 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4626 /// shuffle operation which come from a consecutively from a zero. The
4627 /// search can start in two different directions, from left or right.
4629 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4630 bool ZerosFromLeft, SelectionDAG &DAG) {
4632 for (i = 0; i != NumElems; ++i) {
4633 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4634 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4635 if (!(Elt.getNode() &&
4636 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4643 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4644 /// correspond consecutively to elements from one of the vector operands,
4645 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4647 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4648 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4649 unsigned NumElems, unsigned &OpNum) {
4650 bool SeenV1 = false;
4651 bool SeenV2 = false;
4653 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4654 int Idx = SVOp->getMaskElt(i);
4655 // Ignore undef indicies
4659 if (Idx < (int)NumElems)
4664 // Only accept consecutive elements from the same vector
4665 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4669 OpNum = SeenV1 ? 0 : 1;
4673 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4674 /// logical left shift of a vector.
4675 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4676 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4677 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4678 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4679 false /* check zeros from right */, DAG);
4685 // Considering the elements in the mask that are not consecutive zeros,
4686 // check if they consecutively come from only one of the source vectors.
4688 // V1 = {X, A, B, C} 0
4690 // vector_shuffle V1, V2 <1, 2, 3, X>
4692 if (!isShuffleMaskConsecutive(SVOp,
4693 0, // Mask Start Index
4694 NumElems-NumZeros, // Mask End Index(exclusive)
4695 NumZeros, // Where to start looking in the src vector
4696 NumElems, // Number of elements in vector
4697 OpSrc)) // Which source operand ?
4702 ShVal = SVOp->getOperand(OpSrc);
4706 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4707 /// logical left shift of a vector.
4708 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4709 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4710 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4711 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4712 true /* check zeros from left */, DAG);
4718 // Considering the elements in the mask that are not consecutive zeros,
4719 // check if they consecutively come from only one of the source vectors.
4721 // 0 { A, B, X, X } = V2
4723 // vector_shuffle V1, V2 <X, X, 4, 5>
4725 if (!isShuffleMaskConsecutive(SVOp,
4726 NumZeros, // Mask Start Index
4727 NumElems, // Mask End Index(exclusive)
4728 0, // Where to start looking in the src vector
4729 NumElems, // Number of elements in vector
4730 OpSrc)) // Which source operand ?
4735 ShVal = SVOp->getOperand(OpSrc);
4739 /// isVectorShift - Returns true if the shuffle can be implemented as a
4740 /// logical left or right shift of a vector.
4741 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4742 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4743 // Although the logic below support any bitwidth size, there are no
4744 // shift instructions which handle more than 128-bit vectors.
4745 if (SVOp->getValueType(0).getSizeInBits() > 128)
4748 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4749 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4755 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4757 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4758 unsigned NumNonZero, unsigned NumZero,
4760 const X86Subtarget* Subtarget,
4761 const TargetLowering &TLI) {
4765 DebugLoc dl = Op.getDebugLoc();
4768 for (unsigned i = 0; i < 16; ++i) {
4769 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4770 if (ThisIsNonZero && First) {
4772 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4774 V = DAG.getUNDEF(MVT::v8i16);
4779 SDValue ThisElt(0, 0), LastElt(0, 0);
4780 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4781 if (LastIsNonZero) {
4782 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4783 MVT::i16, Op.getOperand(i-1));
4785 if (ThisIsNonZero) {
4786 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4787 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4788 ThisElt, DAG.getConstant(8, MVT::i8));
4790 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4794 if (ThisElt.getNode())
4795 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4796 DAG.getIntPtrConstant(i/2));
4800 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4803 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4805 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4806 unsigned NumNonZero, unsigned NumZero,
4808 const X86Subtarget* Subtarget,
4809 const TargetLowering &TLI) {
4813 DebugLoc dl = Op.getDebugLoc();
4816 for (unsigned i = 0; i < 8; ++i) {
4817 bool isNonZero = (NonZeros & (1 << i)) != 0;
4821 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4823 V = DAG.getUNDEF(MVT::v8i16);
4826 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4827 MVT::v8i16, V, Op.getOperand(i),
4828 DAG.getIntPtrConstant(i));
4835 /// getVShift - Return a vector logical shift node.
4837 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4838 unsigned NumBits, SelectionDAG &DAG,
4839 const TargetLowering &TLI, DebugLoc dl) {
4840 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4841 EVT ShVT = MVT::v2i64;
4842 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4843 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4844 return DAG.getNode(ISD::BITCAST, dl, VT,
4845 DAG.getNode(Opc, dl, ShVT, SrcOp,
4846 DAG.getConstant(NumBits,
4847 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4851 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4852 SelectionDAG &DAG) const {
4854 // Check if the scalar load can be widened into a vector load. And if
4855 // the address is "base + cst" see if the cst can be "absorbed" into
4856 // the shuffle mask.
4857 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4858 SDValue Ptr = LD->getBasePtr();
4859 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4861 EVT PVT = LD->getValueType(0);
4862 if (PVT != MVT::i32 && PVT != MVT::f32)
4867 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4868 FI = FINode->getIndex();
4870 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4871 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4872 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4873 Offset = Ptr.getConstantOperandVal(1);
4874 Ptr = Ptr.getOperand(0);
4879 // FIXME: 256-bit vector instructions don't require a strict alignment,
4880 // improve this code to support it better.
4881 unsigned RequiredAlign = VT.getSizeInBits()/8;
4882 SDValue Chain = LD->getChain();
4883 // Make sure the stack object alignment is at least 16 or 32.
4884 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4885 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4886 if (MFI->isFixedObjectIndex(FI)) {
4887 // Can't change the alignment. FIXME: It's possible to compute
4888 // the exact stack offset and reference FI + adjust offset instead.
4889 // If someone *really* cares about this. That's the way to implement it.
4892 MFI->setObjectAlignment(FI, RequiredAlign);
4896 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4897 // Ptr + (Offset & ~15).
4900 if ((Offset % RequiredAlign) & 3)
4902 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4904 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4905 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4907 int EltNo = (Offset - StartOffset) >> 2;
4908 unsigned NumElems = VT.getVectorNumElements();
4910 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4911 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4912 LD->getPointerInfo().getWithOffset(StartOffset),
4913 false, false, false, 0);
4915 SmallVector<int, 8> Mask;
4916 for (unsigned i = 0; i != NumElems; ++i)
4917 Mask.push_back(EltNo);
4919 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4925 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4926 /// vector of type 'VT', see if the elements can be replaced by a single large
4927 /// load which has the same value as a build_vector whose operands are 'elts'.
4929 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4931 /// FIXME: we'd also like to handle the case where the last elements are zero
4932 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4933 /// There's even a handy isZeroNode for that purpose.
4934 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4935 DebugLoc &DL, SelectionDAG &DAG) {
4936 EVT EltVT = VT.getVectorElementType();
4937 unsigned NumElems = Elts.size();
4939 LoadSDNode *LDBase = NULL;
4940 unsigned LastLoadedElt = -1U;
4942 // For each element in the initializer, see if we've found a load or an undef.
4943 // If we don't find an initial load element, or later load elements are
4944 // non-consecutive, bail out.
4945 for (unsigned i = 0; i < NumElems; ++i) {
4946 SDValue Elt = Elts[i];
4948 if (!Elt.getNode() ||
4949 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4952 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4954 LDBase = cast<LoadSDNode>(Elt.getNode());
4958 if (Elt.getOpcode() == ISD::UNDEF)
4961 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4962 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4967 // If we have found an entire vector of loads and undefs, then return a large
4968 // load of the entire vector width starting at the base pointer. If we found
4969 // consecutive loads for the low half, generate a vzext_load node.
4970 if (LastLoadedElt == NumElems - 1) {
4971 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4972 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4973 LDBase->getPointerInfo(),
4974 LDBase->isVolatile(), LDBase->isNonTemporal(),
4975 LDBase->isInvariant(), 0);
4976 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4977 LDBase->getPointerInfo(),
4978 LDBase->isVolatile(), LDBase->isNonTemporal(),
4979 LDBase->isInvariant(), LDBase->getAlignment());
4981 if (NumElems == 4 && LastLoadedElt == 1 &&
4982 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4983 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4984 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4986 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4987 LDBase->getPointerInfo(),
4988 LDBase->getAlignment(),
4989 false/*isVolatile*/, true/*ReadMem*/,
4991 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4996 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4997 /// to generate a splat value for the following cases:
4998 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4999 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5000 /// a scalar load, or a constant.
5001 /// The VBROADCAST node is returned when a pattern is found,
5002 /// or SDValue() otherwise.
5004 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
5005 if (!Subtarget->hasAVX())
5008 EVT VT = Op.getValueType();
5009 DebugLoc dl = Op.getDebugLoc();
5011 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5012 "Unsupported vector type for broadcast.");
5017 switch (Op.getOpcode()) {
5019 // Unknown pattern found.
5022 case ISD::BUILD_VECTOR: {
5023 // The BUILD_VECTOR node must be a splat.
5024 if (!isSplatVector(Op.getNode()))
5027 Ld = Op.getOperand(0);
5028 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5029 Ld.getOpcode() == ISD::ConstantFP);
5031 // The suspected load node has several users. Make sure that all
5032 // of its users are from the BUILD_VECTOR node.
5033 // Constants may have multiple users.
5034 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5039 case ISD::VECTOR_SHUFFLE: {
5040 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5042 // Shuffles must have a splat mask where the first element is
5044 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5047 SDValue Sc = Op.getOperand(0);
5048 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5049 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5051 if (!Subtarget->hasAVX2())
5054 // Use the register form of the broadcast instruction available on AVX2.
5055 if (VT.is256BitVector())
5056 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5057 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5060 Ld = Sc.getOperand(0);
5061 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5062 Ld.getOpcode() == ISD::ConstantFP);
5064 // The scalar_to_vector node and the suspected
5065 // load node must have exactly one user.
5066 // Constants may have multiple users.
5067 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5073 bool Is256 = VT.getSizeInBits() == 256;
5075 // Handle the broadcasting a single constant scalar from the constant pool
5076 // into a vector. On Sandybridge it is still better to load a constant vector
5077 // from the constant pool and not to broadcast it from a scalar.
5078 if (ConstSplatVal && Subtarget->hasAVX2()) {
5079 EVT CVT = Ld.getValueType();
5080 assert(!CVT.isVector() && "Must not broadcast a vector type");
5081 unsigned ScalarSize = CVT.getSizeInBits();
5083 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5084 const Constant *C = 0;
5085 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5086 C = CI->getConstantIntValue();
5087 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5088 C = CF->getConstantFPValue();
5090 assert(C && "Invalid constant type");
5092 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5093 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5094 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5095 MachinePointerInfo::getConstantPool(),
5096 false, false, false, Alignment);
5098 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5102 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5103 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5105 // Handle AVX2 in-register broadcasts.
5106 if (!IsLoad && Subtarget->hasAVX2() &&
5107 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5108 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5110 // The scalar source must be a normal load.
5114 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5115 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5117 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5118 // double since there is no vbroadcastsd xmm
5119 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5120 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5121 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5124 // Unsupported broadcast.
5129 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5130 DebugLoc dl = Op.getDebugLoc();
5132 EVT VT = Op.getValueType();
5133 EVT ExtVT = VT.getVectorElementType();
5134 unsigned NumElems = Op.getNumOperands();
5136 // Vectors containing all zeros can be matched by pxor and xorps later
5137 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5138 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5139 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5140 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5143 return getZeroVector(VT, Subtarget, DAG, dl);
5146 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5147 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5148 // vpcmpeqd on 256-bit vectors.
5149 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5150 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5153 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5156 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5157 if (Broadcast.getNode())
5160 unsigned EVTBits = ExtVT.getSizeInBits();
5162 unsigned NumZero = 0;
5163 unsigned NumNonZero = 0;
5164 unsigned NonZeros = 0;
5165 bool IsAllConstants = true;
5166 SmallSet<SDValue, 8> Values;
5167 for (unsigned i = 0; i < NumElems; ++i) {
5168 SDValue Elt = Op.getOperand(i);
5169 if (Elt.getOpcode() == ISD::UNDEF)
5172 if (Elt.getOpcode() != ISD::Constant &&
5173 Elt.getOpcode() != ISD::ConstantFP)
5174 IsAllConstants = false;
5175 if (X86::isZeroNode(Elt))
5178 NonZeros |= (1 << i);
5183 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5184 if (NumNonZero == 0)
5185 return DAG.getUNDEF(VT);
5187 // Special case for single non-zero, non-undef, element.
5188 if (NumNonZero == 1) {
5189 unsigned Idx = CountTrailingZeros_32(NonZeros);
5190 SDValue Item = Op.getOperand(Idx);
5192 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5193 // the value are obviously zero, truncate the value to i32 and do the
5194 // insertion that way. Only do this if the value is non-constant or if the
5195 // value is a constant being inserted into element 0. It is cheaper to do
5196 // a constant pool load than it is to do a movd + shuffle.
5197 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5198 (!IsAllConstants || Idx == 0)) {
5199 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5201 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5202 EVT VecVT = MVT::v4i32;
5203 unsigned VecElts = 4;
5205 // Truncate the value (which may itself be a constant) to i32, and
5206 // convert it to a vector with movd (S2V+shuffle to zero extend).
5207 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5208 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5209 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5211 // Now we have our 32-bit value zero extended in the low element of
5212 // a vector. If Idx != 0, swizzle it into place.
5214 SmallVector<int, 4> Mask;
5215 Mask.push_back(Idx);
5216 for (unsigned i = 1; i != VecElts; ++i)
5218 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5221 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5225 // If we have a constant or non-constant insertion into the low element of
5226 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5227 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5228 // depending on what the source datatype is.
5231 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5233 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5234 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5235 if (VT.getSizeInBits() == 256) {
5236 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5237 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5238 Item, DAG.getIntPtrConstant(0));
5240 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5241 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5242 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5243 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5246 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5247 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5248 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5249 if (VT.getSizeInBits() == 256) {
5250 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5251 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5253 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5254 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5256 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5260 // Is it a vector logical left shift?
5261 if (NumElems == 2 && Idx == 1 &&
5262 X86::isZeroNode(Op.getOperand(0)) &&
5263 !X86::isZeroNode(Op.getOperand(1))) {
5264 unsigned NumBits = VT.getSizeInBits();
5265 return getVShift(true, VT,
5266 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5267 VT, Op.getOperand(1)),
5268 NumBits/2, DAG, *this, dl);
5271 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5274 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5275 // is a non-constant being inserted into an element other than the low one,
5276 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5277 // movd/movss) to move this into the low element, then shuffle it into
5279 if (EVTBits == 32) {
5280 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5282 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5283 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5284 SmallVector<int, 8> MaskVec;
5285 for (unsigned i = 0; i != NumElems; ++i)
5286 MaskVec.push_back(i == Idx ? 0 : 1);
5287 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5291 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5292 if (Values.size() == 1) {
5293 if (EVTBits == 32) {
5294 // Instead of a shuffle like this:
5295 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5296 // Check if it's possible to issue this instead.
5297 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5298 unsigned Idx = CountTrailingZeros_32(NonZeros);
5299 SDValue Item = Op.getOperand(Idx);
5300 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5301 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5306 // A vector full of immediates; various special cases are already
5307 // handled, so this is best done with a single constant-pool load.
5311 // For AVX-length vectors, build the individual 128-bit pieces and use
5312 // shuffles to put them in place.
5313 if (VT.getSizeInBits() == 256) {
5314 SmallVector<SDValue, 32> V;
5315 for (unsigned i = 0; i != NumElems; ++i)
5316 V.push_back(Op.getOperand(i));
5318 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5320 // Build both the lower and upper subvector.
5321 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5322 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5325 // Recreate the wider vector with the lower and upper part.
5326 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5329 // Let legalizer expand 2-wide build_vectors.
5330 if (EVTBits == 64) {
5331 if (NumNonZero == 1) {
5332 // One half is zero or undef.
5333 unsigned Idx = CountTrailingZeros_32(NonZeros);
5334 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5335 Op.getOperand(Idx));
5336 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5341 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5342 if (EVTBits == 8 && NumElems == 16) {
5343 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5345 if (V.getNode()) return V;
5348 if (EVTBits == 16 && NumElems == 8) {
5349 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5351 if (V.getNode()) return V;
5354 // If element VT is == 32 bits, turn it into a number of shuffles.
5355 SmallVector<SDValue, 8> V(NumElems);
5356 if (NumElems == 4 && NumZero > 0) {
5357 for (unsigned i = 0; i < 4; ++i) {
5358 bool isZero = !(NonZeros & (1 << i));
5360 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5362 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5365 for (unsigned i = 0; i < 2; ++i) {
5366 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5369 V[i] = V[i*2]; // Must be a zero vector.
5372 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5375 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5378 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5383 bool Reverse1 = (NonZeros & 0x3) == 2;
5384 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5388 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5389 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5391 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5394 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5395 // Check for a build vector of consecutive loads.
5396 for (unsigned i = 0; i < NumElems; ++i)
5397 V[i] = Op.getOperand(i);
5399 // Check for elements which are consecutive loads.
5400 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5404 // For SSE 4.1, use insertps to put the high elements into the low element.
5405 if (getSubtarget()->hasSSE41()) {
5407 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5408 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5410 Result = DAG.getUNDEF(VT);
5412 for (unsigned i = 1; i < NumElems; ++i) {
5413 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5414 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5415 Op.getOperand(i), DAG.getIntPtrConstant(i));
5420 // Otherwise, expand into a number of unpckl*, start by extending each of
5421 // our (non-undef) elements to the full vector width with the element in the
5422 // bottom slot of the vector (which generates no code for SSE).
5423 for (unsigned i = 0; i < NumElems; ++i) {
5424 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5425 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5427 V[i] = DAG.getUNDEF(VT);
5430 // Next, we iteratively mix elements, e.g. for v4f32:
5431 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5432 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5433 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5434 unsigned EltStride = NumElems >> 1;
5435 while (EltStride != 0) {
5436 for (unsigned i = 0; i < EltStride; ++i) {
5437 // If V[i+EltStride] is undef and this is the first round of mixing,
5438 // then it is safe to just drop this shuffle: V[i] is already in the
5439 // right place, the one element (since it's the first round) being
5440 // inserted as undef can be dropped. This isn't safe for successive
5441 // rounds because they will permute elements within both vectors.
5442 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5443 EltStride == NumElems/2)
5446 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5455 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5456 // them in a MMX register. This is better than doing a stack convert.
5457 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5458 DebugLoc dl = Op.getDebugLoc();
5459 EVT ResVT = Op.getValueType();
5461 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5462 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5464 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5465 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5466 InVec = Op.getOperand(1);
5467 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5468 unsigned NumElts = ResVT.getVectorNumElements();
5469 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5470 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5471 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5473 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5474 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5475 Mask[0] = 0; Mask[1] = 2;
5476 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5478 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5481 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5482 // to create 256-bit vectors from two other 128-bit ones.
5483 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5484 DebugLoc dl = Op.getDebugLoc();
5485 EVT ResVT = Op.getValueType();
5487 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5489 SDValue V1 = Op.getOperand(0);
5490 SDValue V2 = Op.getOperand(1);
5491 unsigned NumElems = ResVT.getVectorNumElements();
5493 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5497 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5498 EVT ResVT = Op.getValueType();
5500 assert(Op.getNumOperands() == 2);
5501 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5502 "Unsupported CONCAT_VECTORS for value type");
5504 // We support concatenate two MMX registers and place them in a MMX register.
5505 // This is better than doing a stack convert.
5506 if (ResVT.is128BitVector())
5507 return LowerMMXCONCAT_VECTORS(Op, DAG);
5509 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5510 // from two other 128-bit ones.
5511 return LowerAVXCONCAT_VECTORS(Op, DAG);
5514 // Try to lower a shuffle node into a simple blend instruction.
5515 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5516 const X86Subtarget *Subtarget,
5517 SelectionDAG &DAG) {
5518 SDValue V1 = SVOp->getOperand(0);
5519 SDValue V2 = SVOp->getOperand(1);
5520 DebugLoc dl = SVOp->getDebugLoc();
5521 MVT VT = SVOp->getValueType(0).getSimpleVT();
5522 unsigned NumElems = VT.getVectorNumElements();
5524 if (!Subtarget->hasSSE41())
5530 switch (VT.SimpleTy) {
5531 default: return SDValue();
5533 ISDNo = X86ISD::BLENDPW;
5538 ISDNo = X86ISD::BLENDPS;
5543 ISDNo = X86ISD::BLENDPD;
5548 if (!Subtarget->hasAVX())
5550 ISDNo = X86ISD::BLENDPS;
5555 if (!Subtarget->hasAVX())
5557 ISDNo = X86ISD::BLENDPD;
5561 assert(ISDNo && "Invalid Op Number");
5563 unsigned MaskVals = 0;
5565 for (unsigned i = 0; i != NumElems; ++i) {
5566 int EltIdx = SVOp->getMaskElt(i);
5567 if (EltIdx == (int)i || EltIdx < 0)
5569 else if (EltIdx == (int)(i + NumElems))
5570 continue; // Bit is set to zero;
5575 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5576 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5577 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5578 DAG.getConstant(MaskVals, MVT::i32));
5579 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5582 // v8i16 shuffles - Prefer shuffles in the following order:
5583 // 1. [all] pshuflw, pshufhw, optional move
5584 // 2. [ssse3] 1 x pshufb
5585 // 3. [ssse3] 2 x pshufb + 1 x por
5586 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5588 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5589 SelectionDAG &DAG) const {
5590 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5591 SDValue V1 = SVOp->getOperand(0);
5592 SDValue V2 = SVOp->getOperand(1);
5593 DebugLoc dl = SVOp->getDebugLoc();
5594 SmallVector<int, 8> MaskVals;
5596 // Determine if more than 1 of the words in each of the low and high quadwords
5597 // of the result come from the same quadword of one of the two inputs. Undef
5598 // mask values count as coming from any quadword, for better codegen.
5599 unsigned LoQuad[] = { 0, 0, 0, 0 };
5600 unsigned HiQuad[] = { 0, 0, 0, 0 };
5601 std::bitset<4> InputQuads;
5602 for (unsigned i = 0; i < 8; ++i) {
5603 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5604 int EltIdx = SVOp->getMaskElt(i);
5605 MaskVals.push_back(EltIdx);
5614 InputQuads.set(EltIdx / 4);
5617 int BestLoQuad = -1;
5618 unsigned MaxQuad = 1;
5619 for (unsigned i = 0; i < 4; ++i) {
5620 if (LoQuad[i] > MaxQuad) {
5622 MaxQuad = LoQuad[i];
5626 int BestHiQuad = -1;
5628 for (unsigned i = 0; i < 4; ++i) {
5629 if (HiQuad[i] > MaxQuad) {
5631 MaxQuad = HiQuad[i];
5635 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5636 // of the two input vectors, shuffle them into one input vector so only a
5637 // single pshufb instruction is necessary. If There are more than 2 input
5638 // quads, disable the next transformation since it does not help SSSE3.
5639 bool V1Used = InputQuads[0] || InputQuads[1];
5640 bool V2Used = InputQuads[2] || InputQuads[3];
5641 if (Subtarget->hasSSSE3()) {
5642 if (InputQuads.count() == 2 && V1Used && V2Used) {
5643 BestLoQuad = InputQuads[0] ? 0 : 1;
5644 BestHiQuad = InputQuads[2] ? 2 : 3;
5646 if (InputQuads.count() > 2) {
5652 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5653 // the shuffle mask. If a quad is scored as -1, that means that it contains
5654 // words from all 4 input quadwords.
5656 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5658 BestLoQuad < 0 ? 0 : BestLoQuad,
5659 BestHiQuad < 0 ? 1 : BestHiQuad
5661 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5662 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5663 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5664 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5666 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5667 // source words for the shuffle, to aid later transformations.
5668 bool AllWordsInNewV = true;
5669 bool InOrder[2] = { true, true };
5670 for (unsigned i = 0; i != 8; ++i) {
5671 int idx = MaskVals[i];
5673 InOrder[i/4] = false;
5674 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5676 AllWordsInNewV = false;
5680 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5681 if (AllWordsInNewV) {
5682 for (int i = 0; i != 8; ++i) {
5683 int idx = MaskVals[i];
5686 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5687 if ((idx != i) && idx < 4)
5689 if ((idx != i) && idx > 3)
5698 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5699 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5700 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5701 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5702 unsigned TargetMask = 0;
5703 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5704 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5705 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5706 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5707 getShufflePSHUFLWImmediate(SVOp);
5708 V1 = NewV.getOperand(0);
5709 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5713 // If we have SSSE3, and all words of the result are from 1 input vector,
5714 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5715 // is present, fall back to case 4.
5716 if (Subtarget->hasSSSE3()) {
5717 SmallVector<SDValue,16> pshufbMask;
5719 // If we have elements from both input vectors, set the high bit of the
5720 // shuffle mask element to zero out elements that come from V2 in the V1
5721 // mask, and elements that come from V1 in the V2 mask, so that the two
5722 // results can be OR'd together.
5723 bool TwoInputs = V1Used && V2Used;
5724 for (unsigned i = 0; i != 8; ++i) {
5725 int EltIdx = MaskVals[i] * 2;
5726 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5727 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5728 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5729 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5731 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5732 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5733 DAG.getNode(ISD::BUILD_VECTOR, dl,
5734 MVT::v16i8, &pshufbMask[0], 16));
5736 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5738 // Calculate the shuffle mask for the second input, shuffle it, and
5739 // OR it with the first shuffled input.
5741 for (unsigned i = 0; i != 8; ++i) {
5742 int EltIdx = MaskVals[i] * 2;
5743 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5744 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5745 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5746 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5748 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5749 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5750 DAG.getNode(ISD::BUILD_VECTOR, dl,
5751 MVT::v16i8, &pshufbMask[0], 16));
5752 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5753 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5756 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5757 // and update MaskVals with new element order.
5758 std::bitset<8> InOrder;
5759 if (BestLoQuad >= 0) {
5760 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5761 for (int i = 0; i != 4; ++i) {
5762 int idx = MaskVals[i];
5765 } else if ((idx / 4) == BestLoQuad) {
5770 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5773 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5774 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5775 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5777 getShufflePSHUFLWImmediate(SVOp), DAG);
5781 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5782 // and update MaskVals with the new element order.
5783 if (BestHiQuad >= 0) {
5784 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5785 for (unsigned i = 4; i != 8; ++i) {
5786 int idx = MaskVals[i];
5789 } else if ((idx / 4) == BestHiQuad) {
5790 MaskV[i] = (idx & 3) + 4;
5794 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5797 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5798 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5799 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5801 getShufflePSHUFHWImmediate(SVOp), DAG);
5805 // In case BestHi & BestLo were both -1, which means each quadword has a word
5806 // from each of the four input quadwords, calculate the InOrder bitvector now
5807 // before falling through to the insert/extract cleanup.
5808 if (BestLoQuad == -1 && BestHiQuad == -1) {
5810 for (int i = 0; i != 8; ++i)
5811 if (MaskVals[i] < 0 || MaskVals[i] == i)
5815 // The other elements are put in the right place using pextrw and pinsrw.
5816 for (unsigned i = 0; i != 8; ++i) {
5819 int EltIdx = MaskVals[i];
5822 SDValue ExtOp = (EltIdx < 8) ?
5823 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5824 DAG.getIntPtrConstant(EltIdx)) :
5825 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5826 DAG.getIntPtrConstant(EltIdx - 8));
5827 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5828 DAG.getIntPtrConstant(i));
5833 // v16i8 shuffles - Prefer shuffles in the following order:
5834 // 1. [ssse3] 1 x pshufb
5835 // 2. [ssse3] 2 x pshufb + 1 x por
5836 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5838 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5840 const X86TargetLowering &TLI) {
5841 SDValue V1 = SVOp->getOperand(0);
5842 SDValue V2 = SVOp->getOperand(1);
5843 DebugLoc dl = SVOp->getDebugLoc();
5844 ArrayRef<int> MaskVals = SVOp->getMask();
5846 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5848 // If we have SSSE3, case 1 is generated when all result bytes come from
5849 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5850 // present, fall back to case 3.
5852 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5853 if (TLI.getSubtarget()->hasSSSE3()) {
5854 SmallVector<SDValue,16> pshufbMask;
5856 // If all result elements are from one input vector, then only translate
5857 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5859 // Otherwise, we have elements from both input vectors, and must zero out
5860 // elements that come from V2 in the first mask, and V1 in the second mask
5861 // so that we can OR them together.
5862 for (unsigned i = 0; i != 16; ++i) {
5863 int EltIdx = MaskVals[i];
5864 if (EltIdx < 0 || EltIdx >= 16)
5866 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5868 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5869 DAG.getNode(ISD::BUILD_VECTOR, dl,
5870 MVT::v16i8, &pshufbMask[0], 16));
5874 // Calculate the shuffle mask for the second input, shuffle it, and
5875 // OR it with the first shuffled input.
5877 for (unsigned i = 0; i != 16; ++i) {
5878 int EltIdx = MaskVals[i];
5879 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5880 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5882 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5883 DAG.getNode(ISD::BUILD_VECTOR, dl,
5884 MVT::v16i8, &pshufbMask[0], 16));
5885 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5888 // No SSSE3 - Calculate in place words and then fix all out of place words
5889 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5890 // the 16 different words that comprise the two doublequadword input vectors.
5891 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5892 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5894 for (int i = 0; i != 8; ++i) {
5895 int Elt0 = MaskVals[i*2];
5896 int Elt1 = MaskVals[i*2+1];
5898 // This word of the result is all undef, skip it.
5899 if (Elt0 < 0 && Elt1 < 0)
5902 // This word of the result is already in the correct place, skip it.
5903 if ((Elt0 == i*2) && (Elt1 == i*2+1))
5906 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5907 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5910 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5911 // using a single extract together, load it and store it.
5912 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5913 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5914 DAG.getIntPtrConstant(Elt1 / 2));
5915 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5916 DAG.getIntPtrConstant(i));
5920 // If Elt1 is defined, extract it from the appropriate source. If the
5921 // source byte is not also odd, shift the extracted word left 8 bits
5922 // otherwise clear the bottom 8 bits if we need to do an or.
5924 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5925 DAG.getIntPtrConstant(Elt1 / 2));
5926 if ((Elt1 & 1) == 0)
5927 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5929 TLI.getShiftAmountTy(InsElt.getValueType())));
5931 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5932 DAG.getConstant(0xFF00, MVT::i16));
5934 // If Elt0 is defined, extract it from the appropriate source. If the
5935 // source byte is not also even, shift the extracted word right 8 bits. If
5936 // Elt1 was also defined, OR the extracted values together before
5937 // inserting them in the result.
5939 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5940 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5941 if ((Elt0 & 1) != 0)
5942 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5944 TLI.getShiftAmountTy(InsElt0.getValueType())));
5946 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5947 DAG.getConstant(0x00FF, MVT::i16));
5948 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5951 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5952 DAG.getIntPtrConstant(i));
5954 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5957 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5958 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5959 /// done when every pair / quad of shuffle mask elements point to elements in
5960 /// the right sequence. e.g.
5961 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5963 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5964 SelectionDAG &DAG, DebugLoc dl) {
5965 MVT VT = SVOp->getValueType(0).getSimpleVT();
5966 unsigned NumElems = VT.getVectorNumElements();
5969 switch (VT.SimpleTy) {
5970 default: llvm_unreachable("Unexpected!");
5971 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
5972 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
5973 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
5974 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
5975 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
5976 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
5979 SmallVector<int, 8> MaskVec;
5980 for (unsigned i = 0; i != NumElems; i += Scale) {
5982 for (unsigned j = 0; j != Scale; ++j) {
5983 int EltIdx = SVOp->getMaskElt(i+j);
5987 StartIdx = (EltIdx / Scale);
5988 if (EltIdx != (int)(StartIdx*Scale + j))
5991 MaskVec.push_back(StartIdx);
5994 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
5995 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
5996 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5999 /// getVZextMovL - Return a zero-extending vector move low node.
6001 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6002 SDValue SrcOp, SelectionDAG &DAG,
6003 const X86Subtarget *Subtarget, DebugLoc dl) {
6004 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6005 LoadSDNode *LD = NULL;
6006 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6007 LD = dyn_cast<LoadSDNode>(SrcOp);
6009 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6011 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6012 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6013 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6014 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6015 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6017 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6018 return DAG.getNode(ISD::BITCAST, dl, VT,
6019 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6020 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6028 return DAG.getNode(ISD::BITCAST, dl, VT,
6029 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6030 DAG.getNode(ISD::BITCAST, dl,
6034 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6035 /// which could not be matched by any known target speficic shuffle
6037 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6039 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6040 if (NewOp.getNode())
6043 EVT VT = SVOp->getValueType(0);
6045 unsigned NumElems = VT.getVectorNumElements();
6046 unsigned NumLaneElems = NumElems / 2;
6048 DebugLoc dl = SVOp->getDebugLoc();
6049 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6050 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6053 SmallVector<int, 16> Mask;
6054 for (unsigned l = 0; l < 2; ++l) {
6055 // Build a shuffle mask for the output, discovering on the fly which
6056 // input vectors to use as shuffle operands (recorded in InputUsed).
6057 // If building a suitable shuffle vector proves too hard, then bail
6058 // out with UseBuildVector set.
6059 bool UseBuildVector = false;
6060 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6061 unsigned LaneStart = l * NumLaneElems;
6062 for (unsigned i = 0; i != NumLaneElems; ++i) {
6063 // The mask element. This indexes into the input.
6064 int Idx = SVOp->getMaskElt(i+LaneStart);
6066 // the mask element does not index into any input vector.
6071 // The input vector this mask element indexes into.
6072 int Input = Idx / NumLaneElems;
6074 // Turn the index into an offset from the start of the input vector.
6075 Idx -= Input * NumLaneElems;
6077 // Find or create a shuffle vector operand to hold this input.
6079 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6080 if (InputUsed[OpNo] == Input)
6081 // This input vector is already an operand.
6083 if (InputUsed[OpNo] < 0) {
6084 // Create a new operand for this input vector.
6085 InputUsed[OpNo] = Input;
6090 if (OpNo >= array_lengthof(InputUsed)) {
6091 // More than two input vectors used! Give up on trying to create a
6092 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6093 UseBuildVector = true;
6097 // Add the mask index for the new shuffle vector.
6098 Mask.push_back(Idx + OpNo * NumLaneElems);
6101 if (UseBuildVector) {
6102 SmallVector<SDValue, 16> SVOps;
6103 for (unsigned i = 0; i != NumLaneElems; ++i) {
6104 // The mask element. This indexes into the input.
6105 int Idx = SVOp->getMaskElt(i+LaneStart);
6107 SVOps.push_back(DAG.getUNDEF(EltVT));
6111 // The input vector this mask element indexes into.
6112 int Input = Idx / NumElems;
6114 // Turn the index into an offset from the start of the input vector.
6115 Idx -= Input * NumElems;
6117 // Extract the vector element by hand.
6118 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6119 SVOp->getOperand(Input),
6120 DAG.getIntPtrConstant(Idx)));
6123 // Construct the output using a BUILD_VECTOR.
6124 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6126 } else if (InputUsed[0] < 0) {
6127 // No input vectors were used! The result is undefined.
6128 Output[l] = DAG.getUNDEF(NVT);
6130 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6131 (InputUsed[0] % 2) * NumLaneElems,
6133 // If only one input was used, use an undefined vector for the other.
6134 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6135 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6136 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6137 // At least one input vector was used. Create a new shuffle vector.
6138 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6144 // Concatenate the result back
6145 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6148 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6149 /// 4 elements, and match them with several different shuffle types.
6151 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6152 SDValue V1 = SVOp->getOperand(0);
6153 SDValue V2 = SVOp->getOperand(1);
6154 DebugLoc dl = SVOp->getDebugLoc();
6155 EVT VT = SVOp->getValueType(0);
6157 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6159 std::pair<int, int> Locs[4];
6160 int Mask1[] = { -1, -1, -1, -1 };
6161 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6165 for (unsigned i = 0; i != 4; ++i) {
6166 int Idx = PermMask[i];
6168 Locs[i] = std::make_pair(-1, -1);
6170 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6172 Locs[i] = std::make_pair(0, NumLo);
6176 Locs[i] = std::make_pair(1, NumHi);
6178 Mask1[2+NumHi] = Idx;
6184 if (NumLo <= 2 && NumHi <= 2) {
6185 // If no more than two elements come from either vector. This can be
6186 // implemented with two shuffles. First shuffle gather the elements.
6187 // The second shuffle, which takes the first shuffle as both of its
6188 // vector operands, put the elements into the right order.
6189 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6191 int Mask2[] = { -1, -1, -1, -1 };
6193 for (unsigned i = 0; i != 4; ++i)
6194 if (Locs[i].first != -1) {
6195 unsigned Idx = (i < 2) ? 0 : 4;
6196 Idx += Locs[i].first * 2 + Locs[i].second;
6200 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6203 if (NumLo == 3 || NumHi == 3) {
6204 // Otherwise, we must have three elements from one vector, call it X, and
6205 // one element from the other, call it Y. First, use a shufps to build an
6206 // intermediate vector with the one element from Y and the element from X
6207 // that will be in the same half in the final destination (the indexes don't
6208 // matter). Then, use a shufps to build the final vector, taking the half
6209 // containing the element from Y from the intermediate, and the other half
6212 // Normalize it so the 3 elements come from V1.
6213 CommuteVectorShuffleMask(PermMask, 4);
6217 // Find the element from V2.
6219 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6220 int Val = PermMask[HiIndex];
6227 Mask1[0] = PermMask[HiIndex];
6229 Mask1[2] = PermMask[HiIndex^1];
6231 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6234 Mask1[0] = PermMask[0];
6235 Mask1[1] = PermMask[1];
6236 Mask1[2] = HiIndex & 1 ? 6 : 4;
6237 Mask1[3] = HiIndex & 1 ? 4 : 6;
6238 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6241 Mask1[0] = HiIndex & 1 ? 2 : 0;
6242 Mask1[1] = HiIndex & 1 ? 0 : 2;
6243 Mask1[2] = PermMask[2];
6244 Mask1[3] = PermMask[3];
6249 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6252 // Break it into (shuffle shuffle_hi, shuffle_lo).
6253 int LoMask[] = { -1, -1, -1, -1 };
6254 int HiMask[] = { -1, -1, -1, -1 };
6256 int *MaskPtr = LoMask;
6257 unsigned MaskIdx = 0;
6260 for (unsigned i = 0; i != 4; ++i) {
6267 int Idx = PermMask[i];
6269 Locs[i] = std::make_pair(-1, -1);
6270 } else if (Idx < 4) {
6271 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6272 MaskPtr[LoIdx] = Idx;
6275 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6276 MaskPtr[HiIdx] = Idx;
6281 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6282 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6283 int MaskOps[] = { -1, -1, -1, -1 };
6284 for (unsigned i = 0; i != 4; ++i)
6285 if (Locs[i].first != -1)
6286 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6287 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6290 static bool MayFoldVectorLoad(SDValue V) {
6291 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6292 V = V.getOperand(0);
6293 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6294 V = V.getOperand(0);
6295 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6296 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6297 // BUILD_VECTOR (load), undef
6298 V = V.getOperand(0);
6304 // FIXME: the version above should always be used. Since there's
6305 // a bug where several vector shuffles can't be folded because the
6306 // DAG is not updated during lowering and a node claims to have two
6307 // uses while it only has one, use this version, and let isel match
6308 // another instruction if the load really happens to have more than
6309 // one use. Remove this version after this bug get fixed.
6310 // rdar://8434668, PR8156
6311 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6312 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6313 V = V.getOperand(0);
6314 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6315 V = V.getOperand(0);
6316 if (ISD::isNormalLoad(V.getNode()))
6322 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6323 EVT VT = Op.getValueType();
6325 // Canonizalize to v2f64.
6326 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6327 return DAG.getNode(ISD::BITCAST, dl, VT,
6328 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6333 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6335 SDValue V1 = Op.getOperand(0);
6336 SDValue V2 = Op.getOperand(1);
6337 EVT VT = Op.getValueType();
6339 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6341 if (HasSSE2 && VT == MVT::v2f64)
6342 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6344 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6345 return DAG.getNode(ISD::BITCAST, dl, VT,
6346 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6347 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6348 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6352 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6353 SDValue V1 = Op.getOperand(0);
6354 SDValue V2 = Op.getOperand(1);
6355 EVT VT = Op.getValueType();
6357 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6358 "unsupported shuffle type");
6360 if (V2.getOpcode() == ISD::UNDEF)
6364 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6368 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6369 SDValue V1 = Op.getOperand(0);
6370 SDValue V2 = Op.getOperand(1);
6371 EVT VT = Op.getValueType();
6372 unsigned NumElems = VT.getVectorNumElements();
6374 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6375 // operand of these instructions is only memory, so check if there's a
6376 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6378 bool CanFoldLoad = false;
6380 // Trivial case, when V2 comes from a load.
6381 if (MayFoldVectorLoad(V2))
6384 // When V1 is a load, it can be folded later into a store in isel, example:
6385 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6387 // (MOVLPSmr addr:$src1, VR128:$src2)
6388 // So, recognize this potential and also use MOVLPS or MOVLPD
6389 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6392 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6394 if (HasSSE2 && NumElems == 2)
6395 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6398 // If we don't care about the second element, proceed to use movss.
6399 if (SVOp->getMaskElt(1) != -1)
6400 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6403 // movl and movlp will both match v2i64, but v2i64 is never matched by
6404 // movl earlier because we make it strict to avoid messing with the movlp load
6405 // folding logic (see the code above getMOVLP call). Match it here then,
6406 // this is horrible, but will stay like this until we move all shuffle
6407 // matching to x86 specific nodes. Note that for the 1st condition all
6408 // types are matched with movsd.
6410 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6411 // as to remove this logic from here, as much as possible
6412 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6413 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6414 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6417 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6419 // Invert the operand order and use SHUFPS to match it.
6420 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6421 getShuffleSHUFImmediate(SVOp), DAG);
6425 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6426 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6427 EVT VT = Op.getValueType();
6428 DebugLoc dl = Op.getDebugLoc();
6429 SDValue V1 = Op.getOperand(0);
6430 SDValue V2 = Op.getOperand(1);
6432 if (isZeroShuffle(SVOp))
6433 return getZeroVector(VT, Subtarget, DAG, dl);
6435 // Handle splat operations
6436 if (SVOp->isSplat()) {
6437 unsigned NumElem = VT.getVectorNumElements();
6438 int Size = VT.getSizeInBits();
6440 // Use vbroadcast whenever the splat comes from a foldable load
6441 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6442 if (Broadcast.getNode())
6445 // Handle splats by matching through known shuffle masks
6446 if ((Size == 128 && NumElem <= 4) ||
6447 (Size == 256 && NumElem < 8))
6450 // All remaning splats are promoted to target supported vector shuffles.
6451 return PromoteSplat(SVOp, DAG);
6454 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6456 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6457 VT == MVT::v16i16 || VT == MVT::v32i8) {
6458 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6459 if (NewOp.getNode())
6460 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6461 } else if ((VT == MVT::v4i32 ||
6462 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6463 // FIXME: Figure out a cleaner way to do this.
6464 // Try to make use of movq to zero out the top part.
6465 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6466 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6467 if (NewOp.getNode()) {
6468 EVT NewVT = NewOp.getValueType();
6469 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6470 NewVT, true, false))
6471 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6472 DAG, Subtarget, dl);
6474 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6475 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6476 if (NewOp.getNode()) {
6477 EVT NewVT = NewOp.getValueType();
6478 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6479 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6480 DAG, Subtarget, dl);
6488 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6489 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6490 SDValue V1 = Op.getOperand(0);
6491 SDValue V2 = Op.getOperand(1);
6492 EVT VT = Op.getValueType();
6493 DebugLoc dl = Op.getDebugLoc();
6494 unsigned NumElems = VT.getVectorNumElements();
6495 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6496 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6497 bool V1IsSplat = false;
6498 bool V2IsSplat = false;
6499 bool HasSSE2 = Subtarget->hasSSE2();
6500 bool HasAVX = Subtarget->hasAVX();
6501 bool HasAVX2 = Subtarget->hasAVX2();
6502 MachineFunction &MF = DAG.getMachineFunction();
6503 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6505 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6507 if (V1IsUndef && V2IsUndef)
6508 return DAG.getUNDEF(VT);
6510 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6512 // Vector shuffle lowering takes 3 steps:
6514 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6515 // narrowing and commutation of operands should be handled.
6516 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6518 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6519 // so the shuffle can be broken into other shuffles and the legalizer can
6520 // try the lowering again.
6522 // The general idea is that no vector_shuffle operation should be left to
6523 // be matched during isel, all of them must be converted to a target specific
6526 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6527 // narrowing and commutation of operands should be handled. The actual code
6528 // doesn't include all of those, work in progress...
6529 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6530 if (NewOp.getNode())
6533 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6535 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6536 // unpckh_undef). Only use pshufd if speed is more important than size.
6537 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6538 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6539 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6540 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6542 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6543 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6544 return getMOVDDup(Op, dl, V1, DAG);
6546 if (isMOVHLPS_v_undef_Mask(M, VT))
6547 return getMOVHighToLow(Op, dl, DAG);
6549 // Use to match splats
6550 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6551 (VT == MVT::v2f64 || VT == MVT::v2i64))
6552 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6554 if (isPSHUFDMask(M, VT)) {
6555 // The actual implementation will match the mask in the if above and then
6556 // during isel it can match several different instructions, not only pshufd
6557 // as its name says, sad but true, emulate the behavior for now...
6558 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6559 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6561 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6563 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6564 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6566 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6567 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6569 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6573 // Check if this can be converted into a logical shift.
6574 bool isLeft = false;
6577 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6578 if (isShift && ShVal.hasOneUse()) {
6579 // If the shifted value has multiple uses, it may be cheaper to use
6580 // v_set0 + movlhps or movhlps, etc.
6581 EVT EltVT = VT.getVectorElementType();
6582 ShAmt *= EltVT.getSizeInBits();
6583 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6586 if (isMOVLMask(M, VT)) {
6587 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6588 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6589 if (!isMOVLPMask(M, VT)) {
6590 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6591 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6593 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6594 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6598 // FIXME: fold these into legal mask.
6599 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6600 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6602 if (isMOVHLPSMask(M, VT))
6603 return getMOVHighToLow(Op, dl, DAG);
6605 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6606 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6608 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6609 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6611 if (isMOVLPMask(M, VT))
6612 return getMOVLP(Op, dl, DAG, HasSSE2);
6614 if (ShouldXformToMOVHLPS(M, VT) ||
6615 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6616 return CommuteVectorShuffle(SVOp, DAG);
6619 // No better options. Use a vshldq / vsrldq.
6620 EVT EltVT = VT.getVectorElementType();
6621 ShAmt *= EltVT.getSizeInBits();
6622 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6625 bool Commuted = false;
6626 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6627 // 1,1,1,1 -> v8i16 though.
6628 V1IsSplat = isSplatVector(V1.getNode());
6629 V2IsSplat = isSplatVector(V2.getNode());
6631 // Canonicalize the splat or undef, if present, to be on the RHS.
6632 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6633 CommuteVectorShuffleMask(M, NumElems);
6635 std::swap(V1IsSplat, V2IsSplat);
6639 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6640 // Shuffling low element of v1 into undef, just return v1.
6643 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6644 // the instruction selector will not match, so get a canonical MOVL with
6645 // swapped operands to undo the commute.
6646 return getMOVL(DAG, dl, VT, V2, V1);
6649 if (isUNPCKLMask(M, VT, HasAVX2))
6650 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6652 if (isUNPCKHMask(M, VT, HasAVX2))
6653 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6656 // Normalize mask so all entries that point to V2 points to its first
6657 // element then try to match unpck{h|l} again. If match, return a
6658 // new vector_shuffle with the corrected mask.p
6659 SmallVector<int, 8> NewMask(M.begin(), M.end());
6660 NormalizeMask(NewMask, NumElems);
6661 if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6662 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6663 if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6664 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6668 // Commute is back and try unpck* again.
6669 // FIXME: this seems wrong.
6670 CommuteVectorShuffleMask(M, NumElems);
6672 std::swap(V1IsSplat, V2IsSplat);
6675 if (isUNPCKLMask(M, VT, HasAVX2))
6676 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6678 if (isUNPCKHMask(M, VT, HasAVX2))
6679 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6682 // Normalize the node to match x86 shuffle ops if needed
6683 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6684 return CommuteVectorShuffle(SVOp, DAG);
6686 // The checks below are all present in isShuffleMaskLegal, but they are
6687 // inlined here right now to enable us to directly emit target specific
6688 // nodes, and remove one by one until they don't return Op anymore.
6690 if (isPALIGNRMask(M, VT, Subtarget))
6691 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6692 getShufflePALIGNRImmediate(SVOp),
6695 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6696 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6697 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6698 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6701 if (isPSHUFHWMask(M, VT, HasAVX2))
6702 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6703 getShufflePSHUFHWImmediate(SVOp),
6706 if (isPSHUFLWMask(M, VT, HasAVX2))
6707 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6708 getShufflePSHUFLWImmediate(SVOp),
6711 if (isSHUFPMask(M, VT, HasAVX))
6712 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6713 getShuffleSHUFImmediate(SVOp), DAG);
6715 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6716 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6717 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6718 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6720 //===--------------------------------------------------------------------===//
6721 // Generate target specific nodes for 128 or 256-bit shuffles only
6722 // supported in the AVX instruction set.
6725 // Handle VMOVDDUPY permutations
6726 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6727 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6729 // Handle VPERMILPS/D* permutations
6730 if (isVPERMILPMask(M, VT, HasAVX)) {
6731 if (HasAVX2 && VT == MVT::v8i32)
6732 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6733 getShuffleSHUFImmediate(SVOp), DAG);
6734 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6735 getShuffleSHUFImmediate(SVOp), DAG);
6738 // Handle VPERM2F128/VPERM2I128 permutations
6739 if (isVPERM2X128Mask(M, VT, HasAVX))
6740 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6741 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6743 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6744 if (BlendOp.getNode())
6747 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6748 SmallVector<SDValue, 8> permclMask;
6749 for (unsigned i = 0; i != 8; ++i) {
6750 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6752 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6754 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6755 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6756 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6759 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6760 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6761 getShuffleCLImmediate(SVOp), DAG);
6764 //===--------------------------------------------------------------------===//
6765 // Since no target specific shuffle was selected for this generic one,
6766 // lower it into other known shuffles. FIXME: this isn't true yet, but
6767 // this is the plan.
6770 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6771 if (VT == MVT::v8i16) {
6772 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6773 if (NewOp.getNode())
6777 if (VT == MVT::v16i8) {
6778 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6779 if (NewOp.getNode())
6783 // Handle all 128-bit wide vectors with 4 elements, and match them with
6784 // several different shuffle types.
6785 if (NumElems == 4 && VT.getSizeInBits() == 128)
6786 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6788 // Handle general 256-bit shuffles
6789 if (VT.is256BitVector())
6790 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6796 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6797 SelectionDAG &DAG) const {
6798 EVT VT = Op.getValueType();
6799 DebugLoc dl = Op.getDebugLoc();
6801 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6804 if (VT.getSizeInBits() == 8) {
6805 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6806 Op.getOperand(0), Op.getOperand(1));
6807 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6808 DAG.getValueType(VT));
6809 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6812 if (VT.getSizeInBits() == 16) {
6813 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6814 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6816 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6817 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6818 DAG.getNode(ISD::BITCAST, dl,
6822 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6823 Op.getOperand(0), Op.getOperand(1));
6824 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6825 DAG.getValueType(VT));
6826 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6829 if (VT == MVT::f32) {
6830 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6831 // the result back to FR32 register. It's only worth matching if the
6832 // result has a single use which is a store or a bitcast to i32. And in
6833 // the case of a store, it's not worth it if the index is a constant 0,
6834 // because a MOVSSmr can be used instead, which is smaller and faster.
6835 if (!Op.hasOneUse())
6837 SDNode *User = *Op.getNode()->use_begin();
6838 if ((User->getOpcode() != ISD::STORE ||
6839 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6840 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6841 (User->getOpcode() != ISD::BITCAST ||
6842 User->getValueType(0) != MVT::i32))
6844 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6845 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6848 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6851 if (VT == MVT::i32 || VT == MVT::i64) {
6852 // ExtractPS/pextrq works with constant index.
6853 if (isa<ConstantSDNode>(Op.getOperand(1)))
6861 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6862 SelectionDAG &DAG) const {
6863 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6866 SDValue Vec = Op.getOperand(0);
6867 EVT VecVT = Vec.getValueType();
6869 // If this is a 256-bit vector result, first extract the 128-bit vector and
6870 // then extract the element from the 128-bit vector.
6871 if (VecVT.getSizeInBits() == 256) {
6872 DebugLoc dl = Op.getNode()->getDebugLoc();
6873 unsigned NumElems = VecVT.getVectorNumElements();
6874 SDValue Idx = Op.getOperand(1);
6875 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6877 // Get the 128-bit vector.
6878 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6880 if (IdxVal >= NumElems/2)
6881 IdxVal -= NumElems/2;
6882 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6883 DAG.getConstant(IdxVal, MVT::i32));
6886 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6888 if (Subtarget->hasSSE41()) {
6889 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6894 EVT VT = Op.getValueType();
6895 DebugLoc dl = Op.getDebugLoc();
6896 // TODO: handle v16i8.
6897 if (VT.getSizeInBits() == 16) {
6898 SDValue Vec = Op.getOperand(0);
6899 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6901 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6902 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6903 DAG.getNode(ISD::BITCAST, dl,
6906 // Transform it so it match pextrw which produces a 32-bit result.
6907 EVT EltVT = MVT::i32;
6908 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6909 Op.getOperand(0), Op.getOperand(1));
6910 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6911 DAG.getValueType(VT));
6912 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6915 if (VT.getSizeInBits() == 32) {
6916 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6920 // SHUFPS the element to the lowest double word, then movss.
6921 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6922 EVT VVT = Op.getOperand(0).getValueType();
6923 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6924 DAG.getUNDEF(VVT), Mask);
6925 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6926 DAG.getIntPtrConstant(0));
6929 if (VT.getSizeInBits() == 64) {
6930 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6931 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6932 // to match extract_elt for f64.
6933 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6937 // UNPCKHPD the element to the lowest double word, then movsd.
6938 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6939 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6940 int Mask[2] = { 1, -1 };
6941 EVT VVT = Op.getOperand(0).getValueType();
6942 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6943 DAG.getUNDEF(VVT), Mask);
6944 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6945 DAG.getIntPtrConstant(0));
6952 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6953 SelectionDAG &DAG) const {
6954 EVT VT = Op.getValueType();
6955 EVT EltVT = VT.getVectorElementType();
6956 DebugLoc dl = Op.getDebugLoc();
6958 SDValue N0 = Op.getOperand(0);
6959 SDValue N1 = Op.getOperand(1);
6960 SDValue N2 = Op.getOperand(2);
6962 if (VT.getSizeInBits() == 256)
6965 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6966 isa<ConstantSDNode>(N2)) {
6968 if (VT == MVT::v8i16)
6969 Opc = X86ISD::PINSRW;
6970 else if (VT == MVT::v16i8)
6971 Opc = X86ISD::PINSRB;
6973 Opc = X86ISD::PINSRB;
6975 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6977 if (N1.getValueType() != MVT::i32)
6978 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6979 if (N2.getValueType() != MVT::i32)
6980 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6981 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6984 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6985 // Bits [7:6] of the constant are the source select. This will always be
6986 // zero here. The DAG Combiner may combine an extract_elt index into these
6987 // bits. For example (insert (extract, 3), 2) could be matched by putting
6988 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6989 // Bits [5:4] of the constant are the destination select. This is the
6990 // value of the incoming immediate.
6991 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6992 // combine either bitwise AND or insert of float 0.0 to set these bits.
6993 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6994 // Create this as a scalar to vector..
6995 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6996 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6999 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7000 // PINSR* works with constant index.
7007 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7008 EVT VT = Op.getValueType();
7009 EVT EltVT = VT.getVectorElementType();
7011 DebugLoc dl = Op.getDebugLoc();
7012 SDValue N0 = Op.getOperand(0);
7013 SDValue N1 = Op.getOperand(1);
7014 SDValue N2 = Op.getOperand(2);
7016 // If this is a 256-bit vector result, first extract the 128-bit vector,
7017 // insert the element into the extracted half and then place it back.
7018 if (VT.getSizeInBits() == 256) {
7019 if (!isa<ConstantSDNode>(N2))
7022 // Get the desired 128-bit vector half.
7023 unsigned NumElems = VT.getVectorNumElements();
7024 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7025 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7027 // Insert the element into the desired half.
7028 bool Upper = IdxVal >= NumElems/2;
7029 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7030 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7032 // Insert the changed part back to the 256-bit vector
7033 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7036 if (Subtarget->hasSSE41())
7037 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7039 if (EltVT == MVT::i8)
7042 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7043 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7044 // as its second argument.
7045 if (N1.getValueType() != MVT::i32)
7046 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7047 if (N2.getValueType() != MVT::i32)
7048 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7049 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7055 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7056 LLVMContext *Context = DAG.getContext();
7057 DebugLoc dl = Op.getDebugLoc();
7058 EVT OpVT = Op.getValueType();
7060 // If this is a 256-bit vector result, first insert into a 128-bit
7061 // vector and then insert into the 256-bit vector.
7062 if (OpVT.getSizeInBits() > 128) {
7063 // Insert into a 128-bit vector.
7064 EVT VT128 = EVT::getVectorVT(*Context,
7065 OpVT.getVectorElementType(),
7066 OpVT.getVectorNumElements() / 2);
7068 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7070 // Insert the 128-bit vector.
7071 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7074 if (OpVT == MVT::v1i64 &&
7075 Op.getOperand(0).getValueType() == MVT::i64)
7076 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7078 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7079 assert(OpVT.getSizeInBits() == 128 && "Expected an SSE type!");
7080 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7081 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7084 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7085 // a simple subregister reference or explicit instructions to grab
7086 // upper bits of a vector.
7088 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7089 if (Subtarget->hasAVX()) {
7090 DebugLoc dl = Op.getNode()->getDebugLoc();
7091 SDValue Vec = Op.getNode()->getOperand(0);
7092 SDValue Idx = Op.getNode()->getOperand(1);
7094 if (Op.getNode()->getValueType(0).getSizeInBits() == 128 &&
7095 Vec.getNode()->getValueType(0).getSizeInBits() == 256 &&
7096 isa<ConstantSDNode>(Idx)) {
7097 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7098 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7104 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7105 // simple superregister reference or explicit instructions to insert
7106 // the upper bits of a vector.
7108 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7109 if (Subtarget->hasAVX()) {
7110 DebugLoc dl = Op.getNode()->getDebugLoc();
7111 SDValue Vec = Op.getNode()->getOperand(0);
7112 SDValue SubVec = Op.getNode()->getOperand(1);
7113 SDValue Idx = Op.getNode()->getOperand(2);
7115 if (Op.getNode()->getValueType(0).getSizeInBits() == 256 &&
7116 SubVec.getNode()->getValueType(0).getSizeInBits() == 128 &&
7117 isa<ConstantSDNode>(Idx)) {
7118 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7119 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7125 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7126 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7127 // one of the above mentioned nodes. It has to be wrapped because otherwise
7128 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7129 // be used to form addressing mode. These wrapped nodes will be selected
7132 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7133 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7135 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7137 unsigned char OpFlag = 0;
7138 unsigned WrapperKind = X86ISD::Wrapper;
7139 CodeModel::Model M = getTargetMachine().getCodeModel();
7141 if (Subtarget->isPICStyleRIPRel() &&
7142 (M == CodeModel::Small || M == CodeModel::Kernel))
7143 WrapperKind = X86ISD::WrapperRIP;
7144 else if (Subtarget->isPICStyleGOT())
7145 OpFlag = X86II::MO_GOTOFF;
7146 else if (Subtarget->isPICStyleStubPIC())
7147 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7149 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7151 CP->getOffset(), OpFlag);
7152 DebugLoc DL = CP->getDebugLoc();
7153 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7154 // With PIC, the address is actually $g + Offset.
7156 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7157 DAG.getNode(X86ISD::GlobalBaseReg,
7158 DebugLoc(), getPointerTy()),
7165 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7166 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7168 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7170 unsigned char OpFlag = 0;
7171 unsigned WrapperKind = X86ISD::Wrapper;
7172 CodeModel::Model M = getTargetMachine().getCodeModel();
7174 if (Subtarget->isPICStyleRIPRel() &&
7175 (M == CodeModel::Small || M == CodeModel::Kernel))
7176 WrapperKind = X86ISD::WrapperRIP;
7177 else if (Subtarget->isPICStyleGOT())
7178 OpFlag = X86II::MO_GOTOFF;
7179 else if (Subtarget->isPICStyleStubPIC())
7180 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7182 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7184 DebugLoc DL = JT->getDebugLoc();
7185 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7187 // With PIC, the address is actually $g + Offset.
7189 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7190 DAG.getNode(X86ISD::GlobalBaseReg,
7191 DebugLoc(), getPointerTy()),
7198 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7199 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7201 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7203 unsigned char OpFlag = 0;
7204 unsigned WrapperKind = X86ISD::Wrapper;
7205 CodeModel::Model M = getTargetMachine().getCodeModel();
7207 if (Subtarget->isPICStyleRIPRel() &&
7208 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7209 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7210 OpFlag = X86II::MO_GOTPCREL;
7211 WrapperKind = X86ISD::WrapperRIP;
7212 } else if (Subtarget->isPICStyleGOT()) {
7213 OpFlag = X86II::MO_GOT;
7214 } else if (Subtarget->isPICStyleStubPIC()) {
7215 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7216 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7217 OpFlag = X86II::MO_DARWIN_NONLAZY;
7220 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7222 DebugLoc DL = Op.getDebugLoc();
7223 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7226 // With PIC, the address is actually $g + Offset.
7227 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7228 !Subtarget->is64Bit()) {
7229 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7230 DAG.getNode(X86ISD::GlobalBaseReg,
7231 DebugLoc(), getPointerTy()),
7235 // For symbols that require a load from a stub to get the address, emit the
7237 if (isGlobalStubReference(OpFlag))
7238 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7239 MachinePointerInfo::getGOT(), false, false, false, 0);
7245 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7246 // Create the TargetBlockAddressAddress node.
7247 unsigned char OpFlags =
7248 Subtarget->ClassifyBlockAddressReference();
7249 CodeModel::Model M = getTargetMachine().getCodeModel();
7250 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7251 DebugLoc dl = Op.getDebugLoc();
7252 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7253 /*isTarget=*/true, OpFlags);
7255 if (Subtarget->isPICStyleRIPRel() &&
7256 (M == CodeModel::Small || M == CodeModel::Kernel))
7257 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7259 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7261 // With PIC, the address is actually $g + Offset.
7262 if (isGlobalRelativeToPICBase(OpFlags)) {
7263 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7264 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7272 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7274 SelectionDAG &DAG) const {
7275 // Create the TargetGlobalAddress node, folding in the constant
7276 // offset if it is legal.
7277 unsigned char OpFlags =
7278 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7279 CodeModel::Model M = getTargetMachine().getCodeModel();
7281 if (OpFlags == X86II::MO_NO_FLAG &&
7282 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7283 // A direct static reference to a global.
7284 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7287 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7290 if (Subtarget->isPICStyleRIPRel() &&
7291 (M == CodeModel::Small || M == CodeModel::Kernel))
7292 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7294 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7296 // With PIC, the address is actually $g + Offset.
7297 if (isGlobalRelativeToPICBase(OpFlags)) {
7298 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7299 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7303 // For globals that require a load from a stub to get the address, emit the
7305 if (isGlobalStubReference(OpFlags))
7306 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7307 MachinePointerInfo::getGOT(), false, false, false, 0);
7309 // If there was a non-zero offset that we didn't fold, create an explicit
7312 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7313 DAG.getConstant(Offset, getPointerTy()));
7319 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7320 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7321 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7322 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7326 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7327 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7328 unsigned char OperandFlags, bool LocalDynamic = false) {
7329 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7330 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7331 DebugLoc dl = GA->getDebugLoc();
7332 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7333 GA->getValueType(0),
7337 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7341 SDValue Ops[] = { Chain, TGA, *InFlag };
7342 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7344 SDValue Ops[] = { Chain, TGA };
7345 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7348 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7349 MFI->setAdjustsStack(true);
7351 SDValue Flag = Chain.getValue(1);
7352 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7355 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7357 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7360 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7361 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7362 DAG.getNode(X86ISD::GlobalBaseReg,
7363 DebugLoc(), PtrVT), InFlag);
7364 InFlag = Chain.getValue(1);
7366 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7369 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7371 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7373 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7374 X86::RAX, X86II::MO_TLSGD);
7377 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7381 DebugLoc dl = GA->getDebugLoc();
7383 // Get the start address of the TLS block for this module.
7384 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7385 .getInfo<X86MachineFunctionInfo>();
7386 MFI->incNumLocalDynamicTLSAccesses();
7390 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7391 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7394 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7395 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7396 InFlag = Chain.getValue(1);
7397 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7398 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7401 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7405 unsigned char OperandFlags = X86II::MO_DTPOFF;
7406 unsigned WrapperKind = X86ISD::Wrapper;
7407 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7408 GA->getValueType(0),
7409 GA->getOffset(), OperandFlags);
7410 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7412 // Add x@dtpoff with the base.
7413 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7416 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7417 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7418 const EVT PtrVT, TLSModel::Model model,
7419 bool is64Bit, bool isPIC) {
7420 DebugLoc dl = GA->getDebugLoc();
7422 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7423 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7424 is64Bit ? 257 : 256));
7426 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7427 DAG.getIntPtrConstant(0),
7428 MachinePointerInfo(Ptr),
7429 false, false, false, 0);
7431 unsigned char OperandFlags = 0;
7432 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7434 unsigned WrapperKind = X86ISD::Wrapper;
7435 if (model == TLSModel::LocalExec) {
7436 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7437 } else if (model == TLSModel::InitialExec) {
7439 OperandFlags = X86II::MO_GOTTPOFF;
7440 WrapperKind = X86ISD::WrapperRIP;
7442 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7445 llvm_unreachable("Unexpected model");
7448 // emit "addl x@ntpoff,%eax" (local exec)
7449 // or "addl x@indntpoff,%eax" (initial exec)
7450 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7451 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7452 GA->getValueType(0),
7453 GA->getOffset(), OperandFlags);
7454 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7456 if (model == TLSModel::InitialExec) {
7457 if (isPIC && !is64Bit) {
7458 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7459 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7463 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7464 MachinePointerInfo::getGOT(), false, false, false,
7468 // The address of the thread local variable is the add of the thread
7469 // pointer with the offset of the variable.
7470 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7474 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7476 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7477 const GlobalValue *GV = GA->getGlobal();
7479 if (Subtarget->isTargetELF()) {
7480 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7483 case TLSModel::GeneralDynamic:
7484 if (Subtarget->is64Bit())
7485 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7486 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7487 case TLSModel::LocalDynamic:
7488 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7489 Subtarget->is64Bit());
7490 case TLSModel::InitialExec:
7491 case TLSModel::LocalExec:
7492 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7493 Subtarget->is64Bit(),
7494 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7496 llvm_unreachable("Unknown TLS model.");
7499 if (Subtarget->isTargetDarwin()) {
7500 // Darwin only has one model of TLS. Lower to that.
7501 unsigned char OpFlag = 0;
7502 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7503 X86ISD::WrapperRIP : X86ISD::Wrapper;
7505 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7507 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7508 !Subtarget->is64Bit();
7510 OpFlag = X86II::MO_TLVP_PIC_BASE;
7512 OpFlag = X86II::MO_TLVP;
7513 DebugLoc DL = Op.getDebugLoc();
7514 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7515 GA->getValueType(0),
7516 GA->getOffset(), OpFlag);
7517 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7519 // With PIC32, the address is actually $g + Offset.
7521 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7522 DAG.getNode(X86ISD::GlobalBaseReg,
7523 DebugLoc(), getPointerTy()),
7526 // Lowering the machine isd will make sure everything is in the right
7528 SDValue Chain = DAG.getEntryNode();
7529 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7530 SDValue Args[] = { Chain, Offset };
7531 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7533 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7534 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7535 MFI->setAdjustsStack(true);
7537 // And our return value (tls address) is in the standard call return value
7539 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7540 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7544 if (Subtarget->isTargetWindows()) {
7545 // Just use the implicit TLS architecture
7546 // Need to generate someting similar to:
7547 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7549 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7550 // mov rcx, qword [rdx+rcx*8]
7551 // mov eax, .tls$:tlsvar
7552 // [rax+rcx] contains the address
7553 // Windows 64bit: gs:0x58
7554 // Windows 32bit: fs:__tls_array
7556 // If GV is an alias then use the aliasee for determining
7557 // thread-localness.
7558 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7559 GV = GA->resolveAliasedGlobal(false);
7560 DebugLoc dl = GA->getDebugLoc();
7561 SDValue Chain = DAG.getEntryNode();
7563 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7564 // %gs:0x58 (64-bit).
7565 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7566 ? Type::getInt8PtrTy(*DAG.getContext(),
7568 : Type::getInt32PtrTy(*DAG.getContext(),
7571 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7572 Subtarget->is64Bit()
7573 ? DAG.getIntPtrConstant(0x58)
7574 : DAG.getExternalSymbol("_tls_array",
7576 MachinePointerInfo(Ptr),
7577 false, false, false, 0);
7579 // Load the _tls_index variable
7580 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7581 if (Subtarget->is64Bit())
7582 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7583 IDX, MachinePointerInfo(), MVT::i32,
7586 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7587 false, false, false, 0);
7589 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7591 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7593 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7594 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7595 false, false, false, 0);
7597 // Get the offset of start of .tls section
7598 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7599 GA->getValueType(0),
7600 GA->getOffset(), X86II::MO_SECREL);
7601 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7603 // The address of the thread local variable is the add of the thread
7604 // pointer with the offset of the variable.
7605 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7608 llvm_unreachable("TLS not implemented for this target.");
7612 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7613 /// and take a 2 x i32 value to shift plus a shift amount.
7614 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7615 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7616 EVT VT = Op.getValueType();
7617 unsigned VTBits = VT.getSizeInBits();
7618 DebugLoc dl = Op.getDebugLoc();
7619 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7620 SDValue ShOpLo = Op.getOperand(0);
7621 SDValue ShOpHi = Op.getOperand(1);
7622 SDValue ShAmt = Op.getOperand(2);
7623 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7624 DAG.getConstant(VTBits - 1, MVT::i8))
7625 : DAG.getConstant(0, VT);
7628 if (Op.getOpcode() == ISD::SHL_PARTS) {
7629 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7630 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7632 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7633 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7636 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7637 DAG.getConstant(VTBits, MVT::i8));
7638 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7639 AndNode, DAG.getConstant(0, MVT::i8));
7642 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7643 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7644 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7646 if (Op.getOpcode() == ISD::SHL_PARTS) {
7647 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7648 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7650 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7651 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7654 SDValue Ops[2] = { Lo, Hi };
7655 return DAG.getMergeValues(Ops, 2, dl);
7658 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7659 SelectionDAG &DAG) const {
7660 EVT SrcVT = Op.getOperand(0).getValueType();
7662 if (SrcVT.isVector())
7665 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7666 "Unknown SINT_TO_FP to lower!");
7668 // These are really Legal; return the operand so the caller accepts it as
7670 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7672 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7673 Subtarget->is64Bit()) {
7677 DebugLoc dl = Op.getDebugLoc();
7678 unsigned Size = SrcVT.getSizeInBits()/8;
7679 MachineFunction &MF = DAG.getMachineFunction();
7680 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7681 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7682 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7684 MachinePointerInfo::getFixedStack(SSFI),
7686 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7689 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7691 SelectionDAG &DAG) const {
7693 DebugLoc DL = Op.getDebugLoc();
7695 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7697 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7699 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7701 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7703 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7704 MachineMemOperand *MMO;
7706 int SSFI = FI->getIndex();
7708 DAG.getMachineFunction()
7709 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7710 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7712 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7713 StackSlot = StackSlot.getOperand(1);
7715 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7716 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7718 Tys, Ops, array_lengthof(Ops),
7722 Chain = Result.getValue(1);
7723 SDValue InFlag = Result.getValue(2);
7725 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7726 // shouldn't be necessary except that RFP cannot be live across
7727 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7728 MachineFunction &MF = DAG.getMachineFunction();
7729 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7730 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7731 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7732 Tys = DAG.getVTList(MVT::Other);
7734 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7736 MachineMemOperand *MMO =
7737 DAG.getMachineFunction()
7738 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7739 MachineMemOperand::MOStore, SSFISize, SSFISize);
7741 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7742 Ops, array_lengthof(Ops),
7743 Op.getValueType(), MMO);
7744 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7745 MachinePointerInfo::getFixedStack(SSFI),
7746 false, false, false, 0);
7752 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7753 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7754 SelectionDAG &DAG) const {
7755 // This algorithm is not obvious. Here it is what we're trying to output:
7758 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7759 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7763 pshufd $0x4e, %xmm0, %xmm1
7768 DebugLoc dl = Op.getDebugLoc();
7769 LLVMContext *Context = DAG.getContext();
7771 // Build some magic constants.
7772 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7773 Constant *C0 = ConstantDataVector::get(*Context, CV0);
7774 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7776 SmallVector<Constant*,2> CV1;
7778 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7780 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7781 Constant *C1 = ConstantVector::get(CV1);
7782 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7784 // Load the 64-bit value into an XMM register.
7785 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7787 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7788 MachinePointerInfo::getConstantPool(),
7789 false, false, false, 16);
7790 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7791 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7794 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7795 MachinePointerInfo::getConstantPool(),
7796 false, false, false, 16);
7797 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7798 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7801 if (Subtarget->hasSSE3()) {
7802 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7803 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7805 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7806 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7808 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7809 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7813 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7814 DAG.getIntPtrConstant(0));
7817 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7818 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7819 SelectionDAG &DAG) const {
7820 DebugLoc dl = Op.getDebugLoc();
7821 // FP constant to bias correct the final result.
7822 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7825 // Load the 32-bit value into an XMM register.
7826 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7829 // Zero out the upper parts of the register.
7830 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7832 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7833 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7834 DAG.getIntPtrConstant(0));
7836 // Or the load with the bias.
7837 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7838 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7839 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7841 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7842 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7843 MVT::v2f64, Bias)));
7844 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7845 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7846 DAG.getIntPtrConstant(0));
7848 // Subtract the bias.
7849 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7851 // Handle final rounding.
7852 EVT DestVT = Op.getValueType();
7854 if (DestVT.bitsLT(MVT::f64))
7855 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7856 DAG.getIntPtrConstant(0));
7857 if (DestVT.bitsGT(MVT::f64))
7858 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7860 // Handle final rounding.
7864 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7865 SelectionDAG &DAG) const {
7866 SDValue N0 = Op.getOperand(0);
7867 DebugLoc dl = Op.getDebugLoc();
7869 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7870 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7871 // the optimization here.
7872 if (DAG.SignBitIsZero(N0))
7873 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7875 EVT SrcVT = N0.getValueType();
7876 EVT DstVT = Op.getValueType();
7877 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7878 return LowerUINT_TO_FP_i64(Op, DAG);
7879 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7880 return LowerUINT_TO_FP_i32(Op, DAG);
7881 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7884 // Make a 64-bit buffer, and use it to build an FILD.
7885 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7886 if (SrcVT == MVT::i32) {
7887 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7888 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7889 getPointerTy(), StackSlot, WordOff);
7890 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7891 StackSlot, MachinePointerInfo(),
7893 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7894 OffsetSlot, MachinePointerInfo(),
7896 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7900 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7901 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7902 StackSlot, MachinePointerInfo(),
7904 // For i64 source, we need to add the appropriate power of 2 if the input
7905 // was negative. This is the same as the optimization in
7906 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7907 // we must be careful to do the computation in x87 extended precision, not
7908 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7909 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7910 MachineMemOperand *MMO =
7911 DAG.getMachineFunction()
7912 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7913 MachineMemOperand::MOLoad, 8, 8);
7915 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7916 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7917 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7920 APInt FF(32, 0x5F800000ULL);
7922 // Check whether the sign bit is set.
7923 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7924 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7927 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7928 SDValue FudgePtr = DAG.getConstantPool(
7929 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7932 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7933 SDValue Zero = DAG.getIntPtrConstant(0);
7934 SDValue Four = DAG.getIntPtrConstant(4);
7935 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7937 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7939 // Load the value out, extending it from f32 to f80.
7940 // FIXME: Avoid the extend by constructing the right constant pool?
7941 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7942 FudgePtr, MachinePointerInfo::getConstantPool(),
7943 MVT::f32, false, false, 4);
7944 // Extend everything to 80 bits to force it to be done on x87.
7945 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7946 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7949 std::pair<SDValue,SDValue> X86TargetLowering::
7950 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
7951 DebugLoc DL = Op.getDebugLoc();
7953 EVT DstTy = Op.getValueType();
7955 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
7956 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7960 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7961 DstTy.getSimpleVT() >= MVT::i16 &&
7962 "Unknown FP_TO_INT to lower!");
7964 // These are really Legal.
7965 if (DstTy == MVT::i32 &&
7966 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7967 return std::make_pair(SDValue(), SDValue());
7968 if (Subtarget->is64Bit() &&
7969 DstTy == MVT::i64 &&
7970 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7971 return std::make_pair(SDValue(), SDValue());
7973 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
7974 // stack slot, or into the FTOL runtime function.
7975 MachineFunction &MF = DAG.getMachineFunction();
7976 unsigned MemSize = DstTy.getSizeInBits()/8;
7977 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7978 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7981 if (!IsSigned && isIntegerTypeFTOL(DstTy))
7982 Opc = X86ISD::WIN_FTOL;
7984 switch (DstTy.getSimpleVT().SimpleTy) {
7985 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7986 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7987 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7988 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7991 SDValue Chain = DAG.getEntryNode();
7992 SDValue Value = Op.getOperand(0);
7993 EVT TheVT = Op.getOperand(0).getValueType();
7994 // FIXME This causes a redundant load/store if the SSE-class value is already
7995 // in memory, such as if it is on the callstack.
7996 if (isScalarFPTypeInSSEReg(TheVT)) {
7997 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7998 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7999 MachinePointerInfo::getFixedStack(SSFI),
8001 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8003 Chain, StackSlot, DAG.getValueType(TheVT)
8006 MachineMemOperand *MMO =
8007 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8008 MachineMemOperand::MOLoad, MemSize, MemSize);
8009 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8011 Chain = Value.getValue(1);
8012 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8013 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8016 MachineMemOperand *MMO =
8017 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8018 MachineMemOperand::MOStore, MemSize, MemSize);
8020 if (Opc != X86ISD::WIN_FTOL) {
8021 // Build the FP_TO_INT*_IN_MEM
8022 SDValue Ops[] = { Chain, Value, StackSlot };
8023 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8024 Ops, 3, DstTy, MMO);
8025 return std::make_pair(FIST, StackSlot);
8027 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8028 DAG.getVTList(MVT::Other, MVT::Glue),
8030 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8031 MVT::i32, ftol.getValue(1));
8032 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8033 MVT::i32, eax.getValue(2));
8034 SDValue Ops[] = { eax, edx };
8035 SDValue pair = IsReplace
8036 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8037 : DAG.getMergeValues(Ops, 2, DL);
8038 return std::make_pair(pair, SDValue());
8042 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8043 SelectionDAG &DAG) const {
8044 if (Op.getValueType().isVector())
8047 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8048 /*IsSigned=*/ true, /*IsReplace=*/ false);
8049 SDValue FIST = Vals.first, StackSlot = Vals.second;
8050 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8051 if (FIST.getNode() == 0) return Op;
8053 if (StackSlot.getNode())
8055 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8056 FIST, StackSlot, MachinePointerInfo(),
8057 false, false, false, 0);
8059 // The node is the result.
8063 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8064 SelectionDAG &DAG) const {
8065 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8066 /*IsSigned=*/ false, /*IsReplace=*/ false);
8067 SDValue FIST = Vals.first, StackSlot = Vals.second;
8068 assert(FIST.getNode() && "Unexpected failure");
8070 if (StackSlot.getNode())
8072 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8073 FIST, StackSlot, MachinePointerInfo(),
8074 false, false, false, 0);
8076 // The node is the result.
8080 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8081 SelectionDAG &DAG) const {
8082 LLVMContext *Context = DAG.getContext();
8083 DebugLoc dl = Op.getDebugLoc();
8084 EVT VT = Op.getValueType();
8087 EltVT = VT.getVectorElementType();
8089 if (EltVT == MVT::f64) {
8090 C = ConstantVector::getSplat(2,
8091 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8093 C = ConstantVector::getSplat(4,
8094 ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8096 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8097 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8098 MachinePointerInfo::getConstantPool(),
8099 false, false, false, 16);
8100 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8103 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8104 LLVMContext *Context = DAG.getContext();
8105 DebugLoc dl = Op.getDebugLoc();
8106 EVT VT = Op.getValueType();
8108 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8109 if (VT.isVector()) {
8110 EltVT = VT.getVectorElementType();
8111 NumElts = VT.getVectorNumElements();
8114 if (EltVT == MVT::f64)
8115 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8117 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8118 C = ConstantVector::getSplat(NumElts, C);
8119 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8120 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8121 MachinePointerInfo::getConstantPool(),
8122 false, false, false, 16);
8123 if (VT.isVector()) {
8124 MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
8125 return DAG.getNode(ISD::BITCAST, dl, VT,
8126 DAG.getNode(ISD::XOR, dl, XORVT,
8127 DAG.getNode(ISD::BITCAST, dl, XORVT,
8129 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8132 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8135 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8136 LLVMContext *Context = DAG.getContext();
8137 SDValue Op0 = Op.getOperand(0);
8138 SDValue Op1 = Op.getOperand(1);
8139 DebugLoc dl = Op.getDebugLoc();
8140 EVT VT = Op.getValueType();
8141 EVT SrcVT = Op1.getValueType();
8143 // If second operand is smaller, extend it first.
8144 if (SrcVT.bitsLT(VT)) {
8145 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8148 // And if it is bigger, shrink it first.
8149 if (SrcVT.bitsGT(VT)) {
8150 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8154 // At this point the operands and the result should have the same
8155 // type, and that won't be f80 since that is not custom lowered.
8157 // First get the sign bit of second operand.
8158 SmallVector<Constant*,4> CV;
8159 if (SrcVT == MVT::f64) {
8160 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8161 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8163 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8164 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8165 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8166 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8168 Constant *C = ConstantVector::get(CV);
8169 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8170 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8171 MachinePointerInfo::getConstantPool(),
8172 false, false, false, 16);
8173 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8175 // Shift sign bit right or left if the two operands have different types.
8176 if (SrcVT.bitsGT(VT)) {
8177 // Op0 is MVT::f32, Op1 is MVT::f64.
8178 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8179 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8180 DAG.getConstant(32, MVT::i32));
8181 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8182 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8183 DAG.getIntPtrConstant(0));
8186 // Clear first operand sign bit.
8188 if (VT == MVT::f64) {
8189 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8190 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8192 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8193 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8194 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8195 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8197 C = ConstantVector::get(CV);
8198 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8199 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8200 MachinePointerInfo::getConstantPool(),
8201 false, false, false, 16);
8202 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8204 // Or the value with the sign bit.
8205 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8208 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8209 SDValue N0 = Op.getOperand(0);
8210 DebugLoc dl = Op.getDebugLoc();
8211 EVT VT = Op.getValueType();
8213 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8214 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8215 DAG.getConstant(1, VT));
8216 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8219 /// Emit nodes that will be selected as "test Op0,Op0", or something
8221 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8222 SelectionDAG &DAG) const {
8223 DebugLoc dl = Op.getDebugLoc();
8225 // CF and OF aren't always set the way we want. Determine which
8226 // of these we need.
8227 bool NeedCF = false;
8228 bool NeedOF = false;
8231 case X86::COND_A: case X86::COND_AE:
8232 case X86::COND_B: case X86::COND_BE:
8235 case X86::COND_G: case X86::COND_GE:
8236 case X86::COND_L: case X86::COND_LE:
8237 case X86::COND_O: case X86::COND_NO:
8242 // See if we can use the EFLAGS value from the operand instead of
8243 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8244 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8245 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8246 // Emit a CMP with 0, which is the TEST pattern.
8247 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8248 DAG.getConstant(0, Op.getValueType()));
8250 unsigned Opcode = 0;
8251 unsigned NumOperands = 0;
8252 switch (Op.getNode()->getOpcode()) {
8254 // Due to an isel shortcoming, be conservative if this add is likely to be
8255 // selected as part of a load-modify-store instruction. When the root node
8256 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8257 // uses of other nodes in the match, such as the ADD in this case. This
8258 // leads to the ADD being left around and reselected, with the result being
8259 // two adds in the output. Alas, even if none our users are stores, that
8260 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8261 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8262 // climbing the DAG back to the root, and it doesn't seem to be worth the
8264 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8265 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8266 if (UI->getOpcode() != ISD::CopyToReg &&
8267 UI->getOpcode() != ISD::SETCC &&
8268 UI->getOpcode() != ISD::STORE)
8271 if (ConstantSDNode *C =
8272 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8273 // An add of one will be selected as an INC.
8274 if (C->getAPIntValue() == 1) {
8275 Opcode = X86ISD::INC;
8280 // An add of negative one (subtract of one) will be selected as a DEC.
8281 if (C->getAPIntValue().isAllOnesValue()) {
8282 Opcode = X86ISD::DEC;
8288 // Otherwise use a regular EFLAGS-setting add.
8289 Opcode = X86ISD::ADD;
8293 // If the primary and result isn't used, don't bother using X86ISD::AND,
8294 // because a TEST instruction will be better.
8295 bool NonFlagUse = false;
8296 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8297 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8299 unsigned UOpNo = UI.getOperandNo();
8300 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8301 // Look pass truncate.
8302 UOpNo = User->use_begin().getOperandNo();
8303 User = *User->use_begin();
8306 if (User->getOpcode() != ISD::BRCOND &&
8307 User->getOpcode() != ISD::SETCC &&
8308 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8321 // Due to the ISEL shortcoming noted above, be conservative if this op is
8322 // likely to be selected as part of a load-modify-store instruction.
8323 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8324 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8325 if (UI->getOpcode() == ISD::STORE)
8328 // Otherwise use a regular EFLAGS-setting instruction.
8329 switch (Op.getNode()->getOpcode()) {
8330 default: llvm_unreachable("unexpected operator!");
8332 Opcode = X86ISD::SUB;
8334 case ISD::OR: Opcode = X86ISD::OR; break;
8335 case ISD::XOR: Opcode = X86ISD::XOR; break;
8336 case ISD::AND: Opcode = X86ISD::AND; break;
8348 return SDValue(Op.getNode(), 1);
8355 // Emit a CMP with 0, which is the TEST pattern.
8356 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8357 DAG.getConstant(0, Op.getValueType()));
8359 if (Opcode == X86ISD::CMP) {
8360 SDValue New = DAG.getNode(Opcode, dl, MVT::i32, Op.getOperand(0),
8362 // We can't replace usage of SUB with CMP.
8363 // The SUB node will be removed later because there is no use of it.
8364 return SDValue(New.getNode(), 0);
8367 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8368 SmallVector<SDValue, 4> Ops;
8369 for (unsigned i = 0; i != NumOperands; ++i)
8370 Ops.push_back(Op.getOperand(i));
8372 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8373 DAG.ReplaceAllUsesWith(Op, New);
8374 return SDValue(New.getNode(), 1);
8377 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8379 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8380 SelectionDAG &DAG) const {
8381 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8382 if (C->getAPIntValue() == 0)
8383 return EmitTest(Op0, X86CC, DAG);
8385 DebugLoc dl = Op0.getDebugLoc();
8386 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8387 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8388 // Use SUB instead of CMP to enable CSE between SUB and CMP.
8389 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8390 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8392 return SDValue(Sub.getNode(), 1);
8394 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8397 /// Convert a comparison if required by the subtarget.
8398 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8399 SelectionDAG &DAG) const {
8400 // If the subtarget does not support the FUCOMI instruction, floating-point
8401 // comparisons have to be converted.
8402 if (Subtarget->hasCMov() ||
8403 Cmp.getOpcode() != X86ISD::CMP ||
8404 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8405 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8408 // The instruction selector will select an FUCOM instruction instead of
8409 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8410 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8411 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8412 DebugLoc dl = Cmp.getDebugLoc();
8413 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8414 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8415 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8416 DAG.getConstant(8, MVT::i8));
8417 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8418 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8421 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8422 /// if it's possible.
8423 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8424 DebugLoc dl, SelectionDAG &DAG) const {
8425 SDValue Op0 = And.getOperand(0);
8426 SDValue Op1 = And.getOperand(1);
8427 if (Op0.getOpcode() == ISD::TRUNCATE)
8428 Op0 = Op0.getOperand(0);
8429 if (Op1.getOpcode() == ISD::TRUNCATE)
8430 Op1 = Op1.getOperand(0);
8433 if (Op1.getOpcode() == ISD::SHL)
8434 std::swap(Op0, Op1);
8435 if (Op0.getOpcode() == ISD::SHL) {
8436 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8437 if (And00C->getZExtValue() == 1) {
8438 // If we looked past a truncate, check that it's only truncating away
8440 unsigned BitWidth = Op0.getValueSizeInBits();
8441 unsigned AndBitWidth = And.getValueSizeInBits();
8442 if (BitWidth > AndBitWidth) {
8444 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8445 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8449 RHS = Op0.getOperand(1);
8451 } else if (Op1.getOpcode() == ISD::Constant) {
8452 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8453 uint64_t AndRHSVal = AndRHS->getZExtValue();
8454 SDValue AndLHS = Op0;
8456 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8457 LHS = AndLHS.getOperand(0);
8458 RHS = AndLHS.getOperand(1);
8461 // Use BT if the immediate can't be encoded in a TEST instruction.
8462 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8464 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8468 if (LHS.getNode()) {
8469 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8470 // instruction. Since the shift amount is in-range-or-undefined, we know
8471 // that doing a bittest on the i32 value is ok. We extend to i32 because
8472 // the encoding for the i16 version is larger than the i32 version.
8473 // Also promote i16 to i32 for performance / code size reason.
8474 if (LHS.getValueType() == MVT::i8 ||
8475 LHS.getValueType() == MVT::i16)
8476 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8478 // If the operand types disagree, extend the shift amount to match. Since
8479 // BT ignores high bits (like shifts) we can use anyextend.
8480 if (LHS.getValueType() != RHS.getValueType())
8481 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8483 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8484 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8485 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8486 DAG.getConstant(Cond, MVT::i8), BT);
8492 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8494 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8496 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8497 SDValue Op0 = Op.getOperand(0);
8498 SDValue Op1 = Op.getOperand(1);
8499 DebugLoc dl = Op.getDebugLoc();
8500 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8502 // Optimize to BT if possible.
8503 // Lower (X & (1 << N)) == 0 to BT(X, N).
8504 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8505 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8506 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8507 Op1.getOpcode() == ISD::Constant &&
8508 cast<ConstantSDNode>(Op1)->isNullValue() &&
8509 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8510 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8511 if (NewSetCC.getNode())
8515 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8517 if (Op1.getOpcode() == ISD::Constant &&
8518 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8519 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8520 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8522 // If the input is a setcc, then reuse the input setcc or use a new one with
8523 // the inverted condition.
8524 if (Op0.getOpcode() == X86ISD::SETCC) {
8525 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8526 bool Invert = (CC == ISD::SETNE) ^
8527 cast<ConstantSDNode>(Op1)->isNullValue();
8528 if (!Invert) return Op0;
8530 CCode = X86::GetOppositeBranchCondition(CCode);
8531 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8532 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8536 bool isFP = Op1.getValueType().isFloatingPoint();
8537 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8538 if (X86CC == X86::COND_INVALID)
8541 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8542 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8543 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8544 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8547 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8548 // ones, and then concatenate the result back.
8549 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8550 EVT VT = Op.getValueType();
8552 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8553 "Unsupported value type for operation");
8555 unsigned NumElems = VT.getVectorNumElements();
8556 DebugLoc dl = Op.getDebugLoc();
8557 SDValue CC = Op.getOperand(2);
8559 // Extract the LHS vectors
8560 SDValue LHS = Op.getOperand(0);
8561 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8562 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8564 // Extract the RHS vectors
8565 SDValue RHS = Op.getOperand(1);
8566 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8567 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8569 // Issue the operation on the smaller types and concatenate the result back
8570 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8571 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8572 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8573 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8574 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8578 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8580 SDValue Op0 = Op.getOperand(0);
8581 SDValue Op1 = Op.getOperand(1);
8582 SDValue CC = Op.getOperand(2);
8583 EVT VT = Op.getValueType();
8584 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8585 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8586 DebugLoc dl = Op.getDebugLoc();
8590 EVT EltVT = Op0.getValueType().getVectorElementType();
8591 assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT;
8595 // SSE Condition code mapping:
8604 switch (SetCCOpcode) {
8607 case ISD::SETEQ: SSECC = 0; break;
8609 case ISD::SETGT: Swap = true; // Fallthrough
8611 case ISD::SETOLT: SSECC = 1; break;
8613 case ISD::SETGE: Swap = true; // Fallthrough
8615 case ISD::SETOLE: SSECC = 2; break;
8616 case ISD::SETUO: SSECC = 3; break;
8618 case ISD::SETNE: SSECC = 4; break;
8619 case ISD::SETULE: Swap = true;
8620 case ISD::SETUGE: SSECC = 5; break;
8621 case ISD::SETULT: Swap = true;
8622 case ISD::SETUGT: SSECC = 6; break;
8623 case ISD::SETO: SSECC = 7; break;
8626 std::swap(Op0, Op1);
8628 // In the two special cases we can't handle, emit two comparisons.
8630 if (SetCCOpcode == ISD::SETUEQ) {
8632 UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8633 DAG.getConstant(3, MVT::i8));
8634 EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8635 DAG.getConstant(0, MVT::i8));
8636 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8638 if (SetCCOpcode == ISD::SETONE) {
8640 ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8641 DAG.getConstant(7, MVT::i8));
8642 NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8643 DAG.getConstant(4, MVT::i8));
8644 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8646 llvm_unreachable("Illegal FP comparison");
8648 // Handle all other FP comparisons here.
8649 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8650 DAG.getConstant(SSECC, MVT::i8));
8653 // Break 256-bit integer vector compare into smaller ones.
8654 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8655 return Lower256IntVSETCC(Op, DAG);
8657 // We are handling one of the integer comparisons here. Since SSE only has
8658 // GT and EQ comparisons for integer, swapping operands and multiple
8659 // operations may be required for some comparisons.
8661 bool Swap = false, Invert = false, FlipSigns = false;
8663 switch (SetCCOpcode) {
8665 case ISD::SETNE: Invert = true;
8666 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
8667 case ISD::SETLT: Swap = true;
8668 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
8669 case ISD::SETGE: Swap = true;
8670 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
8671 case ISD::SETULT: Swap = true;
8672 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8673 case ISD::SETUGE: Swap = true;
8674 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8677 std::swap(Op0, Op1);
8679 // Check that the operation in question is available (most are plain SSE2,
8680 // but PCMPGTQ and PCMPEQQ have different requirements).
8681 if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8683 if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8686 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8687 // bits of the inputs before performing those operations.
8689 EVT EltVT = VT.getVectorElementType();
8690 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8692 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8693 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8695 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8696 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8699 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8701 // If the logical-not of the result is required, perform that now.
8703 Result = DAG.getNOT(dl, Result, VT);
8708 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8709 static bool isX86LogicalCmp(SDValue Op) {
8710 unsigned Opc = Op.getNode()->getOpcode();
8711 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8712 Opc == X86ISD::SAHF)
8714 if (Op.getResNo() == 1 &&
8715 (Opc == X86ISD::ADD ||
8716 Opc == X86ISD::SUB ||
8717 Opc == X86ISD::ADC ||
8718 Opc == X86ISD::SBB ||
8719 Opc == X86ISD::SMUL ||
8720 Opc == X86ISD::UMUL ||
8721 Opc == X86ISD::INC ||
8722 Opc == X86ISD::DEC ||
8723 Opc == X86ISD::OR ||
8724 Opc == X86ISD::XOR ||
8725 Opc == X86ISD::AND))
8728 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8734 static bool isZero(SDValue V) {
8735 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8736 return C && C->isNullValue();
8739 static bool isAllOnes(SDValue V) {
8740 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8741 return C && C->isAllOnesValue();
8744 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8745 if (V.getOpcode() != ISD::TRUNCATE)
8748 SDValue VOp0 = V.getOperand(0);
8749 unsigned InBits = VOp0.getValueSizeInBits();
8750 unsigned Bits = V.getValueSizeInBits();
8751 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8754 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8755 bool addTest = true;
8756 SDValue Cond = Op.getOperand(0);
8757 SDValue Op1 = Op.getOperand(1);
8758 SDValue Op2 = Op.getOperand(2);
8759 DebugLoc DL = Op.getDebugLoc();
8762 if (Cond.getOpcode() == ISD::SETCC) {
8763 SDValue NewCond = LowerSETCC(Cond, DAG);
8764 if (NewCond.getNode())
8768 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8769 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8770 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8771 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8772 if (Cond.getOpcode() == X86ISD::SETCC &&
8773 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8774 isZero(Cond.getOperand(1).getOperand(1))) {
8775 SDValue Cmp = Cond.getOperand(1);
8777 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8779 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8780 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8781 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8783 SDValue CmpOp0 = Cmp.getOperand(0);
8784 // Apply further optimizations for special cases
8785 // (select (x != 0), -1, 0) -> neg & sbb
8786 // (select (x == 0), 0, -1) -> neg & sbb
8787 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8788 if (YC->isNullValue() &&
8789 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8790 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8791 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8792 DAG.getConstant(0, CmpOp0.getValueType()),
8794 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8795 DAG.getConstant(X86::COND_B, MVT::i8),
8796 SDValue(Neg.getNode(), 1));
8800 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8801 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8802 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8804 SDValue Res = // Res = 0 or -1.
8805 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8806 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8808 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8809 Res = DAG.getNOT(DL, Res, Res.getValueType());
8811 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8812 if (N2C == 0 || !N2C->isNullValue())
8813 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8818 // Look past (and (setcc_carry (cmp ...)), 1).
8819 if (Cond.getOpcode() == ISD::AND &&
8820 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8821 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8822 if (C && C->getAPIntValue() == 1)
8823 Cond = Cond.getOperand(0);
8826 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8827 // setting operand in place of the X86ISD::SETCC.
8828 unsigned CondOpcode = Cond.getOpcode();
8829 if (CondOpcode == X86ISD::SETCC ||
8830 CondOpcode == X86ISD::SETCC_CARRY) {
8831 CC = Cond.getOperand(0);
8833 SDValue Cmp = Cond.getOperand(1);
8834 unsigned Opc = Cmp.getOpcode();
8835 EVT VT = Op.getValueType();
8837 bool IllegalFPCMov = false;
8838 if (VT.isFloatingPoint() && !VT.isVector() &&
8839 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8840 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8842 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8843 Opc == X86ISD::BT) { // FIXME
8847 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8848 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8849 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8850 Cond.getOperand(0).getValueType() != MVT::i8)) {
8851 SDValue LHS = Cond.getOperand(0);
8852 SDValue RHS = Cond.getOperand(1);
8856 switch (CondOpcode) {
8857 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8858 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8859 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8860 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8861 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8862 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8863 default: llvm_unreachable("unexpected overflowing operator");
8865 if (CondOpcode == ISD::UMULO)
8866 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8869 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8871 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8873 if (CondOpcode == ISD::UMULO)
8874 Cond = X86Op.getValue(2);
8876 Cond = X86Op.getValue(1);
8878 CC = DAG.getConstant(X86Cond, MVT::i8);
8883 // Look pass the truncate if the high bits are known zero.
8884 if (isTruncWithZeroHighBitsInput(Cond, DAG))
8885 Cond = Cond.getOperand(0);
8887 // We know the result of AND is compared against zero. Try to match
8889 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8890 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8891 if (NewSetCC.getNode()) {
8892 CC = NewSetCC.getOperand(0);
8893 Cond = NewSetCC.getOperand(1);
8900 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8901 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8904 // a < b ? -1 : 0 -> RES = ~setcc_carry
8905 // a < b ? 0 : -1 -> RES = setcc_carry
8906 // a >= b ? -1 : 0 -> RES = setcc_carry
8907 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8908 if (Cond.getOpcode() == X86ISD::SUB) {
8909 Cond = ConvertCmpIfNecessary(Cond, DAG);
8910 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8912 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8913 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8914 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8915 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8916 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8917 return DAG.getNOT(DL, Res, Res.getValueType());
8922 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8923 // condition is true.
8924 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8925 SDValue Ops[] = { Op2, Op1, CC, Cond };
8926 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8929 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8930 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8931 // from the AND / OR.
8932 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8933 Opc = Op.getOpcode();
8934 if (Opc != ISD::OR && Opc != ISD::AND)
8936 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8937 Op.getOperand(0).hasOneUse() &&
8938 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8939 Op.getOperand(1).hasOneUse());
8942 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8943 // 1 and that the SETCC node has a single use.
8944 static bool isXor1OfSetCC(SDValue Op) {
8945 if (Op.getOpcode() != ISD::XOR)
8947 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8948 if (N1C && N1C->getAPIntValue() == 1) {
8949 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8950 Op.getOperand(0).hasOneUse();
8955 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8956 bool addTest = true;
8957 SDValue Chain = Op.getOperand(0);
8958 SDValue Cond = Op.getOperand(1);
8959 SDValue Dest = Op.getOperand(2);
8960 DebugLoc dl = Op.getDebugLoc();
8962 bool Inverted = false;
8964 if (Cond.getOpcode() == ISD::SETCC) {
8965 // Check for setcc([su]{add,sub,mul}o == 0).
8966 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8967 isa<ConstantSDNode>(Cond.getOperand(1)) &&
8968 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8969 Cond.getOperand(0).getResNo() == 1 &&
8970 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8971 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8972 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8973 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8974 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8975 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8977 Cond = Cond.getOperand(0);
8979 SDValue NewCond = LowerSETCC(Cond, DAG);
8980 if (NewCond.getNode())
8985 // FIXME: LowerXALUO doesn't handle these!!
8986 else if (Cond.getOpcode() == X86ISD::ADD ||
8987 Cond.getOpcode() == X86ISD::SUB ||
8988 Cond.getOpcode() == X86ISD::SMUL ||
8989 Cond.getOpcode() == X86ISD::UMUL)
8990 Cond = LowerXALUO(Cond, DAG);
8993 // Look pass (and (setcc_carry (cmp ...)), 1).
8994 if (Cond.getOpcode() == ISD::AND &&
8995 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8996 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8997 if (C && C->getAPIntValue() == 1)
8998 Cond = Cond.getOperand(0);
9001 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9002 // setting operand in place of the X86ISD::SETCC.
9003 unsigned CondOpcode = Cond.getOpcode();
9004 if (CondOpcode == X86ISD::SETCC ||
9005 CondOpcode == X86ISD::SETCC_CARRY) {
9006 CC = Cond.getOperand(0);
9008 SDValue Cmp = Cond.getOperand(1);
9009 unsigned Opc = Cmp.getOpcode();
9010 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9011 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9015 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9019 // These can only come from an arithmetic instruction with overflow,
9020 // e.g. SADDO, UADDO.
9021 Cond = Cond.getNode()->getOperand(1);
9027 CondOpcode = Cond.getOpcode();
9028 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9029 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9030 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9031 Cond.getOperand(0).getValueType() != MVT::i8)) {
9032 SDValue LHS = Cond.getOperand(0);
9033 SDValue RHS = Cond.getOperand(1);
9037 switch (CondOpcode) {
9038 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9039 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9040 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9041 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9042 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9043 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9044 default: llvm_unreachable("unexpected overflowing operator");
9047 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9048 if (CondOpcode == ISD::UMULO)
9049 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9052 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9054 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9056 if (CondOpcode == ISD::UMULO)
9057 Cond = X86Op.getValue(2);
9059 Cond = X86Op.getValue(1);
9061 CC = DAG.getConstant(X86Cond, MVT::i8);
9065 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9066 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9067 if (CondOpc == ISD::OR) {
9068 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9069 // two branches instead of an explicit OR instruction with a
9071 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9072 isX86LogicalCmp(Cmp)) {
9073 CC = Cond.getOperand(0).getOperand(0);
9074 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9075 Chain, Dest, CC, Cmp);
9076 CC = Cond.getOperand(1).getOperand(0);
9080 } else { // ISD::AND
9081 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9082 // two branches instead of an explicit AND instruction with a
9083 // separate test. However, we only do this if this block doesn't
9084 // have a fall-through edge, because this requires an explicit
9085 // jmp when the condition is false.
9086 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9087 isX86LogicalCmp(Cmp) &&
9088 Op.getNode()->hasOneUse()) {
9089 X86::CondCode CCode =
9090 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9091 CCode = X86::GetOppositeBranchCondition(CCode);
9092 CC = DAG.getConstant(CCode, MVT::i8);
9093 SDNode *User = *Op.getNode()->use_begin();
9094 // Look for an unconditional branch following this conditional branch.
9095 // We need this because we need to reverse the successors in order
9096 // to implement FCMP_OEQ.
9097 if (User->getOpcode() == ISD::BR) {
9098 SDValue FalseBB = User->getOperand(1);
9100 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9101 assert(NewBR == User);
9105 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9106 Chain, Dest, CC, Cmp);
9107 X86::CondCode CCode =
9108 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9109 CCode = X86::GetOppositeBranchCondition(CCode);
9110 CC = DAG.getConstant(CCode, MVT::i8);
9116 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9117 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9118 // It should be transformed during dag combiner except when the condition
9119 // is set by a arithmetics with overflow node.
9120 X86::CondCode CCode =
9121 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9122 CCode = X86::GetOppositeBranchCondition(CCode);
9123 CC = DAG.getConstant(CCode, MVT::i8);
9124 Cond = Cond.getOperand(0).getOperand(1);
9126 } else if (Cond.getOpcode() == ISD::SETCC &&
9127 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9128 // For FCMP_OEQ, we can emit
9129 // two branches instead of an explicit AND instruction with a
9130 // separate test. However, we only do this if this block doesn't
9131 // have a fall-through edge, because this requires an explicit
9132 // jmp when the condition is false.
9133 if (Op.getNode()->hasOneUse()) {
9134 SDNode *User = *Op.getNode()->use_begin();
9135 // Look for an unconditional branch following this conditional branch.
9136 // We need this because we need to reverse the successors in order
9137 // to implement FCMP_OEQ.
9138 if (User->getOpcode() == ISD::BR) {
9139 SDValue FalseBB = User->getOperand(1);
9141 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9142 assert(NewBR == User);
9146 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9147 Cond.getOperand(0), Cond.getOperand(1));
9148 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9149 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9150 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9151 Chain, Dest, CC, Cmp);
9152 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9157 } else if (Cond.getOpcode() == ISD::SETCC &&
9158 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9159 // For FCMP_UNE, we can emit
9160 // two branches instead of an explicit AND instruction with a
9161 // separate test. However, we only do this if this block doesn't
9162 // have a fall-through edge, because this requires an explicit
9163 // jmp when the condition is false.
9164 if (Op.getNode()->hasOneUse()) {
9165 SDNode *User = *Op.getNode()->use_begin();
9166 // Look for an unconditional branch following this conditional branch.
9167 // We need this because we need to reverse the successors in order
9168 // to implement FCMP_UNE.
9169 if (User->getOpcode() == ISD::BR) {
9170 SDValue FalseBB = User->getOperand(1);
9172 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9173 assert(NewBR == User);
9176 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9177 Cond.getOperand(0), Cond.getOperand(1));
9178 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9179 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9180 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9181 Chain, Dest, CC, Cmp);
9182 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9192 // Look pass the truncate if the high bits are known zero.
9193 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9194 Cond = Cond.getOperand(0);
9196 // We know the result of AND is compared against zero. Try to match
9198 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9199 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9200 if (NewSetCC.getNode()) {
9201 CC = NewSetCC.getOperand(0);
9202 Cond = NewSetCC.getOperand(1);
9209 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9210 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9212 Cond = ConvertCmpIfNecessary(Cond, DAG);
9213 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9214 Chain, Dest, CC, Cond);
9218 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9219 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9220 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9221 // that the guard pages used by the OS virtual memory manager are allocated in
9222 // correct sequence.
9224 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9225 SelectionDAG &DAG) const {
9226 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9227 getTargetMachine().Options.EnableSegmentedStacks) &&
9228 "This should be used only on Windows targets or when segmented stacks "
9230 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9231 DebugLoc dl = Op.getDebugLoc();
9234 SDValue Chain = Op.getOperand(0);
9235 SDValue Size = Op.getOperand(1);
9236 // FIXME: Ensure alignment here
9238 bool Is64Bit = Subtarget->is64Bit();
9239 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9241 if (getTargetMachine().Options.EnableSegmentedStacks) {
9242 MachineFunction &MF = DAG.getMachineFunction();
9243 MachineRegisterInfo &MRI = MF.getRegInfo();
9246 // The 64 bit implementation of segmented stacks needs to clobber both r10
9247 // r11. This makes it impossible to use it along with nested parameters.
9248 const Function *F = MF.getFunction();
9250 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9252 if (I->hasNestAttr())
9253 report_fatal_error("Cannot use segmented stacks with functions that "
9254 "have nested arguments.");
9257 const TargetRegisterClass *AddrRegClass =
9258 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9259 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9260 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9261 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9262 DAG.getRegister(Vreg, SPTy));
9263 SDValue Ops1[2] = { Value, Chain };
9264 return DAG.getMergeValues(Ops1, 2, dl);
9267 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9269 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9270 Flag = Chain.getValue(1);
9271 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9273 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9274 Flag = Chain.getValue(1);
9276 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9278 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9279 return DAG.getMergeValues(Ops1, 2, dl);
9283 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9284 MachineFunction &MF = DAG.getMachineFunction();
9285 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9287 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9288 DebugLoc DL = Op.getDebugLoc();
9290 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9291 // vastart just stores the address of the VarArgsFrameIndex slot into the
9292 // memory location argument.
9293 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9295 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9296 MachinePointerInfo(SV), false, false, 0);
9300 // gp_offset (0 - 6 * 8)
9301 // fp_offset (48 - 48 + 8 * 16)
9302 // overflow_arg_area (point to parameters coming in memory).
9304 SmallVector<SDValue, 8> MemOps;
9305 SDValue FIN = Op.getOperand(1);
9307 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9308 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9310 FIN, MachinePointerInfo(SV), false, false, 0);
9311 MemOps.push_back(Store);
9314 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9315 FIN, DAG.getIntPtrConstant(4));
9316 Store = DAG.getStore(Op.getOperand(0), DL,
9317 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9319 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9320 MemOps.push_back(Store);
9322 // Store ptr to overflow_arg_area
9323 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9324 FIN, DAG.getIntPtrConstant(4));
9325 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9327 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9328 MachinePointerInfo(SV, 8),
9330 MemOps.push_back(Store);
9332 // Store ptr to reg_save_area.
9333 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9334 FIN, DAG.getIntPtrConstant(8));
9335 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9337 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9338 MachinePointerInfo(SV, 16), false, false, 0);
9339 MemOps.push_back(Store);
9340 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9341 &MemOps[0], MemOps.size());
9344 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9345 assert(Subtarget->is64Bit() &&
9346 "LowerVAARG only handles 64-bit va_arg!");
9347 assert((Subtarget->isTargetLinux() ||
9348 Subtarget->isTargetDarwin()) &&
9349 "Unhandled target in LowerVAARG");
9350 assert(Op.getNode()->getNumOperands() == 4);
9351 SDValue Chain = Op.getOperand(0);
9352 SDValue SrcPtr = Op.getOperand(1);
9353 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9354 unsigned Align = Op.getConstantOperandVal(3);
9355 DebugLoc dl = Op.getDebugLoc();
9357 EVT ArgVT = Op.getNode()->getValueType(0);
9358 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9359 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9362 // Decide which area this value should be read from.
9363 // TODO: Implement the AMD64 ABI in its entirety. This simple
9364 // selection mechanism works only for the basic types.
9365 if (ArgVT == MVT::f80) {
9366 llvm_unreachable("va_arg for f80 not yet implemented");
9367 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9368 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9369 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9370 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9372 llvm_unreachable("Unhandled argument type in LowerVAARG");
9376 // Sanity Check: Make sure using fp_offset makes sense.
9377 assert(!getTargetMachine().Options.UseSoftFloat &&
9378 !(DAG.getMachineFunction()
9379 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9380 Subtarget->hasSSE1());
9383 // Insert VAARG_64 node into the DAG
9384 // VAARG_64 returns two values: Variable Argument Address, Chain
9385 SmallVector<SDValue, 11> InstOps;
9386 InstOps.push_back(Chain);
9387 InstOps.push_back(SrcPtr);
9388 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9389 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9390 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9391 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9392 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9393 VTs, &InstOps[0], InstOps.size(),
9395 MachinePointerInfo(SV),
9400 Chain = VAARG.getValue(1);
9402 // Load the next argument and return it
9403 return DAG.getLoad(ArgVT, dl,
9406 MachinePointerInfo(),
9407 false, false, false, 0);
9410 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9411 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9412 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9413 SDValue Chain = Op.getOperand(0);
9414 SDValue DstPtr = Op.getOperand(1);
9415 SDValue SrcPtr = Op.getOperand(2);
9416 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9417 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9418 DebugLoc DL = Op.getDebugLoc();
9420 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9421 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9423 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9426 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9427 // may or may not be a constant. Takes immediate version of shift as input.
9428 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9429 SDValue SrcOp, SDValue ShAmt,
9430 SelectionDAG &DAG) {
9431 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9433 if (isa<ConstantSDNode>(ShAmt)) {
9434 // Constant may be a TargetConstant. Use a regular constant.
9435 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9437 default: llvm_unreachable("Unknown target vector shift node");
9441 return DAG.getNode(Opc, dl, VT, SrcOp,
9442 DAG.getConstant(ShiftAmt, MVT::i32));
9446 // Change opcode to non-immediate version
9448 default: llvm_unreachable("Unknown target vector shift node");
9449 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9450 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9451 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9454 // Need to build a vector containing shift amount
9455 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9458 ShOps[1] = DAG.getConstant(0, MVT::i32);
9459 ShOps[2] = DAG.getUNDEF(MVT::i32);
9460 ShOps[3] = DAG.getUNDEF(MVT::i32);
9461 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9463 // The return type has to be a 128-bit type with the same element
9464 // type as the input type.
9465 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9466 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9468 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9469 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9473 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9474 DebugLoc dl = Op.getDebugLoc();
9475 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9477 default: return SDValue(); // Don't custom lower most intrinsics.
9478 // Comparison intrinsics.
9479 case Intrinsic::x86_sse_comieq_ss:
9480 case Intrinsic::x86_sse_comilt_ss:
9481 case Intrinsic::x86_sse_comile_ss:
9482 case Intrinsic::x86_sse_comigt_ss:
9483 case Intrinsic::x86_sse_comige_ss:
9484 case Intrinsic::x86_sse_comineq_ss:
9485 case Intrinsic::x86_sse_ucomieq_ss:
9486 case Intrinsic::x86_sse_ucomilt_ss:
9487 case Intrinsic::x86_sse_ucomile_ss:
9488 case Intrinsic::x86_sse_ucomigt_ss:
9489 case Intrinsic::x86_sse_ucomige_ss:
9490 case Intrinsic::x86_sse_ucomineq_ss:
9491 case Intrinsic::x86_sse2_comieq_sd:
9492 case Intrinsic::x86_sse2_comilt_sd:
9493 case Intrinsic::x86_sse2_comile_sd:
9494 case Intrinsic::x86_sse2_comigt_sd:
9495 case Intrinsic::x86_sse2_comige_sd:
9496 case Intrinsic::x86_sse2_comineq_sd:
9497 case Intrinsic::x86_sse2_ucomieq_sd:
9498 case Intrinsic::x86_sse2_ucomilt_sd:
9499 case Intrinsic::x86_sse2_ucomile_sd:
9500 case Intrinsic::x86_sse2_ucomigt_sd:
9501 case Intrinsic::x86_sse2_ucomige_sd:
9502 case Intrinsic::x86_sse2_ucomineq_sd: {
9504 ISD::CondCode CC = ISD::SETCC_INVALID;
9506 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9507 case Intrinsic::x86_sse_comieq_ss:
9508 case Intrinsic::x86_sse2_comieq_sd:
9512 case Intrinsic::x86_sse_comilt_ss:
9513 case Intrinsic::x86_sse2_comilt_sd:
9517 case Intrinsic::x86_sse_comile_ss:
9518 case Intrinsic::x86_sse2_comile_sd:
9522 case Intrinsic::x86_sse_comigt_ss:
9523 case Intrinsic::x86_sse2_comigt_sd:
9527 case Intrinsic::x86_sse_comige_ss:
9528 case Intrinsic::x86_sse2_comige_sd:
9532 case Intrinsic::x86_sse_comineq_ss:
9533 case Intrinsic::x86_sse2_comineq_sd:
9537 case Intrinsic::x86_sse_ucomieq_ss:
9538 case Intrinsic::x86_sse2_ucomieq_sd:
9539 Opc = X86ISD::UCOMI;
9542 case Intrinsic::x86_sse_ucomilt_ss:
9543 case Intrinsic::x86_sse2_ucomilt_sd:
9544 Opc = X86ISD::UCOMI;
9547 case Intrinsic::x86_sse_ucomile_ss:
9548 case Intrinsic::x86_sse2_ucomile_sd:
9549 Opc = X86ISD::UCOMI;
9552 case Intrinsic::x86_sse_ucomigt_ss:
9553 case Intrinsic::x86_sse2_ucomigt_sd:
9554 Opc = X86ISD::UCOMI;
9557 case Intrinsic::x86_sse_ucomige_ss:
9558 case Intrinsic::x86_sse2_ucomige_sd:
9559 Opc = X86ISD::UCOMI;
9562 case Intrinsic::x86_sse_ucomineq_ss:
9563 case Intrinsic::x86_sse2_ucomineq_sd:
9564 Opc = X86ISD::UCOMI;
9569 SDValue LHS = Op.getOperand(1);
9570 SDValue RHS = Op.getOperand(2);
9571 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9572 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9573 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9574 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9575 DAG.getConstant(X86CC, MVT::i8), Cond);
9576 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9578 // Arithmetic intrinsics.
9579 case Intrinsic::x86_sse2_pmulu_dq:
9580 case Intrinsic::x86_avx2_pmulu_dq:
9581 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9582 Op.getOperand(1), Op.getOperand(2));
9583 case Intrinsic::x86_sse3_hadd_ps:
9584 case Intrinsic::x86_sse3_hadd_pd:
9585 case Intrinsic::x86_avx_hadd_ps_256:
9586 case Intrinsic::x86_avx_hadd_pd_256:
9587 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9588 Op.getOperand(1), Op.getOperand(2));
9589 case Intrinsic::x86_sse3_hsub_ps:
9590 case Intrinsic::x86_sse3_hsub_pd:
9591 case Intrinsic::x86_avx_hsub_ps_256:
9592 case Intrinsic::x86_avx_hsub_pd_256:
9593 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9594 Op.getOperand(1), Op.getOperand(2));
9595 case Intrinsic::x86_ssse3_phadd_w_128:
9596 case Intrinsic::x86_ssse3_phadd_d_128:
9597 case Intrinsic::x86_avx2_phadd_w:
9598 case Intrinsic::x86_avx2_phadd_d:
9599 return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9600 Op.getOperand(1), Op.getOperand(2));
9601 case Intrinsic::x86_ssse3_phsub_w_128:
9602 case Intrinsic::x86_ssse3_phsub_d_128:
9603 case Intrinsic::x86_avx2_phsub_w:
9604 case Intrinsic::x86_avx2_phsub_d:
9605 return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9606 Op.getOperand(1), Op.getOperand(2));
9607 case Intrinsic::x86_avx2_psllv_d:
9608 case Intrinsic::x86_avx2_psllv_q:
9609 case Intrinsic::x86_avx2_psllv_d_256:
9610 case Intrinsic::x86_avx2_psllv_q_256:
9611 return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9612 Op.getOperand(1), Op.getOperand(2));
9613 case Intrinsic::x86_avx2_psrlv_d:
9614 case Intrinsic::x86_avx2_psrlv_q:
9615 case Intrinsic::x86_avx2_psrlv_d_256:
9616 case Intrinsic::x86_avx2_psrlv_q_256:
9617 return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9618 Op.getOperand(1), Op.getOperand(2));
9619 case Intrinsic::x86_avx2_psrav_d:
9620 case Intrinsic::x86_avx2_psrav_d_256:
9621 return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9622 Op.getOperand(1), Op.getOperand(2));
9623 case Intrinsic::x86_ssse3_pshuf_b_128:
9624 case Intrinsic::x86_avx2_pshuf_b:
9625 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9626 Op.getOperand(1), Op.getOperand(2));
9627 case Intrinsic::x86_ssse3_psign_b_128:
9628 case Intrinsic::x86_ssse3_psign_w_128:
9629 case Intrinsic::x86_ssse3_psign_d_128:
9630 case Intrinsic::x86_avx2_psign_b:
9631 case Intrinsic::x86_avx2_psign_w:
9632 case Intrinsic::x86_avx2_psign_d:
9633 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9634 Op.getOperand(1), Op.getOperand(2));
9635 case Intrinsic::x86_sse41_insertps:
9636 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9637 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9638 case Intrinsic::x86_avx_vperm2f128_ps_256:
9639 case Intrinsic::x86_avx_vperm2f128_pd_256:
9640 case Intrinsic::x86_avx_vperm2f128_si_256:
9641 case Intrinsic::x86_avx2_vperm2i128:
9642 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9643 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9644 case Intrinsic::x86_avx2_permd:
9645 case Intrinsic::x86_avx2_permps:
9646 // Operands intentionally swapped. Mask is last operand to intrinsic,
9647 // but second operand for node/intruction.
9648 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9649 Op.getOperand(2), Op.getOperand(1));
9651 // ptest and testp intrinsics. The intrinsic these come from are designed to
9652 // return an integer value, not just an instruction so lower it to the ptest
9653 // or testp pattern and a setcc for the result.
9654 case Intrinsic::x86_sse41_ptestz:
9655 case Intrinsic::x86_sse41_ptestc:
9656 case Intrinsic::x86_sse41_ptestnzc:
9657 case Intrinsic::x86_avx_ptestz_256:
9658 case Intrinsic::x86_avx_ptestc_256:
9659 case Intrinsic::x86_avx_ptestnzc_256:
9660 case Intrinsic::x86_avx_vtestz_ps:
9661 case Intrinsic::x86_avx_vtestc_ps:
9662 case Intrinsic::x86_avx_vtestnzc_ps:
9663 case Intrinsic::x86_avx_vtestz_pd:
9664 case Intrinsic::x86_avx_vtestc_pd:
9665 case Intrinsic::x86_avx_vtestnzc_pd:
9666 case Intrinsic::x86_avx_vtestz_ps_256:
9667 case Intrinsic::x86_avx_vtestc_ps_256:
9668 case Intrinsic::x86_avx_vtestnzc_ps_256:
9669 case Intrinsic::x86_avx_vtestz_pd_256:
9670 case Intrinsic::x86_avx_vtestc_pd_256:
9671 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9672 bool IsTestPacked = false;
9675 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9676 case Intrinsic::x86_avx_vtestz_ps:
9677 case Intrinsic::x86_avx_vtestz_pd:
9678 case Intrinsic::x86_avx_vtestz_ps_256:
9679 case Intrinsic::x86_avx_vtestz_pd_256:
9680 IsTestPacked = true; // Fallthrough
9681 case Intrinsic::x86_sse41_ptestz:
9682 case Intrinsic::x86_avx_ptestz_256:
9684 X86CC = X86::COND_E;
9686 case Intrinsic::x86_avx_vtestc_ps:
9687 case Intrinsic::x86_avx_vtestc_pd:
9688 case Intrinsic::x86_avx_vtestc_ps_256:
9689 case Intrinsic::x86_avx_vtestc_pd_256:
9690 IsTestPacked = true; // Fallthrough
9691 case Intrinsic::x86_sse41_ptestc:
9692 case Intrinsic::x86_avx_ptestc_256:
9694 X86CC = X86::COND_B;
9696 case Intrinsic::x86_avx_vtestnzc_ps:
9697 case Intrinsic::x86_avx_vtestnzc_pd:
9698 case Intrinsic::x86_avx_vtestnzc_ps_256:
9699 case Intrinsic::x86_avx_vtestnzc_pd_256:
9700 IsTestPacked = true; // Fallthrough
9701 case Intrinsic::x86_sse41_ptestnzc:
9702 case Intrinsic::x86_avx_ptestnzc_256:
9704 X86CC = X86::COND_A;
9708 SDValue LHS = Op.getOperand(1);
9709 SDValue RHS = Op.getOperand(2);
9710 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9711 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9712 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9713 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9714 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9717 // SSE/AVX shift intrinsics
9718 case Intrinsic::x86_sse2_psll_w:
9719 case Intrinsic::x86_sse2_psll_d:
9720 case Intrinsic::x86_sse2_psll_q:
9721 case Intrinsic::x86_avx2_psll_w:
9722 case Intrinsic::x86_avx2_psll_d:
9723 case Intrinsic::x86_avx2_psll_q:
9724 return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9725 Op.getOperand(1), Op.getOperand(2));
9726 case Intrinsic::x86_sse2_psrl_w:
9727 case Intrinsic::x86_sse2_psrl_d:
9728 case Intrinsic::x86_sse2_psrl_q:
9729 case Intrinsic::x86_avx2_psrl_w:
9730 case Intrinsic::x86_avx2_psrl_d:
9731 case Intrinsic::x86_avx2_psrl_q:
9732 return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9733 Op.getOperand(1), Op.getOperand(2));
9734 case Intrinsic::x86_sse2_psra_w:
9735 case Intrinsic::x86_sse2_psra_d:
9736 case Intrinsic::x86_avx2_psra_w:
9737 case Intrinsic::x86_avx2_psra_d:
9738 return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9739 Op.getOperand(1), Op.getOperand(2));
9740 case Intrinsic::x86_sse2_pslli_w:
9741 case Intrinsic::x86_sse2_pslli_d:
9742 case Intrinsic::x86_sse2_pslli_q:
9743 case Intrinsic::x86_avx2_pslli_w:
9744 case Intrinsic::x86_avx2_pslli_d:
9745 case Intrinsic::x86_avx2_pslli_q:
9746 return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9747 Op.getOperand(1), Op.getOperand(2), DAG);
9748 case Intrinsic::x86_sse2_psrli_w:
9749 case Intrinsic::x86_sse2_psrli_d:
9750 case Intrinsic::x86_sse2_psrli_q:
9751 case Intrinsic::x86_avx2_psrli_w:
9752 case Intrinsic::x86_avx2_psrli_d:
9753 case Intrinsic::x86_avx2_psrli_q:
9754 return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9755 Op.getOperand(1), Op.getOperand(2), DAG);
9756 case Intrinsic::x86_sse2_psrai_w:
9757 case Intrinsic::x86_sse2_psrai_d:
9758 case Intrinsic::x86_avx2_psrai_w:
9759 case Intrinsic::x86_avx2_psrai_d:
9760 return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9761 Op.getOperand(1), Op.getOperand(2), DAG);
9762 // Fix vector shift instructions where the last operand is a non-immediate
9764 case Intrinsic::x86_mmx_pslli_w:
9765 case Intrinsic::x86_mmx_pslli_d:
9766 case Intrinsic::x86_mmx_pslli_q:
9767 case Intrinsic::x86_mmx_psrli_w:
9768 case Intrinsic::x86_mmx_psrli_d:
9769 case Intrinsic::x86_mmx_psrli_q:
9770 case Intrinsic::x86_mmx_psrai_w:
9771 case Intrinsic::x86_mmx_psrai_d: {
9772 SDValue ShAmt = Op.getOperand(2);
9773 if (isa<ConstantSDNode>(ShAmt))
9776 unsigned NewIntNo = 0;
9778 case Intrinsic::x86_mmx_pslli_w:
9779 NewIntNo = Intrinsic::x86_mmx_psll_w;
9781 case Intrinsic::x86_mmx_pslli_d:
9782 NewIntNo = Intrinsic::x86_mmx_psll_d;
9784 case Intrinsic::x86_mmx_pslli_q:
9785 NewIntNo = Intrinsic::x86_mmx_psll_q;
9787 case Intrinsic::x86_mmx_psrli_w:
9788 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9790 case Intrinsic::x86_mmx_psrli_d:
9791 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9793 case Intrinsic::x86_mmx_psrli_q:
9794 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9796 case Intrinsic::x86_mmx_psrai_w:
9797 NewIntNo = Intrinsic::x86_mmx_psra_w;
9799 case Intrinsic::x86_mmx_psrai_d:
9800 NewIntNo = Intrinsic::x86_mmx_psra_d;
9802 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9805 // The vector shift intrinsics with scalars uses 32b shift amounts but
9806 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9808 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9809 DAG.getConstant(0, MVT::i32));
9810 // FIXME this must be lowered to get rid of the invalid type.
9812 EVT VT = Op.getValueType();
9813 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9814 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9815 DAG.getConstant(NewIntNo, MVT::i32),
9816 Op.getOperand(1), ShAmt);
9818 case Intrinsic::x86_sse42_pcmpistria128:
9819 case Intrinsic::x86_sse42_pcmpestria128:
9820 case Intrinsic::x86_sse42_pcmpistric128:
9821 case Intrinsic::x86_sse42_pcmpestric128:
9822 case Intrinsic::x86_sse42_pcmpistrio128:
9823 case Intrinsic::x86_sse42_pcmpestrio128:
9824 case Intrinsic::x86_sse42_pcmpistris128:
9825 case Intrinsic::x86_sse42_pcmpestris128:
9826 case Intrinsic::x86_sse42_pcmpistriz128:
9827 case Intrinsic::x86_sse42_pcmpestriz128: {
9831 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9832 case Intrinsic::x86_sse42_pcmpistria128:
9833 Opcode = X86ISD::PCMPISTRI;
9834 X86CC = X86::COND_A;
9836 case Intrinsic::x86_sse42_pcmpestria128:
9837 Opcode = X86ISD::PCMPESTRI;
9838 X86CC = X86::COND_A;
9840 case Intrinsic::x86_sse42_pcmpistric128:
9841 Opcode = X86ISD::PCMPISTRI;
9842 X86CC = X86::COND_B;
9844 case Intrinsic::x86_sse42_pcmpestric128:
9845 Opcode = X86ISD::PCMPESTRI;
9846 X86CC = X86::COND_B;
9848 case Intrinsic::x86_sse42_pcmpistrio128:
9849 Opcode = X86ISD::PCMPISTRI;
9850 X86CC = X86::COND_O;
9852 case Intrinsic::x86_sse42_pcmpestrio128:
9853 Opcode = X86ISD::PCMPESTRI;
9854 X86CC = X86::COND_O;
9856 case Intrinsic::x86_sse42_pcmpistris128:
9857 Opcode = X86ISD::PCMPISTRI;
9858 X86CC = X86::COND_S;
9860 case Intrinsic::x86_sse42_pcmpestris128:
9861 Opcode = X86ISD::PCMPESTRI;
9862 X86CC = X86::COND_S;
9864 case Intrinsic::x86_sse42_pcmpistriz128:
9865 Opcode = X86ISD::PCMPISTRI;
9866 X86CC = X86::COND_E;
9868 case Intrinsic::x86_sse42_pcmpestriz128:
9869 Opcode = X86ISD::PCMPESTRI;
9870 X86CC = X86::COND_E;
9873 SmallVector<SDValue, 5> NewOps;
9874 NewOps.append(Op->op_begin()+1, Op->op_end());
9875 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9876 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
9877 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9878 DAG.getConstant(X86CC, MVT::i8),
9879 SDValue(PCMP.getNode(), 1));
9880 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9882 case Intrinsic::x86_sse42_pcmpistri128:
9883 case Intrinsic::x86_sse42_pcmpestri128: {
9885 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
9886 Opcode = X86ISD::PCMPISTRI;
9888 Opcode = X86ISD::PCMPESTRI;
9890 SmallVector<SDValue, 5> NewOps;
9891 NewOps.append(Op->op_begin()+1, Op->op_end());
9892 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9893 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
9899 X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9900 DebugLoc dl = Op.getDebugLoc();
9901 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9903 default: return SDValue(); // Don't custom lower most intrinsics.
9905 // RDRAND intrinsics.
9906 case Intrinsic::x86_rdrand_16:
9907 case Intrinsic::x86_rdrand_32:
9908 case Intrinsic::x86_rdrand_64: {
9909 // Emit the node with the right value type.
9910 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
9911 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
9913 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
9914 // return the value from Rand, which is always 0, casted to i32.
9915 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
9916 DAG.getConstant(1, Op->getValueType(1)),
9917 DAG.getConstant(X86::COND_B, MVT::i32),
9918 SDValue(Result.getNode(), 1) };
9919 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
9920 DAG.getVTList(Op->getValueType(1), MVT::Glue),
9923 // Return { result, isValid, chain }.
9924 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
9925 SDValue(Result.getNode(), 2));
9930 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9931 SelectionDAG &DAG) const {
9932 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9933 MFI->setReturnAddressIsTaken(true);
9935 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9936 DebugLoc dl = Op.getDebugLoc();
9939 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9941 DAG.getConstant(TD->getPointerSize(),
9942 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9943 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9944 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9946 MachinePointerInfo(), false, false, false, 0);
9949 // Just load the return address.
9950 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9951 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9952 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9955 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9956 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9957 MFI->setFrameAddressIsTaken(true);
9959 EVT VT = Op.getValueType();
9960 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9961 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9962 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9963 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9965 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9966 MachinePointerInfo(),
9967 false, false, false, 0);
9971 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9972 SelectionDAG &DAG) const {
9973 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9976 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9977 SDValue Chain = Op.getOperand(0);
9978 SDValue Offset = Op.getOperand(1);
9979 SDValue Handler = Op.getOperand(2);
9980 DebugLoc dl = Op.getDebugLoc();
9982 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9983 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9985 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9987 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9988 DAG.getIntPtrConstant(TD->getPointerSize()));
9989 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9990 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9992 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9994 return DAG.getNode(X86ISD::EH_RETURN, dl,
9996 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9999 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
10000 SelectionDAG &DAG) const {
10001 return Op.getOperand(0);
10004 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10005 SelectionDAG &DAG) const {
10006 SDValue Root = Op.getOperand(0);
10007 SDValue Trmp = Op.getOperand(1); // trampoline
10008 SDValue FPtr = Op.getOperand(2); // nested function
10009 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10010 DebugLoc dl = Op.getDebugLoc();
10012 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10014 if (Subtarget->is64Bit()) {
10015 SDValue OutChains[6];
10017 // Large code-model.
10018 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10019 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10021 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10022 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10024 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10026 // Load the pointer to the nested function into R11.
10027 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10028 SDValue Addr = Trmp;
10029 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10030 Addr, MachinePointerInfo(TrmpAddr),
10033 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10034 DAG.getConstant(2, MVT::i64));
10035 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10036 MachinePointerInfo(TrmpAddr, 2),
10039 // Load the 'nest' parameter value into R10.
10040 // R10 is specified in X86CallingConv.td
10041 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10042 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10043 DAG.getConstant(10, MVT::i64));
10044 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10045 Addr, MachinePointerInfo(TrmpAddr, 10),
10048 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10049 DAG.getConstant(12, MVT::i64));
10050 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10051 MachinePointerInfo(TrmpAddr, 12),
10054 // Jump to the nested function.
10055 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10056 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10057 DAG.getConstant(20, MVT::i64));
10058 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10059 Addr, MachinePointerInfo(TrmpAddr, 20),
10062 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10063 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10064 DAG.getConstant(22, MVT::i64));
10065 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10066 MachinePointerInfo(TrmpAddr, 22),
10069 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10071 const Function *Func =
10072 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10073 CallingConv::ID CC = Func->getCallingConv();
10078 llvm_unreachable("Unsupported calling convention");
10079 case CallingConv::C:
10080 case CallingConv::X86_StdCall: {
10081 // Pass 'nest' parameter in ECX.
10082 // Must be kept in sync with X86CallingConv.td
10083 NestReg = X86::ECX;
10085 // Check that ECX wasn't needed by an 'inreg' parameter.
10086 FunctionType *FTy = Func->getFunctionType();
10087 const AttrListPtr &Attrs = Func->getAttributes();
10089 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10090 unsigned InRegCount = 0;
10093 for (FunctionType::param_iterator I = FTy->param_begin(),
10094 E = FTy->param_end(); I != E; ++I, ++Idx)
10095 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10096 // FIXME: should only count parameters that are lowered to integers.
10097 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10099 if (InRegCount > 2) {
10100 report_fatal_error("Nest register in use - reduce number of inreg"
10106 case CallingConv::X86_FastCall:
10107 case CallingConv::X86_ThisCall:
10108 case CallingConv::Fast:
10109 // Pass 'nest' parameter in EAX.
10110 // Must be kept in sync with X86CallingConv.td
10111 NestReg = X86::EAX;
10115 SDValue OutChains[4];
10116 SDValue Addr, Disp;
10118 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10119 DAG.getConstant(10, MVT::i32));
10120 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10122 // This is storing the opcode for MOV32ri.
10123 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10124 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10125 OutChains[0] = DAG.getStore(Root, dl,
10126 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10127 Trmp, MachinePointerInfo(TrmpAddr),
10130 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10131 DAG.getConstant(1, MVT::i32));
10132 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10133 MachinePointerInfo(TrmpAddr, 1),
10136 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10137 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10138 DAG.getConstant(5, MVT::i32));
10139 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10140 MachinePointerInfo(TrmpAddr, 5),
10143 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10144 DAG.getConstant(6, MVT::i32));
10145 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10146 MachinePointerInfo(TrmpAddr, 6),
10149 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10153 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10154 SelectionDAG &DAG) const {
10156 The rounding mode is in bits 11:10 of FPSR, and has the following
10158 00 Round to nearest
10163 FLT_ROUNDS, on the other hand, expects the following:
10170 To perform the conversion, we do:
10171 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10174 MachineFunction &MF = DAG.getMachineFunction();
10175 const TargetMachine &TM = MF.getTarget();
10176 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10177 unsigned StackAlignment = TFI.getStackAlignment();
10178 EVT VT = Op.getValueType();
10179 DebugLoc DL = Op.getDebugLoc();
10181 // Save FP Control Word to stack slot
10182 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10183 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10186 MachineMemOperand *MMO =
10187 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10188 MachineMemOperand::MOStore, 2, 2);
10190 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10191 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10192 DAG.getVTList(MVT::Other),
10193 Ops, 2, MVT::i16, MMO);
10195 // Load FP Control Word from stack slot
10196 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10197 MachinePointerInfo(), false, false, false, 0);
10199 // Transform as necessary
10201 DAG.getNode(ISD::SRL, DL, MVT::i16,
10202 DAG.getNode(ISD::AND, DL, MVT::i16,
10203 CWD, DAG.getConstant(0x800, MVT::i16)),
10204 DAG.getConstant(11, MVT::i8));
10206 DAG.getNode(ISD::SRL, DL, MVT::i16,
10207 DAG.getNode(ISD::AND, DL, MVT::i16,
10208 CWD, DAG.getConstant(0x400, MVT::i16)),
10209 DAG.getConstant(9, MVT::i8));
10212 DAG.getNode(ISD::AND, DL, MVT::i16,
10213 DAG.getNode(ISD::ADD, DL, MVT::i16,
10214 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10215 DAG.getConstant(1, MVT::i16)),
10216 DAG.getConstant(3, MVT::i16));
10219 return DAG.getNode((VT.getSizeInBits() < 16 ?
10220 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10223 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10224 EVT VT = Op.getValueType();
10226 unsigned NumBits = VT.getSizeInBits();
10227 DebugLoc dl = Op.getDebugLoc();
10229 Op = Op.getOperand(0);
10230 if (VT == MVT::i8) {
10231 // Zero extend to i32 since there is not an i8 bsr.
10233 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10236 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10237 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10238 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10240 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10243 DAG.getConstant(NumBits+NumBits-1, OpVT),
10244 DAG.getConstant(X86::COND_E, MVT::i8),
10247 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10249 // Finally xor with NumBits-1.
10250 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10253 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10257 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10258 SelectionDAG &DAG) const {
10259 EVT VT = Op.getValueType();
10261 unsigned NumBits = VT.getSizeInBits();
10262 DebugLoc dl = Op.getDebugLoc();
10264 Op = Op.getOperand(0);
10265 if (VT == MVT::i8) {
10266 // Zero extend to i32 since there is not an i8 bsr.
10268 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10271 // Issue a bsr (scan bits in reverse).
10272 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10273 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10275 // And xor with NumBits-1.
10276 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10279 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10283 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10284 EVT VT = Op.getValueType();
10285 unsigned NumBits = VT.getSizeInBits();
10286 DebugLoc dl = Op.getDebugLoc();
10287 Op = Op.getOperand(0);
10289 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10290 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10291 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10293 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10296 DAG.getConstant(NumBits, VT),
10297 DAG.getConstant(X86::COND_E, MVT::i8),
10300 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10303 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10304 // ones, and then concatenate the result back.
10305 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10306 EVT VT = Op.getValueType();
10308 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10309 "Unsupported value type for operation");
10311 unsigned NumElems = VT.getVectorNumElements();
10312 DebugLoc dl = Op.getDebugLoc();
10314 // Extract the LHS vectors
10315 SDValue LHS = Op.getOperand(0);
10316 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10317 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10319 // Extract the RHS vectors
10320 SDValue RHS = Op.getOperand(1);
10321 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10322 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10324 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10325 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10327 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10328 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10329 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10332 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10333 assert(Op.getValueType().getSizeInBits() == 256 &&
10334 Op.getValueType().isInteger() &&
10335 "Only handle AVX 256-bit vector integer operation");
10336 return Lower256IntArith(Op, DAG);
10339 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10340 assert(Op.getValueType().getSizeInBits() == 256 &&
10341 Op.getValueType().isInteger() &&
10342 "Only handle AVX 256-bit vector integer operation");
10343 return Lower256IntArith(Op, DAG);
10346 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10347 EVT VT = Op.getValueType();
10349 // Decompose 256-bit ops into smaller 128-bit ops.
10350 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10351 return Lower256IntArith(Op, DAG);
10353 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10354 "Only know how to lower V2I64/V4I64 multiply");
10356 DebugLoc dl = Op.getDebugLoc();
10358 // Ahi = psrlqi(a, 32);
10359 // Bhi = psrlqi(b, 32);
10361 // AloBlo = pmuludq(a, b);
10362 // AloBhi = pmuludq(a, Bhi);
10363 // AhiBlo = pmuludq(Ahi, b);
10365 // AloBhi = psllqi(AloBhi, 32);
10366 // AhiBlo = psllqi(AhiBlo, 32);
10367 // return AloBlo + AloBhi + AhiBlo;
10369 SDValue A = Op.getOperand(0);
10370 SDValue B = Op.getOperand(1);
10372 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10374 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10375 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10377 // Bit cast to 32-bit vectors for MULUDQ
10378 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10379 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10380 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10381 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10382 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10384 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10385 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10386 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10388 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10389 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10391 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10392 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10395 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10397 EVT VT = Op.getValueType();
10398 DebugLoc dl = Op.getDebugLoc();
10399 SDValue R = Op.getOperand(0);
10400 SDValue Amt = Op.getOperand(1);
10401 LLVMContext *Context = DAG.getContext();
10403 if (!Subtarget->hasSSE2())
10406 // Optimize shl/srl/sra with constant shift amount.
10407 if (isSplatVector(Amt.getNode())) {
10408 SDValue SclrAmt = Amt->getOperand(0);
10409 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10410 uint64_t ShiftAmt = C->getZExtValue();
10412 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10413 (Subtarget->hasAVX2() &&
10414 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10415 if (Op.getOpcode() == ISD::SHL)
10416 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10417 DAG.getConstant(ShiftAmt, MVT::i32));
10418 if (Op.getOpcode() == ISD::SRL)
10419 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10420 DAG.getConstant(ShiftAmt, MVT::i32));
10421 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10422 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10423 DAG.getConstant(ShiftAmt, MVT::i32));
10426 if (VT == MVT::v16i8) {
10427 if (Op.getOpcode() == ISD::SHL) {
10428 // Make a large shift.
10429 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10430 DAG.getConstant(ShiftAmt, MVT::i32));
10431 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10432 // Zero out the rightmost bits.
10433 SmallVector<SDValue, 16> V(16,
10434 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10436 return DAG.getNode(ISD::AND, dl, VT, SHL,
10437 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10439 if (Op.getOpcode() == ISD::SRL) {
10440 // Make a large shift.
10441 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10442 DAG.getConstant(ShiftAmt, MVT::i32));
10443 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10444 // Zero out the leftmost bits.
10445 SmallVector<SDValue, 16> V(16,
10446 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10448 return DAG.getNode(ISD::AND, dl, VT, SRL,
10449 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10451 if (Op.getOpcode() == ISD::SRA) {
10452 if (ShiftAmt == 7) {
10453 // R s>> 7 === R s< 0
10454 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10455 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10458 // R s>> a === ((R u>> a) ^ m) - m
10459 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10460 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10462 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10463 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10464 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10467 llvm_unreachable("Unknown shift opcode.");
10470 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10471 if (Op.getOpcode() == ISD::SHL) {
10472 // Make a large shift.
10473 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10474 DAG.getConstant(ShiftAmt, MVT::i32));
10475 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10476 // Zero out the rightmost bits.
10477 SmallVector<SDValue, 32> V(32,
10478 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10480 return DAG.getNode(ISD::AND, dl, VT, SHL,
10481 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10483 if (Op.getOpcode() == ISD::SRL) {
10484 // Make a large shift.
10485 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10486 DAG.getConstant(ShiftAmt, MVT::i32));
10487 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10488 // Zero out the leftmost bits.
10489 SmallVector<SDValue, 32> V(32,
10490 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10492 return DAG.getNode(ISD::AND, dl, VT, SRL,
10493 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10495 if (Op.getOpcode() == ISD::SRA) {
10496 if (ShiftAmt == 7) {
10497 // R s>> 7 === R s< 0
10498 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10499 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10502 // R s>> a === ((R u>> a) ^ m) - m
10503 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10504 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10506 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10507 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10508 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10511 llvm_unreachable("Unknown shift opcode.");
10516 // Lower SHL with variable shift amount.
10517 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10518 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10519 DAG.getConstant(23, MVT::i32));
10521 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10522 Constant *C = ConstantDataVector::get(*Context, CV);
10523 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10524 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10525 MachinePointerInfo::getConstantPool(),
10526 false, false, false, 16);
10528 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10529 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10530 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10531 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10533 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10534 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10537 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10538 DAG.getConstant(5, MVT::i32));
10539 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10541 // Turn 'a' into a mask suitable for VSELECT
10542 SDValue VSelM = DAG.getConstant(0x80, VT);
10543 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10544 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10546 SDValue CM1 = DAG.getConstant(0x0f, VT);
10547 SDValue CM2 = DAG.getConstant(0x3f, VT);
10549 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10550 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10551 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10552 DAG.getConstant(4, MVT::i32), DAG);
10553 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10554 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10557 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10558 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10559 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10561 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10562 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10563 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10564 DAG.getConstant(2, MVT::i32), DAG);
10565 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10566 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10569 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10570 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10571 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10573 // return VSELECT(r, r+r, a);
10574 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10575 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10579 // Decompose 256-bit shifts into smaller 128-bit shifts.
10580 if (VT.getSizeInBits() == 256) {
10581 unsigned NumElems = VT.getVectorNumElements();
10582 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10583 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10585 // Extract the two vectors
10586 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10587 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10589 // Recreate the shift amount vectors
10590 SDValue Amt1, Amt2;
10591 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10592 // Constant shift amount
10593 SmallVector<SDValue, 4> Amt1Csts;
10594 SmallVector<SDValue, 4> Amt2Csts;
10595 for (unsigned i = 0; i != NumElems/2; ++i)
10596 Amt1Csts.push_back(Amt->getOperand(i));
10597 for (unsigned i = NumElems/2; i != NumElems; ++i)
10598 Amt2Csts.push_back(Amt->getOperand(i));
10600 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10601 &Amt1Csts[0], NumElems/2);
10602 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10603 &Amt2Csts[0], NumElems/2);
10605 // Variable shift amount
10606 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10607 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10610 // Issue new vector shifts for the smaller types
10611 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10612 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10614 // Concatenate the result back
10615 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10621 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10622 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10623 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10624 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10625 // has only one use.
10626 SDNode *N = Op.getNode();
10627 SDValue LHS = N->getOperand(0);
10628 SDValue RHS = N->getOperand(1);
10629 unsigned BaseOp = 0;
10631 DebugLoc DL = Op.getDebugLoc();
10632 switch (Op.getOpcode()) {
10633 default: llvm_unreachable("Unknown ovf instruction!");
10635 // A subtract of one will be selected as a INC. Note that INC doesn't
10636 // set CF, so we can't do this for UADDO.
10637 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10639 BaseOp = X86ISD::INC;
10640 Cond = X86::COND_O;
10643 BaseOp = X86ISD::ADD;
10644 Cond = X86::COND_O;
10647 BaseOp = X86ISD::ADD;
10648 Cond = X86::COND_B;
10651 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10652 // set CF, so we can't do this for USUBO.
10653 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10655 BaseOp = X86ISD::DEC;
10656 Cond = X86::COND_O;
10659 BaseOp = X86ISD::SUB;
10660 Cond = X86::COND_O;
10663 BaseOp = X86ISD::SUB;
10664 Cond = X86::COND_B;
10667 BaseOp = X86ISD::SMUL;
10668 Cond = X86::COND_O;
10670 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10671 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10673 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10676 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10677 DAG.getConstant(X86::COND_O, MVT::i32),
10678 SDValue(Sum.getNode(), 2));
10680 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10684 // Also sets EFLAGS.
10685 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10686 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10689 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10690 DAG.getConstant(Cond, MVT::i32),
10691 SDValue(Sum.getNode(), 1));
10693 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10696 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10697 SelectionDAG &DAG) const {
10698 DebugLoc dl = Op.getDebugLoc();
10699 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10700 EVT VT = Op.getValueType();
10702 if (!Subtarget->hasSSE2() || !VT.isVector())
10705 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10706 ExtraVT.getScalarType().getSizeInBits();
10707 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10709 switch (VT.getSimpleVT().SimpleTy) {
10710 default: return SDValue();
10713 if (!Subtarget->hasAVX())
10715 if (!Subtarget->hasAVX2()) {
10716 // needs to be split
10717 unsigned NumElems = VT.getVectorNumElements();
10719 // Extract the LHS vectors
10720 SDValue LHS = Op.getOperand(0);
10721 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10722 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10724 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10725 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10727 EVT ExtraEltVT = ExtraVT.getVectorElementType();
10728 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10729 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10731 SDValue Extra = DAG.getValueType(ExtraVT);
10733 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10734 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10736 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10741 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10742 Op.getOperand(0), ShAmt, DAG);
10743 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10749 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10750 DebugLoc dl = Op.getDebugLoc();
10752 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10753 // There isn't any reason to disable it if the target processor supports it.
10754 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10755 SDValue Chain = Op.getOperand(0);
10756 SDValue Zero = DAG.getConstant(0, MVT::i32);
10758 DAG.getRegister(X86::ESP, MVT::i32), // Base
10759 DAG.getTargetConstant(1, MVT::i8), // Scale
10760 DAG.getRegister(0, MVT::i32), // Index
10761 DAG.getTargetConstant(0, MVT::i32), // Disp
10762 DAG.getRegister(0, MVT::i32), // Segment.
10767 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10768 array_lengthof(Ops));
10769 return SDValue(Res, 0);
10772 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10774 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10776 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10777 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10778 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10779 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10781 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10782 if (!Op1 && !Op2 && !Op3 && Op4)
10783 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10785 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10786 if (Op1 && !Op2 && !Op3 && !Op4)
10787 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10789 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10791 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10794 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10795 SelectionDAG &DAG) const {
10796 DebugLoc dl = Op.getDebugLoc();
10797 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10798 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10799 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10800 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10802 // The only fence that needs an instruction is a sequentially-consistent
10803 // cross-thread fence.
10804 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10805 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10806 // no-sse2). There isn't any reason to disable it if the target processor
10808 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10809 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10811 SDValue Chain = Op.getOperand(0);
10812 SDValue Zero = DAG.getConstant(0, MVT::i32);
10814 DAG.getRegister(X86::ESP, MVT::i32), // Base
10815 DAG.getTargetConstant(1, MVT::i8), // Scale
10816 DAG.getRegister(0, MVT::i32), // Index
10817 DAG.getTargetConstant(0, MVT::i32), // Disp
10818 DAG.getRegister(0, MVT::i32), // Segment.
10823 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10824 array_lengthof(Ops));
10825 return SDValue(Res, 0);
10828 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10829 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10833 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10834 EVT T = Op.getValueType();
10835 DebugLoc DL = Op.getDebugLoc();
10838 switch(T.getSimpleVT().SimpleTy) {
10839 default: llvm_unreachable("Invalid value type!");
10840 case MVT::i8: Reg = X86::AL; size = 1; break;
10841 case MVT::i16: Reg = X86::AX; size = 2; break;
10842 case MVT::i32: Reg = X86::EAX; size = 4; break;
10844 assert(Subtarget->is64Bit() && "Node not type legal!");
10845 Reg = X86::RAX; size = 8;
10848 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10849 Op.getOperand(2), SDValue());
10850 SDValue Ops[] = { cpIn.getValue(0),
10853 DAG.getTargetConstant(size, MVT::i8),
10854 cpIn.getValue(1) };
10855 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10856 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10857 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10860 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10864 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10865 SelectionDAG &DAG) const {
10866 assert(Subtarget->is64Bit() && "Result not type legalized?");
10867 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10868 SDValue TheChain = Op.getOperand(0);
10869 DebugLoc dl = Op.getDebugLoc();
10870 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10871 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10872 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10874 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10875 DAG.getConstant(32, MVT::i8));
10877 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10880 return DAG.getMergeValues(Ops, 2, dl);
10883 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10884 SelectionDAG &DAG) const {
10885 EVT SrcVT = Op.getOperand(0).getValueType();
10886 EVT DstVT = Op.getValueType();
10887 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10888 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10889 assert((DstVT == MVT::i64 ||
10890 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10891 "Unexpected custom BITCAST");
10892 // i64 <=> MMX conversions are Legal.
10893 if (SrcVT==MVT::i64 && DstVT.isVector())
10895 if (DstVT==MVT::i64 && SrcVT.isVector())
10897 // MMX <=> MMX conversions are Legal.
10898 if (SrcVT.isVector() && DstVT.isVector())
10900 // All other conversions need to be expanded.
10904 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10905 SDNode *Node = Op.getNode();
10906 DebugLoc dl = Node->getDebugLoc();
10907 EVT T = Node->getValueType(0);
10908 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10909 DAG.getConstant(0, T), Node->getOperand(2));
10910 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10911 cast<AtomicSDNode>(Node)->getMemoryVT(),
10912 Node->getOperand(0),
10913 Node->getOperand(1), negOp,
10914 cast<AtomicSDNode>(Node)->getSrcValue(),
10915 cast<AtomicSDNode>(Node)->getAlignment(),
10916 cast<AtomicSDNode>(Node)->getOrdering(),
10917 cast<AtomicSDNode>(Node)->getSynchScope());
10920 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10921 SDNode *Node = Op.getNode();
10922 DebugLoc dl = Node->getDebugLoc();
10923 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10925 // Convert seq_cst store -> xchg
10926 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10927 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10928 // (The only way to get a 16-byte store is cmpxchg16b)
10929 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10930 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10931 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10932 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10933 cast<AtomicSDNode>(Node)->getMemoryVT(),
10934 Node->getOperand(0),
10935 Node->getOperand(1), Node->getOperand(2),
10936 cast<AtomicSDNode>(Node)->getMemOperand(),
10937 cast<AtomicSDNode>(Node)->getOrdering(),
10938 cast<AtomicSDNode>(Node)->getSynchScope());
10939 return Swap.getValue(1);
10941 // Other atomic stores have a simple pattern.
10945 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10946 EVT VT = Op.getNode()->getValueType(0);
10948 // Let legalize expand this if it isn't a legal type yet.
10949 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10952 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10955 bool ExtraOp = false;
10956 switch (Op.getOpcode()) {
10957 default: llvm_unreachable("Invalid code");
10958 case ISD::ADDC: Opc = X86ISD::ADD; break;
10959 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10960 case ISD::SUBC: Opc = X86ISD::SUB; break;
10961 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10965 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10967 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10968 Op.getOperand(1), Op.getOperand(2));
10971 /// LowerOperation - Provide custom lowering hooks for some operations.
10973 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10974 switch (Op.getOpcode()) {
10975 default: llvm_unreachable("Should not custom lower this!");
10976 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10977 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10978 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10979 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10980 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10981 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10982 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10983 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10984 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10985 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10986 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10987 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10988 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10989 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10990 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10991 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10992 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10993 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10994 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10995 case ISD::SHL_PARTS:
10996 case ISD::SRA_PARTS:
10997 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10998 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10999 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11000 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11001 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11002 case ISD::FABS: return LowerFABS(Op, DAG);
11003 case ISD::FNEG: return LowerFNEG(Op, DAG);
11004 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11005 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11006 case ISD::SETCC: return LowerSETCC(Op, DAG);
11007 case ISD::SELECT: return LowerSELECT(Op, DAG);
11008 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11009 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11010 case ISD::VASTART: return LowerVASTART(Op, DAG);
11011 case ISD::VAARG: return LowerVAARG(Op, DAG);
11012 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
11013 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11014 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11015 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11016 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11017 case ISD::FRAME_TO_ARGS_OFFSET:
11018 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11019 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11020 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11021 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11022 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11023 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11024 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11025 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11026 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11027 case ISD::MUL: return LowerMUL(Op, DAG);
11030 case ISD::SHL: return LowerShift(Op, DAG);
11036 case ISD::UMULO: return LowerXALUO(Op, DAG);
11037 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
11038 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11042 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11043 case ISD::ADD: return LowerADD(Op, DAG);
11044 case ISD::SUB: return LowerSUB(Op, DAG);
11048 static void ReplaceATOMIC_LOAD(SDNode *Node,
11049 SmallVectorImpl<SDValue> &Results,
11050 SelectionDAG &DAG) {
11051 DebugLoc dl = Node->getDebugLoc();
11052 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11054 // Convert wide load -> cmpxchg8b/cmpxchg16b
11055 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11056 // (The only way to get a 16-byte load is cmpxchg16b)
11057 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11058 SDValue Zero = DAG.getConstant(0, VT);
11059 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11060 Node->getOperand(0),
11061 Node->getOperand(1), Zero, Zero,
11062 cast<AtomicSDNode>(Node)->getMemOperand(),
11063 cast<AtomicSDNode>(Node)->getOrdering(),
11064 cast<AtomicSDNode>(Node)->getSynchScope());
11065 Results.push_back(Swap.getValue(0));
11066 Results.push_back(Swap.getValue(1));
11069 void X86TargetLowering::
11070 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11071 SelectionDAG &DAG, unsigned NewOp) const {
11072 DebugLoc dl = Node->getDebugLoc();
11073 assert (Node->getValueType(0) == MVT::i64 &&
11074 "Only know how to expand i64 atomics");
11076 SDValue Chain = Node->getOperand(0);
11077 SDValue In1 = Node->getOperand(1);
11078 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11079 Node->getOperand(2), DAG.getIntPtrConstant(0));
11080 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11081 Node->getOperand(2), DAG.getIntPtrConstant(1));
11082 SDValue Ops[] = { Chain, In1, In2L, In2H };
11083 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11085 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11086 cast<MemSDNode>(Node)->getMemOperand());
11087 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11088 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11089 Results.push_back(Result.getValue(2));
11092 /// ReplaceNodeResults - Replace a node with an illegal result type
11093 /// with a new node built out of custom code.
11094 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11095 SmallVectorImpl<SDValue>&Results,
11096 SelectionDAG &DAG) const {
11097 DebugLoc dl = N->getDebugLoc();
11098 switch (N->getOpcode()) {
11100 llvm_unreachable("Do not know how to custom type legalize this operation!");
11101 case ISD::SIGN_EXTEND_INREG:
11106 // We don't want to expand or promote these.
11108 case ISD::FP_TO_SINT:
11109 case ISD::FP_TO_UINT: {
11110 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11112 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11115 std::pair<SDValue,SDValue> Vals =
11116 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11117 SDValue FIST = Vals.first, StackSlot = Vals.second;
11118 if (FIST.getNode() != 0) {
11119 EVT VT = N->getValueType(0);
11120 // Return a load from the stack slot.
11121 if (StackSlot.getNode() != 0)
11122 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11123 MachinePointerInfo(),
11124 false, false, false, 0));
11126 Results.push_back(FIST);
11130 case ISD::READCYCLECOUNTER: {
11131 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11132 SDValue TheChain = N->getOperand(0);
11133 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11134 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11136 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11138 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11139 SDValue Ops[] = { eax, edx };
11140 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11141 Results.push_back(edx.getValue(1));
11144 case ISD::ATOMIC_CMP_SWAP: {
11145 EVT T = N->getValueType(0);
11146 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11147 bool Regs64bit = T == MVT::i128;
11148 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11149 SDValue cpInL, cpInH;
11150 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11151 DAG.getConstant(0, HalfT));
11152 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11153 DAG.getConstant(1, HalfT));
11154 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11155 Regs64bit ? X86::RAX : X86::EAX,
11157 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11158 Regs64bit ? X86::RDX : X86::EDX,
11159 cpInH, cpInL.getValue(1));
11160 SDValue swapInL, swapInH;
11161 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11162 DAG.getConstant(0, HalfT));
11163 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11164 DAG.getConstant(1, HalfT));
11165 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11166 Regs64bit ? X86::RBX : X86::EBX,
11167 swapInL, cpInH.getValue(1));
11168 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11169 Regs64bit ? X86::RCX : X86::ECX,
11170 swapInH, swapInL.getValue(1));
11171 SDValue Ops[] = { swapInH.getValue(0),
11173 swapInH.getValue(1) };
11174 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11175 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11176 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11177 X86ISD::LCMPXCHG8_DAG;
11178 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11180 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11181 Regs64bit ? X86::RAX : X86::EAX,
11182 HalfT, Result.getValue(1));
11183 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11184 Regs64bit ? X86::RDX : X86::EDX,
11185 HalfT, cpOutL.getValue(2));
11186 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11187 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11188 Results.push_back(cpOutH.getValue(1));
11191 case ISD::ATOMIC_LOAD_ADD:
11192 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11194 case ISD::ATOMIC_LOAD_AND:
11195 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11197 case ISD::ATOMIC_LOAD_NAND:
11198 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11200 case ISD::ATOMIC_LOAD_OR:
11201 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11203 case ISD::ATOMIC_LOAD_SUB:
11204 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11206 case ISD::ATOMIC_LOAD_XOR:
11207 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11209 case ISD::ATOMIC_SWAP:
11210 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11212 case ISD::ATOMIC_LOAD:
11213 ReplaceATOMIC_LOAD(N, Results, DAG);
11217 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11219 default: return NULL;
11220 case X86ISD::BSF: return "X86ISD::BSF";
11221 case X86ISD::BSR: return "X86ISD::BSR";
11222 case X86ISD::SHLD: return "X86ISD::SHLD";
11223 case X86ISD::SHRD: return "X86ISD::SHRD";
11224 case X86ISD::FAND: return "X86ISD::FAND";
11225 case X86ISD::FOR: return "X86ISD::FOR";
11226 case X86ISD::FXOR: return "X86ISD::FXOR";
11227 case X86ISD::FSRL: return "X86ISD::FSRL";
11228 case X86ISD::FILD: return "X86ISD::FILD";
11229 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11230 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11231 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11232 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11233 case X86ISD::FLD: return "X86ISD::FLD";
11234 case X86ISD::FST: return "X86ISD::FST";
11235 case X86ISD::CALL: return "X86ISD::CALL";
11236 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11237 case X86ISD::BT: return "X86ISD::BT";
11238 case X86ISD::CMP: return "X86ISD::CMP";
11239 case X86ISD::COMI: return "X86ISD::COMI";
11240 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11241 case X86ISD::SETCC: return "X86ISD::SETCC";
11242 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11243 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11244 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11245 case X86ISD::CMOV: return "X86ISD::CMOV";
11246 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11247 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11248 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11249 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11250 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11251 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11252 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11253 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11254 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11255 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11256 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11257 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11258 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11259 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11260 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11261 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11262 case X86ISD::BLENDPW: return "X86ISD::BLENDPW";
11263 case X86ISD::BLENDPS: return "X86ISD::BLENDPS";
11264 case X86ISD::BLENDPD: return "X86ISD::BLENDPD";
11265 case X86ISD::HADD: return "X86ISD::HADD";
11266 case X86ISD::HSUB: return "X86ISD::HSUB";
11267 case X86ISD::FHADD: return "X86ISD::FHADD";
11268 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11269 case X86ISD::FMAX: return "X86ISD::FMAX";
11270 case X86ISD::FMIN: return "X86ISD::FMIN";
11271 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11272 case X86ISD::FRCP: return "X86ISD::FRCP";
11273 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11274 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
11275 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11276 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11277 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11278 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11279 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11280 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11281 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11282 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11283 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11284 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11285 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11286 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11287 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11288 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11289 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11290 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11291 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11292 case X86ISD::VSHL: return "X86ISD::VSHL";
11293 case X86ISD::VSRL: return "X86ISD::VSRL";
11294 case X86ISD::VSRA: return "X86ISD::VSRA";
11295 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11296 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11297 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11298 case X86ISD::CMPP: return "X86ISD::CMPP";
11299 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11300 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11301 case X86ISD::ADD: return "X86ISD::ADD";
11302 case X86ISD::SUB: return "X86ISD::SUB";
11303 case X86ISD::ADC: return "X86ISD::ADC";
11304 case X86ISD::SBB: return "X86ISD::SBB";
11305 case X86ISD::SMUL: return "X86ISD::SMUL";
11306 case X86ISD::UMUL: return "X86ISD::UMUL";
11307 case X86ISD::INC: return "X86ISD::INC";
11308 case X86ISD::DEC: return "X86ISD::DEC";
11309 case X86ISD::OR: return "X86ISD::OR";
11310 case X86ISD::XOR: return "X86ISD::XOR";
11311 case X86ISD::AND: return "X86ISD::AND";
11312 case X86ISD::ANDN: return "X86ISD::ANDN";
11313 case X86ISD::BLSI: return "X86ISD::BLSI";
11314 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11315 case X86ISD::BLSR: return "X86ISD::BLSR";
11316 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11317 case X86ISD::PTEST: return "X86ISD::PTEST";
11318 case X86ISD::TESTP: return "X86ISD::TESTP";
11319 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11320 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11321 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11322 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11323 case X86ISD::SHUFP: return "X86ISD::SHUFP";
11324 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11325 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11326 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11327 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11328 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11329 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11330 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11331 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11332 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11333 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11334 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
11335 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
11336 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11337 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
11338 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
11339 case X86ISD::VPERMV: return "X86ISD::VPERMV";
11340 case X86ISD::VPERMI: return "X86ISD::VPERMI";
11341 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
11342 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11343 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11344 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11345 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11346 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11347 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
11348 case X86ISD::SAHF: return "X86ISD::SAHF";
11349 case X86ISD::RDRAND: return "X86ISD::RDRAND";
11350 case X86ISD::FMADD: return "X86ISD::FMADD";
11351 case X86ISD::FMSUB: return "X86ISD::FMSUB";
11352 case X86ISD::FNMADD: return "X86ISD::FNMADD";
11353 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
11354 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
11355 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
11359 // isLegalAddressingMode - Return true if the addressing mode represented
11360 // by AM is legal for this target, for a load/store of the specified type.
11361 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11363 // X86 supports extremely general addressing modes.
11364 CodeModel::Model M = getTargetMachine().getCodeModel();
11365 Reloc::Model R = getTargetMachine().getRelocationModel();
11367 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11368 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11373 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11375 // If a reference to this global requires an extra load, we can't fold it.
11376 if (isGlobalStubReference(GVFlags))
11379 // If BaseGV requires a register for the PIC base, we cannot also have a
11380 // BaseReg specified.
11381 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11384 // If lower 4G is not available, then we must use rip-relative addressing.
11385 if ((M != CodeModel::Small || R != Reloc::Static) &&
11386 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11390 switch (AM.Scale) {
11396 // These scales always work.
11401 // These scales are formed with basereg+scalereg. Only accept if there is
11406 default: // Other stuff never works.
11414 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11415 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11417 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11418 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11419 if (NumBits1 <= NumBits2)
11424 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11425 return Imm == (int32_t)Imm;
11428 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11429 // Can also use sub to handle negated immediates.
11430 return Imm == (int32_t)Imm;
11433 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11434 if (!VT1.isInteger() || !VT2.isInteger())
11436 unsigned NumBits1 = VT1.getSizeInBits();
11437 unsigned NumBits2 = VT2.getSizeInBits();
11438 if (NumBits1 <= NumBits2)
11443 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11444 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11445 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11448 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11449 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11450 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11453 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11454 // i16 instructions are longer (0x66 prefix) and potentially slower.
11455 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11458 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11459 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11460 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11461 /// are assumed to be legal.
11463 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11465 // Very little shuffling can be done for 64-bit vectors right now.
11466 if (VT.getSizeInBits() == 64)
11469 // FIXME: pshufb, blends, shifts.
11470 return (VT.getVectorNumElements() == 2 ||
11471 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11472 isMOVLMask(M, VT) ||
11473 isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11474 isPSHUFDMask(M, VT) ||
11475 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11476 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11477 isPALIGNRMask(M, VT, Subtarget) ||
11478 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11479 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11480 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11481 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11485 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11487 unsigned NumElts = VT.getVectorNumElements();
11488 // FIXME: This collection of masks seems suspect.
11491 if (NumElts == 4 && VT.getSizeInBits() == 128) {
11492 return (isMOVLMask(Mask, VT) ||
11493 isCommutedMOVLMask(Mask, VT, true) ||
11494 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11495 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11500 //===----------------------------------------------------------------------===//
11501 // X86 Scheduler Hooks
11502 //===----------------------------------------------------------------------===//
11504 // private utility function
11505 MachineBasicBlock *
11506 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11507 MachineBasicBlock *MBB,
11514 const TargetRegisterClass *RC,
11515 bool Invert) const {
11516 // For the atomic bitwise operator, we generate
11519 // ld t1 = [bitinstr.addr]
11520 // op t2 = t1, [bitinstr.val]
11521 // not t3 = t2 (if Invert)
11523 // lcs dest = [bitinstr.addr], t3 [EAX is implicit]
11525 // fallthrough -->nextMBB
11526 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11527 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11528 MachineFunction::iterator MBBIter = MBB;
11531 /// First build the CFG
11532 MachineFunction *F = MBB->getParent();
11533 MachineBasicBlock *thisMBB = MBB;
11534 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11535 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11536 F->insert(MBBIter, newMBB);
11537 F->insert(MBBIter, nextMBB);
11539 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11540 nextMBB->splice(nextMBB->begin(), thisMBB,
11541 llvm::next(MachineBasicBlock::iterator(bInstr)),
11543 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11545 // Update thisMBB to fall through to newMBB
11546 thisMBB->addSuccessor(newMBB);
11548 // newMBB jumps to itself and fall through to nextMBB
11549 newMBB->addSuccessor(nextMBB);
11550 newMBB->addSuccessor(newMBB);
11552 // Insert instructions into newMBB based on incoming instruction
11553 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11554 "unexpected number of operands");
11555 DebugLoc dl = bInstr->getDebugLoc();
11556 MachineOperand& destOper = bInstr->getOperand(0);
11557 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11558 int numArgs = bInstr->getNumOperands() - 1;
11559 for (int i=0; i < numArgs; ++i)
11560 argOpers[i] = &bInstr->getOperand(i+1);
11562 // x86 address has 4 operands: base, index, scale, and displacement
11563 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11564 int valArgIndx = lastAddrIndx + 1;
11566 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11567 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11568 for (int i=0; i <= lastAddrIndx; ++i)
11569 (*MIB).addOperand(*argOpers[i]);
11571 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11572 assert((argOpers[valArgIndx]->isReg() ||
11573 argOpers[valArgIndx]->isImm()) &&
11574 "invalid operand");
11575 if (argOpers[valArgIndx]->isReg())
11576 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11578 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11580 (*MIB).addOperand(*argOpers[valArgIndx]);
11582 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11584 MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11589 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11592 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11593 for (int i=0; i <= lastAddrIndx; ++i)
11594 (*MIB).addOperand(*argOpers[i]);
11596 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11597 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11598 bInstr->memoperands_end());
11600 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11601 MIB.addReg(EAXreg);
11604 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11606 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11610 // private utility function: 64 bit atomics on 32 bit host.
11611 MachineBasicBlock *
11612 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11613 MachineBasicBlock *MBB,
11618 bool Invert) const {
11619 // For the atomic bitwise operator, we generate
11620 // thisMBB (instructions are in pairs, except cmpxchg8b)
11621 // ld t1,t2 = [bitinstr.addr]
11623 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11624 // op t5, t6 <- out1, out2, [bitinstr.val]
11625 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11626 // neg t7, t8 < t5, t6 (if Invert)
11627 // mov ECX, EBX <- t5, t6
11628 // mov EAX, EDX <- t1, t2
11629 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11630 // mov t3, t4 <- EAX, EDX
11632 // result in out1, out2
11633 // fallthrough -->nextMBB
11635 const TargetRegisterClass *RC = &X86::GR32RegClass;
11636 const unsigned LoadOpc = X86::MOV32rm;
11637 const unsigned NotOpc = X86::NOT32r;
11638 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11639 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11640 MachineFunction::iterator MBBIter = MBB;
11643 /// First build the CFG
11644 MachineFunction *F = MBB->getParent();
11645 MachineBasicBlock *thisMBB = MBB;
11646 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11647 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11648 F->insert(MBBIter, newMBB);
11649 F->insert(MBBIter, nextMBB);
11651 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11652 nextMBB->splice(nextMBB->begin(), thisMBB,
11653 llvm::next(MachineBasicBlock::iterator(bInstr)),
11655 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11657 // Update thisMBB to fall through to newMBB
11658 thisMBB->addSuccessor(newMBB);
11660 // newMBB jumps to itself and fall through to nextMBB
11661 newMBB->addSuccessor(nextMBB);
11662 newMBB->addSuccessor(newMBB);
11664 DebugLoc dl = bInstr->getDebugLoc();
11665 // Insert instructions into newMBB based on incoming instruction
11666 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11667 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11668 "unexpected number of operands");
11669 MachineOperand& dest1Oper = bInstr->getOperand(0);
11670 MachineOperand& dest2Oper = bInstr->getOperand(1);
11671 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11672 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11673 argOpers[i] = &bInstr->getOperand(i+2);
11675 // We use some of the operands multiple times, so conservatively just
11676 // clear any kill flags that might be present.
11677 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11678 argOpers[i]->setIsKill(false);
11681 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11682 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11684 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11685 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11686 for (int i=0; i <= lastAddrIndx; ++i)
11687 (*MIB).addOperand(*argOpers[i]);
11688 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11689 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11690 // add 4 to displacement.
11691 for (int i=0; i <= lastAddrIndx-2; ++i)
11692 (*MIB).addOperand(*argOpers[i]);
11693 MachineOperand newOp3 = *(argOpers[3]);
11694 if (newOp3.isImm())
11695 newOp3.setImm(newOp3.getImm()+4);
11697 newOp3.setOffset(newOp3.getOffset()+4);
11698 (*MIB).addOperand(newOp3);
11699 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11701 // t3/4 are defined later, at the bottom of the loop
11702 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11703 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11704 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11705 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11706 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11707 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11709 // The subsequent operations should be using the destination registers of
11710 // the PHI instructions.
11711 t1 = dest1Oper.getReg();
11712 t2 = dest2Oper.getReg();
11714 int valArgIndx = lastAddrIndx + 1;
11715 assert((argOpers[valArgIndx]->isReg() ||
11716 argOpers[valArgIndx]->isImm()) &&
11717 "invalid operand");
11718 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11719 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11720 if (argOpers[valArgIndx]->isReg())
11721 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11723 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11724 if (regOpcL != X86::MOV32rr)
11726 (*MIB).addOperand(*argOpers[valArgIndx]);
11727 assert(argOpers[valArgIndx + 1]->isReg() ==
11728 argOpers[valArgIndx]->isReg());
11729 assert(argOpers[valArgIndx + 1]->isImm() ==
11730 argOpers[valArgIndx]->isImm());
11731 if (argOpers[valArgIndx + 1]->isReg())
11732 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11734 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11735 if (regOpcH != X86::MOV32rr)
11737 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11741 t7 = F->getRegInfo().createVirtualRegister(RC);
11742 t8 = F->getRegInfo().createVirtualRegister(RC);
11743 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11744 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11750 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11752 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11755 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11757 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11760 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11761 for (int i=0; i <= lastAddrIndx; ++i)
11762 (*MIB).addOperand(*argOpers[i]);
11764 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11765 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11766 bInstr->memoperands_end());
11768 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11769 MIB.addReg(X86::EAX);
11770 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11771 MIB.addReg(X86::EDX);
11774 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11776 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11780 // private utility function
11781 MachineBasicBlock *
11782 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11783 MachineBasicBlock *MBB,
11784 unsigned cmovOpc) const {
11785 // For the atomic min/max operator, we generate
11788 // ld t1 = [min/max.addr]
11789 // mov t2 = [min/max.val]
11791 // cmov[cond] t2 = t1
11793 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11795 // fallthrough -->nextMBB
11797 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11798 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11799 MachineFunction::iterator MBBIter = MBB;
11802 /// First build the CFG
11803 MachineFunction *F = MBB->getParent();
11804 MachineBasicBlock *thisMBB = MBB;
11805 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11806 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11807 F->insert(MBBIter, newMBB);
11808 F->insert(MBBIter, nextMBB);
11810 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11811 nextMBB->splice(nextMBB->begin(), thisMBB,
11812 llvm::next(MachineBasicBlock::iterator(mInstr)),
11814 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11816 // Update thisMBB to fall through to newMBB
11817 thisMBB->addSuccessor(newMBB);
11819 // newMBB jumps to newMBB and fall through to nextMBB
11820 newMBB->addSuccessor(nextMBB);
11821 newMBB->addSuccessor(newMBB);
11823 DebugLoc dl = mInstr->getDebugLoc();
11824 // Insert instructions into newMBB based on incoming instruction
11825 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11826 "unexpected number of operands");
11827 MachineOperand& destOper = mInstr->getOperand(0);
11828 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11829 int numArgs = mInstr->getNumOperands() - 1;
11830 for (int i=0; i < numArgs; ++i)
11831 argOpers[i] = &mInstr->getOperand(i+1);
11833 // x86 address has 4 operands: base, index, scale, and displacement
11834 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11835 int valArgIndx = lastAddrIndx + 1;
11837 unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11838 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11839 for (int i=0; i <= lastAddrIndx; ++i)
11840 (*MIB).addOperand(*argOpers[i]);
11842 // We only support register and immediate values
11843 assert((argOpers[valArgIndx]->isReg() ||
11844 argOpers[valArgIndx]->isImm()) &&
11845 "invalid operand");
11847 unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11848 if (argOpers[valArgIndx]->isReg())
11849 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11851 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11852 (*MIB).addOperand(*argOpers[valArgIndx]);
11854 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11857 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11862 unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11863 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11867 // Cmp and exchange if none has modified the memory location
11868 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11869 for (int i=0; i <= lastAddrIndx; ++i)
11870 (*MIB).addOperand(*argOpers[i]);
11872 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11873 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11874 mInstr->memoperands_end());
11876 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11877 MIB.addReg(X86::EAX);
11880 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11882 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11886 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11887 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11888 // in the .td file.
11889 MachineBasicBlock *
11890 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11891 unsigned numArgs, bool memArg) const {
11892 assert(Subtarget->hasSSE42() &&
11893 "Target must have SSE4.2 or AVX features enabled");
11895 DebugLoc dl = MI->getDebugLoc();
11896 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11898 if (!Subtarget->hasAVX()) {
11900 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11902 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11905 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11907 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11910 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11911 for (unsigned i = 0; i < numArgs; ++i) {
11912 MachineOperand &Op = MI->getOperand(i+1);
11913 if (!(Op.isReg() && Op.isImplicit()))
11914 MIB.addOperand(Op);
11916 BuildMI(*BB, MI, dl,
11917 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
11918 .addReg(X86::XMM0);
11920 MI->eraseFromParent();
11924 MachineBasicBlock *
11925 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11926 DebugLoc dl = MI->getDebugLoc();
11927 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11929 // Address into RAX/EAX, other two args into ECX, EDX.
11930 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11931 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11932 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11933 for (int i = 0; i < X86::AddrNumOperands; ++i)
11934 MIB.addOperand(MI->getOperand(i));
11936 unsigned ValOps = X86::AddrNumOperands;
11937 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11938 .addReg(MI->getOperand(ValOps).getReg());
11939 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11940 .addReg(MI->getOperand(ValOps+1).getReg());
11942 // The instruction doesn't actually take any operands though.
11943 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11945 MI->eraseFromParent(); // The pseudo is gone now.
11949 MachineBasicBlock *
11950 X86TargetLowering::EmitVAARG64WithCustomInserter(
11952 MachineBasicBlock *MBB) const {
11953 // Emit va_arg instruction on X86-64.
11955 // Operands to this pseudo-instruction:
11956 // 0 ) Output : destination address (reg)
11957 // 1-5) Input : va_list address (addr, i64mem)
11958 // 6 ) ArgSize : Size (in bytes) of vararg type
11959 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11960 // 8 ) Align : Alignment of type
11961 // 9 ) EFLAGS (implicit-def)
11963 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11964 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11966 unsigned DestReg = MI->getOperand(0).getReg();
11967 MachineOperand &Base = MI->getOperand(1);
11968 MachineOperand &Scale = MI->getOperand(2);
11969 MachineOperand &Index = MI->getOperand(3);
11970 MachineOperand &Disp = MI->getOperand(4);
11971 MachineOperand &Segment = MI->getOperand(5);
11972 unsigned ArgSize = MI->getOperand(6).getImm();
11973 unsigned ArgMode = MI->getOperand(7).getImm();
11974 unsigned Align = MI->getOperand(8).getImm();
11976 // Memory Reference
11977 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11978 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11979 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11981 // Machine Information
11982 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11983 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11984 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11985 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11986 DebugLoc DL = MI->getDebugLoc();
11988 // struct va_list {
11991 // i64 overflow_area (address)
11992 // i64 reg_save_area (address)
11994 // sizeof(va_list) = 24
11995 // alignment(va_list) = 8
11997 unsigned TotalNumIntRegs = 6;
11998 unsigned TotalNumXMMRegs = 8;
11999 bool UseGPOffset = (ArgMode == 1);
12000 bool UseFPOffset = (ArgMode == 2);
12001 unsigned MaxOffset = TotalNumIntRegs * 8 +
12002 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12004 /* Align ArgSize to a multiple of 8 */
12005 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12006 bool NeedsAlign = (Align > 8);
12008 MachineBasicBlock *thisMBB = MBB;
12009 MachineBasicBlock *overflowMBB;
12010 MachineBasicBlock *offsetMBB;
12011 MachineBasicBlock *endMBB;
12013 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
12014 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
12015 unsigned OffsetReg = 0;
12017 if (!UseGPOffset && !UseFPOffset) {
12018 // If we only pull from the overflow region, we don't create a branch.
12019 // We don't need to alter control flow.
12020 OffsetDestReg = 0; // unused
12021 OverflowDestReg = DestReg;
12024 overflowMBB = thisMBB;
12027 // First emit code to check if gp_offset (or fp_offset) is below the bound.
12028 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12029 // If not, pull from overflow_area. (branch to overflowMBB)
12034 // offsetMBB overflowMBB
12039 // Registers for the PHI in endMBB
12040 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12041 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12043 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12044 MachineFunction *MF = MBB->getParent();
12045 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12046 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12047 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12049 MachineFunction::iterator MBBIter = MBB;
12052 // Insert the new basic blocks
12053 MF->insert(MBBIter, offsetMBB);
12054 MF->insert(MBBIter, overflowMBB);
12055 MF->insert(MBBIter, endMBB);
12057 // Transfer the remainder of MBB and its successor edges to endMBB.
12058 endMBB->splice(endMBB->begin(), thisMBB,
12059 llvm::next(MachineBasicBlock::iterator(MI)),
12061 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12063 // Make offsetMBB and overflowMBB successors of thisMBB
12064 thisMBB->addSuccessor(offsetMBB);
12065 thisMBB->addSuccessor(overflowMBB);
12067 // endMBB is a successor of both offsetMBB and overflowMBB
12068 offsetMBB->addSuccessor(endMBB);
12069 overflowMBB->addSuccessor(endMBB);
12071 // Load the offset value into a register
12072 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12073 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12077 .addDisp(Disp, UseFPOffset ? 4 : 0)
12078 .addOperand(Segment)
12079 .setMemRefs(MMOBegin, MMOEnd);
12081 // Check if there is enough room left to pull this argument.
12082 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12084 .addImm(MaxOffset + 8 - ArgSizeA8);
12086 // Branch to "overflowMBB" if offset >= max
12087 // Fall through to "offsetMBB" otherwise
12088 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12089 .addMBB(overflowMBB);
12092 // In offsetMBB, emit code to use the reg_save_area.
12094 assert(OffsetReg != 0);
12096 // Read the reg_save_area address.
12097 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12098 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12103 .addOperand(Segment)
12104 .setMemRefs(MMOBegin, MMOEnd);
12106 // Zero-extend the offset
12107 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12108 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12111 .addImm(X86::sub_32bit);
12113 // Add the offset to the reg_save_area to get the final address.
12114 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12115 .addReg(OffsetReg64)
12116 .addReg(RegSaveReg);
12118 // Compute the offset for the next argument
12119 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12120 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12122 .addImm(UseFPOffset ? 16 : 8);
12124 // Store it back into the va_list.
12125 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12129 .addDisp(Disp, UseFPOffset ? 4 : 0)
12130 .addOperand(Segment)
12131 .addReg(NextOffsetReg)
12132 .setMemRefs(MMOBegin, MMOEnd);
12135 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12140 // Emit code to use overflow area
12143 // Load the overflow_area address into a register.
12144 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12145 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12150 .addOperand(Segment)
12151 .setMemRefs(MMOBegin, MMOEnd);
12153 // If we need to align it, do so. Otherwise, just copy the address
12154 // to OverflowDestReg.
12156 // Align the overflow address
12157 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12158 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12160 // aligned_addr = (addr + (align-1)) & ~(align-1)
12161 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12162 .addReg(OverflowAddrReg)
12165 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12167 .addImm(~(uint64_t)(Align-1));
12169 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12170 .addReg(OverflowAddrReg);
12173 // Compute the next overflow address after this argument.
12174 // (the overflow address should be kept 8-byte aligned)
12175 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12176 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12177 .addReg(OverflowDestReg)
12178 .addImm(ArgSizeA8);
12180 // Store the new overflow address.
12181 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12186 .addOperand(Segment)
12187 .addReg(NextAddrReg)
12188 .setMemRefs(MMOBegin, MMOEnd);
12190 // If we branched, emit the PHI to the front of endMBB.
12192 BuildMI(*endMBB, endMBB->begin(), DL,
12193 TII->get(X86::PHI), DestReg)
12194 .addReg(OffsetDestReg).addMBB(offsetMBB)
12195 .addReg(OverflowDestReg).addMBB(overflowMBB);
12198 // Erase the pseudo instruction
12199 MI->eraseFromParent();
12204 MachineBasicBlock *
12205 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12207 MachineBasicBlock *MBB) const {
12208 // Emit code to save XMM registers to the stack. The ABI says that the
12209 // number of registers to save is given in %al, so it's theoretically
12210 // possible to do an indirect jump trick to avoid saving all of them,
12211 // however this code takes a simpler approach and just executes all
12212 // of the stores if %al is non-zero. It's less code, and it's probably
12213 // easier on the hardware branch predictor, and stores aren't all that
12214 // expensive anyway.
12216 // Create the new basic blocks. One block contains all the XMM stores,
12217 // and one block is the final destination regardless of whether any
12218 // stores were performed.
12219 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12220 MachineFunction *F = MBB->getParent();
12221 MachineFunction::iterator MBBIter = MBB;
12223 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12224 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12225 F->insert(MBBIter, XMMSaveMBB);
12226 F->insert(MBBIter, EndMBB);
12228 // Transfer the remainder of MBB and its successor edges to EndMBB.
12229 EndMBB->splice(EndMBB->begin(), MBB,
12230 llvm::next(MachineBasicBlock::iterator(MI)),
12232 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12234 // The original block will now fall through to the XMM save block.
12235 MBB->addSuccessor(XMMSaveMBB);
12236 // The XMMSaveMBB will fall through to the end block.
12237 XMMSaveMBB->addSuccessor(EndMBB);
12239 // Now add the instructions.
12240 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12241 DebugLoc DL = MI->getDebugLoc();
12243 unsigned CountReg = MI->getOperand(0).getReg();
12244 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12245 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12247 if (!Subtarget->isTargetWin64()) {
12248 // If %al is 0, branch around the XMM save block.
12249 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12250 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12251 MBB->addSuccessor(EndMBB);
12254 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12255 // In the XMM save block, save all the XMM argument registers.
12256 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12257 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12258 MachineMemOperand *MMO =
12259 F->getMachineMemOperand(
12260 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12261 MachineMemOperand::MOStore,
12262 /*Size=*/16, /*Align=*/16);
12263 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12264 .addFrameIndex(RegSaveFrameIndex)
12265 .addImm(/*Scale=*/1)
12266 .addReg(/*IndexReg=*/0)
12267 .addImm(/*Disp=*/Offset)
12268 .addReg(/*Segment=*/0)
12269 .addReg(MI->getOperand(i).getReg())
12270 .addMemOperand(MMO);
12273 MI->eraseFromParent(); // The pseudo instruction is gone now.
12278 // The EFLAGS operand of SelectItr might be missing a kill marker
12279 // because there were multiple uses of EFLAGS, and ISel didn't know
12280 // which to mark. Figure out whether SelectItr should have had a
12281 // kill marker, and set it if it should. Returns the correct kill
12283 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12284 MachineBasicBlock* BB,
12285 const TargetRegisterInfo* TRI) {
12286 // Scan forward through BB for a use/def of EFLAGS.
12287 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12288 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12289 const MachineInstr& mi = *miI;
12290 if (mi.readsRegister(X86::EFLAGS))
12292 if (mi.definesRegister(X86::EFLAGS))
12293 break; // Should have kill-flag - update below.
12296 // If we hit the end of the block, check whether EFLAGS is live into a
12298 if (miI == BB->end()) {
12299 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12300 sEnd = BB->succ_end();
12301 sItr != sEnd; ++sItr) {
12302 MachineBasicBlock* succ = *sItr;
12303 if (succ->isLiveIn(X86::EFLAGS))
12308 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12309 // out. SelectMI should have a kill flag on EFLAGS.
12310 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12314 MachineBasicBlock *
12315 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12316 MachineBasicBlock *BB) const {
12317 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12318 DebugLoc DL = MI->getDebugLoc();
12320 // To "insert" a SELECT_CC instruction, we actually have to insert the
12321 // diamond control-flow pattern. The incoming instruction knows the
12322 // destination vreg to set, the condition code register to branch on, the
12323 // true/false values to select between, and a branch opcode to use.
12324 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12325 MachineFunction::iterator It = BB;
12331 // cmpTY ccX, r1, r2
12333 // fallthrough --> copy0MBB
12334 MachineBasicBlock *thisMBB = BB;
12335 MachineFunction *F = BB->getParent();
12336 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12337 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12338 F->insert(It, copy0MBB);
12339 F->insert(It, sinkMBB);
12341 // If the EFLAGS register isn't dead in the terminator, then claim that it's
12342 // live into the sink and copy blocks.
12343 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12344 if (!MI->killsRegister(X86::EFLAGS) &&
12345 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12346 copy0MBB->addLiveIn(X86::EFLAGS);
12347 sinkMBB->addLiveIn(X86::EFLAGS);
12350 // Transfer the remainder of BB and its successor edges to sinkMBB.
12351 sinkMBB->splice(sinkMBB->begin(), BB,
12352 llvm::next(MachineBasicBlock::iterator(MI)),
12354 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12356 // Add the true and fallthrough blocks as its successors.
12357 BB->addSuccessor(copy0MBB);
12358 BB->addSuccessor(sinkMBB);
12360 // Create the conditional branch instruction.
12362 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12363 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12366 // %FalseValue = ...
12367 // # fallthrough to sinkMBB
12368 copy0MBB->addSuccessor(sinkMBB);
12371 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12373 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12374 TII->get(X86::PHI), MI->getOperand(0).getReg())
12375 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12376 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12378 MI->eraseFromParent(); // The pseudo instruction is gone now.
12382 MachineBasicBlock *
12383 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12384 bool Is64Bit) const {
12385 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12386 DebugLoc DL = MI->getDebugLoc();
12387 MachineFunction *MF = BB->getParent();
12388 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12390 assert(getTargetMachine().Options.EnableSegmentedStacks);
12392 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12393 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12396 // ... [Till the alloca]
12397 // If stacklet is not large enough, jump to mallocMBB
12400 // Allocate by subtracting from RSP
12401 // Jump to continueMBB
12404 // Allocate by call to runtime
12408 // [rest of original BB]
12411 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12412 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12413 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12415 MachineRegisterInfo &MRI = MF->getRegInfo();
12416 const TargetRegisterClass *AddrRegClass =
12417 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12419 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12420 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12421 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12422 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12423 sizeVReg = MI->getOperand(1).getReg(),
12424 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12426 MachineFunction::iterator MBBIter = BB;
12429 MF->insert(MBBIter, bumpMBB);
12430 MF->insert(MBBIter, mallocMBB);
12431 MF->insert(MBBIter, continueMBB);
12433 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12434 (MachineBasicBlock::iterator(MI)), BB->end());
12435 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12437 // Add code to the main basic block to check if the stack limit has been hit,
12438 // and if so, jump to mallocMBB otherwise to bumpMBB.
12439 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12440 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12441 .addReg(tmpSPVReg).addReg(sizeVReg);
12442 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12443 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12444 .addReg(SPLimitVReg);
12445 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12447 // bumpMBB simply decreases the stack pointer, since we know the current
12448 // stacklet has enough space.
12449 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12450 .addReg(SPLimitVReg);
12451 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12452 .addReg(SPLimitVReg);
12453 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12455 // Calls into a routine in libgcc to allocate more space from the heap.
12456 const uint32_t *RegMask =
12457 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12459 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12461 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12462 .addExternalSymbol("__morestack_allocate_stack_space")
12463 .addRegMask(RegMask)
12464 .addReg(X86::RDI, RegState::Implicit)
12465 .addReg(X86::RAX, RegState::ImplicitDefine);
12467 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12469 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12470 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12471 .addExternalSymbol("__morestack_allocate_stack_space")
12472 .addRegMask(RegMask)
12473 .addReg(X86::EAX, RegState::ImplicitDefine);
12477 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12480 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12481 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12482 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12484 // Set up the CFG correctly.
12485 BB->addSuccessor(bumpMBB);
12486 BB->addSuccessor(mallocMBB);
12487 mallocMBB->addSuccessor(continueMBB);
12488 bumpMBB->addSuccessor(continueMBB);
12490 // Take care of the PHI nodes.
12491 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12492 MI->getOperand(0).getReg())
12493 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12494 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12496 // Delete the original pseudo instruction.
12497 MI->eraseFromParent();
12500 return continueMBB;
12503 MachineBasicBlock *
12504 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12505 MachineBasicBlock *BB) const {
12506 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12507 DebugLoc DL = MI->getDebugLoc();
12509 assert(!Subtarget->isTargetEnvMacho());
12511 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12512 // non-trivial part is impdef of ESP.
12514 if (Subtarget->isTargetWin64()) {
12515 if (Subtarget->isTargetCygMing()) {
12516 // ___chkstk(Mingw64):
12517 // Clobbers R10, R11, RAX and EFLAGS.
12519 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12520 .addExternalSymbol("___chkstk")
12521 .addReg(X86::RAX, RegState::Implicit)
12522 .addReg(X86::RSP, RegState::Implicit)
12523 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12524 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12525 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12527 // __chkstk(MSVCRT): does not update stack pointer.
12528 // Clobbers R10, R11 and EFLAGS.
12529 // FIXME: RAX(allocated size) might be reused and not killed.
12530 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12531 .addExternalSymbol("__chkstk")
12532 .addReg(X86::RAX, RegState::Implicit)
12533 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12534 // RAX has the offset to subtracted from RSP.
12535 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12540 const char *StackProbeSymbol =
12541 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12543 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12544 .addExternalSymbol(StackProbeSymbol)
12545 .addReg(X86::EAX, RegState::Implicit)
12546 .addReg(X86::ESP, RegState::Implicit)
12547 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12548 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12549 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12552 MI->eraseFromParent(); // The pseudo instruction is gone now.
12556 MachineBasicBlock *
12557 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12558 MachineBasicBlock *BB) const {
12559 // This is pretty easy. We're taking the value that we received from
12560 // our load from the relocation, sticking it in either RDI (x86-64)
12561 // or EAX and doing an indirect call. The return value will then
12562 // be in the normal return register.
12563 const X86InstrInfo *TII
12564 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12565 DebugLoc DL = MI->getDebugLoc();
12566 MachineFunction *F = BB->getParent();
12568 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12569 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12571 // Get a register mask for the lowered call.
12572 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12573 // proper register mask.
12574 const uint32_t *RegMask =
12575 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12576 if (Subtarget->is64Bit()) {
12577 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12578 TII->get(X86::MOV64rm), X86::RDI)
12580 .addImm(0).addReg(0)
12581 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12582 MI->getOperand(3).getTargetFlags())
12584 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12585 addDirectMem(MIB, X86::RDI);
12586 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12587 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12588 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12589 TII->get(X86::MOV32rm), X86::EAX)
12591 .addImm(0).addReg(0)
12592 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12593 MI->getOperand(3).getTargetFlags())
12595 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12596 addDirectMem(MIB, X86::EAX);
12597 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12599 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12600 TII->get(X86::MOV32rm), X86::EAX)
12601 .addReg(TII->getGlobalBaseReg(F))
12602 .addImm(0).addReg(0)
12603 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12604 MI->getOperand(3).getTargetFlags())
12606 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12607 addDirectMem(MIB, X86::EAX);
12608 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12611 MI->eraseFromParent(); // The pseudo instruction is gone now.
12615 MachineBasicBlock *
12616 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12617 MachineBasicBlock *BB) const {
12618 switch (MI->getOpcode()) {
12619 default: llvm_unreachable("Unexpected instr type to insert");
12620 case X86::TAILJMPd64:
12621 case X86::TAILJMPr64:
12622 case X86::TAILJMPm64:
12623 llvm_unreachable("TAILJMP64 would not be touched here.");
12624 case X86::TCRETURNdi64:
12625 case X86::TCRETURNri64:
12626 case X86::TCRETURNmi64:
12628 case X86::WIN_ALLOCA:
12629 return EmitLoweredWinAlloca(MI, BB);
12630 case X86::SEG_ALLOCA_32:
12631 return EmitLoweredSegAlloca(MI, BB, false);
12632 case X86::SEG_ALLOCA_64:
12633 return EmitLoweredSegAlloca(MI, BB, true);
12634 case X86::TLSCall_32:
12635 case X86::TLSCall_64:
12636 return EmitLoweredTLSCall(MI, BB);
12637 case X86::CMOV_GR8:
12638 case X86::CMOV_FR32:
12639 case X86::CMOV_FR64:
12640 case X86::CMOV_V4F32:
12641 case X86::CMOV_V2F64:
12642 case X86::CMOV_V2I64:
12643 case X86::CMOV_V8F32:
12644 case X86::CMOV_V4F64:
12645 case X86::CMOV_V4I64:
12646 case X86::CMOV_GR16:
12647 case X86::CMOV_GR32:
12648 case X86::CMOV_RFP32:
12649 case X86::CMOV_RFP64:
12650 case X86::CMOV_RFP80:
12651 return EmitLoweredSelect(MI, BB);
12653 case X86::FP32_TO_INT16_IN_MEM:
12654 case X86::FP32_TO_INT32_IN_MEM:
12655 case X86::FP32_TO_INT64_IN_MEM:
12656 case X86::FP64_TO_INT16_IN_MEM:
12657 case X86::FP64_TO_INT32_IN_MEM:
12658 case X86::FP64_TO_INT64_IN_MEM:
12659 case X86::FP80_TO_INT16_IN_MEM:
12660 case X86::FP80_TO_INT32_IN_MEM:
12661 case X86::FP80_TO_INT64_IN_MEM: {
12662 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12663 DebugLoc DL = MI->getDebugLoc();
12665 // Change the floating point control register to use "round towards zero"
12666 // mode when truncating to an integer value.
12667 MachineFunction *F = BB->getParent();
12668 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12669 addFrameReference(BuildMI(*BB, MI, DL,
12670 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12672 // Load the old value of the high byte of the control word...
12674 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12675 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12678 // Set the high part to be round to zero...
12679 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12682 // Reload the modified control word now...
12683 addFrameReference(BuildMI(*BB, MI, DL,
12684 TII->get(X86::FLDCW16m)), CWFrameIdx);
12686 // Restore the memory image of control word to original value
12687 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12690 // Get the X86 opcode to use.
12692 switch (MI->getOpcode()) {
12693 default: llvm_unreachable("illegal opcode!");
12694 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12695 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12696 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12697 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12698 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12699 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12700 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12701 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12702 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12706 MachineOperand &Op = MI->getOperand(0);
12708 AM.BaseType = X86AddressMode::RegBase;
12709 AM.Base.Reg = Op.getReg();
12711 AM.BaseType = X86AddressMode::FrameIndexBase;
12712 AM.Base.FrameIndex = Op.getIndex();
12714 Op = MI->getOperand(1);
12716 AM.Scale = Op.getImm();
12717 Op = MI->getOperand(2);
12719 AM.IndexReg = Op.getImm();
12720 Op = MI->getOperand(3);
12721 if (Op.isGlobal()) {
12722 AM.GV = Op.getGlobal();
12724 AM.Disp = Op.getImm();
12726 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12727 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12729 // Reload the original control word now.
12730 addFrameReference(BuildMI(*BB, MI, DL,
12731 TII->get(X86::FLDCW16m)), CWFrameIdx);
12733 MI->eraseFromParent(); // The pseudo instruction is gone now.
12736 // String/text processing lowering.
12737 case X86::PCMPISTRM128REG:
12738 case X86::VPCMPISTRM128REG:
12739 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12740 case X86::PCMPISTRM128MEM:
12741 case X86::VPCMPISTRM128MEM:
12742 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12743 case X86::PCMPESTRM128REG:
12744 case X86::VPCMPESTRM128REG:
12745 return EmitPCMP(MI, BB, 5, false /* in mem */);
12746 case X86::PCMPESTRM128MEM:
12747 case X86::VPCMPESTRM128MEM:
12748 return EmitPCMP(MI, BB, 5, true /* in mem */);
12750 // Thread synchronization.
12752 return EmitMonitor(MI, BB);
12754 // Atomic Lowering.
12755 case X86::ATOMAND32:
12756 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12757 X86::AND32ri, X86::MOV32rm,
12759 X86::NOT32r, X86::EAX,
12760 &X86::GR32RegClass);
12761 case X86::ATOMOR32:
12762 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12763 X86::OR32ri, X86::MOV32rm,
12765 X86::NOT32r, X86::EAX,
12766 &X86::GR32RegClass);
12767 case X86::ATOMXOR32:
12768 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12769 X86::XOR32ri, X86::MOV32rm,
12771 X86::NOT32r, X86::EAX,
12772 &X86::GR32RegClass);
12773 case X86::ATOMNAND32:
12774 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12775 X86::AND32ri, X86::MOV32rm,
12777 X86::NOT32r, X86::EAX,
12778 &X86::GR32RegClass, true);
12779 case X86::ATOMMIN32:
12780 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12781 case X86::ATOMMAX32:
12782 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12783 case X86::ATOMUMIN32:
12784 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12785 case X86::ATOMUMAX32:
12786 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12788 case X86::ATOMAND16:
12789 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12790 X86::AND16ri, X86::MOV16rm,
12792 X86::NOT16r, X86::AX,
12793 &X86::GR16RegClass);
12794 case X86::ATOMOR16:
12795 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12796 X86::OR16ri, X86::MOV16rm,
12798 X86::NOT16r, X86::AX,
12799 &X86::GR16RegClass);
12800 case X86::ATOMXOR16:
12801 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12802 X86::XOR16ri, X86::MOV16rm,
12804 X86::NOT16r, X86::AX,
12805 &X86::GR16RegClass);
12806 case X86::ATOMNAND16:
12807 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12808 X86::AND16ri, X86::MOV16rm,
12810 X86::NOT16r, X86::AX,
12811 &X86::GR16RegClass, true);
12812 case X86::ATOMMIN16:
12813 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12814 case X86::ATOMMAX16:
12815 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12816 case X86::ATOMUMIN16:
12817 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12818 case X86::ATOMUMAX16:
12819 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12821 case X86::ATOMAND8:
12822 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12823 X86::AND8ri, X86::MOV8rm,
12825 X86::NOT8r, X86::AL,
12826 &X86::GR8RegClass);
12828 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12829 X86::OR8ri, X86::MOV8rm,
12831 X86::NOT8r, X86::AL,
12832 &X86::GR8RegClass);
12833 case X86::ATOMXOR8:
12834 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12835 X86::XOR8ri, X86::MOV8rm,
12837 X86::NOT8r, X86::AL,
12838 &X86::GR8RegClass);
12839 case X86::ATOMNAND8:
12840 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12841 X86::AND8ri, X86::MOV8rm,
12843 X86::NOT8r, X86::AL,
12844 &X86::GR8RegClass, true);
12845 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12846 // This group is for 64-bit host.
12847 case X86::ATOMAND64:
12848 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12849 X86::AND64ri32, X86::MOV64rm,
12851 X86::NOT64r, X86::RAX,
12852 &X86::GR64RegClass);
12853 case X86::ATOMOR64:
12854 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12855 X86::OR64ri32, X86::MOV64rm,
12857 X86::NOT64r, X86::RAX,
12858 &X86::GR64RegClass);
12859 case X86::ATOMXOR64:
12860 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12861 X86::XOR64ri32, X86::MOV64rm,
12863 X86::NOT64r, X86::RAX,
12864 &X86::GR64RegClass);
12865 case X86::ATOMNAND64:
12866 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12867 X86::AND64ri32, X86::MOV64rm,
12869 X86::NOT64r, X86::RAX,
12870 &X86::GR64RegClass, true);
12871 case X86::ATOMMIN64:
12872 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12873 case X86::ATOMMAX64:
12874 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12875 case X86::ATOMUMIN64:
12876 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12877 case X86::ATOMUMAX64:
12878 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12880 // This group does 64-bit operations on a 32-bit host.
12881 case X86::ATOMAND6432:
12882 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12883 X86::AND32rr, X86::AND32rr,
12884 X86::AND32ri, X86::AND32ri,
12886 case X86::ATOMOR6432:
12887 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12888 X86::OR32rr, X86::OR32rr,
12889 X86::OR32ri, X86::OR32ri,
12891 case X86::ATOMXOR6432:
12892 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12893 X86::XOR32rr, X86::XOR32rr,
12894 X86::XOR32ri, X86::XOR32ri,
12896 case X86::ATOMNAND6432:
12897 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12898 X86::AND32rr, X86::AND32rr,
12899 X86::AND32ri, X86::AND32ri,
12901 case X86::ATOMADD6432:
12902 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12903 X86::ADD32rr, X86::ADC32rr,
12904 X86::ADD32ri, X86::ADC32ri,
12906 case X86::ATOMSUB6432:
12907 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12908 X86::SUB32rr, X86::SBB32rr,
12909 X86::SUB32ri, X86::SBB32ri,
12911 case X86::ATOMSWAP6432:
12912 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12913 X86::MOV32rr, X86::MOV32rr,
12914 X86::MOV32ri, X86::MOV32ri,
12916 case X86::VASTART_SAVE_XMM_REGS:
12917 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12919 case X86::VAARG_64:
12920 return EmitVAARG64WithCustomInserter(MI, BB);
12924 //===----------------------------------------------------------------------===//
12925 // X86 Optimization Hooks
12926 //===----------------------------------------------------------------------===//
12928 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12931 const SelectionDAG &DAG,
12932 unsigned Depth) const {
12933 unsigned BitWidth = KnownZero.getBitWidth();
12934 unsigned Opc = Op.getOpcode();
12935 assert((Opc >= ISD::BUILTIN_OP_END ||
12936 Opc == ISD::INTRINSIC_WO_CHAIN ||
12937 Opc == ISD::INTRINSIC_W_CHAIN ||
12938 Opc == ISD::INTRINSIC_VOID) &&
12939 "Should use MaskedValueIsZero if you don't know whether Op"
12940 " is a target node!");
12942 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
12956 // These nodes' second result is a boolean.
12957 if (Op.getResNo() == 0)
12960 case X86ISD::SETCC:
12961 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12963 case ISD::INTRINSIC_WO_CHAIN: {
12964 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12965 unsigned NumLoBits = 0;
12968 case Intrinsic::x86_sse_movmsk_ps:
12969 case Intrinsic::x86_avx_movmsk_ps_256:
12970 case Intrinsic::x86_sse2_movmsk_pd:
12971 case Intrinsic::x86_avx_movmsk_pd_256:
12972 case Intrinsic::x86_mmx_pmovmskb:
12973 case Intrinsic::x86_sse2_pmovmskb_128:
12974 case Intrinsic::x86_avx2_pmovmskb: {
12975 // High bits of movmskp{s|d}, pmovmskb are known zero.
12977 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12978 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
12979 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
12980 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
12981 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
12982 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
12983 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
12984 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
12986 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
12995 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12996 unsigned Depth) const {
12997 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12998 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12999 return Op.getValueType().getScalarType().getSizeInBits();
13005 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13006 /// node is a GlobalAddress + offset.
13007 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13008 const GlobalValue* &GA,
13009 int64_t &Offset) const {
13010 if (N->getOpcode() == X86ISD::Wrapper) {
13011 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13012 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13013 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13017 return TargetLowering::isGAPlusOffset(N, GA, Offset);
13020 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13021 /// same as extracting the high 128-bit part of 256-bit vector and then
13022 /// inserting the result into the low part of a new 256-bit vector
13023 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13024 EVT VT = SVOp->getValueType(0);
13025 unsigned NumElems = VT.getVectorNumElements();
13027 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13028 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13029 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13030 SVOp->getMaskElt(j) >= 0)
13036 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13037 /// same as extracting the low 128-bit part of 256-bit vector and then
13038 /// inserting the result into the high part of a new 256-bit vector
13039 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13040 EVT VT = SVOp->getValueType(0);
13041 unsigned NumElems = VT.getVectorNumElements();
13043 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13044 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13045 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13046 SVOp->getMaskElt(j) >= 0)
13052 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13053 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13054 TargetLowering::DAGCombinerInfo &DCI,
13055 const X86Subtarget* Subtarget) {
13056 DebugLoc dl = N->getDebugLoc();
13057 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13058 SDValue V1 = SVOp->getOperand(0);
13059 SDValue V2 = SVOp->getOperand(1);
13060 EVT VT = SVOp->getValueType(0);
13061 unsigned NumElems = VT.getVectorNumElements();
13063 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13064 V2.getOpcode() == ISD::CONCAT_VECTORS) {
13068 // V UNDEF BUILD_VECTOR UNDEF
13070 // CONCAT_VECTOR CONCAT_VECTOR
13073 // RESULT: V + zero extended
13075 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13076 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13077 V1.getOperand(1).getOpcode() != ISD::UNDEF)
13080 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13083 // To match the shuffle mask, the first half of the mask should
13084 // be exactly the first vector, and all the rest a splat with the
13085 // first element of the second one.
13086 for (unsigned i = 0; i != NumElems/2; ++i)
13087 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13088 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13091 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13092 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13093 if (Ld->hasNUsesOfValue(1, 0)) {
13094 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13095 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13097 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13099 Ld->getPointerInfo(),
13100 Ld->getAlignment(),
13101 false/*isVolatile*/, true/*ReadMem*/,
13102 false/*WriteMem*/);
13103 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13107 // Emit a zeroed vector and insert the desired subvector on its
13109 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13110 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13111 return DCI.CombineTo(N, InsV);
13114 //===--------------------------------------------------------------------===//
13115 // Combine some shuffles into subvector extracts and inserts:
13118 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13119 if (isShuffleHigh128VectorInsertLow(SVOp)) {
13120 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13121 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13122 return DCI.CombineTo(N, InsV);
13125 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13126 if (isShuffleLow128VectorInsertHigh(SVOp)) {
13127 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13128 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13129 return DCI.CombineTo(N, InsV);
13135 /// PerformShuffleCombine - Performs several different shuffle combines.
13136 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13137 TargetLowering::DAGCombinerInfo &DCI,
13138 const X86Subtarget *Subtarget) {
13139 DebugLoc dl = N->getDebugLoc();
13140 EVT VT = N->getValueType(0);
13142 // Don't create instructions with illegal types after legalize types has run.
13143 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13144 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13147 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13148 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13149 N->getOpcode() == ISD::VECTOR_SHUFFLE)
13150 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13152 // Only handle 128 wide vector from here on.
13153 if (VT.getSizeInBits() != 128)
13156 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13157 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13158 // consecutive, non-overlapping, and in the right order.
13159 SmallVector<SDValue, 16> Elts;
13160 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13161 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13163 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13167 /// DCI, PerformTruncateCombine - Converts truncate operation to
13168 /// a sequence of vector shuffle operations.
13169 /// It is possible when we truncate 256-bit vector to 128-bit vector
13171 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13172 DAGCombinerInfo &DCI) const {
13173 if (!DCI.isBeforeLegalizeOps())
13176 if (!Subtarget->hasAVX())
13179 EVT VT = N->getValueType(0);
13180 SDValue Op = N->getOperand(0);
13181 EVT OpVT = Op.getValueType();
13182 DebugLoc dl = N->getDebugLoc();
13184 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13186 if (Subtarget->hasAVX2()) {
13187 // AVX2: v4i64 -> v4i32
13190 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13192 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13193 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13196 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13197 DAG.getIntPtrConstant(0));
13200 // AVX: v4i64 -> v4i32
13201 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13202 DAG.getIntPtrConstant(0));
13204 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13205 DAG.getIntPtrConstant(2));
13207 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13208 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13211 static const int ShufMask1[] = {0, 2, 0, 0};
13213 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT), ShufMask1);
13214 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT), ShufMask1);
13217 static const int ShufMask2[] = {0, 1, 4, 5};
13219 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13222 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13224 if (Subtarget->hasAVX2()) {
13225 // AVX2: v8i32 -> v8i16
13227 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13230 SmallVector<SDValue,32> pshufbMask;
13231 for (unsigned i = 0; i < 2; ++i) {
13232 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13233 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13234 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13235 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13236 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13237 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13238 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13239 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13240 for (unsigned j = 0; j < 8; ++j)
13241 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13243 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13244 &pshufbMask[0], 32);
13245 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13247 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13249 static const int ShufMask[] = {0, 2, -1, -1};
13250 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
13253 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13254 DAG.getIntPtrConstant(0));
13256 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13259 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13260 DAG.getIntPtrConstant(0));
13262 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13263 DAG.getIntPtrConstant(4));
13265 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13266 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13269 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13270 -1, -1, -1, -1, -1, -1, -1, -1};
13272 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, DAG.getUNDEF(MVT::v16i8),
13274 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, DAG.getUNDEF(MVT::v16i8),
13277 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13278 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13281 static const int ShufMask2[] = {0, 1, 4, 5};
13283 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13284 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13290 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13291 /// specific shuffle of a load can be folded into a single element load.
13292 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13293 /// shuffles have been customed lowered so we need to handle those here.
13294 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13295 TargetLowering::DAGCombinerInfo &DCI) {
13296 if (DCI.isBeforeLegalizeOps())
13299 SDValue InVec = N->getOperand(0);
13300 SDValue EltNo = N->getOperand(1);
13302 if (!isa<ConstantSDNode>(EltNo))
13305 EVT VT = InVec.getValueType();
13307 bool HasShuffleIntoBitcast = false;
13308 if (InVec.getOpcode() == ISD::BITCAST) {
13309 // Don't duplicate a load with other uses.
13310 if (!InVec.hasOneUse())
13312 EVT BCVT = InVec.getOperand(0).getValueType();
13313 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13315 InVec = InVec.getOperand(0);
13316 HasShuffleIntoBitcast = true;
13319 if (!isTargetShuffle(InVec.getOpcode()))
13322 // Don't duplicate a load with other uses.
13323 if (!InVec.hasOneUse())
13326 SmallVector<int, 16> ShuffleMask;
13328 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13332 // Select the input vector, guarding against out of range extract vector.
13333 unsigned NumElems = VT.getVectorNumElements();
13334 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13335 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13336 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13337 : InVec.getOperand(1);
13339 // If inputs to shuffle are the same for both ops, then allow 2 uses
13340 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13342 if (LdNode.getOpcode() == ISD::BITCAST) {
13343 // Don't duplicate a load with other uses.
13344 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13347 AllowedUses = 1; // only allow 1 load use if we have a bitcast
13348 LdNode = LdNode.getOperand(0);
13351 if (!ISD::isNormalLoad(LdNode.getNode()))
13354 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13356 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13359 if (HasShuffleIntoBitcast) {
13360 // If there's a bitcast before the shuffle, check if the load type and
13361 // alignment is valid.
13362 unsigned Align = LN0->getAlignment();
13363 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13364 unsigned NewAlign = TLI.getTargetData()->
13365 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13367 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13371 // All checks match so transform back to vector_shuffle so that DAG combiner
13372 // can finish the job
13373 DebugLoc dl = N->getDebugLoc();
13375 // Create shuffle node taking into account the case that its a unary shuffle
13376 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13377 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13378 InVec.getOperand(0), Shuffle,
13380 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13381 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13385 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13386 /// generation and convert it from being a bunch of shuffles and extracts
13387 /// to a simple store and scalar loads to extract the elements.
13388 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13389 TargetLowering::DAGCombinerInfo &DCI) {
13390 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13391 if (NewOp.getNode())
13394 SDValue InputVector = N->getOperand(0);
13396 // Only operate on vectors of 4 elements, where the alternative shuffling
13397 // gets to be more expensive.
13398 if (InputVector.getValueType() != MVT::v4i32)
13401 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13402 // single use which is a sign-extend or zero-extend, and all elements are
13404 SmallVector<SDNode *, 4> Uses;
13405 unsigned ExtractedElements = 0;
13406 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13407 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13408 if (UI.getUse().getResNo() != InputVector.getResNo())
13411 SDNode *Extract = *UI;
13412 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13415 if (Extract->getValueType(0) != MVT::i32)
13417 if (!Extract->hasOneUse())
13419 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13420 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13422 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13425 // Record which element was extracted.
13426 ExtractedElements |=
13427 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13429 Uses.push_back(Extract);
13432 // If not all the elements were used, this may not be worthwhile.
13433 if (ExtractedElements != 15)
13436 // Ok, we've now decided to do the transformation.
13437 DebugLoc dl = InputVector.getDebugLoc();
13439 // Store the value to a temporary stack slot.
13440 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13441 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13442 MachinePointerInfo(), false, false, 0);
13444 // Replace each use (extract) with a load of the appropriate element.
13445 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13446 UE = Uses.end(); UI != UE; ++UI) {
13447 SDNode *Extract = *UI;
13449 // cOMpute the element's address.
13450 SDValue Idx = Extract->getOperand(1);
13452 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13453 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13454 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13455 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13457 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13458 StackPtr, OffsetVal);
13460 // Load the scalar.
13461 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13462 ScalarAddr, MachinePointerInfo(),
13463 false, false, false, 0);
13465 // Replace the exact with the load.
13466 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13469 // The replacement was made in place; don't return anything.
13473 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13475 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13476 TargetLowering::DAGCombinerInfo &DCI,
13477 const X86Subtarget *Subtarget) {
13478 DebugLoc DL = N->getDebugLoc();
13479 SDValue Cond = N->getOperand(0);
13480 // Get the LHS/RHS of the select.
13481 SDValue LHS = N->getOperand(1);
13482 SDValue RHS = N->getOperand(2);
13483 EVT VT = LHS.getValueType();
13485 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13486 // instructions match the semantics of the common C idiom x<y?x:y but not
13487 // x<=y?x:y, because of how they handle negative zero (which can be
13488 // ignored in unsafe-math mode).
13489 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13490 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13491 (Subtarget->hasSSE2() ||
13492 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13493 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13495 unsigned Opcode = 0;
13496 // Check for x CC y ? x : y.
13497 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13498 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13502 // Converting this to a min would handle NaNs incorrectly, and swapping
13503 // the operands would cause it to handle comparisons between positive
13504 // and negative zero incorrectly.
13505 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13506 if (!DAG.getTarget().Options.UnsafeFPMath &&
13507 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13509 std::swap(LHS, RHS);
13511 Opcode = X86ISD::FMIN;
13514 // Converting this to a min would handle comparisons between positive
13515 // and negative zero incorrectly.
13516 if (!DAG.getTarget().Options.UnsafeFPMath &&
13517 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13519 Opcode = X86ISD::FMIN;
13522 // Converting this to a min would handle both negative zeros and NaNs
13523 // incorrectly, but we can swap the operands to fix both.
13524 std::swap(LHS, RHS);
13528 Opcode = X86ISD::FMIN;
13532 // Converting this to a max would handle comparisons between positive
13533 // and negative zero incorrectly.
13534 if (!DAG.getTarget().Options.UnsafeFPMath &&
13535 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13537 Opcode = X86ISD::FMAX;
13540 // Converting this to a max would handle NaNs incorrectly, and swapping
13541 // the operands would cause it to handle comparisons between positive
13542 // and negative zero incorrectly.
13543 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13544 if (!DAG.getTarget().Options.UnsafeFPMath &&
13545 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13547 std::swap(LHS, RHS);
13549 Opcode = X86ISD::FMAX;
13552 // Converting this to a max would handle both negative zeros and NaNs
13553 // incorrectly, but we can swap the operands to fix both.
13554 std::swap(LHS, RHS);
13558 Opcode = X86ISD::FMAX;
13561 // Check for x CC y ? y : x -- a min/max with reversed arms.
13562 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13563 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13567 // Converting this to a min would handle comparisons between positive
13568 // and negative zero incorrectly, and swapping the operands would
13569 // cause it to handle NaNs incorrectly.
13570 if (!DAG.getTarget().Options.UnsafeFPMath &&
13571 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13572 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13574 std::swap(LHS, RHS);
13576 Opcode = X86ISD::FMIN;
13579 // Converting this to a min would handle NaNs incorrectly.
13580 if (!DAG.getTarget().Options.UnsafeFPMath &&
13581 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13583 Opcode = X86ISD::FMIN;
13586 // Converting this to a min would handle both negative zeros and NaNs
13587 // incorrectly, but we can swap the operands to fix both.
13588 std::swap(LHS, RHS);
13592 Opcode = X86ISD::FMIN;
13596 // Converting this to a max would handle NaNs incorrectly.
13597 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13599 Opcode = X86ISD::FMAX;
13602 // Converting this to a max would handle comparisons between positive
13603 // and negative zero incorrectly, and swapping the operands would
13604 // cause it to handle NaNs incorrectly.
13605 if (!DAG.getTarget().Options.UnsafeFPMath &&
13606 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13607 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13609 std::swap(LHS, RHS);
13611 Opcode = X86ISD::FMAX;
13614 // Converting this to a max would handle both negative zeros and NaNs
13615 // incorrectly, but we can swap the operands to fix both.
13616 std::swap(LHS, RHS);
13620 Opcode = X86ISD::FMAX;
13626 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13629 // If this is a select between two integer constants, try to do some
13631 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13632 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13633 // Don't do this for crazy integer types.
13634 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13635 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13636 // so that TrueC (the true value) is larger than FalseC.
13637 bool NeedsCondInvert = false;
13639 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13640 // Efficiently invertible.
13641 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
13642 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
13643 isa<ConstantSDNode>(Cond.getOperand(1))))) {
13644 NeedsCondInvert = true;
13645 std::swap(TrueC, FalseC);
13648 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13649 if (FalseC->getAPIntValue() == 0 &&
13650 TrueC->getAPIntValue().isPowerOf2()) {
13651 if (NeedsCondInvert) // Invert the condition if needed.
13652 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13653 DAG.getConstant(1, Cond.getValueType()));
13655 // Zero extend the condition if needed.
13656 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13658 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13659 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13660 DAG.getConstant(ShAmt, MVT::i8));
13663 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13664 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13665 if (NeedsCondInvert) // Invert the condition if needed.
13666 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13667 DAG.getConstant(1, Cond.getValueType()));
13669 // Zero extend the condition if needed.
13670 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13671 FalseC->getValueType(0), Cond);
13672 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13673 SDValue(FalseC, 0));
13676 // Optimize cases that will turn into an LEA instruction. This requires
13677 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13678 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13679 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13680 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13682 bool isFastMultiplier = false;
13684 switch ((unsigned char)Diff) {
13686 case 1: // result = add base, cond
13687 case 2: // result = lea base( , cond*2)
13688 case 3: // result = lea base(cond, cond*2)
13689 case 4: // result = lea base( , cond*4)
13690 case 5: // result = lea base(cond, cond*4)
13691 case 8: // result = lea base( , cond*8)
13692 case 9: // result = lea base(cond, cond*8)
13693 isFastMultiplier = true;
13698 if (isFastMultiplier) {
13699 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13700 if (NeedsCondInvert) // Invert the condition if needed.
13701 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13702 DAG.getConstant(1, Cond.getValueType()));
13704 // Zero extend the condition if needed.
13705 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13707 // Scale the condition by the difference.
13709 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13710 DAG.getConstant(Diff, Cond.getValueType()));
13712 // Add the base if non-zero.
13713 if (FalseC->getAPIntValue() != 0)
13714 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13715 SDValue(FalseC, 0));
13722 // Canonicalize max and min:
13723 // (x > y) ? x : y -> (x >= y) ? x : y
13724 // (x < y) ? x : y -> (x <= y) ? x : y
13725 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13726 // the need for an extra compare
13727 // against zero. e.g.
13728 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13730 // testl %edi, %edi
13732 // cmovgl %edi, %eax
13736 // cmovsl %eax, %edi
13737 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13738 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13739 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13740 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13745 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13746 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13747 Cond.getOperand(0), Cond.getOperand(1), NewCC);
13748 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13753 // If we know that this node is legal then we know that it is going to be
13754 // matched by one of the SSE/AVX BLEND instructions. These instructions only
13755 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13756 // to simplify previous instructions.
13757 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13758 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13759 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
13760 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13762 // Don't optimize vector selects that map to mask-registers.
13766 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13767 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13769 APInt KnownZero, KnownOne;
13770 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13771 DCI.isBeforeLegalizeOps());
13772 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13773 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13774 DCI.CommitTargetLoweringOpt(TLO);
13780 // Check whether a boolean test is testing a boolean value generated by
13781 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
13784 // Simplify the following patterns:
13785 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
13786 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
13787 // to (Op EFLAGS Cond)
13789 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
13790 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
13791 // to (Op EFLAGS !Cond)
13793 // where Op could be BRCOND or CMOV.
13795 static SDValue BoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
13796 // Quit if not CMP and SUB with its value result used.
13797 if (Cmp.getOpcode() != X86ISD::CMP &&
13798 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
13801 // Quit if not used as a boolean value.
13802 if (CC != X86::COND_E && CC != X86::COND_NE)
13805 // Check CMP operands. One of them should be 0 or 1 and the other should be
13806 // an SetCC or extended from it.
13807 SDValue Op1 = Cmp.getOperand(0);
13808 SDValue Op2 = Cmp.getOperand(1);
13811 const ConstantSDNode* C = 0;
13812 bool needOppositeCond = (CC == X86::COND_E);
13814 if ((C = dyn_cast<ConstantSDNode>(Op1)))
13816 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
13818 else // Quit if all operands are not constants.
13821 if (C->getZExtValue() == 1)
13822 needOppositeCond = !needOppositeCond;
13823 else if (C->getZExtValue() != 0)
13824 // Quit if the constant is neither 0 or 1.
13827 // Skip 'zext' node.
13828 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
13829 SetCC = SetCC.getOperand(0);
13831 // Quit if not SETCC.
13832 // FIXME: So far we only handle the boolean value generated from SETCC. If
13833 // there is other ways to generate boolean values, we need handle them here
13835 if (SetCC.getOpcode() != X86ISD::SETCC)
13838 // Set the condition code or opposite one if necessary.
13839 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
13840 if (needOppositeCond)
13841 CC = X86::GetOppositeBranchCondition(CC);
13843 return SetCC.getOperand(1);
13846 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13847 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13848 TargetLowering::DAGCombinerInfo &DCI) {
13849 DebugLoc DL = N->getDebugLoc();
13851 // If the flag operand isn't dead, don't touch this CMOV.
13852 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13855 SDValue FalseOp = N->getOperand(0);
13856 SDValue TrueOp = N->getOperand(1);
13857 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13858 SDValue Cond = N->getOperand(3);
13860 if (CC == X86::COND_E || CC == X86::COND_NE) {
13861 switch (Cond.getOpcode()) {
13865 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13866 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13867 return (CC == X86::COND_E) ? FalseOp : TrueOp;
13873 Flags = BoolTestSetCCCombine(Cond, CC);
13874 if (Flags.getNode()) {
13875 SDValue Ops[] = { FalseOp, TrueOp,
13876 DAG.getConstant(CC, MVT::i8), Flags };
13877 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
13878 Ops, array_lengthof(Ops));
13881 // If this is a select between two integer constants, try to do some
13882 // optimizations. Note that the operands are ordered the opposite of SELECT
13884 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13885 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13886 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13887 // larger than FalseC (the false value).
13888 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13889 CC = X86::GetOppositeBranchCondition(CC);
13890 std::swap(TrueC, FalseC);
13893 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
13894 // This is efficient for any integer data type (including i8/i16) and
13896 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13897 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13898 DAG.getConstant(CC, MVT::i8), Cond);
13900 // Zero extend the condition if needed.
13901 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13903 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13904 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13905 DAG.getConstant(ShAmt, MVT::i8));
13906 if (N->getNumValues() == 2) // Dead flag value?
13907 return DCI.CombineTo(N, Cond, SDValue());
13911 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
13912 // for any integer data type, including i8/i16.
13913 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13914 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13915 DAG.getConstant(CC, MVT::i8), Cond);
13917 // Zero extend the condition if needed.
13918 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13919 FalseC->getValueType(0), Cond);
13920 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13921 SDValue(FalseC, 0));
13923 if (N->getNumValues() == 2) // Dead flag value?
13924 return DCI.CombineTo(N, Cond, SDValue());
13928 // Optimize cases that will turn into an LEA instruction. This requires
13929 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13930 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13931 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13932 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13934 bool isFastMultiplier = false;
13936 switch ((unsigned char)Diff) {
13938 case 1: // result = add base, cond
13939 case 2: // result = lea base( , cond*2)
13940 case 3: // result = lea base(cond, cond*2)
13941 case 4: // result = lea base( , cond*4)
13942 case 5: // result = lea base(cond, cond*4)
13943 case 8: // result = lea base( , cond*8)
13944 case 9: // result = lea base(cond, cond*8)
13945 isFastMultiplier = true;
13950 if (isFastMultiplier) {
13951 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13952 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13953 DAG.getConstant(CC, MVT::i8), Cond);
13954 // Zero extend the condition if needed.
13955 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13957 // Scale the condition by the difference.
13959 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13960 DAG.getConstant(Diff, Cond.getValueType()));
13962 // Add the base if non-zero.
13963 if (FalseC->getAPIntValue() != 0)
13964 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13965 SDValue(FalseC, 0));
13966 if (N->getNumValues() == 2) // Dead flag value?
13967 return DCI.CombineTo(N, Cond, SDValue());
13977 /// PerformMulCombine - Optimize a single multiply with constant into two
13978 /// in order to implement it with two cheaper instructions, e.g.
13979 /// LEA + SHL, LEA + LEA.
13980 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13981 TargetLowering::DAGCombinerInfo &DCI) {
13982 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13985 EVT VT = N->getValueType(0);
13986 if (VT != MVT::i64)
13989 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13992 uint64_t MulAmt = C->getZExtValue();
13993 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13996 uint64_t MulAmt1 = 0;
13997 uint64_t MulAmt2 = 0;
13998 if ((MulAmt % 9) == 0) {
14000 MulAmt2 = MulAmt / 9;
14001 } else if ((MulAmt % 5) == 0) {
14003 MulAmt2 = MulAmt / 5;
14004 } else if ((MulAmt % 3) == 0) {
14006 MulAmt2 = MulAmt / 3;
14009 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14010 DebugLoc DL = N->getDebugLoc();
14012 if (isPowerOf2_64(MulAmt2) &&
14013 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14014 // If second multiplifer is pow2, issue it first. We want the multiply by
14015 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14017 std::swap(MulAmt1, MulAmt2);
14020 if (isPowerOf2_64(MulAmt1))
14021 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14022 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14024 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14025 DAG.getConstant(MulAmt1, VT));
14027 if (isPowerOf2_64(MulAmt2))
14028 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14029 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14031 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14032 DAG.getConstant(MulAmt2, VT));
14034 // Do not add new nodes to DAG combiner worklist.
14035 DCI.CombineTo(N, NewMul, false);
14040 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14041 SDValue N0 = N->getOperand(0);
14042 SDValue N1 = N->getOperand(1);
14043 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14044 EVT VT = N0.getValueType();
14046 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14047 // since the result of setcc_c is all zero's or all ones.
14048 if (VT.isInteger() && !VT.isVector() &&
14049 N1C && N0.getOpcode() == ISD::AND &&
14050 N0.getOperand(1).getOpcode() == ISD::Constant) {
14051 SDValue N00 = N0.getOperand(0);
14052 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14053 ((N00.getOpcode() == ISD::ANY_EXTEND ||
14054 N00.getOpcode() == ISD::ZERO_EXTEND) &&
14055 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14056 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14057 APInt ShAmt = N1C->getAPIntValue();
14058 Mask = Mask.shl(ShAmt);
14060 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14061 N00, DAG.getConstant(Mask, VT));
14066 // Hardware support for vector shifts is sparse which makes us scalarize the
14067 // vector operations in many cases. Also, on sandybridge ADD is faster than
14069 // (shl V, 1) -> add V,V
14070 if (isSplatVector(N1.getNode())) {
14071 assert(N0.getValueType().isVector() && "Invalid vector shift type");
14072 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14073 // We shift all of the values by one. In many cases we do not have
14074 // hardware support for this operation. This is better expressed as an ADD
14076 if (N1C && (1 == N1C->getZExtValue())) {
14077 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14084 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14086 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14087 TargetLowering::DAGCombinerInfo &DCI,
14088 const X86Subtarget *Subtarget) {
14089 EVT VT = N->getValueType(0);
14090 if (N->getOpcode() == ISD::SHL) {
14091 SDValue V = PerformSHLCombine(N, DAG);
14092 if (V.getNode()) return V;
14095 // On X86 with SSE2 support, we can transform this to a vector shift if
14096 // all elements are shifted by the same amount. We can't do this in legalize
14097 // because the a constant vector is typically transformed to a constant pool
14098 // so we have no knowledge of the shift amount.
14099 if (!Subtarget->hasSSE2())
14102 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14103 (!Subtarget->hasAVX2() ||
14104 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14107 SDValue ShAmtOp = N->getOperand(1);
14108 EVT EltVT = VT.getVectorElementType();
14109 DebugLoc DL = N->getDebugLoc();
14110 SDValue BaseShAmt = SDValue();
14111 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14112 unsigned NumElts = VT.getVectorNumElements();
14114 for (; i != NumElts; ++i) {
14115 SDValue Arg = ShAmtOp.getOperand(i);
14116 if (Arg.getOpcode() == ISD::UNDEF) continue;
14120 // Handle the case where the build_vector is all undef
14121 // FIXME: Should DAG allow this?
14125 for (; i != NumElts; ++i) {
14126 SDValue Arg = ShAmtOp.getOperand(i);
14127 if (Arg.getOpcode() == ISD::UNDEF) continue;
14128 if (Arg != BaseShAmt) {
14132 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14133 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14134 SDValue InVec = ShAmtOp.getOperand(0);
14135 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14136 unsigned NumElts = InVec.getValueType().getVectorNumElements();
14138 for (; i != NumElts; ++i) {
14139 SDValue Arg = InVec.getOperand(i);
14140 if (Arg.getOpcode() == ISD::UNDEF) continue;
14144 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14145 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14146 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14147 if (C->getZExtValue() == SplatIdx)
14148 BaseShAmt = InVec.getOperand(1);
14151 if (BaseShAmt.getNode() == 0) {
14152 // Don't create instructions with illegal types after legalize
14154 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14155 !DCI.isBeforeLegalize())
14158 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14159 DAG.getIntPtrConstant(0));
14164 // The shift amount is an i32.
14165 if (EltVT.bitsGT(MVT::i32))
14166 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14167 else if (EltVT.bitsLT(MVT::i32))
14168 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14170 // The shift amount is identical so we can do a vector shift.
14171 SDValue ValOp = N->getOperand(0);
14172 switch (N->getOpcode()) {
14174 llvm_unreachable("Unknown shift opcode!");
14176 switch (VT.getSimpleVT().SimpleTy) {
14177 default: return SDValue();
14184 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14187 switch (VT.getSimpleVT().SimpleTy) {
14188 default: return SDValue();
14193 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14196 switch (VT.getSimpleVT().SimpleTy) {
14197 default: return SDValue();
14204 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14210 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
14211 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14212 // and friends. Likewise for OR -> CMPNEQSS.
14213 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14214 TargetLowering::DAGCombinerInfo &DCI,
14215 const X86Subtarget *Subtarget) {
14218 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14219 // we're requiring SSE2 for both.
14220 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14221 SDValue N0 = N->getOperand(0);
14222 SDValue N1 = N->getOperand(1);
14223 SDValue CMP0 = N0->getOperand(1);
14224 SDValue CMP1 = N1->getOperand(1);
14225 DebugLoc DL = N->getDebugLoc();
14227 // The SETCCs should both refer to the same CMP.
14228 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14231 SDValue CMP00 = CMP0->getOperand(0);
14232 SDValue CMP01 = CMP0->getOperand(1);
14233 EVT VT = CMP00.getValueType();
14235 if (VT == MVT::f32 || VT == MVT::f64) {
14236 bool ExpectingFlags = false;
14237 // Check for any users that want flags:
14238 for (SDNode::use_iterator UI = N->use_begin(),
14240 !ExpectingFlags && UI != UE; ++UI)
14241 switch (UI->getOpcode()) {
14246 ExpectingFlags = true;
14248 case ISD::CopyToReg:
14249 case ISD::SIGN_EXTEND:
14250 case ISD::ZERO_EXTEND:
14251 case ISD::ANY_EXTEND:
14255 if (!ExpectingFlags) {
14256 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14257 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14259 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14260 X86::CondCode tmp = cc0;
14265 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
14266 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14267 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14268 X86ISD::NodeType NTOperator = is64BitFP ?
14269 X86ISD::FSETCCsd : X86ISD::FSETCCss;
14270 // FIXME: need symbolic constants for these magic numbers.
14271 // See X86ATTInstPrinter.cpp:printSSECC().
14272 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14273 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14274 DAG.getConstant(x86cc, MVT::i8));
14275 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14277 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14278 DAG.getConstant(1, MVT::i32));
14279 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14280 return OneBitOfTruth;
14288 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14289 /// so it can be folded inside ANDNP.
14290 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14291 EVT VT = N->getValueType(0);
14293 // Match direct AllOnes for 128 and 256-bit vectors
14294 if (ISD::isBuildVectorAllOnes(N))
14297 // Look through a bit convert.
14298 if (N->getOpcode() == ISD::BITCAST)
14299 N = N->getOperand(0).getNode();
14301 // Sometimes the operand may come from a insert_subvector building a 256-bit
14303 if (VT.getSizeInBits() == 256 &&
14304 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14305 SDValue V1 = N->getOperand(0);
14306 SDValue V2 = N->getOperand(1);
14308 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14309 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14310 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14311 ISD::isBuildVectorAllOnes(V2.getNode()))
14318 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14319 TargetLowering::DAGCombinerInfo &DCI,
14320 const X86Subtarget *Subtarget) {
14321 if (DCI.isBeforeLegalizeOps())
14324 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14328 EVT VT = N->getValueType(0);
14330 // Create ANDN, BLSI, and BLSR instructions
14331 // BLSI is X & (-X)
14332 // BLSR is X & (X-1)
14333 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14334 SDValue N0 = N->getOperand(0);
14335 SDValue N1 = N->getOperand(1);
14336 DebugLoc DL = N->getDebugLoc();
14338 // Check LHS for not
14339 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14340 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14341 // Check RHS for not
14342 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14343 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14345 // Check LHS for neg
14346 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14347 isZero(N0.getOperand(0)))
14348 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14350 // Check RHS for neg
14351 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14352 isZero(N1.getOperand(0)))
14353 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14355 // Check LHS for X-1
14356 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14357 isAllOnes(N0.getOperand(1)))
14358 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14360 // Check RHS for X-1
14361 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14362 isAllOnes(N1.getOperand(1)))
14363 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14368 // Want to form ANDNP nodes:
14369 // 1) In the hopes of then easily combining them with OR and AND nodes
14370 // to form PBLEND/PSIGN.
14371 // 2) To match ANDN packed intrinsics
14372 if (VT != MVT::v2i64 && VT != MVT::v4i64)
14375 SDValue N0 = N->getOperand(0);
14376 SDValue N1 = N->getOperand(1);
14377 DebugLoc DL = N->getDebugLoc();
14379 // Check LHS for vnot
14380 if (N0.getOpcode() == ISD::XOR &&
14381 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14382 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14383 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14385 // Check RHS for vnot
14386 if (N1.getOpcode() == ISD::XOR &&
14387 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14388 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14389 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14394 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14395 TargetLowering::DAGCombinerInfo &DCI,
14396 const X86Subtarget *Subtarget) {
14397 if (DCI.isBeforeLegalizeOps())
14400 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14404 EVT VT = N->getValueType(0);
14406 SDValue N0 = N->getOperand(0);
14407 SDValue N1 = N->getOperand(1);
14409 // look for psign/blend
14410 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14411 if (!Subtarget->hasSSSE3() ||
14412 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14415 // Canonicalize pandn to RHS
14416 if (N0.getOpcode() == X86ISD::ANDNP)
14418 // or (and (m, y), (pandn m, x))
14419 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14420 SDValue Mask = N1.getOperand(0);
14421 SDValue X = N1.getOperand(1);
14423 if (N0.getOperand(0) == Mask)
14424 Y = N0.getOperand(1);
14425 if (N0.getOperand(1) == Mask)
14426 Y = N0.getOperand(0);
14428 // Check to see if the mask appeared in both the AND and ANDNP and
14432 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14433 // Look through mask bitcast.
14434 if (Mask.getOpcode() == ISD::BITCAST)
14435 Mask = Mask.getOperand(0);
14436 if (X.getOpcode() == ISD::BITCAST)
14437 X = X.getOperand(0);
14438 if (Y.getOpcode() == ISD::BITCAST)
14439 Y = Y.getOperand(0);
14441 EVT MaskVT = Mask.getValueType();
14443 // Validate that the Mask operand is a vector sra node.
14444 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14445 // there is no psrai.b
14446 if (Mask.getOpcode() != X86ISD::VSRAI)
14449 // Check that the SRA is all signbits.
14450 SDValue SraC = Mask.getOperand(1);
14451 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
14452 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14453 if ((SraAmt + 1) != EltBits)
14456 DebugLoc DL = N->getDebugLoc();
14458 // Now we know we at least have a plendvb with the mask val. See if
14459 // we can form a psignb/w/d.
14460 // psign = x.type == y.type == mask.type && y = sub(0, x);
14461 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14462 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14463 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14464 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14465 "Unsupported VT for PSIGN");
14466 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14467 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14469 // PBLENDVB only available on SSE 4.1
14470 if (!Subtarget->hasSSE41())
14473 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14475 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14476 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14477 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14478 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14479 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14483 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14486 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14487 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14489 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14491 if (!N0.hasOneUse() || !N1.hasOneUse())
14494 SDValue ShAmt0 = N0.getOperand(1);
14495 if (ShAmt0.getValueType() != MVT::i8)
14497 SDValue ShAmt1 = N1.getOperand(1);
14498 if (ShAmt1.getValueType() != MVT::i8)
14500 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14501 ShAmt0 = ShAmt0.getOperand(0);
14502 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14503 ShAmt1 = ShAmt1.getOperand(0);
14505 DebugLoc DL = N->getDebugLoc();
14506 unsigned Opc = X86ISD::SHLD;
14507 SDValue Op0 = N0.getOperand(0);
14508 SDValue Op1 = N1.getOperand(0);
14509 if (ShAmt0.getOpcode() == ISD::SUB) {
14510 Opc = X86ISD::SHRD;
14511 std::swap(Op0, Op1);
14512 std::swap(ShAmt0, ShAmt1);
14515 unsigned Bits = VT.getSizeInBits();
14516 if (ShAmt1.getOpcode() == ISD::SUB) {
14517 SDValue Sum = ShAmt1.getOperand(0);
14518 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14519 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14520 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14521 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14522 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14523 return DAG.getNode(Opc, DL, VT,
14525 DAG.getNode(ISD::TRUNCATE, DL,
14528 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14529 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14531 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14532 return DAG.getNode(Opc, DL, VT,
14533 N0.getOperand(0), N1.getOperand(0),
14534 DAG.getNode(ISD::TRUNCATE, DL,
14541 // Generate NEG and CMOV for integer abs.
14542 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14543 EVT VT = N->getValueType(0);
14545 // Since X86 does not have CMOV for 8-bit integer, we don't convert
14546 // 8-bit integer abs to NEG and CMOV.
14547 if (VT.isInteger() && VT.getSizeInBits() == 8)
14550 SDValue N0 = N->getOperand(0);
14551 SDValue N1 = N->getOperand(1);
14552 DebugLoc DL = N->getDebugLoc();
14554 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14555 // and change it to SUB and CMOV.
14556 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14557 N0.getOpcode() == ISD::ADD &&
14558 N0.getOperand(1) == N1 &&
14559 N1.getOpcode() == ISD::SRA &&
14560 N1.getOperand(0) == N0.getOperand(0))
14561 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14562 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14563 // Generate SUB & CMOV.
14564 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14565 DAG.getConstant(0, VT), N0.getOperand(0));
14567 SDValue Ops[] = { N0.getOperand(0), Neg,
14568 DAG.getConstant(X86::COND_GE, MVT::i8),
14569 SDValue(Neg.getNode(), 1) };
14570 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14571 Ops, array_lengthof(Ops));
14576 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14577 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14578 TargetLowering::DAGCombinerInfo &DCI,
14579 const X86Subtarget *Subtarget) {
14580 if (DCI.isBeforeLegalizeOps())
14583 if (Subtarget->hasCMov()) {
14584 SDValue RV = performIntegerAbsCombine(N, DAG);
14589 // Try forming BMI if it is available.
14590 if (!Subtarget->hasBMI())
14593 EVT VT = N->getValueType(0);
14595 if (VT != MVT::i32 && VT != MVT::i64)
14598 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14600 // Create BLSMSK instructions by finding X ^ (X-1)
14601 SDValue N0 = N->getOperand(0);
14602 SDValue N1 = N->getOperand(1);
14603 DebugLoc DL = N->getDebugLoc();
14605 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14606 isAllOnes(N0.getOperand(1)))
14607 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14609 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14610 isAllOnes(N1.getOperand(1)))
14611 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14616 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14617 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14618 TargetLowering::DAGCombinerInfo &DCI,
14619 const X86Subtarget *Subtarget) {
14620 LoadSDNode *Ld = cast<LoadSDNode>(N);
14621 EVT RegVT = Ld->getValueType(0);
14622 EVT MemVT = Ld->getMemoryVT();
14623 DebugLoc dl = Ld->getDebugLoc();
14624 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14626 ISD::LoadExtType Ext = Ld->getExtensionType();
14628 // If this is a vector EXT Load then attempt to optimize it using a
14629 // shuffle. We need SSE4 for the shuffles.
14630 // TODO: It is possible to support ZExt by zeroing the undef values
14631 // during the shuffle phase or after the shuffle.
14632 if (RegVT.isVector() && RegVT.isInteger() &&
14633 Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14634 assert(MemVT != RegVT && "Cannot extend to the same type");
14635 assert(MemVT.isVector() && "Must load a vector from memory");
14637 unsigned NumElems = RegVT.getVectorNumElements();
14638 unsigned RegSz = RegVT.getSizeInBits();
14639 unsigned MemSz = MemVT.getSizeInBits();
14640 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14642 // All sizes must be a power of two.
14643 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
14646 // Attempt to load the original value using scalar loads.
14647 // Find the largest scalar type that divides the total loaded size.
14648 MVT SclrLoadTy = MVT::i8;
14649 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14650 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14651 MVT Tp = (MVT::SimpleValueType)tp;
14652 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14657 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14658 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14660 SclrLoadTy = MVT::f64;
14662 // Calculate the number of scalar loads that we need to perform
14663 // in order to load our vector from memory.
14664 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14666 // Represent our vector as a sequence of elements which are the
14667 // largest scalar that we can load.
14668 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14669 RegSz/SclrLoadTy.getSizeInBits());
14671 // Represent the data using the same element type that is stored in
14672 // memory. In practice, we ''widen'' MemVT.
14673 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14674 RegSz/MemVT.getScalarType().getSizeInBits());
14676 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14677 "Invalid vector type");
14679 // We can't shuffle using an illegal type.
14680 if (!TLI.isTypeLegal(WideVecVT))
14683 SmallVector<SDValue, 8> Chains;
14684 SDValue Ptr = Ld->getBasePtr();
14685 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
14686 TLI.getPointerTy());
14687 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14689 for (unsigned i = 0; i < NumLoads; ++i) {
14690 // Perform a single load.
14691 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14692 Ptr, Ld->getPointerInfo(),
14693 Ld->isVolatile(), Ld->isNonTemporal(),
14694 Ld->isInvariant(), Ld->getAlignment());
14695 Chains.push_back(ScalarLoad.getValue(1));
14696 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14697 // another round of DAGCombining.
14699 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14701 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14702 ScalarLoad, DAG.getIntPtrConstant(i));
14704 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14707 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14710 // Bitcast the loaded value to a vector of the original element type, in
14711 // the size of the target vector type.
14712 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14713 unsigned SizeRatio = RegSz/MemSz;
14715 // Redistribute the loaded elements into the different locations.
14716 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14717 for (unsigned i = 0; i != NumElems; ++i)
14718 ShuffleVec[i*SizeRatio] = i;
14720 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14721 DAG.getUNDEF(WideVecVT),
14724 // Bitcast to the requested type.
14725 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14726 // Replace the original load with the new sequence
14727 // and return the new chain.
14728 return DCI.CombineTo(N, Shuff, TF, true);
14734 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14735 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14736 const X86Subtarget *Subtarget) {
14737 StoreSDNode *St = cast<StoreSDNode>(N);
14738 EVT VT = St->getValue().getValueType();
14739 EVT StVT = St->getMemoryVT();
14740 DebugLoc dl = St->getDebugLoc();
14741 SDValue StoredVal = St->getOperand(1);
14742 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14744 // If we are saving a concatenation of two XMM registers, perform two stores.
14745 // On Sandy Bridge, 256-bit memory operations are executed by two
14746 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
14747 // memory operation.
14748 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2() &&
14749 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14750 StoredVal.getNumOperands() == 2) {
14751 SDValue Value0 = StoredVal.getOperand(0);
14752 SDValue Value1 = StoredVal.getOperand(1);
14754 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14755 SDValue Ptr0 = St->getBasePtr();
14756 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14758 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14759 St->getPointerInfo(), St->isVolatile(),
14760 St->isNonTemporal(), St->getAlignment());
14761 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14762 St->getPointerInfo(), St->isVolatile(),
14763 St->isNonTemporal(), St->getAlignment());
14764 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14767 // Optimize trunc store (of multiple scalars) to shuffle and store.
14768 // First, pack all of the elements in one place. Next, store to memory
14769 // in fewer chunks.
14770 if (St->isTruncatingStore() && VT.isVector()) {
14771 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14772 unsigned NumElems = VT.getVectorNumElements();
14773 assert(StVT != VT && "Cannot truncate to the same type");
14774 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14775 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14777 // From, To sizes and ElemCount must be pow of two
14778 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14779 // We are going to use the original vector elt for storing.
14780 // Accumulated smaller vector elements must be a multiple of the store size.
14781 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14783 unsigned SizeRatio = FromSz / ToSz;
14785 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14787 // Create a type on which we perform the shuffle
14788 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14789 StVT.getScalarType(), NumElems*SizeRatio);
14791 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14793 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14794 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14795 for (unsigned i = 0; i != NumElems; ++i)
14796 ShuffleVec[i] = i * SizeRatio;
14798 // Can't shuffle using an illegal type.
14799 if (!TLI.isTypeLegal(WideVecVT))
14802 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14803 DAG.getUNDEF(WideVecVT),
14805 // At this point all of the data is stored at the bottom of the
14806 // register. We now need to save it to mem.
14808 // Find the largest store unit
14809 MVT StoreType = MVT::i8;
14810 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14811 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14812 MVT Tp = (MVT::SimpleValueType)tp;
14813 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
14817 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14818 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
14819 (64 <= NumElems * ToSz))
14820 StoreType = MVT::f64;
14822 // Bitcast the original vector into a vector of store-size units
14823 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14824 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
14825 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14826 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14827 SmallVector<SDValue, 8> Chains;
14828 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14829 TLI.getPointerTy());
14830 SDValue Ptr = St->getBasePtr();
14832 // Perform one or more big stores into memory.
14833 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
14834 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14835 StoreType, ShuffWide,
14836 DAG.getIntPtrConstant(i));
14837 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14838 St->getPointerInfo(), St->isVolatile(),
14839 St->isNonTemporal(), St->getAlignment());
14840 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14841 Chains.push_back(Ch);
14844 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14849 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
14850 // the FP state in cases where an emms may be missing.
14851 // A preferable solution to the general problem is to figure out the right
14852 // places to insert EMMS. This qualifies as a quick hack.
14854 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14855 if (VT.getSizeInBits() != 64)
14858 const Function *F = DAG.getMachineFunction().getFunction();
14859 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14860 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14861 && Subtarget->hasSSE2();
14862 if ((VT.isVector() ||
14863 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14864 isa<LoadSDNode>(St->getValue()) &&
14865 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14866 St->getChain().hasOneUse() && !St->isVolatile()) {
14867 SDNode* LdVal = St->getValue().getNode();
14868 LoadSDNode *Ld = 0;
14869 int TokenFactorIndex = -1;
14870 SmallVector<SDValue, 8> Ops;
14871 SDNode* ChainVal = St->getChain().getNode();
14872 // Must be a store of a load. We currently handle two cases: the load
14873 // is a direct child, and it's under an intervening TokenFactor. It is
14874 // possible to dig deeper under nested TokenFactors.
14875 if (ChainVal == LdVal)
14876 Ld = cast<LoadSDNode>(St->getChain());
14877 else if (St->getValue().hasOneUse() &&
14878 ChainVal->getOpcode() == ISD::TokenFactor) {
14879 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
14880 if (ChainVal->getOperand(i).getNode() == LdVal) {
14881 TokenFactorIndex = i;
14882 Ld = cast<LoadSDNode>(St->getValue());
14884 Ops.push_back(ChainVal->getOperand(i));
14888 if (!Ld || !ISD::isNormalLoad(Ld))
14891 // If this is not the MMX case, i.e. we are just turning i64 load/store
14892 // into f64 load/store, avoid the transformation if there are multiple
14893 // uses of the loaded value.
14894 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14897 DebugLoc LdDL = Ld->getDebugLoc();
14898 DebugLoc StDL = N->getDebugLoc();
14899 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14900 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14902 if (Subtarget->is64Bit() || F64IsLegal) {
14903 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14904 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14905 Ld->getPointerInfo(), Ld->isVolatile(),
14906 Ld->isNonTemporal(), Ld->isInvariant(),
14907 Ld->getAlignment());
14908 SDValue NewChain = NewLd.getValue(1);
14909 if (TokenFactorIndex != -1) {
14910 Ops.push_back(NewChain);
14911 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14914 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14915 St->getPointerInfo(),
14916 St->isVolatile(), St->isNonTemporal(),
14917 St->getAlignment());
14920 // Otherwise, lower to two pairs of 32-bit loads / stores.
14921 SDValue LoAddr = Ld->getBasePtr();
14922 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14923 DAG.getConstant(4, MVT::i32));
14925 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14926 Ld->getPointerInfo(),
14927 Ld->isVolatile(), Ld->isNonTemporal(),
14928 Ld->isInvariant(), Ld->getAlignment());
14929 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14930 Ld->getPointerInfo().getWithOffset(4),
14931 Ld->isVolatile(), Ld->isNonTemporal(),
14933 MinAlign(Ld->getAlignment(), 4));
14935 SDValue NewChain = LoLd.getValue(1);
14936 if (TokenFactorIndex != -1) {
14937 Ops.push_back(LoLd);
14938 Ops.push_back(HiLd);
14939 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14943 LoAddr = St->getBasePtr();
14944 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14945 DAG.getConstant(4, MVT::i32));
14947 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14948 St->getPointerInfo(),
14949 St->isVolatile(), St->isNonTemporal(),
14950 St->getAlignment());
14951 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14952 St->getPointerInfo().getWithOffset(4),
14954 St->isNonTemporal(),
14955 MinAlign(St->getAlignment(), 4));
14956 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14961 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14962 /// and return the operands for the horizontal operation in LHS and RHS. A
14963 /// horizontal operation performs the binary operation on successive elements
14964 /// of its first operand, then on successive elements of its second operand,
14965 /// returning the resulting values in a vector. For example, if
14966 /// A = < float a0, float a1, float a2, float a3 >
14968 /// B = < float b0, float b1, float b2, float b3 >
14969 /// then the result of doing a horizontal operation on A and B is
14970 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14971 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14972 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14973 /// set to A, RHS to B, and the routine returns 'true'.
14974 /// Note that the binary operation should have the property that if one of the
14975 /// operands is UNDEF then the result is UNDEF.
14976 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14977 // Look for the following pattern: if
14978 // A = < float a0, float a1, float a2, float a3 >
14979 // B = < float b0, float b1, float b2, float b3 >
14981 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14982 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14983 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14984 // which is A horizontal-op B.
14986 // At least one of the operands should be a vector shuffle.
14987 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14988 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14991 EVT VT = LHS.getValueType();
14993 assert((VT.is128BitVector() || VT.is256BitVector()) &&
14994 "Unsupported vector type for horizontal add/sub");
14996 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14997 // operate independently on 128-bit lanes.
14998 unsigned NumElts = VT.getVectorNumElements();
14999 unsigned NumLanes = VT.getSizeInBits()/128;
15000 unsigned NumLaneElts = NumElts / NumLanes;
15001 assert((NumLaneElts % 2 == 0) &&
15002 "Vector type should have an even number of elements in each lane");
15003 unsigned HalfLaneElts = NumLaneElts/2;
15005 // View LHS in the form
15006 // LHS = VECTOR_SHUFFLE A, B, LMask
15007 // If LHS is not a shuffle then pretend it is the shuffle
15008 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15009 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15012 SmallVector<int, 16> LMask(NumElts);
15013 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15014 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15015 A = LHS.getOperand(0);
15016 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15017 B = LHS.getOperand(1);
15018 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15019 std::copy(Mask.begin(), Mask.end(), LMask.begin());
15021 if (LHS.getOpcode() != ISD::UNDEF)
15023 for (unsigned i = 0; i != NumElts; ++i)
15027 // Likewise, view RHS in the form
15028 // RHS = VECTOR_SHUFFLE C, D, RMask
15030 SmallVector<int, 16> RMask(NumElts);
15031 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15032 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15033 C = RHS.getOperand(0);
15034 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15035 D = RHS.getOperand(1);
15036 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15037 std::copy(Mask.begin(), Mask.end(), RMask.begin());
15039 if (RHS.getOpcode() != ISD::UNDEF)
15041 for (unsigned i = 0; i != NumElts; ++i)
15045 // Check that the shuffles are both shuffling the same vectors.
15046 if (!(A == C && B == D) && !(A == D && B == C))
15049 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15050 if (!A.getNode() && !B.getNode())
15053 // If A and B occur in reverse order in RHS, then "swap" them (which means
15054 // rewriting the mask).
15056 CommuteVectorShuffleMask(RMask, NumElts);
15058 // At this point LHS and RHS are equivalent to
15059 // LHS = VECTOR_SHUFFLE A, B, LMask
15060 // RHS = VECTOR_SHUFFLE A, B, RMask
15061 // Check that the masks correspond to performing a horizontal operation.
15062 for (unsigned i = 0; i != NumElts; ++i) {
15063 int LIdx = LMask[i], RIdx = RMask[i];
15065 // Ignore any UNDEF components.
15066 if (LIdx < 0 || RIdx < 0 ||
15067 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15068 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15071 // Check that successive elements are being operated on. If not, this is
15072 // not a horizontal operation.
15073 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15074 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15075 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15076 if (!(LIdx == Index && RIdx == Index + 1) &&
15077 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15081 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15082 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15086 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15087 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15088 const X86Subtarget *Subtarget) {
15089 EVT VT = N->getValueType(0);
15090 SDValue LHS = N->getOperand(0);
15091 SDValue RHS = N->getOperand(1);
15093 // Try to synthesize horizontal adds from adds of shuffles.
15094 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15095 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15096 isHorizontalBinOp(LHS, RHS, true))
15097 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15101 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15102 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15103 const X86Subtarget *Subtarget) {
15104 EVT VT = N->getValueType(0);
15105 SDValue LHS = N->getOperand(0);
15106 SDValue RHS = N->getOperand(1);
15108 // Try to synthesize horizontal subs from subs of shuffles.
15109 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15110 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15111 isHorizontalBinOp(LHS, RHS, false))
15112 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15116 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15117 /// X86ISD::FXOR nodes.
15118 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15119 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15120 // F[X]OR(0.0, x) -> x
15121 // F[X]OR(x, 0.0) -> x
15122 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15123 if (C->getValueAPF().isPosZero())
15124 return N->getOperand(1);
15125 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15126 if (C->getValueAPF().isPosZero())
15127 return N->getOperand(0);
15131 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15132 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15133 // FAND(0.0, x) -> 0.0
15134 // FAND(x, 0.0) -> 0.0
15135 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15136 if (C->getValueAPF().isPosZero())
15137 return N->getOperand(0);
15138 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15139 if (C->getValueAPF().isPosZero())
15140 return N->getOperand(1);
15144 static SDValue PerformBTCombine(SDNode *N,
15146 TargetLowering::DAGCombinerInfo &DCI) {
15147 // BT ignores high bits in the bit index operand.
15148 SDValue Op1 = N->getOperand(1);
15149 if (Op1.hasOneUse()) {
15150 unsigned BitWidth = Op1.getValueSizeInBits();
15151 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15152 APInt KnownZero, KnownOne;
15153 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15154 !DCI.isBeforeLegalizeOps());
15155 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15156 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15157 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15158 DCI.CommitTargetLoweringOpt(TLO);
15163 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15164 SDValue Op = N->getOperand(0);
15165 if (Op.getOpcode() == ISD::BITCAST)
15166 Op = Op.getOperand(0);
15167 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15168 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15169 VT.getVectorElementType().getSizeInBits() ==
15170 OpVT.getVectorElementType().getSizeInBits()) {
15171 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15176 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15177 TargetLowering::DAGCombinerInfo &DCI,
15178 const X86Subtarget *Subtarget) {
15179 if (!DCI.isBeforeLegalizeOps())
15182 if (!Subtarget->hasAVX())
15185 EVT VT = N->getValueType(0);
15186 SDValue Op = N->getOperand(0);
15187 EVT OpVT = Op.getValueType();
15188 DebugLoc dl = N->getDebugLoc();
15190 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15191 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15193 if (Subtarget->hasAVX2())
15194 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15196 // Optimize vectors in AVX mode
15197 // Sign extend v8i16 to v8i32 and
15200 // Divide input vector into two parts
15201 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15202 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15203 // concat the vectors to original VT
15205 unsigned NumElems = OpVT.getVectorNumElements();
15206 SmallVector<int,8> ShufMask1(NumElems, -1);
15207 for (unsigned i = 0; i != NumElems/2; ++i)
15210 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15213 SmallVector<int,8> ShufMask2(NumElems, -1);
15214 for (unsigned i = 0; i != NumElems/2; ++i)
15215 ShufMask2[i] = i + NumElems/2;
15217 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15220 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15221 VT.getVectorNumElements()/2);
15223 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15224 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15226 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15231 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15232 const X86Subtarget* Subtarget) {
15233 DebugLoc dl = N->getDebugLoc();
15234 EVT VT = N->getValueType(0);
15236 EVT ScalarVT = VT.getScalarType();
15237 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasFMA())
15240 SDValue A = N->getOperand(0);
15241 SDValue B = N->getOperand(1);
15242 SDValue C = N->getOperand(2);
15244 bool NegA = (A.getOpcode() == ISD::FNEG);
15245 bool NegB = (B.getOpcode() == ISD::FNEG);
15246 bool NegC = (C.getOpcode() == ISD::FNEG);
15248 // Negative multiplication when NegA xor NegB
15249 bool NegMul = (NegA != NegB);
15251 A = A.getOperand(0);
15253 B = B.getOperand(0);
15255 C = C.getOperand(0);
15259 Opcode = (!NegC)? X86ISD::FMADD : X86ISD::FMSUB;
15261 Opcode = (!NegC)? X86ISD::FNMADD : X86ISD::FNMSUB;
15262 return DAG.getNode(Opcode, dl, VT, A, B, C);
15265 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15266 TargetLowering::DAGCombinerInfo &DCI,
15267 const X86Subtarget *Subtarget) {
15268 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
15269 // (and (i32 x86isd::setcc_carry), 1)
15270 // This eliminates the zext. This transformation is necessary because
15271 // ISD::SETCC is always legalized to i8.
15272 DebugLoc dl = N->getDebugLoc();
15273 SDValue N0 = N->getOperand(0);
15274 EVT VT = N->getValueType(0);
15275 EVT OpVT = N0.getValueType();
15277 if (N0.getOpcode() == ISD::AND &&
15279 N0.getOperand(0).hasOneUse()) {
15280 SDValue N00 = N0.getOperand(0);
15281 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15283 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15284 if (!C || C->getZExtValue() != 1)
15286 return DAG.getNode(ISD::AND, dl, VT,
15287 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15288 N00.getOperand(0), N00.getOperand(1)),
15289 DAG.getConstant(1, VT));
15292 // Optimize vectors in AVX mode:
15295 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
15296 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
15297 // Concat upper and lower parts.
15300 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
15301 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
15302 // Concat upper and lower parts.
15304 if (!DCI.isBeforeLegalizeOps())
15307 if (!Subtarget->hasAVX())
15310 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15311 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
15313 if (Subtarget->hasAVX2())
15314 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15316 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15317 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15318 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15320 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15321 VT.getVectorNumElements()/2);
15323 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15324 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15326 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15332 // Optimize x == -y --> x+y == 0
15333 // x != -y --> x+y != 0
15334 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15335 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15336 SDValue LHS = N->getOperand(0);
15337 SDValue RHS = N->getOperand(1);
15339 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15340 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15341 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15342 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15343 LHS.getValueType(), RHS, LHS.getOperand(1));
15344 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15345 addV, DAG.getConstant(0, addV.getValueType()), CC);
15347 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15348 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15349 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15350 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15351 RHS.getValueType(), LHS, RHS.getOperand(1));
15352 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15353 addV, DAG.getConstant(0, addV.getValueType()), CC);
15358 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15359 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15360 DebugLoc DL = N->getDebugLoc();
15361 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15362 SDValue EFLAGS = N->getOperand(1);
15364 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15365 // a zext and produces an all-ones bit which is more useful than 0/1 in some
15367 if (CC == X86::COND_B)
15368 return DAG.getNode(ISD::AND, DL, MVT::i8,
15369 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15370 DAG.getConstant(CC, MVT::i8), EFLAGS),
15371 DAG.getConstant(1, MVT::i8));
15375 Flags = BoolTestSetCCCombine(EFLAGS, CC);
15376 if (Flags.getNode()) {
15377 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15378 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15384 // Optimize branch condition evaluation.
15386 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15387 TargetLowering::DAGCombinerInfo &DCI,
15388 const X86Subtarget *Subtarget) {
15389 DebugLoc DL = N->getDebugLoc();
15390 SDValue Chain = N->getOperand(0);
15391 SDValue Dest = N->getOperand(1);
15392 SDValue EFLAGS = N->getOperand(3);
15393 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15397 Flags = BoolTestSetCCCombine(EFLAGS, CC);
15398 if (Flags.getNode()) {
15399 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15400 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15407 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15408 SDValue Op0 = N->getOperand(0);
15409 EVT InVT = Op0->getValueType(0);
15411 // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15412 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15413 DebugLoc dl = N->getDebugLoc();
15414 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15415 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15416 // Notice that we use SINT_TO_FP because we know that the high bits
15417 // are zero and SINT_TO_FP is better supported by the hardware.
15418 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15424 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15425 const X86TargetLowering *XTLI) {
15426 SDValue Op0 = N->getOperand(0);
15427 EVT InVT = Op0->getValueType(0);
15429 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15430 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15431 DebugLoc dl = N->getDebugLoc();
15432 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15433 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15434 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15437 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15438 // a 32-bit target where SSE doesn't support i64->FP operations.
15439 if (Op0.getOpcode() == ISD::LOAD) {
15440 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15441 EVT VT = Ld->getValueType(0);
15442 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15443 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15444 !XTLI->getSubtarget()->is64Bit() &&
15445 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15446 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15447 Ld->getChain(), Op0, DAG);
15448 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15455 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15456 EVT VT = N->getValueType(0);
15458 // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15459 if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15460 DebugLoc dl = N->getDebugLoc();
15461 MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15462 SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15463 return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15469 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15470 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15471 X86TargetLowering::DAGCombinerInfo &DCI) {
15472 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15473 // the result is either zero or one (depending on the input carry bit).
15474 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15475 if (X86::isZeroNode(N->getOperand(0)) &&
15476 X86::isZeroNode(N->getOperand(1)) &&
15477 // We don't have a good way to replace an EFLAGS use, so only do this when
15479 SDValue(N, 1).use_empty()) {
15480 DebugLoc DL = N->getDebugLoc();
15481 EVT VT = N->getValueType(0);
15482 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15483 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15484 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15485 DAG.getConstant(X86::COND_B,MVT::i8),
15487 DAG.getConstant(1, VT));
15488 return DCI.CombineTo(N, Res1, CarryOut);
15494 // fold (add Y, (sete X, 0)) -> adc 0, Y
15495 // (add Y, (setne X, 0)) -> sbb -1, Y
15496 // (sub (sete X, 0), Y) -> sbb 0, Y
15497 // (sub (setne X, 0), Y) -> adc -1, Y
15498 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15499 DebugLoc DL = N->getDebugLoc();
15501 // Look through ZExts.
15502 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15503 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15506 SDValue SetCC = Ext.getOperand(0);
15507 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15510 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15511 if (CC != X86::COND_E && CC != X86::COND_NE)
15514 SDValue Cmp = SetCC.getOperand(1);
15515 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15516 !X86::isZeroNode(Cmp.getOperand(1)) ||
15517 !Cmp.getOperand(0).getValueType().isInteger())
15520 SDValue CmpOp0 = Cmp.getOperand(0);
15521 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15522 DAG.getConstant(1, CmpOp0.getValueType()));
15524 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15525 if (CC == X86::COND_NE)
15526 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15527 DL, OtherVal.getValueType(), OtherVal,
15528 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15529 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15530 DL, OtherVal.getValueType(), OtherVal,
15531 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15534 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15535 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15536 const X86Subtarget *Subtarget) {
15537 EVT VT = N->getValueType(0);
15538 SDValue Op0 = N->getOperand(0);
15539 SDValue Op1 = N->getOperand(1);
15541 // Try to synthesize horizontal adds from adds of shuffles.
15542 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15543 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15544 isHorizontalBinOp(Op0, Op1, true))
15545 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15547 return OptimizeConditionalInDecrement(N, DAG);
15550 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15551 const X86Subtarget *Subtarget) {
15552 SDValue Op0 = N->getOperand(0);
15553 SDValue Op1 = N->getOperand(1);
15555 // X86 can't encode an immediate LHS of a sub. See if we can push the
15556 // negation into a preceding instruction.
15557 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15558 // If the RHS of the sub is a XOR with one use and a constant, invert the
15559 // immediate. Then add one to the LHS of the sub so we can turn
15560 // X-Y -> X+~Y+1, saving one register.
15561 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15562 isa<ConstantSDNode>(Op1.getOperand(1))) {
15563 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15564 EVT VT = Op0.getValueType();
15565 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15567 DAG.getConstant(~XorC, VT));
15568 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15569 DAG.getConstant(C->getAPIntValue()+1, VT));
15573 // Try to synthesize horizontal adds from adds of shuffles.
15574 EVT VT = N->getValueType(0);
15575 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15576 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15577 isHorizontalBinOp(Op0, Op1, true))
15578 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15580 return OptimizeConditionalInDecrement(N, DAG);
15583 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15584 DAGCombinerInfo &DCI) const {
15585 SelectionDAG &DAG = DCI.DAG;
15586 switch (N->getOpcode()) {
15588 case ISD::EXTRACT_VECTOR_ELT:
15589 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15591 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15592 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
15593 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
15594 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
15595 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
15596 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
15599 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
15600 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
15601 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
15602 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
15603 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
15604 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
15605 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG);
15606 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
15607 case ISD::FP_TO_SINT: return PerformFP_TO_SINTCombine(N, DAG);
15608 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
15609 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
15611 case X86ISD::FOR: return PerformFORCombine(N, DAG);
15612 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
15613 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
15614 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
15615 case ISD::ANY_EXTEND:
15616 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
15617 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
15618 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG, DCI);
15619 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
15620 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
15621 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
15622 case X86ISD::SHUFP: // Handle all target specific shuffles
15623 case X86ISD::PALIGN:
15624 case X86ISD::UNPCKH:
15625 case X86ISD::UNPCKL:
15626 case X86ISD::MOVHLPS:
15627 case X86ISD::MOVLHPS:
15628 case X86ISD::PSHUFD:
15629 case X86ISD::PSHUFHW:
15630 case X86ISD::PSHUFLW:
15631 case X86ISD::MOVSS:
15632 case X86ISD::MOVSD:
15633 case X86ISD::VPERMILP:
15634 case X86ISD::VPERM2X128:
15635 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
15636 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
15642 /// isTypeDesirableForOp - Return true if the target has native support for
15643 /// the specified value type and it is 'desirable' to use the type for the
15644 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
15645 /// instruction encodings are longer and some i16 instructions are slow.
15646 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
15647 if (!isTypeLegal(VT))
15649 if (VT != MVT::i16)
15656 case ISD::SIGN_EXTEND:
15657 case ISD::ZERO_EXTEND:
15658 case ISD::ANY_EXTEND:
15671 /// IsDesirableToPromoteOp - This method query the target whether it is
15672 /// beneficial for dag combiner to promote the specified node. If true, it
15673 /// should return the desired promotion type by reference.
15674 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
15675 EVT VT = Op.getValueType();
15676 if (VT != MVT::i16)
15679 bool Promote = false;
15680 bool Commute = false;
15681 switch (Op.getOpcode()) {
15684 LoadSDNode *LD = cast<LoadSDNode>(Op);
15685 // If the non-extending load has a single use and it's not live out, then it
15686 // might be folded.
15687 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
15688 Op.hasOneUse()*/) {
15689 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15690 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
15691 // The only case where we'd want to promote LOAD (rather then it being
15692 // promoted as an operand is when it's only use is liveout.
15693 if (UI->getOpcode() != ISD::CopyToReg)
15700 case ISD::SIGN_EXTEND:
15701 case ISD::ZERO_EXTEND:
15702 case ISD::ANY_EXTEND:
15707 SDValue N0 = Op.getOperand(0);
15708 // Look out for (store (shl (load), x)).
15709 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
15722 SDValue N0 = Op.getOperand(0);
15723 SDValue N1 = Op.getOperand(1);
15724 if (!Commute && MayFoldLoad(N1))
15726 // Avoid disabling potential load folding opportunities.
15727 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15729 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15739 //===----------------------------------------------------------------------===//
15740 // X86 Inline Assembly Support
15741 //===----------------------------------------------------------------------===//
15744 // Helper to match a string separated by whitespace.
15745 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
15746 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
15748 for (unsigned i = 0, e = args.size(); i != e; ++i) {
15749 StringRef piece(*args[i]);
15750 if (!s.startswith(piece)) // Check if the piece matches.
15753 s = s.substr(piece.size());
15754 StringRef::size_type pos = s.find_first_not_of(" \t");
15755 if (pos == 0) // We matched a prefix.
15763 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
15766 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15767 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15769 std::string AsmStr = IA->getAsmString();
15771 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15772 if (!Ty || Ty->getBitWidth() % 16 != 0)
15775 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15776 SmallVector<StringRef, 4> AsmPieces;
15777 SplitString(AsmStr, AsmPieces, ";\n");
15779 switch (AsmPieces.size()) {
15780 default: return false;
15782 // FIXME: this should verify that we are targeting a 486 or better. If not,
15783 // we will turn this bswap into something that will be lowered to logical
15784 // ops instead of emitting the bswap asm. For now, we don't support 486 or
15785 // lower so don't worry about this.
15787 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
15788 matchAsm(AsmPieces[0], "bswapl", "$0") ||
15789 matchAsm(AsmPieces[0], "bswapq", "$0") ||
15790 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
15791 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
15792 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
15793 // No need to check constraints, nothing other than the equivalent of
15794 // "=r,0" would be valid here.
15795 return IntrinsicLowering::LowerToByteSwap(CI);
15798 // rorw $$8, ${0:w} --> llvm.bswap.i16
15799 if (CI->getType()->isIntegerTy(16) &&
15800 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15801 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
15802 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
15804 const std::string &ConstraintsStr = IA->getConstraintString();
15805 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15806 std::sort(AsmPieces.begin(), AsmPieces.end());
15807 if (AsmPieces.size() == 4 &&
15808 AsmPieces[0] == "~{cc}" &&
15809 AsmPieces[1] == "~{dirflag}" &&
15810 AsmPieces[2] == "~{flags}" &&
15811 AsmPieces[3] == "~{fpsr}")
15812 return IntrinsicLowering::LowerToByteSwap(CI);
15816 if (CI->getType()->isIntegerTy(32) &&
15817 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15818 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
15819 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
15820 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
15822 const std::string &ConstraintsStr = IA->getConstraintString();
15823 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15824 std::sort(AsmPieces.begin(), AsmPieces.end());
15825 if (AsmPieces.size() == 4 &&
15826 AsmPieces[0] == "~{cc}" &&
15827 AsmPieces[1] == "~{dirflag}" &&
15828 AsmPieces[2] == "~{flags}" &&
15829 AsmPieces[3] == "~{fpsr}")
15830 return IntrinsicLowering::LowerToByteSwap(CI);
15833 if (CI->getType()->isIntegerTy(64)) {
15834 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15835 if (Constraints.size() >= 2 &&
15836 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15837 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15838 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
15839 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
15840 matchAsm(AsmPieces[1], "bswap", "%edx") &&
15841 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
15842 return IntrinsicLowering::LowerToByteSwap(CI);
15852 /// getConstraintType - Given a constraint letter, return the type of
15853 /// constraint it is for this target.
15854 X86TargetLowering::ConstraintType
15855 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15856 if (Constraint.size() == 1) {
15857 switch (Constraint[0]) {
15868 return C_RegisterClass;
15892 return TargetLowering::getConstraintType(Constraint);
15895 /// Examine constraint type and operand type and determine a weight value.
15896 /// This object must already have been set up with the operand type
15897 /// and the current alternative constraint selected.
15898 TargetLowering::ConstraintWeight
15899 X86TargetLowering::getSingleConstraintMatchWeight(
15900 AsmOperandInfo &info, const char *constraint) const {
15901 ConstraintWeight weight = CW_Invalid;
15902 Value *CallOperandVal = info.CallOperandVal;
15903 // If we don't have a value, we can't do a match,
15904 // but allow it at the lowest weight.
15905 if (CallOperandVal == NULL)
15907 Type *type = CallOperandVal->getType();
15908 // Look at the constraint type.
15909 switch (*constraint) {
15911 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15922 if (CallOperandVal->getType()->isIntegerTy())
15923 weight = CW_SpecificReg;
15928 if (type->isFloatingPointTy())
15929 weight = CW_SpecificReg;
15932 if (type->isX86_MMXTy() && Subtarget->hasMMX())
15933 weight = CW_SpecificReg;
15937 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
15938 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
15939 weight = CW_Register;
15942 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15943 if (C->getZExtValue() <= 31)
15944 weight = CW_Constant;
15948 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15949 if (C->getZExtValue() <= 63)
15950 weight = CW_Constant;
15954 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15955 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15956 weight = CW_Constant;
15960 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15961 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15962 weight = CW_Constant;
15966 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15967 if (C->getZExtValue() <= 3)
15968 weight = CW_Constant;
15972 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15973 if (C->getZExtValue() <= 0xff)
15974 weight = CW_Constant;
15979 if (dyn_cast<ConstantFP>(CallOperandVal)) {
15980 weight = CW_Constant;
15984 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15985 if ((C->getSExtValue() >= -0x80000000LL) &&
15986 (C->getSExtValue() <= 0x7fffffffLL))
15987 weight = CW_Constant;
15991 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15992 if (C->getZExtValue() <= 0xffffffff)
15993 weight = CW_Constant;
16000 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16001 /// with another that has more specific requirements based on the type of the
16002 /// corresponding operand.
16003 const char *X86TargetLowering::
16004 LowerXConstraint(EVT ConstraintVT) const {
16005 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16006 // 'f' like normal targets.
16007 if (ConstraintVT.isFloatingPoint()) {
16008 if (Subtarget->hasSSE2())
16010 if (Subtarget->hasSSE1())
16014 return TargetLowering::LowerXConstraint(ConstraintVT);
16017 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16018 /// vector. If it is invalid, don't add anything to Ops.
16019 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16020 std::string &Constraint,
16021 std::vector<SDValue>&Ops,
16022 SelectionDAG &DAG) const {
16023 SDValue Result(0, 0);
16025 // Only support length 1 constraints for now.
16026 if (Constraint.length() > 1) return;
16028 char ConstraintLetter = Constraint[0];
16029 switch (ConstraintLetter) {
16032 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16033 if (C->getZExtValue() <= 31) {
16034 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16040 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16041 if (C->getZExtValue() <= 63) {
16042 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16048 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16049 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16050 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16056 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16057 if (C->getZExtValue() <= 255) {
16058 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16064 // 32-bit signed value
16065 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16066 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16067 C->getSExtValue())) {
16068 // Widen to 64 bits here to get it sign extended.
16069 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16072 // FIXME gcc accepts some relocatable values here too, but only in certain
16073 // memory models; it's complicated.
16078 // 32-bit unsigned value
16079 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16080 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16081 C->getZExtValue())) {
16082 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16086 // FIXME gcc accepts some relocatable values here too, but only in certain
16087 // memory models; it's complicated.
16091 // Literal immediates are always ok.
16092 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16093 // Widen to 64 bits here to get it sign extended.
16094 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16098 // In any sort of PIC mode addresses need to be computed at runtime by
16099 // adding in a register or some sort of table lookup. These can't
16100 // be used as immediates.
16101 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16104 // If we are in non-pic codegen mode, we allow the address of a global (with
16105 // an optional displacement) to be used with 'i'.
16106 GlobalAddressSDNode *GA = 0;
16107 int64_t Offset = 0;
16109 // Match either (GA), (GA+C), (GA+C1+C2), etc.
16111 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16112 Offset += GA->getOffset();
16114 } else if (Op.getOpcode() == ISD::ADD) {
16115 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16116 Offset += C->getZExtValue();
16117 Op = Op.getOperand(0);
16120 } else if (Op.getOpcode() == ISD::SUB) {
16121 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16122 Offset += -C->getZExtValue();
16123 Op = Op.getOperand(0);
16128 // Otherwise, this isn't something we can handle, reject it.
16132 const GlobalValue *GV = GA->getGlobal();
16133 // If we require an extra load to get this address, as in PIC mode, we
16134 // can't accept it.
16135 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16136 getTargetMachine())))
16139 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16140 GA->getValueType(0), Offset);
16145 if (Result.getNode()) {
16146 Ops.push_back(Result);
16149 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16152 std::pair<unsigned, const TargetRegisterClass*>
16153 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16155 // First, see if this is a constraint that directly corresponds to an LLVM
16157 if (Constraint.size() == 1) {
16158 // GCC Constraint Letters
16159 switch (Constraint[0]) {
16161 // TODO: Slight differences here in allocation order and leaving
16162 // RIP in the class. Do they matter any more here than they do
16163 // in the normal allocation?
16164 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16165 if (Subtarget->is64Bit()) {
16166 if (VT == MVT::i32 || VT == MVT::f32)
16167 return std::make_pair(0U, &X86::GR32RegClass);
16168 if (VT == MVT::i16)
16169 return std::make_pair(0U, &X86::GR16RegClass);
16170 if (VT == MVT::i8 || VT == MVT::i1)
16171 return std::make_pair(0U, &X86::GR8RegClass);
16172 if (VT == MVT::i64 || VT == MVT::f64)
16173 return std::make_pair(0U, &X86::GR64RegClass);
16176 // 32-bit fallthrough
16177 case 'Q': // Q_REGS
16178 if (VT == MVT::i32 || VT == MVT::f32)
16179 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16180 if (VT == MVT::i16)
16181 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16182 if (VT == MVT::i8 || VT == MVT::i1)
16183 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16184 if (VT == MVT::i64)
16185 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16187 case 'r': // GENERAL_REGS
16188 case 'l': // INDEX_REGS
16189 if (VT == MVT::i8 || VT == MVT::i1)
16190 return std::make_pair(0U, &X86::GR8RegClass);
16191 if (VT == MVT::i16)
16192 return std::make_pair(0U, &X86::GR16RegClass);
16193 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16194 return std::make_pair(0U, &X86::GR32RegClass);
16195 return std::make_pair(0U, &X86::GR64RegClass);
16196 case 'R': // LEGACY_REGS
16197 if (VT == MVT::i8 || VT == MVT::i1)
16198 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16199 if (VT == MVT::i16)
16200 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16201 if (VT == MVT::i32 || !Subtarget->is64Bit())
16202 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16203 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16204 case 'f': // FP Stack registers.
16205 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16206 // value to the correct fpstack register class.
16207 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16208 return std::make_pair(0U, &X86::RFP32RegClass);
16209 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16210 return std::make_pair(0U, &X86::RFP64RegClass);
16211 return std::make_pair(0U, &X86::RFP80RegClass);
16212 case 'y': // MMX_REGS if MMX allowed.
16213 if (!Subtarget->hasMMX()) break;
16214 return std::make_pair(0U, &X86::VR64RegClass);
16215 case 'Y': // SSE_REGS if SSE2 allowed
16216 if (!Subtarget->hasSSE2()) break;
16218 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16219 if (!Subtarget->hasSSE1()) break;
16221 switch (VT.getSimpleVT().SimpleTy) {
16223 // Scalar SSE types.
16226 return std::make_pair(0U, &X86::FR32RegClass);
16229 return std::make_pair(0U, &X86::FR64RegClass);
16237 return std::make_pair(0U, &X86::VR128RegClass);
16245 return std::make_pair(0U, &X86::VR256RegClass);
16251 // Use the default implementation in TargetLowering to convert the register
16252 // constraint into a member of a register class.
16253 std::pair<unsigned, const TargetRegisterClass*> Res;
16254 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16256 // Not found as a standard register?
16257 if (Res.second == 0) {
16258 // Map st(0) -> st(7) -> ST0
16259 if (Constraint.size() == 7 && Constraint[0] == '{' &&
16260 tolower(Constraint[1]) == 's' &&
16261 tolower(Constraint[2]) == 't' &&
16262 Constraint[3] == '(' &&
16263 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16264 Constraint[5] == ')' &&
16265 Constraint[6] == '}') {
16267 Res.first = X86::ST0+Constraint[4]-'0';
16268 Res.second = &X86::RFP80RegClass;
16272 // GCC allows "st(0)" to be called just plain "st".
16273 if (StringRef("{st}").equals_lower(Constraint)) {
16274 Res.first = X86::ST0;
16275 Res.second = &X86::RFP80RegClass;
16280 if (StringRef("{flags}").equals_lower(Constraint)) {
16281 Res.first = X86::EFLAGS;
16282 Res.second = &X86::CCRRegClass;
16286 // 'A' means EAX + EDX.
16287 if (Constraint == "A") {
16288 Res.first = X86::EAX;
16289 Res.second = &X86::GR32_ADRegClass;
16295 // Otherwise, check to see if this is a register class of the wrong value
16296 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16297 // turn into {ax},{dx}.
16298 if (Res.second->hasType(VT))
16299 return Res; // Correct type already, nothing to do.
16301 // All of the single-register GCC register classes map their values onto
16302 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
16303 // really want an 8-bit or 32-bit register, map to the appropriate register
16304 // class and return the appropriate register.
16305 if (Res.second == &X86::GR16RegClass) {
16306 if (VT == MVT::i8) {
16307 unsigned DestReg = 0;
16308 switch (Res.first) {
16310 case X86::AX: DestReg = X86::AL; break;
16311 case X86::DX: DestReg = X86::DL; break;
16312 case X86::CX: DestReg = X86::CL; break;
16313 case X86::BX: DestReg = X86::BL; break;
16316 Res.first = DestReg;
16317 Res.second = &X86::GR8RegClass;
16319 } else if (VT == MVT::i32) {
16320 unsigned DestReg = 0;
16321 switch (Res.first) {
16323 case X86::AX: DestReg = X86::EAX; break;
16324 case X86::DX: DestReg = X86::EDX; break;
16325 case X86::CX: DestReg = X86::ECX; break;
16326 case X86::BX: DestReg = X86::EBX; break;
16327 case X86::SI: DestReg = X86::ESI; break;
16328 case X86::DI: DestReg = X86::EDI; break;
16329 case X86::BP: DestReg = X86::EBP; break;
16330 case X86::SP: DestReg = X86::ESP; break;
16333 Res.first = DestReg;
16334 Res.second = &X86::GR32RegClass;
16336 } else if (VT == MVT::i64) {
16337 unsigned DestReg = 0;
16338 switch (Res.first) {
16340 case X86::AX: DestReg = X86::RAX; break;
16341 case X86::DX: DestReg = X86::RDX; break;
16342 case X86::CX: DestReg = X86::RCX; break;
16343 case X86::BX: DestReg = X86::RBX; break;
16344 case X86::SI: DestReg = X86::RSI; break;
16345 case X86::DI: DestReg = X86::RDI; break;
16346 case X86::BP: DestReg = X86::RBP; break;
16347 case X86::SP: DestReg = X86::RSP; break;
16350 Res.first = DestReg;
16351 Res.second = &X86::GR64RegClass;
16354 } else if (Res.second == &X86::FR32RegClass ||
16355 Res.second == &X86::FR64RegClass ||
16356 Res.second == &X86::VR128RegClass) {
16357 // Handle references to XMM physical registers that got mapped into the
16358 // wrong class. This can happen with constraints like {xmm0} where the
16359 // target independent register mapper will just pick the first match it can
16360 // find, ignoring the required type.
16362 if (VT == MVT::f32 || VT == MVT::i32)
16363 Res.second = &X86::FR32RegClass;
16364 else if (VT == MVT::f64 || VT == MVT::i64)
16365 Res.second = &X86::FR64RegClass;
16366 else if (X86::VR128RegClass.hasType(VT))
16367 Res.second = &X86::VR128RegClass;
16368 else if (X86::VR256RegClass.hasType(VT))
16369 Res.second = &X86::VR256RegClass;