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.is256BitVector() && "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.getIntPtrConstant(NormalizedIdxVal);
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.is128BitVector() && "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.getIntPtrConstant(NormalizedIdxVal);
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 = getDataLayout();
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 // Bypass i32 with i8 on Atom when compiling with O2
186 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
187 addBypassSlowDiv(32, 8);
189 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
190 // Setup Windows compiler runtime calls.
191 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
192 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
193 setLibcallName(RTLIB::SREM_I64, "_allrem");
194 setLibcallName(RTLIB::UREM_I64, "_aullrem");
195 setLibcallName(RTLIB::MUL_I64, "_allmul");
196 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
197 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
198 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
199 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
200 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
202 // The _ftol2 runtime function has an unusual calling conv, which
203 // is modeled by a special pseudo-instruction.
204 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
205 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
206 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
207 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
210 if (Subtarget->isTargetDarwin()) {
211 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
212 setUseUnderscoreSetJmp(false);
213 setUseUnderscoreLongJmp(false);
214 } else if (Subtarget->isTargetMingw()) {
215 // MS runtime is weird: it exports _setjmp, but longjmp!
216 setUseUnderscoreSetJmp(true);
217 setUseUnderscoreLongJmp(false);
219 setUseUnderscoreSetJmp(true);
220 setUseUnderscoreLongJmp(true);
223 // Set up the register classes.
224 addRegisterClass(MVT::i8, &X86::GR8RegClass);
225 addRegisterClass(MVT::i16, &X86::GR16RegClass);
226 addRegisterClass(MVT::i32, &X86::GR32RegClass);
227 if (Subtarget->is64Bit())
228 addRegisterClass(MVT::i64, &X86::GR64RegClass);
230 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
232 // We don't accept any truncstore of integer registers.
233 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
234 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
235 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
236 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
237 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
238 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
240 // SETOEQ and SETUNE require checking two conditions.
241 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
242 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
243 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
244 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
245 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
246 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
248 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
250 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
251 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
252 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
254 if (Subtarget->is64Bit()) {
255 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
256 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
257 } else if (!TM.Options.UseSoftFloat) {
258 // We have an algorithm for SSE2->double, and we turn this into a
259 // 64-bit FILD followed by conditional FADD for other targets.
260 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
261 // We have an algorithm for SSE2, and we turn this into a 64-bit
262 // FILD for other targets.
263 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
266 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
268 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
269 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
271 if (!TM.Options.UseSoftFloat) {
272 // SSE has no i16 to fp conversion, only i32
273 if (X86ScalarSSEf32) {
274 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
275 // f32 and f64 cases are Legal, f80 case is not
276 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
278 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
279 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
283 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
286 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
287 // are Legal, f80 is custom lowered.
288 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
289 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
291 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
293 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
294 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
296 if (X86ScalarSSEf32) {
297 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
298 // f32 and f64 cases are Legal, f80 case is not
299 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
301 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
302 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
305 // Handle FP_TO_UINT by promoting the destination to a larger signed
307 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
308 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
309 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
311 if (Subtarget->is64Bit()) {
312 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
313 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
314 } else if (!TM.Options.UseSoftFloat) {
315 // Since AVX is a superset of SSE3, only check for SSE here.
316 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
317 // Expand FP_TO_UINT into a select.
318 // FIXME: We would like to use a Custom expander here eventually to do
319 // the optimal thing for SSE vs. the default expansion in the legalizer.
320 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
322 // With SSE3 we can use fisttpll to convert to a signed i64; without
323 // SSE, we're stuck with a fistpll.
324 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
327 if (isTargetFTOL()) {
328 // Use the _ftol2 runtime function, which has a pseudo-instruction
329 // to handle its weird calling convention.
330 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
333 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
334 if (!X86ScalarSSEf64) {
335 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
336 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
337 if (Subtarget->is64Bit()) {
338 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
339 // Without SSE, i64->f64 goes through memory.
340 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
344 // Scalar integer divide and remainder are lowered to use operations that
345 // produce two results, to match the available instructions. This exposes
346 // the two-result form to trivial CSE, which is able to combine x/y and x%y
347 // into a single instruction.
349 // Scalar integer multiply-high is also lowered to use two-result
350 // operations, to match the available instructions. However, plain multiply
351 // (low) operations are left as Legal, as there are single-result
352 // instructions for this in x86. Using the two-result multiply instructions
353 // when both high and low results are needed must be arranged by dagcombine.
354 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
356 setOperationAction(ISD::MULHS, VT, Expand);
357 setOperationAction(ISD::MULHU, VT, Expand);
358 setOperationAction(ISD::SDIV, VT, Expand);
359 setOperationAction(ISD::UDIV, VT, Expand);
360 setOperationAction(ISD::SREM, VT, Expand);
361 setOperationAction(ISD::UREM, VT, Expand);
363 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
364 setOperationAction(ISD::ADDC, VT, Custom);
365 setOperationAction(ISD::ADDE, VT, Custom);
366 setOperationAction(ISD::SUBC, VT, Custom);
367 setOperationAction(ISD::SUBE, VT, Custom);
370 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
371 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
372 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
373 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
374 if (Subtarget->is64Bit())
375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
376 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
377 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
378 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
379 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
380 setOperationAction(ISD::FREM , MVT::f32 , Expand);
381 setOperationAction(ISD::FREM , MVT::f64 , Expand);
382 setOperationAction(ISD::FREM , MVT::f80 , Expand);
383 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
385 // Promote the i8 variants and force them on up to i32 which has a shorter
387 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
388 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
389 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
390 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
391 if (Subtarget->hasBMI()) {
392 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
393 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
394 if (Subtarget->is64Bit())
395 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
397 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
398 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
399 if (Subtarget->is64Bit())
400 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
403 if (Subtarget->hasLZCNT()) {
404 // When promoting the i8 variants, force them to i32 for a shorter
406 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
407 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
408 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
409 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
410 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
411 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
412 if (Subtarget->is64Bit())
413 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
415 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
416 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
417 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
418 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
419 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
420 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
421 if (Subtarget->is64Bit()) {
422 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
423 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
427 if (Subtarget->hasPOPCNT()) {
428 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
430 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
431 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
432 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
433 if (Subtarget->is64Bit())
434 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
437 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
438 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
440 // These should be promoted to a larger select which is supported.
441 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
442 // X86 wants to expand cmov itself.
443 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
444 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
445 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
446 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
447 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
448 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
449 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
450 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
451 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
452 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
453 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
454 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
455 if (Subtarget->is64Bit()) {
456 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
457 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
459 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
462 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
463 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
464 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
465 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
466 if (Subtarget->is64Bit())
467 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
468 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
469 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
470 if (Subtarget->is64Bit()) {
471 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
472 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
473 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
474 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
475 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
477 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
478 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
479 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
480 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
481 if (Subtarget->is64Bit()) {
482 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
483 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
484 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
487 if (Subtarget->hasSSE1())
488 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
490 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
491 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
493 // On X86 and X86-64, atomic operations are lowered to locked instructions.
494 // Locked instructions, in turn, have implicit fence semantics (all memory
495 // operations are flushed before issuing the locked instruction, and they
496 // are not buffered), so we can fold away the common pattern of
497 // fence-atomic-fence.
498 setShouldFoldAtomicFences(true);
500 // Expand certain atomics
501 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
503 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
504 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
505 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
508 if (!Subtarget->is64Bit()) {
509 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
510 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
511 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
512 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
513 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
514 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
515 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
516 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
517 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
518 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
519 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
520 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
523 if (Subtarget->hasCmpxchg16b()) {
524 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
527 // FIXME - use subtarget debug flags
528 if (!Subtarget->isTargetDarwin() &&
529 !Subtarget->isTargetELF() &&
530 !Subtarget->isTargetCygMing()) {
531 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
534 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
535 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
536 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
537 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
538 if (Subtarget->is64Bit()) {
539 setExceptionPointerRegister(X86::RAX);
540 setExceptionSelectorRegister(X86::RDX);
542 setExceptionPointerRegister(X86::EAX);
543 setExceptionSelectorRegister(X86::EDX);
545 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
546 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
548 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
549 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
551 setOperationAction(ISD::TRAP, MVT::Other, Legal);
553 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
554 setOperationAction(ISD::VASTART , MVT::Other, Custom);
555 setOperationAction(ISD::VAEND , MVT::Other, Expand);
556 if (Subtarget->is64Bit()) {
557 setOperationAction(ISD::VAARG , MVT::Other, Custom);
558 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
560 setOperationAction(ISD::VAARG , MVT::Other, Expand);
561 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
564 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
565 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
567 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
568 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
569 MVT::i64 : MVT::i32, Custom);
570 else if (TM.Options.EnableSegmentedStacks)
571 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
572 MVT::i64 : MVT::i32, Custom);
574 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
575 MVT::i64 : MVT::i32, Expand);
577 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
578 // f32 and f64 use SSE.
579 // Set up the FP register classes.
580 addRegisterClass(MVT::f32, &X86::FR32RegClass);
581 addRegisterClass(MVT::f64, &X86::FR64RegClass);
583 // Use ANDPD to simulate FABS.
584 setOperationAction(ISD::FABS , MVT::f64, Custom);
585 setOperationAction(ISD::FABS , MVT::f32, Custom);
587 // Use XORP to simulate FNEG.
588 setOperationAction(ISD::FNEG , MVT::f64, Custom);
589 setOperationAction(ISD::FNEG , MVT::f32, Custom);
591 // Use ANDPD and ORPD to simulate FCOPYSIGN.
592 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
593 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
595 // Lower this to FGETSIGNx86 plus an AND.
596 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
597 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
599 // We don't support sin/cos/fmod
600 setOperationAction(ISD::FSIN , MVT::f64, Expand);
601 setOperationAction(ISD::FCOS , MVT::f64, Expand);
602 setOperationAction(ISD::FSIN , MVT::f32, Expand);
603 setOperationAction(ISD::FCOS , MVT::f32, Expand);
605 // Expand FP immediates into loads from the stack, except for the special
607 addLegalFPImmediate(APFloat(+0.0)); // xorpd
608 addLegalFPImmediate(APFloat(+0.0f)); // xorps
609 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
610 // Use SSE for f32, x87 for f64.
611 // Set up the FP register classes.
612 addRegisterClass(MVT::f32, &X86::FR32RegClass);
613 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
615 // Use ANDPS to simulate FABS.
616 setOperationAction(ISD::FABS , MVT::f32, Custom);
618 // Use XORP to simulate FNEG.
619 setOperationAction(ISD::FNEG , MVT::f32, Custom);
621 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
623 // Use ANDPS and ORPS to simulate FCOPYSIGN.
624 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
625 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
627 // We don't support sin/cos/fmod
628 setOperationAction(ISD::FSIN , MVT::f32, Expand);
629 setOperationAction(ISD::FCOS , MVT::f32, Expand);
631 // Special cases we handle for FP constants.
632 addLegalFPImmediate(APFloat(+0.0f)); // xorps
633 addLegalFPImmediate(APFloat(+0.0)); // FLD0
634 addLegalFPImmediate(APFloat(+1.0)); // FLD1
635 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
636 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
638 if (!TM.Options.UnsafeFPMath) {
639 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
640 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
642 } else if (!TM.Options.UseSoftFloat) {
643 // f32 and f64 in x87.
644 // Set up the FP register classes.
645 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
646 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
648 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
649 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
650 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
651 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
653 if (!TM.Options.UnsafeFPMath) {
654 setOperationAction(ISD::FSIN , MVT::f32 , Expand);
655 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
656 setOperationAction(ISD::FCOS , MVT::f32 , Expand);
657 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
659 addLegalFPImmediate(APFloat(+0.0)); // FLD0
660 addLegalFPImmediate(APFloat(+1.0)); // FLD1
661 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
662 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
663 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
664 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
665 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
666 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
669 // We don't support FMA.
670 setOperationAction(ISD::FMA, MVT::f64, Expand);
671 setOperationAction(ISD::FMA, MVT::f32, Expand);
673 // Long double always uses X87.
674 if (!TM.Options.UseSoftFloat) {
675 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
676 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
677 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
679 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
680 addLegalFPImmediate(TmpFlt); // FLD0
682 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
685 APFloat TmpFlt2(+1.0);
686 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
688 addLegalFPImmediate(TmpFlt2); // FLD1
689 TmpFlt2.changeSign();
690 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
693 if (!TM.Options.UnsafeFPMath) {
694 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
695 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
698 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
699 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
700 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
701 setOperationAction(ISD::FRINT, MVT::f80, Expand);
702 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
703 setOperationAction(ISD::FMA, MVT::f80, Expand);
706 // Always use a library call for pow.
707 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
708 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
709 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
711 setOperationAction(ISD::FLOG, MVT::f80, Expand);
712 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
713 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
714 setOperationAction(ISD::FEXP, MVT::f80, Expand);
715 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
717 // First set operation action for all vector types to either promote
718 // (for widening) or expand (for scalarization). Then we will selectively
719 // turn on ones that can be effectively codegen'd.
720 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
721 VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
722 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
737 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
739 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
740 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::FMA, (MVT::SimpleValueType)VT, Expand);
745 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
746 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
747 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
748 setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
749 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
751 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
753 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
756 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
757 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
758 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
759 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
760 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
761 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
762 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
763 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
764 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
765 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
766 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
767 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
768 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
769 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
770 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
771 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
772 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
773 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
774 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
775 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
776 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
777 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
778 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
779 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
780 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
781 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
782 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
783 setTruncStoreAction((MVT::SimpleValueType)VT,
784 (MVT::SimpleValueType)InnerVT, Expand);
785 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
786 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
787 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
790 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
791 // with -msoft-float, disable use of MMX as well.
792 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
793 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
794 // No operations on x86mmx supported, everything uses intrinsics.
797 // MMX-sized vectors (other than x86mmx) are expected to be expanded
798 // into smaller operations.
799 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
800 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
801 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
802 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
803 setOperationAction(ISD::AND, MVT::v8i8, Expand);
804 setOperationAction(ISD::AND, MVT::v4i16, Expand);
805 setOperationAction(ISD::AND, MVT::v2i32, Expand);
806 setOperationAction(ISD::AND, MVT::v1i64, Expand);
807 setOperationAction(ISD::OR, MVT::v8i8, Expand);
808 setOperationAction(ISD::OR, MVT::v4i16, Expand);
809 setOperationAction(ISD::OR, MVT::v2i32, Expand);
810 setOperationAction(ISD::OR, MVT::v1i64, Expand);
811 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
812 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
813 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
814 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
815 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
816 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
817 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
818 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
819 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
820 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
821 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
822 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
823 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
824 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
825 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
826 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
827 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
829 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
830 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
832 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
833 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
834 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
835 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
836 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
837 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
838 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
839 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
840 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
841 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
842 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
843 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
846 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
847 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
849 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
850 // registers cannot be used even for integer operations.
851 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
852 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
853 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
854 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
856 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
857 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
858 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
859 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
860 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
861 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
862 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
863 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
864 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
865 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
866 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
867 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
868 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
869 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
870 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
871 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
872 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
874 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
875 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
876 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
877 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
879 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
880 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
881 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
882 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
883 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
885 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
886 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
887 MVT VT = (MVT::SimpleValueType)i;
888 // Do not attempt to custom lower non-power-of-2 vectors
889 if (!isPowerOf2_32(VT.getVectorNumElements()))
891 // Do not attempt to custom lower non-128-bit vectors
892 if (!VT.is128BitVector())
894 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
895 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
896 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
899 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
900 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
901 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
902 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
903 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
904 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
906 if (Subtarget->is64Bit()) {
907 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
908 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
911 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
912 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
913 MVT VT = (MVT::SimpleValueType)i;
915 // Do not attempt to promote non-128-bit vectors
916 if (!VT.is128BitVector())
919 setOperationAction(ISD::AND, VT, Promote);
920 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
921 setOperationAction(ISD::OR, VT, Promote);
922 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
923 setOperationAction(ISD::XOR, VT, Promote);
924 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
925 setOperationAction(ISD::LOAD, VT, Promote);
926 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
927 setOperationAction(ISD::SELECT, VT, Promote);
928 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
931 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
933 // Custom lower v2i64 and v2f64 selects.
934 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
935 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
936 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
937 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
939 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
940 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
942 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
945 if (Subtarget->hasSSE41()) {
946 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
947 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
948 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
949 setOperationAction(ISD::FRINT, MVT::f32, Legal);
950 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
951 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
952 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
953 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
954 setOperationAction(ISD::FRINT, MVT::f64, Legal);
955 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
957 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
958 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
960 // FIXME: Do we need to handle scalar-to-vector here?
961 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
963 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
964 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
965 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
966 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
967 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
969 // i8 and i16 vectors are custom , because the source register and source
970 // source memory operand types are not the same width. f32 vectors are
971 // custom since the immediate controlling the insert encodes additional
973 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
974 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
975 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
976 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
978 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
979 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
980 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
981 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
983 // FIXME: these should be Legal but thats only for the case where
984 // the index is constant. For now custom expand to deal with that.
985 if (Subtarget->is64Bit()) {
986 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
987 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
991 if (Subtarget->hasSSE2()) {
992 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
993 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
995 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
996 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
998 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
999 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1001 if (Subtarget->hasAVX2()) {
1002 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1003 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
1005 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1006 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1008 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1010 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1011 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1013 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1014 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1016 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1020 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1021 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1022 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1023 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1024 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1025 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1026 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1028 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1029 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1030 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1032 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1033 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1034 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1035 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1036 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1037 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1038 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1039 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1041 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1042 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1043 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1044 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1045 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1046 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1047 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1048 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1050 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1051 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1052 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1054 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1056 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1057 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1059 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1060 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1062 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1063 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1065 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1066 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1067 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1068 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1070 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1071 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1072 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1074 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1075 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1076 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1077 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1079 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1080 setOperationAction(ISD::FMA, MVT::v8f32, Custom);
1081 setOperationAction(ISD::FMA, MVT::v4f64, Custom);
1082 setOperationAction(ISD::FMA, MVT::v4f32, Custom);
1083 setOperationAction(ISD::FMA, MVT::v2f64, Custom);
1084 setOperationAction(ISD::FMA, MVT::f32, Custom);
1085 setOperationAction(ISD::FMA, MVT::f64, Custom);
1088 if (Subtarget->hasAVX2()) {
1089 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1090 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1091 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1092 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1094 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1095 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1096 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1097 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1099 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1100 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1101 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1102 // Don't lower v32i8 because there is no 128-bit byte mul
1104 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1106 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1107 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1109 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1110 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1112 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1114 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1115 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1116 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1117 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1119 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1120 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1121 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1122 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1124 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1125 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1126 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1127 // Don't lower v32i8 because there is no 128-bit byte mul
1129 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1130 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1132 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1133 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1135 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1138 // Custom lower several nodes for 256-bit types.
1139 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1140 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1141 MVT VT = (MVT::SimpleValueType)i;
1143 // Extract subvector is special because the value type
1144 // (result) is 128-bit but the source is 256-bit wide.
1145 if (VT.is128BitVector())
1146 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1148 // Do not attempt to custom lower other non-256-bit vectors
1149 if (!VT.is256BitVector())
1152 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1153 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1154 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1155 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1156 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1157 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1158 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1161 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1162 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1163 MVT VT = (MVT::SimpleValueType)i;
1165 // Do not attempt to promote non-256-bit vectors
1166 if (!VT.is256BitVector())
1169 setOperationAction(ISD::AND, VT, Promote);
1170 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1171 setOperationAction(ISD::OR, VT, Promote);
1172 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1173 setOperationAction(ISD::XOR, VT, Promote);
1174 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1175 setOperationAction(ISD::LOAD, VT, Promote);
1176 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1177 setOperationAction(ISD::SELECT, VT, Promote);
1178 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1182 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1183 // of this type with custom code.
1184 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1185 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1186 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1190 // We want to custom lower some of our intrinsics.
1191 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1192 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1195 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1196 // handle type legalization for these operations here.
1198 // FIXME: We really should do custom legalization for addition and
1199 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1200 // than generic legalization for 64-bit multiplication-with-overflow, though.
1201 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1202 // Add/Sub/Mul with overflow operations are custom lowered.
1204 setOperationAction(ISD::SADDO, VT, Custom);
1205 setOperationAction(ISD::UADDO, VT, Custom);
1206 setOperationAction(ISD::SSUBO, VT, Custom);
1207 setOperationAction(ISD::USUBO, VT, Custom);
1208 setOperationAction(ISD::SMULO, VT, Custom);
1209 setOperationAction(ISD::UMULO, VT, Custom);
1212 // There are no 8-bit 3-address imul/mul instructions
1213 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1214 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1216 if (!Subtarget->is64Bit()) {
1217 // These libcalls are not available in 32-bit.
1218 setLibcallName(RTLIB::SHL_I128, 0);
1219 setLibcallName(RTLIB::SRL_I128, 0);
1220 setLibcallName(RTLIB::SRA_I128, 0);
1223 // We have target-specific dag combine patterns for the following nodes:
1224 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1225 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1226 setTargetDAGCombine(ISD::VSELECT);
1227 setTargetDAGCombine(ISD::SELECT);
1228 setTargetDAGCombine(ISD::SHL);
1229 setTargetDAGCombine(ISD::SRA);
1230 setTargetDAGCombine(ISD::SRL);
1231 setTargetDAGCombine(ISD::OR);
1232 setTargetDAGCombine(ISD::AND);
1233 setTargetDAGCombine(ISD::ADD);
1234 setTargetDAGCombine(ISD::FADD);
1235 setTargetDAGCombine(ISD::FSUB);
1236 setTargetDAGCombine(ISD::FMA);
1237 setTargetDAGCombine(ISD::SUB);
1238 setTargetDAGCombine(ISD::LOAD);
1239 setTargetDAGCombine(ISD::STORE);
1240 setTargetDAGCombine(ISD::ZERO_EXTEND);
1241 setTargetDAGCombine(ISD::ANY_EXTEND);
1242 setTargetDAGCombine(ISD::SIGN_EXTEND);
1243 setTargetDAGCombine(ISD::TRUNCATE);
1244 setTargetDAGCombine(ISD::UINT_TO_FP);
1245 setTargetDAGCombine(ISD::SINT_TO_FP);
1246 setTargetDAGCombine(ISD::SETCC);
1247 setTargetDAGCombine(ISD::FP_TO_SINT);
1248 if (Subtarget->is64Bit())
1249 setTargetDAGCombine(ISD::MUL);
1250 setTargetDAGCombine(ISD::XOR);
1252 computeRegisterProperties();
1254 // On Darwin, -Os means optimize for size without hurting performance,
1255 // do not reduce the limit.
1256 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1257 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1258 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1259 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1260 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1261 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1262 setPrefLoopAlignment(4); // 2^4 bytes.
1263 benefitFromCodePlacementOpt = true;
1265 // Predictable cmov don't hurt on atom because it's in-order.
1266 predictableSelectIsExpensive = !Subtarget->isAtom();
1268 setPrefFunctionAlignment(4); // 2^4 bytes.
1272 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1273 if (!VT.isVector()) return MVT::i8;
1274 return VT.changeVectorElementTypeToInteger();
1278 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1279 /// the desired ByVal argument alignment.
1280 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1283 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1284 if (VTy->getBitWidth() == 128)
1286 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1287 unsigned EltAlign = 0;
1288 getMaxByValAlign(ATy->getElementType(), EltAlign);
1289 if (EltAlign > MaxAlign)
1290 MaxAlign = EltAlign;
1291 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1292 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1293 unsigned EltAlign = 0;
1294 getMaxByValAlign(STy->getElementType(i), EltAlign);
1295 if (EltAlign > MaxAlign)
1296 MaxAlign = EltAlign;
1303 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1304 /// function arguments in the caller parameter area. For X86, aggregates
1305 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1306 /// are at 4-byte boundaries.
1307 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1308 if (Subtarget->is64Bit()) {
1309 // Max of 8 and alignment of type.
1310 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1317 if (Subtarget->hasSSE1())
1318 getMaxByValAlign(Ty, Align);
1322 /// getOptimalMemOpType - Returns the target specific optimal type for load
1323 /// and store operations as a result of memset, memcpy, and memmove
1324 /// lowering. If DstAlign is zero that means it's safe to destination
1325 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1326 /// means there isn't a need to check it against alignment requirement,
1327 /// probably because the source does not need to be loaded. If
1328 /// 'IsZeroVal' is true, that means it's safe to return a
1329 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1330 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1331 /// constant so it does not need to be loaded.
1332 /// It returns EVT::Other if the type should be determined using generic
1333 /// target-independent logic.
1335 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1336 unsigned DstAlign, unsigned SrcAlign,
1339 MachineFunction &MF) const {
1340 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1341 // linux. This is because the stack realignment code can't handle certain
1342 // cases like PR2962. This should be removed when PR2962 is fixed.
1343 const Function *F = MF.getFunction();
1345 !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1347 (Subtarget->isUnalignedMemAccessFast() ||
1348 ((DstAlign == 0 || DstAlign >= 16) &&
1349 (SrcAlign == 0 || SrcAlign >= 16))) &&
1350 Subtarget->getStackAlignment() >= 16) {
1351 if (Subtarget->getStackAlignment() >= 32) {
1352 if (Subtarget->hasAVX2())
1354 if (Subtarget->hasAVX())
1357 if (Subtarget->hasSSE2())
1359 if (Subtarget->hasSSE1())
1361 } else if (!MemcpyStrSrc && Size >= 8 &&
1362 !Subtarget->is64Bit() &&
1363 Subtarget->getStackAlignment() >= 8 &&
1364 Subtarget->hasSSE2()) {
1365 // Do not use f64 to lower memcpy if source is string constant. It's
1366 // better to use i32 to avoid the loads.
1370 if (Subtarget->is64Bit() && Size >= 8)
1375 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1376 /// current function. The returned value is a member of the
1377 /// MachineJumpTableInfo::JTEntryKind enum.
1378 unsigned X86TargetLowering::getJumpTableEncoding() const {
1379 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1381 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1382 Subtarget->isPICStyleGOT())
1383 return MachineJumpTableInfo::EK_Custom32;
1385 // Otherwise, use the normal jump table encoding heuristics.
1386 return TargetLowering::getJumpTableEncoding();
1390 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1391 const MachineBasicBlock *MBB,
1392 unsigned uid,MCContext &Ctx) const{
1393 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1394 Subtarget->isPICStyleGOT());
1395 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1397 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1398 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1401 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1403 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1404 SelectionDAG &DAG) const {
1405 if (!Subtarget->is64Bit())
1406 // This doesn't have DebugLoc associated with it, but is not really the
1407 // same as a Register.
1408 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1412 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1413 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1415 const MCExpr *X86TargetLowering::
1416 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1417 MCContext &Ctx) const {
1418 // X86-64 uses RIP relative addressing based on the jump table label.
1419 if (Subtarget->isPICStyleRIPRel())
1420 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1422 // Otherwise, the reference is relative to the PIC base.
1423 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1426 // FIXME: Why this routine is here? Move to RegInfo!
1427 std::pair<const TargetRegisterClass*, uint8_t>
1428 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1429 const TargetRegisterClass *RRC = 0;
1431 switch (VT.getSimpleVT().SimpleTy) {
1433 return TargetLowering::findRepresentativeClass(VT);
1434 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1435 RRC = Subtarget->is64Bit() ?
1436 (const TargetRegisterClass*)&X86::GR64RegClass :
1437 (const TargetRegisterClass*)&X86::GR32RegClass;
1440 RRC = &X86::VR64RegClass;
1442 case MVT::f32: case MVT::f64:
1443 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1444 case MVT::v4f32: case MVT::v2f64:
1445 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1447 RRC = &X86::VR128RegClass;
1450 return std::make_pair(RRC, Cost);
1453 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1454 unsigned &Offset) const {
1455 if (!Subtarget->isTargetLinux())
1458 if (Subtarget->is64Bit()) {
1459 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1461 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1474 //===----------------------------------------------------------------------===//
1475 // Return Value Calling Convention Implementation
1476 //===----------------------------------------------------------------------===//
1478 #include "X86GenCallingConv.inc"
1481 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1482 MachineFunction &MF, bool isVarArg,
1483 const SmallVectorImpl<ISD::OutputArg> &Outs,
1484 LLVMContext &Context) const {
1485 SmallVector<CCValAssign, 16> RVLocs;
1486 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1488 return CCInfo.CheckReturn(Outs, RetCC_X86);
1492 X86TargetLowering::LowerReturn(SDValue Chain,
1493 CallingConv::ID CallConv, bool isVarArg,
1494 const SmallVectorImpl<ISD::OutputArg> &Outs,
1495 const SmallVectorImpl<SDValue> &OutVals,
1496 DebugLoc dl, SelectionDAG &DAG) const {
1497 MachineFunction &MF = DAG.getMachineFunction();
1498 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1500 SmallVector<CCValAssign, 16> RVLocs;
1501 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1502 RVLocs, *DAG.getContext());
1503 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1505 // Add the regs to the liveout set for the function.
1506 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1507 for (unsigned i = 0; i != RVLocs.size(); ++i)
1508 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1509 MRI.addLiveOut(RVLocs[i].getLocReg());
1513 SmallVector<SDValue, 6> RetOps;
1514 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1515 // Operand #1 = Bytes To Pop
1516 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1519 // Copy the result values into the output registers.
1520 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1521 CCValAssign &VA = RVLocs[i];
1522 assert(VA.isRegLoc() && "Can only return in registers!");
1523 SDValue ValToCopy = OutVals[i];
1524 EVT ValVT = ValToCopy.getValueType();
1526 // Promote values to the appropriate types
1527 if (VA.getLocInfo() == CCValAssign::SExt)
1528 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1529 else if (VA.getLocInfo() == CCValAssign::ZExt)
1530 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1531 else if (VA.getLocInfo() == CCValAssign::AExt)
1532 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1533 else if (VA.getLocInfo() == CCValAssign::BCvt)
1534 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1536 // If this is x86-64, and we disabled SSE, we can't return FP values,
1537 // or SSE or MMX vectors.
1538 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1539 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1540 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1541 report_fatal_error("SSE register return with SSE disabled");
1543 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1544 // llvm-gcc has never done it right and no one has noticed, so this
1545 // should be OK for now.
1546 if (ValVT == MVT::f64 &&
1547 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1548 report_fatal_error("SSE2 register return with SSE2 disabled");
1550 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1551 // the RET instruction and handled by the FP Stackifier.
1552 if (VA.getLocReg() == X86::ST0 ||
1553 VA.getLocReg() == X86::ST1) {
1554 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1555 // change the value to the FP stack register class.
1556 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1557 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1558 RetOps.push_back(ValToCopy);
1559 // Don't emit a copytoreg.
1563 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1564 // which is returned in RAX / RDX.
1565 if (Subtarget->is64Bit()) {
1566 if (ValVT == MVT::x86mmx) {
1567 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1568 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1569 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1571 // If we don't have SSE2 available, convert to v4f32 so the generated
1572 // register is legal.
1573 if (!Subtarget->hasSSE2())
1574 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1579 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1580 Flag = Chain.getValue(1);
1583 // The x86-64 ABI for returning structs by value requires that we copy
1584 // the sret argument into %rax for the return. We saved the argument into
1585 // a virtual register in the entry block, so now we copy the value out
1587 if (Subtarget->is64Bit() &&
1588 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1589 MachineFunction &MF = DAG.getMachineFunction();
1590 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1591 unsigned Reg = FuncInfo->getSRetReturnReg();
1593 "SRetReturnReg should have been set in LowerFormalArguments().");
1594 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1596 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1597 Flag = Chain.getValue(1);
1599 // RAX now acts like a return value.
1600 MRI.addLiveOut(X86::RAX);
1603 RetOps[0] = Chain; // Update chain.
1605 // Add the flag if we have it.
1607 RetOps.push_back(Flag);
1609 return DAG.getNode(X86ISD::RET_FLAG, dl,
1610 MVT::Other, &RetOps[0], RetOps.size());
1613 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1614 if (N->getNumValues() != 1)
1616 if (!N->hasNUsesOfValue(1, 0))
1619 SDValue TCChain = Chain;
1620 SDNode *Copy = *N->use_begin();
1621 if (Copy->getOpcode() == ISD::CopyToReg) {
1622 // If the copy has a glue operand, we conservatively assume it isn't safe to
1623 // perform a tail call.
1624 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1626 TCChain = Copy->getOperand(0);
1627 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1630 bool HasRet = false;
1631 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1633 if (UI->getOpcode() != X86ISD::RET_FLAG)
1646 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1647 ISD::NodeType ExtendKind) const {
1649 // TODO: Is this also valid on 32-bit?
1650 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1651 ReturnMVT = MVT::i8;
1653 ReturnMVT = MVT::i32;
1655 EVT MinVT = getRegisterType(Context, ReturnMVT);
1656 return VT.bitsLT(MinVT) ? MinVT : VT;
1659 /// LowerCallResult - Lower the result values of a call into the
1660 /// appropriate copies out of appropriate physical registers.
1663 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1664 CallingConv::ID CallConv, bool isVarArg,
1665 const SmallVectorImpl<ISD::InputArg> &Ins,
1666 DebugLoc dl, SelectionDAG &DAG,
1667 SmallVectorImpl<SDValue> &InVals) const {
1669 // Assign locations to each value returned by this call.
1670 SmallVector<CCValAssign, 16> RVLocs;
1671 bool Is64Bit = Subtarget->is64Bit();
1672 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1673 getTargetMachine(), RVLocs, *DAG.getContext());
1674 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1676 // Copy all of the result registers out of their specified physreg.
1677 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1678 CCValAssign &VA = RVLocs[i];
1679 EVT CopyVT = VA.getValVT();
1681 // If this is x86-64, and we disabled SSE, we can't return FP values
1682 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1683 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1684 report_fatal_error("SSE register return with SSE disabled");
1689 // If this is a call to a function that returns an fp value on the floating
1690 // point stack, we must guarantee the value is popped from the stack, so
1691 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1692 // if the return value is not used. We use the FpPOP_RETVAL instruction
1694 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1695 // If we prefer to use the value in xmm registers, copy it out as f80 and
1696 // use a truncate to move it from fp stack reg to xmm reg.
1697 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1698 SDValue Ops[] = { Chain, InFlag };
1699 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1700 MVT::Other, MVT::Glue, Ops, 2), 1);
1701 Val = Chain.getValue(0);
1703 // Round the f80 to the right size, which also moves it to the appropriate
1705 if (CopyVT != VA.getValVT())
1706 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1707 // This truncation won't change the value.
1708 DAG.getIntPtrConstant(1));
1710 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1711 CopyVT, InFlag).getValue(1);
1712 Val = Chain.getValue(0);
1714 InFlag = Chain.getValue(2);
1715 InVals.push_back(Val);
1722 //===----------------------------------------------------------------------===//
1723 // C & StdCall & Fast Calling Convention implementation
1724 //===----------------------------------------------------------------------===//
1725 // StdCall calling convention seems to be standard for many Windows' API
1726 // routines and around. It differs from C calling convention just a little:
1727 // callee should clean up the stack, not caller. Symbols should be also
1728 // decorated in some fancy way :) It doesn't support any vector arguments.
1729 // For info on fast calling convention see Fast Calling Convention (tail call)
1730 // implementation LowerX86_32FastCCCallTo.
1732 /// CallIsStructReturn - Determines whether a call uses struct return
1734 enum StructReturnType {
1739 static StructReturnType
1740 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1742 return NotStructReturn;
1744 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1745 if (!Flags.isSRet())
1746 return NotStructReturn;
1747 if (Flags.isInReg())
1748 return RegStructReturn;
1749 return StackStructReturn;
1752 /// ArgsAreStructReturn - Determines whether a function uses struct
1753 /// return semantics.
1754 static StructReturnType
1755 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1757 return NotStructReturn;
1759 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1760 if (!Flags.isSRet())
1761 return NotStructReturn;
1762 if (Flags.isInReg())
1763 return RegStructReturn;
1764 return StackStructReturn;
1767 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1768 /// by "Src" to address "Dst" with size and alignment information specified by
1769 /// the specific parameter attribute. The copy will be passed as a byval
1770 /// function parameter.
1772 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1773 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1775 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1777 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1778 /*isVolatile*/false, /*AlwaysInline=*/true,
1779 MachinePointerInfo(), MachinePointerInfo());
1782 /// IsTailCallConvention - Return true if the calling convention is one that
1783 /// supports tail call optimization.
1784 static bool IsTailCallConvention(CallingConv::ID CC) {
1785 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1788 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1789 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1793 CallingConv::ID CalleeCC = CS.getCallingConv();
1794 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1800 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1801 /// a tailcall target by changing its ABI.
1802 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1803 bool GuaranteedTailCallOpt) {
1804 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1808 X86TargetLowering::LowerMemArgument(SDValue Chain,
1809 CallingConv::ID CallConv,
1810 const SmallVectorImpl<ISD::InputArg> &Ins,
1811 DebugLoc dl, SelectionDAG &DAG,
1812 const CCValAssign &VA,
1813 MachineFrameInfo *MFI,
1815 // Create the nodes corresponding to a load from this parameter slot.
1816 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1817 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1818 getTargetMachine().Options.GuaranteedTailCallOpt);
1819 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1822 // If value is passed by pointer we have address passed instead of the value
1824 if (VA.getLocInfo() == CCValAssign::Indirect)
1825 ValVT = VA.getLocVT();
1827 ValVT = VA.getValVT();
1829 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1830 // changed with more analysis.
1831 // In case of tail call optimization mark all arguments mutable. Since they
1832 // could be overwritten by lowering of arguments in case of a tail call.
1833 if (Flags.isByVal()) {
1834 unsigned Bytes = Flags.getByValSize();
1835 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1836 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1837 return DAG.getFrameIndex(FI, getPointerTy());
1839 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1840 VA.getLocMemOffset(), isImmutable);
1841 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1842 return DAG.getLoad(ValVT, dl, Chain, FIN,
1843 MachinePointerInfo::getFixedStack(FI),
1844 false, false, false, 0);
1849 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1850 CallingConv::ID CallConv,
1852 const SmallVectorImpl<ISD::InputArg> &Ins,
1855 SmallVectorImpl<SDValue> &InVals)
1857 MachineFunction &MF = DAG.getMachineFunction();
1858 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1860 const Function* Fn = MF.getFunction();
1861 if (Fn->hasExternalLinkage() &&
1862 Subtarget->isTargetCygMing() &&
1863 Fn->getName() == "main")
1864 FuncInfo->setForceFramePointer(true);
1866 MachineFrameInfo *MFI = MF.getFrameInfo();
1867 bool Is64Bit = Subtarget->is64Bit();
1868 bool IsWindows = Subtarget->isTargetWindows();
1869 bool IsWin64 = Subtarget->isTargetWin64();
1871 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1872 "Var args not supported with calling convention fastcc or ghc");
1874 // Assign locations to all of the incoming arguments.
1875 SmallVector<CCValAssign, 16> ArgLocs;
1876 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1877 ArgLocs, *DAG.getContext());
1879 // Allocate shadow area for Win64
1881 CCInfo.AllocateStack(32, 8);
1884 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1886 unsigned LastVal = ~0U;
1888 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1889 CCValAssign &VA = ArgLocs[i];
1890 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1892 assert(VA.getValNo() != LastVal &&
1893 "Don't support value assigned to multiple locs yet");
1895 LastVal = VA.getValNo();
1897 if (VA.isRegLoc()) {
1898 EVT RegVT = VA.getLocVT();
1899 const TargetRegisterClass *RC;
1900 if (RegVT == MVT::i32)
1901 RC = &X86::GR32RegClass;
1902 else if (Is64Bit && RegVT == MVT::i64)
1903 RC = &X86::GR64RegClass;
1904 else if (RegVT == MVT::f32)
1905 RC = &X86::FR32RegClass;
1906 else if (RegVT == MVT::f64)
1907 RC = &X86::FR64RegClass;
1908 else if (RegVT.is256BitVector())
1909 RC = &X86::VR256RegClass;
1910 else if (RegVT.is128BitVector())
1911 RC = &X86::VR128RegClass;
1912 else if (RegVT == MVT::x86mmx)
1913 RC = &X86::VR64RegClass;
1915 llvm_unreachable("Unknown argument type!");
1917 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1918 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1920 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1921 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1923 if (VA.getLocInfo() == CCValAssign::SExt)
1924 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1925 DAG.getValueType(VA.getValVT()));
1926 else if (VA.getLocInfo() == CCValAssign::ZExt)
1927 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1928 DAG.getValueType(VA.getValVT()));
1929 else if (VA.getLocInfo() == CCValAssign::BCvt)
1930 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1932 if (VA.isExtInLoc()) {
1933 // Handle MMX values passed in XMM regs.
1934 if (RegVT.isVector()) {
1935 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1938 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1941 assert(VA.isMemLoc());
1942 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1945 // If value is passed via pointer - do a load.
1946 if (VA.getLocInfo() == CCValAssign::Indirect)
1947 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1948 MachinePointerInfo(), false, false, false, 0);
1950 InVals.push_back(ArgValue);
1953 // The x86-64 ABI for returning structs by value requires that we copy
1954 // the sret argument into %rax for the return. Save the argument into
1955 // a virtual register so that we can access it from the return points.
1956 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1957 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1958 unsigned Reg = FuncInfo->getSRetReturnReg();
1960 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1961 FuncInfo->setSRetReturnReg(Reg);
1963 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1964 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1967 unsigned StackSize = CCInfo.getNextStackOffset();
1968 // Align stack specially for tail calls.
1969 if (FuncIsMadeTailCallSafe(CallConv,
1970 MF.getTarget().Options.GuaranteedTailCallOpt))
1971 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1973 // If the function takes variable number of arguments, make a frame index for
1974 // the start of the first vararg value... for expansion of llvm.va_start.
1976 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1977 CallConv != CallingConv::X86_ThisCall)) {
1978 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1981 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1983 // FIXME: We should really autogenerate these arrays
1984 static const uint16_t GPR64ArgRegsWin64[] = {
1985 X86::RCX, X86::RDX, X86::R8, X86::R9
1987 static const uint16_t GPR64ArgRegs64Bit[] = {
1988 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1990 static const uint16_t XMMArgRegs64Bit[] = {
1991 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1992 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1994 const uint16_t *GPR64ArgRegs;
1995 unsigned NumXMMRegs = 0;
1998 // The XMM registers which might contain var arg parameters are shadowed
1999 // in their paired GPR. So we only need to save the GPR to their home
2001 TotalNumIntRegs = 4;
2002 GPR64ArgRegs = GPR64ArgRegsWin64;
2004 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2005 GPR64ArgRegs = GPR64ArgRegs64Bit;
2007 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2010 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2013 bool NoImplicitFloatOps = Fn->getFnAttributes().
2014 hasAttribute(Attributes::NoImplicitFloat);
2015 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2016 "SSE register cannot be used when SSE is disabled!");
2017 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2018 NoImplicitFloatOps) &&
2019 "SSE register cannot be used when SSE is disabled!");
2020 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2021 !Subtarget->hasSSE1())
2022 // Kernel mode asks for SSE to be disabled, so don't push them
2024 TotalNumXMMRegs = 0;
2027 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2028 // Get to the caller-allocated home save location. Add 8 to account
2029 // for the return address.
2030 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2031 FuncInfo->setRegSaveFrameIndex(
2032 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2033 // Fixup to set vararg frame on shadow area (4 x i64).
2035 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2037 // For X86-64, if there are vararg parameters that are passed via
2038 // registers, then we must store them to their spots on the stack so
2039 // they may be loaded by deferencing the result of va_next.
2040 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2041 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2042 FuncInfo->setRegSaveFrameIndex(
2043 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2047 // Store the integer parameter registers.
2048 SmallVector<SDValue, 8> MemOps;
2049 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2051 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2052 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2053 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2054 DAG.getIntPtrConstant(Offset));
2055 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2056 &X86::GR64RegClass);
2057 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2059 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2060 MachinePointerInfo::getFixedStack(
2061 FuncInfo->getRegSaveFrameIndex(), Offset),
2063 MemOps.push_back(Store);
2067 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2068 // Now store the XMM (fp + vector) parameter registers.
2069 SmallVector<SDValue, 11> SaveXMMOps;
2070 SaveXMMOps.push_back(Chain);
2072 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2073 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2074 SaveXMMOps.push_back(ALVal);
2076 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2077 FuncInfo->getRegSaveFrameIndex()));
2078 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2079 FuncInfo->getVarArgsFPOffset()));
2081 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2082 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2083 &X86::VR128RegClass);
2084 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2085 SaveXMMOps.push_back(Val);
2087 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2089 &SaveXMMOps[0], SaveXMMOps.size()));
2092 if (!MemOps.empty())
2093 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2094 &MemOps[0], MemOps.size());
2098 // Some CCs need callee pop.
2099 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2100 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2101 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2103 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2104 // If this is an sret function, the return should pop the hidden pointer.
2105 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2106 argsAreStructReturn(Ins) == StackStructReturn)
2107 FuncInfo->setBytesToPopOnReturn(4);
2111 // RegSaveFrameIndex is X86-64 only.
2112 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2113 if (CallConv == CallingConv::X86_FastCall ||
2114 CallConv == CallingConv::X86_ThisCall)
2115 // fastcc functions can't have varargs.
2116 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2119 FuncInfo->setArgumentStackSize(StackSize);
2125 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2126 SDValue StackPtr, SDValue Arg,
2127 DebugLoc dl, SelectionDAG &DAG,
2128 const CCValAssign &VA,
2129 ISD::ArgFlagsTy Flags) const {
2130 unsigned LocMemOffset = VA.getLocMemOffset();
2131 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2132 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2133 if (Flags.isByVal())
2134 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2136 return DAG.getStore(Chain, dl, Arg, PtrOff,
2137 MachinePointerInfo::getStack(LocMemOffset),
2141 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2142 /// optimization is performed and it is required.
2144 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2145 SDValue &OutRetAddr, SDValue Chain,
2146 bool IsTailCall, bool Is64Bit,
2147 int FPDiff, DebugLoc dl) const {
2148 // Adjust the Return address stack slot.
2149 EVT VT = getPointerTy();
2150 OutRetAddr = getReturnAddressFrameIndex(DAG);
2152 // Load the "old" Return address.
2153 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2154 false, false, false, 0);
2155 return SDValue(OutRetAddr.getNode(), 1);
2158 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2159 /// optimization is performed and it is required (FPDiff!=0).
2161 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2162 SDValue Chain, SDValue RetAddrFrIdx,
2163 bool Is64Bit, int FPDiff, DebugLoc dl) {
2164 // Store the return address to the appropriate stack slot.
2165 if (!FPDiff) return Chain;
2166 // Calculate the new stack slot for the return address.
2167 int SlotSize = Is64Bit ? 8 : 4;
2168 int NewReturnAddrFI =
2169 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2170 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2171 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2172 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2173 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2179 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2180 SmallVectorImpl<SDValue> &InVals) const {
2181 SelectionDAG &DAG = CLI.DAG;
2182 DebugLoc &dl = CLI.DL;
2183 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2184 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2185 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2186 SDValue Chain = CLI.Chain;
2187 SDValue Callee = CLI.Callee;
2188 CallingConv::ID CallConv = CLI.CallConv;
2189 bool &isTailCall = CLI.IsTailCall;
2190 bool isVarArg = CLI.IsVarArg;
2192 MachineFunction &MF = DAG.getMachineFunction();
2193 bool Is64Bit = Subtarget->is64Bit();
2194 bool IsWin64 = Subtarget->isTargetWin64();
2195 bool IsWindows = Subtarget->isTargetWindows();
2196 StructReturnType SR = callIsStructReturn(Outs);
2197 bool IsSibcall = false;
2199 if (MF.getTarget().Options.DisableTailCalls)
2203 // Check if it's really possible to do a tail call.
2204 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2205 isVarArg, SR != NotStructReturn,
2206 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2207 Outs, OutVals, Ins, DAG);
2209 // Sibcalls are automatically detected tailcalls which do not require
2211 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2218 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2219 "Var args not supported with calling convention fastcc or ghc");
2221 // Analyze operands of the call, assigning locations to each operand.
2222 SmallVector<CCValAssign, 16> ArgLocs;
2223 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2224 ArgLocs, *DAG.getContext());
2226 // Allocate shadow area for Win64
2228 CCInfo.AllocateStack(32, 8);
2231 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2233 // Get a count of how many bytes are to be pushed on the stack.
2234 unsigned NumBytes = CCInfo.getNextStackOffset();
2236 // This is a sibcall. The memory operands are available in caller's
2237 // own caller's stack.
2239 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2240 IsTailCallConvention(CallConv))
2241 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2244 if (isTailCall && !IsSibcall) {
2245 // Lower arguments at fp - stackoffset + fpdiff.
2246 unsigned NumBytesCallerPushed =
2247 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2248 FPDiff = NumBytesCallerPushed - NumBytes;
2250 // Set the delta of movement of the returnaddr stackslot.
2251 // But only set if delta is greater than previous delta.
2252 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2253 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2257 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2259 SDValue RetAddrFrIdx;
2260 // Load return address for tail calls.
2261 if (isTailCall && FPDiff)
2262 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2263 Is64Bit, FPDiff, dl);
2265 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2266 SmallVector<SDValue, 8> MemOpChains;
2269 // Walk the register/memloc assignments, inserting copies/loads. In the case
2270 // of tail call optimization arguments are handle later.
2271 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2272 CCValAssign &VA = ArgLocs[i];
2273 EVT RegVT = VA.getLocVT();
2274 SDValue Arg = OutVals[i];
2275 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2276 bool isByVal = Flags.isByVal();
2278 // Promote the value if needed.
2279 switch (VA.getLocInfo()) {
2280 default: llvm_unreachable("Unknown loc info!");
2281 case CCValAssign::Full: break;
2282 case CCValAssign::SExt:
2283 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2285 case CCValAssign::ZExt:
2286 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2288 case CCValAssign::AExt:
2289 if (RegVT.is128BitVector()) {
2290 // Special case: passing MMX values in XMM registers.
2291 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2292 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2293 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2295 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2297 case CCValAssign::BCvt:
2298 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2300 case CCValAssign::Indirect: {
2301 // Store the argument.
2302 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2303 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2304 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2305 MachinePointerInfo::getFixedStack(FI),
2312 if (VA.isRegLoc()) {
2313 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2314 if (isVarArg && IsWin64) {
2315 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2316 // shadow reg if callee is a varargs function.
2317 unsigned ShadowReg = 0;
2318 switch (VA.getLocReg()) {
2319 case X86::XMM0: ShadowReg = X86::RCX; break;
2320 case X86::XMM1: ShadowReg = X86::RDX; break;
2321 case X86::XMM2: ShadowReg = X86::R8; break;
2322 case X86::XMM3: ShadowReg = X86::R9; break;
2325 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2327 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2328 assert(VA.isMemLoc());
2329 if (StackPtr.getNode() == 0)
2330 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2331 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2332 dl, DAG, VA, Flags));
2336 if (!MemOpChains.empty())
2337 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2338 &MemOpChains[0], MemOpChains.size());
2340 if (Subtarget->isPICStyleGOT()) {
2341 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2344 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2345 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2347 // If we are tail calling and generating PIC/GOT style code load the
2348 // address of the callee into ECX. The value in ecx is used as target of
2349 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2350 // for tail calls on PIC/GOT architectures. Normally we would just put the
2351 // address of GOT into ebx and then call target@PLT. But for tail calls
2352 // ebx would be restored (since ebx is callee saved) before jumping to the
2355 // Note: The actual moving to ECX is done further down.
2356 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2357 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2358 !G->getGlobal()->hasProtectedVisibility())
2359 Callee = LowerGlobalAddress(Callee, DAG);
2360 else if (isa<ExternalSymbolSDNode>(Callee))
2361 Callee = LowerExternalSymbol(Callee, DAG);
2365 if (Is64Bit && isVarArg && !IsWin64) {
2366 // From AMD64 ABI document:
2367 // For calls that may call functions that use varargs or stdargs
2368 // (prototype-less calls or calls to functions containing ellipsis (...) in
2369 // the declaration) %al is used as hidden argument to specify the number
2370 // of SSE registers used. The contents of %al do not need to match exactly
2371 // the number of registers, but must be an ubound on the number of SSE
2372 // registers used and is in the range 0 - 8 inclusive.
2374 // Count the number of XMM registers allocated.
2375 static const uint16_t XMMArgRegs[] = {
2376 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2377 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2379 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2380 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2381 && "SSE registers cannot be used when SSE is disabled");
2383 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2384 DAG.getConstant(NumXMMRegs, MVT::i8)));
2387 // For tail calls lower the arguments to the 'real' stack slot.
2389 // Force all the incoming stack arguments to be loaded from the stack
2390 // before any new outgoing arguments are stored to the stack, because the
2391 // outgoing stack slots may alias the incoming argument stack slots, and
2392 // the alias isn't otherwise explicit. This is slightly more conservative
2393 // than necessary, because it means that each store effectively depends
2394 // on every argument instead of just those arguments it would clobber.
2395 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2397 SmallVector<SDValue, 8> MemOpChains2;
2400 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2401 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2402 CCValAssign &VA = ArgLocs[i];
2405 assert(VA.isMemLoc());
2406 SDValue Arg = OutVals[i];
2407 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2408 // Create frame index.
2409 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2410 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2411 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2412 FIN = DAG.getFrameIndex(FI, getPointerTy());
2414 if (Flags.isByVal()) {
2415 // Copy relative to framepointer.
2416 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2417 if (StackPtr.getNode() == 0)
2418 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2420 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2422 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2426 // Store relative to framepointer.
2427 MemOpChains2.push_back(
2428 DAG.getStore(ArgChain, dl, Arg, FIN,
2429 MachinePointerInfo::getFixedStack(FI),
2435 if (!MemOpChains2.empty())
2436 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2437 &MemOpChains2[0], MemOpChains2.size());
2439 // Store the return address to the appropriate stack slot.
2440 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2444 // Build a sequence of copy-to-reg nodes chained together with token chain
2445 // and flag operands which copy the outgoing args into registers.
2447 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2448 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2449 RegsToPass[i].second, InFlag);
2450 InFlag = Chain.getValue(1);
2453 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2454 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2455 // In the 64-bit large code model, we have to make all calls
2456 // through a register, since the call instruction's 32-bit
2457 // pc-relative offset may not be large enough to hold the whole
2459 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2460 // If the callee is a GlobalAddress node (quite common, every direct call
2461 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2464 // We should use extra load for direct calls to dllimported functions in
2466 const GlobalValue *GV = G->getGlobal();
2467 if (!GV->hasDLLImportLinkage()) {
2468 unsigned char OpFlags = 0;
2469 bool ExtraLoad = false;
2470 unsigned WrapperKind = ISD::DELETED_NODE;
2472 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2473 // external symbols most go through the PLT in PIC mode. If the symbol
2474 // has hidden or protected visibility, or if it is static or local, then
2475 // we don't need to use the PLT - we can directly call it.
2476 if (Subtarget->isTargetELF() &&
2477 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2478 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2479 OpFlags = X86II::MO_PLT;
2480 } else if (Subtarget->isPICStyleStubAny() &&
2481 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2482 (!Subtarget->getTargetTriple().isMacOSX() ||
2483 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2484 // PC-relative references to external symbols should go through $stub,
2485 // unless we're building with the leopard linker or later, which
2486 // automatically synthesizes these stubs.
2487 OpFlags = X86II::MO_DARWIN_STUB;
2488 } else if (Subtarget->isPICStyleRIPRel() &&
2489 isa<Function>(GV) &&
2490 cast<Function>(GV)->getFnAttributes().
2491 hasAttribute(Attributes::NonLazyBind)) {
2492 // If the function is marked as non-lazy, generate an indirect call
2493 // which loads from the GOT directly. This avoids runtime overhead
2494 // at the cost of eager binding (and one extra byte of encoding).
2495 OpFlags = X86II::MO_GOTPCREL;
2496 WrapperKind = X86ISD::WrapperRIP;
2500 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2501 G->getOffset(), OpFlags);
2503 // Add a wrapper if needed.
2504 if (WrapperKind != ISD::DELETED_NODE)
2505 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2506 // Add extra indirection if needed.
2508 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2509 MachinePointerInfo::getGOT(),
2510 false, false, false, 0);
2512 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2513 unsigned char OpFlags = 0;
2515 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2516 // external symbols should go through the PLT.
2517 if (Subtarget->isTargetELF() &&
2518 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2519 OpFlags = X86II::MO_PLT;
2520 } else if (Subtarget->isPICStyleStubAny() &&
2521 (!Subtarget->getTargetTriple().isMacOSX() ||
2522 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2523 // PC-relative references to external symbols should go through $stub,
2524 // unless we're building with the leopard linker or later, which
2525 // automatically synthesizes these stubs.
2526 OpFlags = X86II::MO_DARWIN_STUB;
2529 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2533 // Returns a chain & a flag for retval copy to use.
2534 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2535 SmallVector<SDValue, 8> Ops;
2537 if (!IsSibcall && isTailCall) {
2538 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2539 DAG.getIntPtrConstant(0, true), InFlag);
2540 InFlag = Chain.getValue(1);
2543 Ops.push_back(Chain);
2544 Ops.push_back(Callee);
2547 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2549 // Add argument registers to the end of the list so that they are known live
2551 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2552 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2553 RegsToPass[i].second.getValueType()));
2555 // Add a register mask operand representing the call-preserved registers.
2556 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2557 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2558 assert(Mask && "Missing call preserved mask for calling convention");
2559 Ops.push_back(DAG.getRegisterMask(Mask));
2561 if (InFlag.getNode())
2562 Ops.push_back(InFlag);
2566 //// If this is the first return lowered for this function, add the regs
2567 //// to the liveout set for the function.
2568 // This isn't right, although it's probably harmless on x86; liveouts
2569 // should be computed from returns not tail calls. Consider a void
2570 // function making a tail call to a function returning int.
2571 return DAG.getNode(X86ISD::TC_RETURN, dl,
2572 NodeTys, &Ops[0], Ops.size());
2575 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2576 InFlag = Chain.getValue(1);
2578 // Create the CALLSEQ_END node.
2579 unsigned NumBytesForCalleeToPush;
2580 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2581 getTargetMachine().Options.GuaranteedTailCallOpt))
2582 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2583 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2584 SR == StackStructReturn)
2585 // If this is a call to a struct-return function, the callee
2586 // pops the hidden struct pointer, so we have to push it back.
2587 // This is common for Darwin/X86, Linux & Mingw32 targets.
2588 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2589 NumBytesForCalleeToPush = 4;
2591 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2593 // Returns a flag for retval copy to use.
2595 Chain = DAG.getCALLSEQ_END(Chain,
2596 DAG.getIntPtrConstant(NumBytes, true),
2597 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2600 InFlag = Chain.getValue(1);
2603 // Handle result values, copying them out of physregs into vregs that we
2605 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2606 Ins, dl, DAG, InVals);
2610 //===----------------------------------------------------------------------===//
2611 // Fast Calling Convention (tail call) implementation
2612 //===----------------------------------------------------------------------===//
2614 // Like std call, callee cleans arguments, convention except that ECX is
2615 // reserved for storing the tail called function address. Only 2 registers are
2616 // free for argument passing (inreg). Tail call optimization is performed
2618 // * tailcallopt is enabled
2619 // * caller/callee are fastcc
2620 // On X86_64 architecture with GOT-style position independent code only local
2621 // (within module) calls are supported at the moment.
2622 // To keep the stack aligned according to platform abi the function
2623 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2624 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2625 // If a tail called function callee has more arguments than the caller the
2626 // caller needs to make sure that there is room to move the RETADDR to. This is
2627 // achieved by reserving an area the size of the argument delta right after the
2628 // original REtADDR, but before the saved framepointer or the spilled registers
2629 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2641 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2642 /// for a 16 byte align requirement.
2644 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2645 SelectionDAG& DAG) const {
2646 MachineFunction &MF = DAG.getMachineFunction();
2647 const TargetMachine &TM = MF.getTarget();
2648 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2649 unsigned StackAlignment = TFI.getStackAlignment();
2650 uint64_t AlignMask = StackAlignment - 1;
2651 int64_t Offset = StackSize;
2652 uint64_t SlotSize = TD->getPointerSize();
2653 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2654 // Number smaller than 12 so just add the difference.
2655 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2657 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2658 Offset = ((~AlignMask) & Offset) + StackAlignment +
2659 (StackAlignment-SlotSize);
2664 /// MatchingStackOffset - Return true if the given stack call argument is
2665 /// already available in the same position (relatively) of the caller's
2666 /// incoming argument stack.
2668 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2669 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2670 const X86InstrInfo *TII) {
2671 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2673 if (Arg.getOpcode() == ISD::CopyFromReg) {
2674 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2675 if (!TargetRegisterInfo::isVirtualRegister(VR))
2677 MachineInstr *Def = MRI->getVRegDef(VR);
2680 if (!Flags.isByVal()) {
2681 if (!TII->isLoadFromStackSlot(Def, FI))
2684 unsigned Opcode = Def->getOpcode();
2685 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2686 Def->getOperand(1).isFI()) {
2687 FI = Def->getOperand(1).getIndex();
2688 Bytes = Flags.getByValSize();
2692 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2693 if (Flags.isByVal())
2694 // ByVal argument is passed in as a pointer but it's now being
2695 // dereferenced. e.g.
2696 // define @foo(%struct.X* %A) {
2697 // tail call @bar(%struct.X* byval %A)
2700 SDValue Ptr = Ld->getBasePtr();
2701 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2704 FI = FINode->getIndex();
2705 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2706 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2707 FI = FINode->getIndex();
2708 Bytes = Flags.getByValSize();
2712 assert(FI != INT_MAX);
2713 if (!MFI->isFixedObjectIndex(FI))
2715 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2718 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2719 /// for tail call optimization. Targets which want to do tail call
2720 /// optimization should implement this function.
2722 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2723 CallingConv::ID CalleeCC,
2725 bool isCalleeStructRet,
2726 bool isCallerStructRet,
2728 const SmallVectorImpl<ISD::OutputArg> &Outs,
2729 const SmallVectorImpl<SDValue> &OutVals,
2730 const SmallVectorImpl<ISD::InputArg> &Ins,
2731 SelectionDAG& DAG) const {
2732 if (!IsTailCallConvention(CalleeCC) &&
2733 CalleeCC != CallingConv::C)
2736 // If -tailcallopt is specified, make fastcc functions tail-callable.
2737 const MachineFunction &MF = DAG.getMachineFunction();
2738 const Function *CallerF = DAG.getMachineFunction().getFunction();
2740 // If the function return type is x86_fp80 and the callee return type is not,
2741 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2742 // perform a tailcall optimization here.
2743 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2746 CallingConv::ID CallerCC = CallerF->getCallingConv();
2747 bool CCMatch = CallerCC == CalleeCC;
2749 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2750 if (IsTailCallConvention(CalleeCC) && CCMatch)
2755 // Look for obvious safe cases to perform tail call optimization that do not
2756 // require ABI changes. This is what gcc calls sibcall.
2758 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2759 // emit a special epilogue.
2760 if (RegInfo->needsStackRealignment(MF))
2763 // Also avoid sibcall optimization if either caller or callee uses struct
2764 // return semantics.
2765 if (isCalleeStructRet || isCallerStructRet)
2768 // An stdcall caller is expected to clean up its arguments; the callee
2769 // isn't going to do that.
2770 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2773 // Do not sibcall optimize vararg calls unless all arguments are passed via
2775 if (isVarArg && !Outs.empty()) {
2777 // Optimizing for varargs on Win64 is unlikely to be safe without
2778 // additional testing.
2779 if (Subtarget->isTargetWin64())
2782 SmallVector<CCValAssign, 16> ArgLocs;
2783 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2784 getTargetMachine(), ArgLocs, *DAG.getContext());
2786 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2787 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2788 if (!ArgLocs[i].isRegLoc())
2792 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2793 // stack. Therefore, if it's not used by the call it is not safe to optimize
2794 // this into a sibcall.
2795 bool Unused = false;
2796 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2803 SmallVector<CCValAssign, 16> RVLocs;
2804 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2805 getTargetMachine(), RVLocs, *DAG.getContext());
2806 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2807 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2808 CCValAssign &VA = RVLocs[i];
2809 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2814 // If the calling conventions do not match, then we'd better make sure the
2815 // results are returned in the same way as what the caller expects.
2817 SmallVector<CCValAssign, 16> RVLocs1;
2818 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2819 getTargetMachine(), RVLocs1, *DAG.getContext());
2820 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2822 SmallVector<CCValAssign, 16> RVLocs2;
2823 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2824 getTargetMachine(), RVLocs2, *DAG.getContext());
2825 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2827 if (RVLocs1.size() != RVLocs2.size())
2829 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2830 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2832 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2834 if (RVLocs1[i].isRegLoc()) {
2835 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2838 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2844 // If the callee takes no arguments then go on to check the results of the
2846 if (!Outs.empty()) {
2847 // Check if stack adjustment is needed. For now, do not do this if any
2848 // argument is passed on the stack.
2849 SmallVector<CCValAssign, 16> ArgLocs;
2850 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2851 getTargetMachine(), ArgLocs, *DAG.getContext());
2853 // Allocate shadow area for Win64
2854 if (Subtarget->isTargetWin64()) {
2855 CCInfo.AllocateStack(32, 8);
2858 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2859 if (CCInfo.getNextStackOffset()) {
2860 MachineFunction &MF = DAG.getMachineFunction();
2861 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2864 // Check if the arguments are already laid out in the right way as
2865 // the caller's fixed stack objects.
2866 MachineFrameInfo *MFI = MF.getFrameInfo();
2867 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2868 const X86InstrInfo *TII =
2869 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2870 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2871 CCValAssign &VA = ArgLocs[i];
2872 SDValue Arg = OutVals[i];
2873 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2874 if (VA.getLocInfo() == CCValAssign::Indirect)
2876 if (!VA.isRegLoc()) {
2877 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2884 // If the tailcall address may be in a register, then make sure it's
2885 // possible to register allocate for it. In 32-bit, the call address can
2886 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2887 // callee-saved registers are restored. These happen to be the same
2888 // registers used to pass 'inreg' arguments so watch out for those.
2889 if (!Subtarget->is64Bit() &&
2890 !isa<GlobalAddressSDNode>(Callee) &&
2891 !isa<ExternalSymbolSDNode>(Callee)) {
2892 unsigned NumInRegs = 0;
2893 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2894 CCValAssign &VA = ArgLocs[i];
2897 unsigned Reg = VA.getLocReg();
2900 case X86::EAX: case X86::EDX: case X86::ECX:
2901 if (++NumInRegs == 3)
2913 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2914 const TargetLibraryInfo *libInfo) const {
2915 return X86::createFastISel(funcInfo, libInfo);
2919 //===----------------------------------------------------------------------===//
2920 // Other Lowering Hooks
2921 //===----------------------------------------------------------------------===//
2923 static bool MayFoldLoad(SDValue Op) {
2924 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2927 static bool MayFoldIntoStore(SDValue Op) {
2928 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2931 static bool isTargetShuffle(unsigned Opcode) {
2933 default: return false;
2934 case X86ISD::PSHUFD:
2935 case X86ISD::PSHUFHW:
2936 case X86ISD::PSHUFLW:
2938 case X86ISD::PALIGN:
2939 case X86ISD::MOVLHPS:
2940 case X86ISD::MOVLHPD:
2941 case X86ISD::MOVHLPS:
2942 case X86ISD::MOVLPS:
2943 case X86ISD::MOVLPD:
2944 case X86ISD::MOVSHDUP:
2945 case X86ISD::MOVSLDUP:
2946 case X86ISD::MOVDDUP:
2949 case X86ISD::UNPCKL:
2950 case X86ISD::UNPCKH:
2951 case X86ISD::VPERMILP:
2952 case X86ISD::VPERM2X128:
2953 case X86ISD::VPERMI:
2958 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2959 SDValue V1, SelectionDAG &DAG) {
2961 default: llvm_unreachable("Unknown x86 shuffle node");
2962 case X86ISD::MOVSHDUP:
2963 case X86ISD::MOVSLDUP:
2964 case X86ISD::MOVDDUP:
2965 return DAG.getNode(Opc, dl, VT, V1);
2969 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2970 SDValue V1, unsigned TargetMask,
2971 SelectionDAG &DAG) {
2973 default: llvm_unreachable("Unknown x86 shuffle node");
2974 case X86ISD::PSHUFD:
2975 case X86ISD::PSHUFHW:
2976 case X86ISD::PSHUFLW:
2977 case X86ISD::VPERMILP:
2978 case X86ISD::VPERMI:
2979 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2983 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2984 SDValue V1, SDValue V2, unsigned TargetMask,
2985 SelectionDAG &DAG) {
2987 default: llvm_unreachable("Unknown x86 shuffle node");
2988 case X86ISD::PALIGN:
2990 case X86ISD::VPERM2X128:
2991 return DAG.getNode(Opc, dl, VT, V1, V2,
2992 DAG.getConstant(TargetMask, MVT::i8));
2996 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2997 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2999 default: llvm_unreachable("Unknown x86 shuffle node");
3000 case X86ISD::MOVLHPS:
3001 case X86ISD::MOVLHPD:
3002 case X86ISD::MOVHLPS:
3003 case X86ISD::MOVLPS:
3004 case X86ISD::MOVLPD:
3007 case X86ISD::UNPCKL:
3008 case X86ISD::UNPCKH:
3009 return DAG.getNode(Opc, dl, VT, V1, V2);
3013 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3014 MachineFunction &MF = DAG.getMachineFunction();
3015 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3016 int ReturnAddrIndex = FuncInfo->getRAIndex();
3018 if (ReturnAddrIndex == 0) {
3019 // Set up a frame object for the return address.
3020 uint64_t SlotSize = TD->getPointerSize();
3021 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3023 FuncInfo->setRAIndex(ReturnAddrIndex);
3026 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3030 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3031 bool hasSymbolicDisplacement) {
3032 // Offset should fit into 32 bit immediate field.
3033 if (!isInt<32>(Offset))
3036 // If we don't have a symbolic displacement - we don't have any extra
3038 if (!hasSymbolicDisplacement)
3041 // FIXME: Some tweaks might be needed for medium code model.
3042 if (M != CodeModel::Small && M != CodeModel::Kernel)
3045 // For small code model we assume that latest object is 16MB before end of 31
3046 // bits boundary. We may also accept pretty large negative constants knowing
3047 // that all objects are in the positive half of address space.
3048 if (M == CodeModel::Small && Offset < 16*1024*1024)
3051 // For kernel code model we know that all object resist in the negative half
3052 // of 32bits address space. We may not accept negative offsets, since they may
3053 // be just off and we may accept pretty large positive ones.
3054 if (M == CodeModel::Kernel && Offset > 0)
3060 /// isCalleePop - Determines whether the callee is required to pop its
3061 /// own arguments. Callee pop is necessary to support tail calls.
3062 bool X86::isCalleePop(CallingConv::ID CallingConv,
3063 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3067 switch (CallingConv) {
3070 case CallingConv::X86_StdCall:
3072 case CallingConv::X86_FastCall:
3074 case CallingConv::X86_ThisCall:
3076 case CallingConv::Fast:
3078 case CallingConv::GHC:
3083 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3084 /// specific condition code, returning the condition code and the LHS/RHS of the
3085 /// comparison to make.
3086 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3087 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3089 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3090 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3091 // X > -1 -> X == 0, jump !sign.
3092 RHS = DAG.getConstant(0, RHS.getValueType());
3093 return X86::COND_NS;
3095 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3096 // X < 0 -> X == 0, jump on sign.
3099 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3101 RHS = DAG.getConstant(0, RHS.getValueType());
3102 return X86::COND_LE;
3106 switch (SetCCOpcode) {
3107 default: llvm_unreachable("Invalid integer condition!");
3108 case ISD::SETEQ: return X86::COND_E;
3109 case ISD::SETGT: return X86::COND_G;
3110 case ISD::SETGE: return X86::COND_GE;
3111 case ISD::SETLT: return X86::COND_L;
3112 case ISD::SETLE: return X86::COND_LE;
3113 case ISD::SETNE: return X86::COND_NE;
3114 case ISD::SETULT: return X86::COND_B;
3115 case ISD::SETUGT: return X86::COND_A;
3116 case ISD::SETULE: return X86::COND_BE;
3117 case ISD::SETUGE: return X86::COND_AE;
3121 // First determine if it is required or is profitable to flip the operands.
3123 // If LHS is a foldable load, but RHS is not, flip the condition.
3124 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3125 !ISD::isNON_EXTLoad(RHS.getNode())) {
3126 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3127 std::swap(LHS, RHS);
3130 switch (SetCCOpcode) {
3136 std::swap(LHS, RHS);
3140 // On a floating point condition, the flags are set as follows:
3142 // 0 | 0 | 0 | X > Y
3143 // 0 | 0 | 1 | X < Y
3144 // 1 | 0 | 0 | X == Y
3145 // 1 | 1 | 1 | unordered
3146 switch (SetCCOpcode) {
3147 default: llvm_unreachable("Condcode should be pre-legalized away");
3149 case ISD::SETEQ: return X86::COND_E;
3150 case ISD::SETOLT: // flipped
3152 case ISD::SETGT: return X86::COND_A;
3153 case ISD::SETOLE: // flipped
3155 case ISD::SETGE: return X86::COND_AE;
3156 case ISD::SETUGT: // flipped
3158 case ISD::SETLT: return X86::COND_B;
3159 case ISD::SETUGE: // flipped
3161 case ISD::SETLE: return X86::COND_BE;
3163 case ISD::SETNE: return X86::COND_NE;
3164 case ISD::SETUO: return X86::COND_P;
3165 case ISD::SETO: return X86::COND_NP;
3167 case ISD::SETUNE: return X86::COND_INVALID;
3171 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3172 /// code. Current x86 isa includes the following FP cmov instructions:
3173 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3174 static bool hasFPCMov(unsigned X86CC) {
3190 /// isFPImmLegal - Returns true if the target can instruction select the
3191 /// specified FP immediate natively. If false, the legalizer will
3192 /// materialize the FP immediate as a load from a constant pool.
3193 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3194 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3195 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3201 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3202 /// the specified range (L, H].
3203 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3204 return (Val < 0) || (Val >= Low && Val < Hi);
3207 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3208 /// specified value.
3209 static bool isUndefOrEqual(int Val, int CmpVal) {
3210 if (Val < 0 || Val == CmpVal)
3215 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3216 /// from position Pos and ending in Pos+Size, falls within the specified
3217 /// sequential range (L, L+Pos]. or is undef.
3218 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3219 unsigned Pos, unsigned Size, int Low) {
3220 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3221 if (!isUndefOrEqual(Mask[i], Low))
3226 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3227 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3228 /// the second operand.
3229 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3230 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3231 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3232 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3233 return (Mask[0] < 2 && Mask[1] < 2);
3237 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3238 /// is suitable for input to PSHUFHW.
3239 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3240 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3243 // Lower quadword copied in order or undef.
3244 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3247 // Upper quadword shuffled.
3248 for (unsigned i = 4; i != 8; ++i)
3249 if (!isUndefOrInRange(Mask[i], 4, 8))
3252 if (VT == MVT::v16i16) {
3253 // Lower quadword copied in order or undef.
3254 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3257 // Upper quadword shuffled.
3258 for (unsigned i = 12; i != 16; ++i)
3259 if (!isUndefOrInRange(Mask[i], 12, 16))
3266 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3267 /// is suitable for input to PSHUFLW.
3268 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3269 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3272 // Upper quadword copied in order.
3273 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3276 // Lower quadword shuffled.
3277 for (unsigned i = 0; i != 4; ++i)
3278 if (!isUndefOrInRange(Mask[i], 0, 4))
3281 if (VT == MVT::v16i16) {
3282 // Upper quadword copied in order.
3283 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3286 // Lower quadword shuffled.
3287 for (unsigned i = 8; i != 12; ++i)
3288 if (!isUndefOrInRange(Mask[i], 8, 12))
3295 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3296 /// is suitable for input to PALIGNR.
3297 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3298 const X86Subtarget *Subtarget) {
3299 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3300 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3303 unsigned NumElts = VT.getVectorNumElements();
3304 unsigned NumLanes = VT.getSizeInBits()/128;
3305 unsigned NumLaneElts = NumElts/NumLanes;
3307 // Do not handle 64-bit element shuffles with palignr.
3308 if (NumLaneElts == 2)
3311 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3313 for (i = 0; i != NumLaneElts; ++i) {
3318 // Lane is all undef, go to next lane
3319 if (i == NumLaneElts)
3322 int Start = Mask[i+l];
3324 // Make sure its in this lane in one of the sources
3325 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3326 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3329 // If not lane 0, then we must match lane 0
3330 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3333 // Correct second source to be contiguous with first source
3334 if (Start >= (int)NumElts)
3335 Start -= NumElts - NumLaneElts;
3337 // Make sure we're shifting in the right direction.
3338 if (Start <= (int)(i+l))
3343 // Check the rest of the elements to see if they are consecutive.
3344 for (++i; i != NumLaneElts; ++i) {
3345 int Idx = Mask[i+l];
3347 // Make sure its in this lane
3348 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3349 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3352 // If not lane 0, then we must match lane 0
3353 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3356 if (Idx >= (int)NumElts)
3357 Idx -= NumElts - NumLaneElts;
3359 if (!isUndefOrEqual(Idx, Start+i))
3368 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3369 /// the two vector operands have swapped position.
3370 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3371 unsigned NumElems) {
3372 for (unsigned i = 0; i != NumElems; ++i) {
3376 else if (idx < (int)NumElems)
3377 Mask[i] = idx + NumElems;
3379 Mask[i] = idx - NumElems;
3383 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3384 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3385 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3386 /// reverse of what x86 shuffles want.
3387 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3388 bool Commuted = false) {
3389 if (!HasAVX && VT.getSizeInBits() == 256)
3392 unsigned NumElems = VT.getVectorNumElements();
3393 unsigned NumLanes = VT.getSizeInBits()/128;
3394 unsigned NumLaneElems = NumElems/NumLanes;
3396 if (NumLaneElems != 2 && NumLaneElems != 4)
3399 // VSHUFPSY divides the resulting vector into 4 chunks.
3400 // The sources are also splitted into 4 chunks, and each destination
3401 // chunk must come from a different source chunk.
3403 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3404 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3406 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3407 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3409 // VSHUFPDY divides the resulting vector into 4 chunks.
3410 // The sources are also splitted into 4 chunks, and each destination
3411 // chunk must come from a different source chunk.
3413 // SRC1 => X3 X2 X1 X0
3414 // SRC2 => Y3 Y2 Y1 Y0
3416 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3418 unsigned HalfLaneElems = NumLaneElems/2;
3419 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3420 for (unsigned i = 0; i != NumLaneElems; ++i) {
3421 int Idx = Mask[i+l];
3422 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3423 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3425 // For VSHUFPSY, the mask of the second half must be the same as the
3426 // first but with the appropriate offsets. This works in the same way as
3427 // VPERMILPS works with masks.
3428 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3430 if (!isUndefOrEqual(Idx, Mask[i]+l))
3438 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3439 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3440 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3441 if (!VT.is128BitVector())
3444 unsigned NumElems = VT.getVectorNumElements();
3449 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3450 return isUndefOrEqual(Mask[0], 6) &&
3451 isUndefOrEqual(Mask[1], 7) &&
3452 isUndefOrEqual(Mask[2], 2) &&
3453 isUndefOrEqual(Mask[3], 3);
3456 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3457 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3459 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3460 if (!VT.is128BitVector())
3463 unsigned NumElems = VT.getVectorNumElements();
3468 return isUndefOrEqual(Mask[0], 2) &&
3469 isUndefOrEqual(Mask[1], 3) &&
3470 isUndefOrEqual(Mask[2], 2) &&
3471 isUndefOrEqual(Mask[3], 3);
3474 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3475 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3476 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3477 if (!VT.is128BitVector())
3480 unsigned NumElems = VT.getVectorNumElements();
3482 if (NumElems != 2 && NumElems != 4)
3485 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3486 if (!isUndefOrEqual(Mask[i], i + NumElems))
3489 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3490 if (!isUndefOrEqual(Mask[i], i))
3496 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3497 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3498 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3499 if (!VT.is128BitVector())
3502 unsigned NumElems = VT.getVectorNumElements();
3504 if (NumElems != 2 && NumElems != 4)
3507 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3508 if (!isUndefOrEqual(Mask[i], i))
3511 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3512 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3519 // Some special combinations that can be optimized.
3522 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3523 SelectionDAG &DAG) {
3524 EVT VT = SVOp->getValueType(0);
3525 DebugLoc dl = SVOp->getDebugLoc();
3527 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3530 ArrayRef<int> Mask = SVOp->getMask();
3532 // These are the special masks that may be optimized.
3533 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3534 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3535 bool MatchEvenMask = true;
3536 bool MatchOddMask = true;
3537 for (int i=0; i<8; ++i) {
3538 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3539 MatchEvenMask = false;
3540 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3541 MatchOddMask = false;
3544 if (!MatchEvenMask && !MatchOddMask)
3547 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3549 SDValue Op0 = SVOp->getOperand(0);
3550 SDValue Op1 = SVOp->getOperand(1);
3552 if (MatchEvenMask) {
3553 // Shift the second operand right to 32 bits.
3554 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3555 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3557 // Shift the first operand left to 32 bits.
3558 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3559 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3561 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3562 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3565 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3566 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3567 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3568 bool HasAVX2, bool V2IsSplat = false) {
3569 unsigned NumElts = VT.getVectorNumElements();
3571 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3572 "Unsupported vector type for unpckh");
3574 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3575 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3578 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3579 // independently on 128-bit lanes.
3580 unsigned NumLanes = VT.getSizeInBits()/128;
3581 unsigned NumLaneElts = NumElts/NumLanes;
3583 for (unsigned l = 0; l != NumLanes; ++l) {
3584 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3585 i != (l+1)*NumLaneElts;
3588 int BitI1 = Mask[i+1];
3589 if (!isUndefOrEqual(BitI, j))
3592 if (!isUndefOrEqual(BitI1, NumElts))
3595 if (!isUndefOrEqual(BitI1, j + NumElts))
3604 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3605 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3606 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3607 bool HasAVX2, bool V2IsSplat = false) {
3608 unsigned NumElts = VT.getVectorNumElements();
3610 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3611 "Unsupported vector type for unpckh");
3613 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3614 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3617 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3618 // independently on 128-bit lanes.
3619 unsigned NumLanes = VT.getSizeInBits()/128;
3620 unsigned NumLaneElts = NumElts/NumLanes;
3622 for (unsigned l = 0; l != NumLanes; ++l) {
3623 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3624 i != (l+1)*NumLaneElts; i += 2, ++j) {
3626 int BitI1 = Mask[i+1];
3627 if (!isUndefOrEqual(BitI, j))
3630 if (isUndefOrEqual(BitI1, NumElts))
3633 if (!isUndefOrEqual(BitI1, j+NumElts))
3641 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3642 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3644 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3646 unsigned NumElts = VT.getVectorNumElements();
3648 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3649 "Unsupported vector type for unpckh");
3651 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3652 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3655 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3656 // FIXME: Need a better way to get rid of this, there's no latency difference
3657 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3658 // the former later. We should also remove the "_undef" special mask.
3659 if (NumElts == 4 && VT.getSizeInBits() == 256)
3662 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3663 // independently on 128-bit lanes.
3664 unsigned NumLanes = VT.getSizeInBits()/128;
3665 unsigned NumLaneElts = NumElts/NumLanes;
3667 for (unsigned l = 0; l != NumLanes; ++l) {
3668 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3669 i != (l+1)*NumLaneElts;
3672 int BitI1 = Mask[i+1];
3674 if (!isUndefOrEqual(BitI, j))
3676 if (!isUndefOrEqual(BitI1, j))
3684 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3685 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3687 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3688 unsigned NumElts = VT.getVectorNumElements();
3690 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3691 "Unsupported vector type for unpckh");
3693 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3694 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3697 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3698 // independently on 128-bit lanes.
3699 unsigned NumLanes = VT.getSizeInBits()/128;
3700 unsigned NumLaneElts = NumElts/NumLanes;
3702 for (unsigned l = 0; l != NumLanes; ++l) {
3703 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3704 i != (l+1)*NumLaneElts; i += 2, ++j) {
3706 int BitI1 = Mask[i+1];
3707 if (!isUndefOrEqual(BitI, j))
3709 if (!isUndefOrEqual(BitI1, j))
3716 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3717 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3718 /// MOVSD, and MOVD, i.e. setting the lowest element.
3719 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3720 if (VT.getVectorElementType().getSizeInBits() < 32)
3722 if (!VT.is128BitVector())
3725 unsigned NumElts = VT.getVectorNumElements();
3727 if (!isUndefOrEqual(Mask[0], NumElts))
3730 for (unsigned i = 1; i != NumElts; ++i)
3731 if (!isUndefOrEqual(Mask[i], i))
3737 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3738 /// as permutations between 128-bit chunks or halves. As an example: this
3740 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3741 /// The first half comes from the second half of V1 and the second half from the
3742 /// the second half of V2.
3743 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3744 if (!HasAVX || !VT.is256BitVector())
3747 // The shuffle result is divided into half A and half B. In total the two
3748 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3749 // B must come from C, D, E or F.
3750 unsigned HalfSize = VT.getVectorNumElements()/2;
3751 bool MatchA = false, MatchB = false;
3753 // Check if A comes from one of C, D, E, F.
3754 for (unsigned Half = 0; Half != 4; ++Half) {
3755 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3761 // Check if B comes from one of C, D, E, F.
3762 for (unsigned Half = 0; Half != 4; ++Half) {
3763 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3769 return MatchA && MatchB;
3772 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3773 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3774 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3775 EVT VT = SVOp->getValueType(0);
3777 unsigned HalfSize = VT.getVectorNumElements()/2;
3779 unsigned FstHalf = 0, SndHalf = 0;
3780 for (unsigned i = 0; i < HalfSize; ++i) {
3781 if (SVOp->getMaskElt(i) > 0) {
3782 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3786 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3787 if (SVOp->getMaskElt(i) > 0) {
3788 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3793 return (FstHalf | (SndHalf << 4));
3796 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3797 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3798 /// Note that VPERMIL mask matching is different depending whether theunderlying
3799 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3800 /// to the same elements of the low, but to the higher half of the source.
3801 /// In VPERMILPD the two lanes could be shuffled independently of each other
3802 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3803 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3807 unsigned NumElts = VT.getVectorNumElements();
3808 // Only match 256-bit with 32/64-bit types
3809 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3812 unsigned NumLanes = VT.getSizeInBits()/128;
3813 unsigned LaneSize = NumElts/NumLanes;
3814 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3815 for (unsigned i = 0; i != LaneSize; ++i) {
3816 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3818 if (NumElts != 8 || l == 0)
3820 // VPERMILPS handling
3823 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3831 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3832 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3833 /// element of vector 2 and the other elements to come from vector 1 in order.
3834 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3835 bool V2IsSplat = false, bool V2IsUndef = false) {
3836 if (!VT.is128BitVector())
3839 unsigned NumOps = VT.getVectorNumElements();
3840 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3843 if (!isUndefOrEqual(Mask[0], 0))
3846 for (unsigned i = 1; i != NumOps; ++i)
3847 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3848 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3849 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3855 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3856 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3857 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3858 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3859 const X86Subtarget *Subtarget) {
3860 if (!Subtarget->hasSSE3())
3863 unsigned NumElems = VT.getVectorNumElements();
3865 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3866 (VT.getSizeInBits() == 256 && NumElems != 8))
3869 // "i+1" is the value the indexed mask element must have
3870 for (unsigned i = 0; i != NumElems; i += 2)
3871 if (!isUndefOrEqual(Mask[i], i+1) ||
3872 !isUndefOrEqual(Mask[i+1], i+1))
3878 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3879 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3880 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3881 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3882 const X86Subtarget *Subtarget) {
3883 if (!Subtarget->hasSSE3())
3886 unsigned NumElems = VT.getVectorNumElements();
3888 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3889 (VT.getSizeInBits() == 256 && NumElems != 8))
3892 // "i" is the value the indexed mask element must have
3893 for (unsigned i = 0; i != NumElems; i += 2)
3894 if (!isUndefOrEqual(Mask[i], i) ||
3895 !isUndefOrEqual(Mask[i+1], i))
3901 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3902 /// specifies a shuffle of elements that is suitable for input to 256-bit
3903 /// version of MOVDDUP.
3904 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3905 if (!HasAVX || !VT.is256BitVector())
3908 unsigned NumElts = VT.getVectorNumElements();
3912 for (unsigned i = 0; i != NumElts/2; ++i)
3913 if (!isUndefOrEqual(Mask[i], 0))
3915 for (unsigned i = NumElts/2; i != NumElts; ++i)
3916 if (!isUndefOrEqual(Mask[i], NumElts/2))
3921 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3922 /// specifies a shuffle of elements that is suitable for input to 128-bit
3923 /// version of MOVDDUP.
3924 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3925 if (!VT.is128BitVector())
3928 unsigned e = VT.getVectorNumElements() / 2;
3929 for (unsigned i = 0; i != e; ++i)
3930 if (!isUndefOrEqual(Mask[i], i))
3932 for (unsigned i = 0; i != e; ++i)
3933 if (!isUndefOrEqual(Mask[e+i], i))
3938 /// isVEXTRACTF128Index - Return true if the specified
3939 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3940 /// suitable for input to VEXTRACTF128.
3941 bool X86::isVEXTRACTF128Index(SDNode *N) {
3942 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3945 // The index should be aligned on a 128-bit boundary.
3947 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3949 unsigned VL = N->getValueType(0).getVectorNumElements();
3950 unsigned VBits = N->getValueType(0).getSizeInBits();
3951 unsigned ElSize = VBits / VL;
3952 bool Result = (Index * ElSize) % 128 == 0;
3957 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3958 /// operand specifies a subvector insert that is suitable for input to
3960 bool X86::isVINSERTF128Index(SDNode *N) {
3961 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3964 // The index should be aligned on a 128-bit boundary.
3966 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3968 unsigned VL = N->getValueType(0).getVectorNumElements();
3969 unsigned VBits = N->getValueType(0).getSizeInBits();
3970 unsigned ElSize = VBits / VL;
3971 bool Result = (Index * ElSize) % 128 == 0;
3976 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3977 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3978 /// Handles 128-bit and 256-bit.
3979 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3980 EVT VT = N->getValueType(0);
3982 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3983 "Unsupported vector type for PSHUF/SHUFP");
3985 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3986 // independently on 128-bit lanes.
3987 unsigned NumElts = VT.getVectorNumElements();
3988 unsigned NumLanes = VT.getSizeInBits()/128;
3989 unsigned NumLaneElts = NumElts/NumLanes;
3991 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3992 "Only supports 2 or 4 elements per lane");
3994 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3996 for (unsigned i = 0; i != NumElts; ++i) {
3997 int Elt = N->getMaskElt(i);
3998 if (Elt < 0) continue;
3999 Elt &= NumLaneElts - 1;
4000 unsigned ShAmt = (i << Shift) % 8;
4001 Mask |= Elt << ShAmt;
4007 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4008 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4009 static unsigned getShufflePSHUFHWImmediate(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 last 4.
4020 for (unsigned i = 0; i < 4; ++i) {
4021 int Elt = N->getMaskElt(l+i+4);
4022 if (Elt < 0) continue;
4023 Elt &= 0x3; // only 2-bits.
4024 Mask |= Elt << (i * 2);
4031 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4032 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4033 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4034 EVT VT = N->getValueType(0);
4036 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4037 "Unsupported vector type for PSHUFHW");
4039 unsigned NumElts = VT.getVectorNumElements();
4042 for (unsigned l = 0; l != NumElts; l += 8) {
4043 // 8 nodes per lane, but we only care about the first 4.
4044 for (unsigned i = 0; i < 4; ++i) {
4045 int Elt = N->getMaskElt(l+i);
4046 if (Elt < 0) continue;
4047 Elt &= 0x3; // only 2-bits
4048 Mask |= Elt << (i * 2);
4055 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4056 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4057 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4058 EVT VT = SVOp->getValueType(0);
4059 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4061 unsigned NumElts = VT.getVectorNumElements();
4062 unsigned NumLanes = VT.getSizeInBits()/128;
4063 unsigned NumLaneElts = NumElts/NumLanes;
4067 for (i = 0; i != NumElts; ++i) {
4068 Val = SVOp->getMaskElt(i);
4072 if (Val >= (int)NumElts)
4073 Val -= NumElts - NumLaneElts;
4075 assert(Val - i > 0 && "PALIGNR imm should be positive");
4076 return (Val - i) * EltSize;
4079 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4080 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4082 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4083 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4084 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4087 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4089 EVT VecVT = N->getOperand(0).getValueType();
4090 EVT ElVT = VecVT.getVectorElementType();
4092 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4093 return Index / NumElemsPerChunk;
4096 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4097 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4099 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4100 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4101 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4104 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4106 EVT VecVT = N->getValueType(0);
4107 EVT ElVT = VecVT.getVectorElementType();
4109 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4110 return Index / NumElemsPerChunk;
4113 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4114 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4115 /// Handles 256-bit.
4116 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4117 EVT VT = N->getValueType(0);
4119 unsigned NumElts = VT.getVectorNumElements();
4121 assert((VT.is256BitVector() && NumElts == 4) &&
4122 "Unsupported vector type for VPERMQ/VPERMPD");
4125 for (unsigned i = 0; i != NumElts; ++i) {
4126 int Elt = N->getMaskElt(i);
4129 Mask |= Elt << (i*2);
4134 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4136 bool X86::isZeroNode(SDValue Elt) {
4137 return ((isa<ConstantSDNode>(Elt) &&
4138 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4139 (isa<ConstantFPSDNode>(Elt) &&
4140 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4143 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4144 /// their permute mask.
4145 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4146 SelectionDAG &DAG) {
4147 EVT VT = SVOp->getValueType(0);
4148 unsigned NumElems = VT.getVectorNumElements();
4149 SmallVector<int, 8> MaskVec;
4151 for (unsigned i = 0; i != NumElems; ++i) {
4152 int Idx = SVOp->getMaskElt(i);
4154 if (Idx < (int)NumElems)
4159 MaskVec.push_back(Idx);
4161 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4162 SVOp->getOperand(0), &MaskVec[0]);
4165 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4166 /// match movhlps. The lower half elements should come from upper half of
4167 /// V1 (and in order), and the upper half elements should come from the upper
4168 /// half of V2 (and in order).
4169 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4170 if (!VT.is128BitVector())
4172 if (VT.getVectorNumElements() != 4)
4174 for (unsigned i = 0, e = 2; i != e; ++i)
4175 if (!isUndefOrEqual(Mask[i], i+2))
4177 for (unsigned i = 2; i != 4; ++i)
4178 if (!isUndefOrEqual(Mask[i], i+4))
4183 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4184 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4186 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4187 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4189 N = N->getOperand(0).getNode();
4190 if (!ISD::isNON_EXTLoad(N))
4193 *LD = cast<LoadSDNode>(N);
4197 // Test whether the given value is a vector value which will be legalized
4199 static bool WillBeConstantPoolLoad(SDNode *N) {
4200 if (N->getOpcode() != ISD::BUILD_VECTOR)
4203 // Check for any non-constant elements.
4204 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4205 switch (N->getOperand(i).getNode()->getOpcode()) {
4207 case ISD::ConstantFP:
4214 // Vectors of all-zeros and all-ones are materialized with special
4215 // instructions rather than being loaded.
4216 return !ISD::isBuildVectorAllZeros(N) &&
4217 !ISD::isBuildVectorAllOnes(N);
4220 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4221 /// match movlp{s|d}. The lower half elements should come from lower half of
4222 /// V1 (and in order), and the upper half elements should come from the upper
4223 /// half of V2 (and in order). And since V1 will become the source of the
4224 /// MOVLP, it must be either a vector load or a scalar load to vector.
4225 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4226 ArrayRef<int> Mask, EVT VT) {
4227 if (!VT.is128BitVector())
4230 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4232 // Is V2 is a vector load, don't do this transformation. We will try to use
4233 // load folding shufps op.
4234 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4237 unsigned NumElems = VT.getVectorNumElements();
4239 if (NumElems != 2 && NumElems != 4)
4241 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4242 if (!isUndefOrEqual(Mask[i], i))
4244 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4245 if (!isUndefOrEqual(Mask[i], i+NumElems))
4250 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4252 static bool isSplatVector(SDNode *N) {
4253 if (N->getOpcode() != ISD::BUILD_VECTOR)
4256 SDValue SplatValue = N->getOperand(0);
4257 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4258 if (N->getOperand(i) != SplatValue)
4263 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4264 /// to an zero vector.
4265 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4266 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4267 SDValue V1 = N->getOperand(0);
4268 SDValue V2 = N->getOperand(1);
4269 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4270 for (unsigned i = 0; i != NumElems; ++i) {
4271 int Idx = N->getMaskElt(i);
4272 if (Idx >= (int)NumElems) {
4273 unsigned Opc = V2.getOpcode();
4274 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4276 if (Opc != ISD::BUILD_VECTOR ||
4277 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4279 } else if (Idx >= 0) {
4280 unsigned Opc = V1.getOpcode();
4281 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4283 if (Opc != ISD::BUILD_VECTOR ||
4284 !X86::isZeroNode(V1.getOperand(Idx)))
4291 /// getZeroVector - Returns a vector of specified type with all zero elements.
4293 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4294 SelectionDAG &DAG, DebugLoc dl) {
4295 assert(VT.isVector() && "Expected a vector type");
4296 unsigned Size = VT.getSizeInBits();
4298 // Always build SSE zero vectors as <4 x i32> bitcasted
4299 // to their dest type. This ensures they get CSE'd.
4301 if (Size == 128) { // SSE
4302 if (Subtarget->hasSSE2()) { // SSE2
4303 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4304 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4306 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4307 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4309 } else if (Size == 256) { // AVX
4310 if (Subtarget->hasAVX2()) { // AVX2
4311 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4312 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4313 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4315 // 256-bit logic and arithmetic instructions in AVX are all
4316 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4317 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4318 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4319 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4322 llvm_unreachable("Unexpected vector type");
4324 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4327 /// getOnesVector - Returns a vector of specified type with all bits set.
4328 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4329 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4330 /// Then bitcast to their original type, ensuring they get CSE'd.
4331 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4333 assert(VT.isVector() && "Expected a vector type");
4334 unsigned Size = VT.getSizeInBits();
4336 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4339 if (HasAVX2) { // AVX2
4340 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4341 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4343 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4344 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4346 } else if (Size == 128) {
4347 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4349 llvm_unreachable("Unexpected vector type");
4351 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4354 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4355 /// that point to V2 points to its first element.
4356 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4357 for (unsigned i = 0; i != NumElems; ++i) {
4358 if (Mask[i] > (int)NumElems) {
4364 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4365 /// operation of specified width.
4366 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4368 unsigned NumElems = VT.getVectorNumElements();
4369 SmallVector<int, 8> Mask;
4370 Mask.push_back(NumElems);
4371 for (unsigned i = 1; i != NumElems; ++i)
4373 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4376 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4377 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4379 unsigned NumElems = VT.getVectorNumElements();
4380 SmallVector<int, 8> Mask;
4381 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4383 Mask.push_back(i + NumElems);
4385 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4388 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4389 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4391 unsigned NumElems = VT.getVectorNumElements();
4392 SmallVector<int, 8> Mask;
4393 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4394 Mask.push_back(i + Half);
4395 Mask.push_back(i + NumElems + Half);
4397 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4400 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4401 // a generic shuffle instruction because the target has no such instructions.
4402 // Generate shuffles which repeat i16 and i8 several times until they can be
4403 // represented by v4f32 and then be manipulated by target suported shuffles.
4404 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4405 EVT VT = V.getValueType();
4406 int NumElems = VT.getVectorNumElements();
4407 DebugLoc dl = V.getDebugLoc();
4409 while (NumElems > 4) {
4410 if (EltNo < NumElems/2) {
4411 V = getUnpackl(DAG, dl, VT, V, V);
4413 V = getUnpackh(DAG, dl, VT, V, V);
4414 EltNo -= NumElems/2;
4421 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4422 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4423 EVT VT = V.getValueType();
4424 DebugLoc dl = V.getDebugLoc();
4425 unsigned Size = VT.getSizeInBits();
4428 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4429 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4430 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4432 } else if (Size == 256) {
4433 // To use VPERMILPS to splat scalars, the second half of indicies must
4434 // refer to the higher part, which is a duplication of the lower one,
4435 // because VPERMILPS can only handle in-lane permutations.
4436 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4437 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4439 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4440 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4443 llvm_unreachable("Vector size not supported");
4445 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4448 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4449 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4450 EVT SrcVT = SV->getValueType(0);
4451 SDValue V1 = SV->getOperand(0);
4452 DebugLoc dl = SV->getDebugLoc();
4454 int EltNo = SV->getSplatIndex();
4455 int NumElems = SrcVT.getVectorNumElements();
4456 unsigned Size = SrcVT.getSizeInBits();
4458 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4459 "Unknown how to promote splat for type");
4461 // Extract the 128-bit part containing the splat element and update
4462 // the splat element index when it refers to the higher register.
4464 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4465 if (EltNo >= NumElems/2)
4466 EltNo -= NumElems/2;
4469 // All i16 and i8 vector types can't be used directly by a generic shuffle
4470 // instruction because the target has no such instruction. Generate shuffles
4471 // which repeat i16 and i8 several times until they fit in i32, and then can
4472 // be manipulated by target suported shuffles.
4473 EVT EltVT = SrcVT.getVectorElementType();
4474 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4475 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4477 // Recreate the 256-bit vector and place the same 128-bit vector
4478 // into the low and high part. This is necessary because we want
4479 // to use VPERM* to shuffle the vectors
4481 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4484 return getLegalSplat(DAG, V1, EltNo);
4487 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4488 /// vector of zero or undef vector. This produces a shuffle where the low
4489 /// element of V2 is swizzled into the zero/undef vector, landing at element
4490 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4491 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4493 const X86Subtarget *Subtarget,
4494 SelectionDAG &DAG) {
4495 EVT VT = V2.getValueType();
4497 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4498 unsigned NumElems = VT.getVectorNumElements();
4499 SmallVector<int, 16> MaskVec;
4500 for (unsigned i = 0; i != NumElems; ++i)
4501 // If this is the insertion idx, put the low elt of V2 here.
4502 MaskVec.push_back(i == Idx ? NumElems : i);
4503 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4506 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4507 /// target specific opcode. Returns true if the Mask could be calculated.
4508 /// Sets IsUnary to true if only uses one source.
4509 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4510 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4511 unsigned NumElems = VT.getVectorNumElements();
4515 switch(N->getOpcode()) {
4517 ImmN = N->getOperand(N->getNumOperands()-1);
4518 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4520 case X86ISD::UNPCKH:
4521 DecodeUNPCKHMask(VT, Mask);
4523 case X86ISD::UNPCKL:
4524 DecodeUNPCKLMask(VT, Mask);
4526 case X86ISD::MOVHLPS:
4527 DecodeMOVHLPSMask(NumElems, Mask);
4529 case X86ISD::MOVLHPS:
4530 DecodeMOVLHPSMask(NumElems, Mask);
4532 case X86ISD::PSHUFD:
4533 case X86ISD::VPERMILP:
4534 ImmN = N->getOperand(N->getNumOperands()-1);
4535 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4538 case X86ISD::PSHUFHW:
4539 ImmN = N->getOperand(N->getNumOperands()-1);
4540 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4543 case X86ISD::PSHUFLW:
4544 ImmN = N->getOperand(N->getNumOperands()-1);
4545 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4548 case X86ISD::VPERMI:
4549 ImmN = N->getOperand(N->getNumOperands()-1);
4550 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4554 case X86ISD::MOVSD: {
4555 // The index 0 always comes from the first element of the second source,
4556 // this is why MOVSS and MOVSD are used in the first place. The other
4557 // elements come from the other positions of the first source vector
4558 Mask.push_back(NumElems);
4559 for (unsigned i = 1; i != NumElems; ++i) {
4564 case X86ISD::VPERM2X128:
4565 ImmN = N->getOperand(N->getNumOperands()-1);
4566 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4567 if (Mask.empty()) return false;
4569 case X86ISD::MOVDDUP:
4570 case X86ISD::MOVLHPD:
4571 case X86ISD::MOVLPD:
4572 case X86ISD::MOVLPS:
4573 case X86ISD::MOVSHDUP:
4574 case X86ISD::MOVSLDUP:
4575 case X86ISD::PALIGN:
4576 // Not yet implemented
4578 default: llvm_unreachable("unknown target shuffle node");
4584 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4585 /// element of the result of the vector shuffle.
4586 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4589 return SDValue(); // Limit search depth.
4591 SDValue V = SDValue(N, 0);
4592 EVT VT = V.getValueType();
4593 unsigned Opcode = V.getOpcode();
4595 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4596 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4597 int Elt = SV->getMaskElt(Index);
4600 return DAG.getUNDEF(VT.getVectorElementType());
4602 unsigned NumElems = VT.getVectorNumElements();
4603 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4604 : SV->getOperand(1);
4605 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4608 // Recurse into target specific vector shuffles to find scalars.
4609 if (isTargetShuffle(Opcode)) {
4610 MVT ShufVT = V.getValueType().getSimpleVT();
4611 unsigned NumElems = ShufVT.getVectorNumElements();
4612 SmallVector<int, 16> ShuffleMask;
4616 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4619 int Elt = ShuffleMask[Index];
4621 return DAG.getUNDEF(ShufVT.getVectorElementType());
4623 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4625 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4629 // Actual nodes that may contain scalar elements
4630 if (Opcode == ISD::BITCAST) {
4631 V = V.getOperand(0);
4632 EVT SrcVT = V.getValueType();
4633 unsigned NumElems = VT.getVectorNumElements();
4635 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4639 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4640 return (Index == 0) ? V.getOperand(0)
4641 : DAG.getUNDEF(VT.getVectorElementType());
4643 if (V.getOpcode() == ISD::BUILD_VECTOR)
4644 return V.getOperand(Index);
4649 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4650 /// shuffle operation which come from a consecutively from a zero. The
4651 /// search can start in two different directions, from left or right.
4653 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4654 bool ZerosFromLeft, SelectionDAG &DAG) {
4656 for (i = 0; i != NumElems; ++i) {
4657 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4658 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4659 if (!(Elt.getNode() &&
4660 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4667 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4668 /// correspond consecutively to elements from one of the vector operands,
4669 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4671 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4672 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4673 unsigned NumElems, unsigned &OpNum) {
4674 bool SeenV1 = false;
4675 bool SeenV2 = false;
4677 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4678 int Idx = SVOp->getMaskElt(i);
4679 // Ignore undef indicies
4683 if (Idx < (int)NumElems)
4688 // Only accept consecutive elements from the same vector
4689 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4693 OpNum = SeenV1 ? 0 : 1;
4697 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4698 /// logical left shift of a vector.
4699 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4700 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4701 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4702 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4703 false /* check zeros from right */, DAG);
4709 // Considering the elements in the mask that are not consecutive zeros,
4710 // check if they consecutively come from only one of the source vectors.
4712 // V1 = {X, A, B, C} 0
4714 // vector_shuffle V1, V2 <1, 2, 3, X>
4716 if (!isShuffleMaskConsecutive(SVOp,
4717 0, // Mask Start Index
4718 NumElems-NumZeros, // Mask End Index(exclusive)
4719 NumZeros, // Where to start looking in the src vector
4720 NumElems, // Number of elements in vector
4721 OpSrc)) // Which source operand ?
4726 ShVal = SVOp->getOperand(OpSrc);
4730 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4731 /// logical left shift of a vector.
4732 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4733 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4734 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4735 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4736 true /* check zeros from left */, DAG);
4742 // Considering the elements in the mask that are not consecutive zeros,
4743 // check if they consecutively come from only one of the source vectors.
4745 // 0 { A, B, X, X } = V2
4747 // vector_shuffle V1, V2 <X, X, 4, 5>
4749 if (!isShuffleMaskConsecutive(SVOp,
4750 NumZeros, // Mask Start Index
4751 NumElems, // Mask End Index(exclusive)
4752 0, // Where to start looking in the src vector
4753 NumElems, // Number of elements in vector
4754 OpSrc)) // Which source operand ?
4759 ShVal = SVOp->getOperand(OpSrc);
4763 /// isVectorShift - Returns true if the shuffle can be implemented as a
4764 /// logical left or right shift of a vector.
4765 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4766 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4767 // Although the logic below support any bitwidth size, there are no
4768 // shift instructions which handle more than 128-bit vectors.
4769 if (!SVOp->getValueType(0).is128BitVector())
4772 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4773 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4779 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4781 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4782 unsigned NumNonZero, unsigned NumZero,
4784 const X86Subtarget* Subtarget,
4785 const TargetLowering &TLI) {
4789 DebugLoc dl = Op.getDebugLoc();
4792 for (unsigned i = 0; i < 16; ++i) {
4793 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4794 if (ThisIsNonZero && First) {
4796 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4798 V = DAG.getUNDEF(MVT::v8i16);
4803 SDValue ThisElt(0, 0), LastElt(0, 0);
4804 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4805 if (LastIsNonZero) {
4806 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4807 MVT::i16, Op.getOperand(i-1));
4809 if (ThisIsNonZero) {
4810 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4811 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4812 ThisElt, DAG.getConstant(8, MVT::i8));
4814 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4818 if (ThisElt.getNode())
4819 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4820 DAG.getIntPtrConstant(i/2));
4824 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4827 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4829 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4830 unsigned NumNonZero, unsigned NumZero,
4832 const X86Subtarget* Subtarget,
4833 const TargetLowering &TLI) {
4837 DebugLoc dl = Op.getDebugLoc();
4840 for (unsigned i = 0; i < 8; ++i) {
4841 bool isNonZero = (NonZeros & (1 << i)) != 0;
4845 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4847 V = DAG.getUNDEF(MVT::v8i16);
4850 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4851 MVT::v8i16, V, Op.getOperand(i),
4852 DAG.getIntPtrConstant(i));
4859 /// getVShift - Return a vector logical shift node.
4861 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4862 unsigned NumBits, SelectionDAG &DAG,
4863 const TargetLowering &TLI, DebugLoc dl) {
4864 assert(VT.is128BitVector() && "Unknown type for VShift");
4865 EVT ShVT = MVT::v2i64;
4866 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4867 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4868 return DAG.getNode(ISD::BITCAST, dl, VT,
4869 DAG.getNode(Opc, dl, ShVT, SrcOp,
4870 DAG.getConstant(NumBits,
4871 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4875 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4876 SelectionDAG &DAG) const {
4878 // Check if the scalar load can be widened into a vector load. And if
4879 // the address is "base + cst" see if the cst can be "absorbed" into
4880 // the shuffle mask.
4881 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4882 SDValue Ptr = LD->getBasePtr();
4883 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4885 EVT PVT = LD->getValueType(0);
4886 if (PVT != MVT::i32 && PVT != MVT::f32)
4891 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4892 FI = FINode->getIndex();
4894 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4895 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4896 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4897 Offset = Ptr.getConstantOperandVal(1);
4898 Ptr = Ptr.getOperand(0);
4903 // FIXME: 256-bit vector instructions don't require a strict alignment,
4904 // improve this code to support it better.
4905 unsigned RequiredAlign = VT.getSizeInBits()/8;
4906 SDValue Chain = LD->getChain();
4907 // Make sure the stack object alignment is at least 16 or 32.
4908 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4909 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4910 if (MFI->isFixedObjectIndex(FI)) {
4911 // Can't change the alignment. FIXME: It's possible to compute
4912 // the exact stack offset and reference FI + adjust offset instead.
4913 // If someone *really* cares about this. That's the way to implement it.
4916 MFI->setObjectAlignment(FI, RequiredAlign);
4920 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4921 // Ptr + (Offset & ~15).
4924 if ((Offset % RequiredAlign) & 3)
4926 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4928 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4929 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4931 int EltNo = (Offset - StartOffset) >> 2;
4932 unsigned NumElems = VT.getVectorNumElements();
4934 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4935 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4936 LD->getPointerInfo().getWithOffset(StartOffset),
4937 false, false, false, 0);
4939 SmallVector<int, 8> Mask;
4940 for (unsigned i = 0; i != NumElems; ++i)
4941 Mask.push_back(EltNo);
4943 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4949 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4950 /// vector of type 'VT', see if the elements can be replaced by a single large
4951 /// load which has the same value as a build_vector whose operands are 'elts'.
4953 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4955 /// FIXME: we'd also like to handle the case where the last elements are zero
4956 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4957 /// There's even a handy isZeroNode for that purpose.
4958 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4959 DebugLoc &DL, SelectionDAG &DAG) {
4960 EVT EltVT = VT.getVectorElementType();
4961 unsigned NumElems = Elts.size();
4963 LoadSDNode *LDBase = NULL;
4964 unsigned LastLoadedElt = -1U;
4966 // For each element in the initializer, see if we've found a load or an undef.
4967 // If we don't find an initial load element, or later load elements are
4968 // non-consecutive, bail out.
4969 for (unsigned i = 0; i < NumElems; ++i) {
4970 SDValue Elt = Elts[i];
4972 if (!Elt.getNode() ||
4973 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4976 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4978 LDBase = cast<LoadSDNode>(Elt.getNode());
4982 if (Elt.getOpcode() == ISD::UNDEF)
4985 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4986 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4991 // If we have found an entire vector of loads and undefs, then return a large
4992 // load of the entire vector width starting at the base pointer. If we found
4993 // consecutive loads for the low half, generate a vzext_load node.
4994 if (LastLoadedElt == NumElems - 1) {
4995 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4996 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4997 LDBase->getPointerInfo(),
4998 LDBase->isVolatile(), LDBase->isNonTemporal(),
4999 LDBase->isInvariant(), 0);
5000 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5001 LDBase->getPointerInfo(),
5002 LDBase->isVolatile(), LDBase->isNonTemporal(),
5003 LDBase->isInvariant(), LDBase->getAlignment());
5005 if (NumElems == 4 && LastLoadedElt == 1 &&
5006 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5007 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5008 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5010 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5011 LDBase->getPointerInfo(),
5012 LDBase->getAlignment(),
5013 false/*isVolatile*/, true/*ReadMem*/,
5016 // Make sure the newly-created LOAD is in the same position as LDBase in
5017 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5018 // update uses of LDBase's output chain to use the TokenFactor.
5019 if (LDBase->hasAnyUseOfValue(1)) {
5020 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5021 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5022 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5023 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5024 SDValue(ResNode.getNode(), 1));
5027 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5032 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5033 /// to generate a splat value for the following cases:
5034 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5035 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5036 /// a scalar load, or a constant.
5037 /// The VBROADCAST node is returned when a pattern is found,
5038 /// or SDValue() otherwise.
5040 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5041 if (!Subtarget->hasAVX())
5044 EVT VT = Op.getValueType();
5045 DebugLoc dl = Op.getDebugLoc();
5047 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5048 "Unsupported vector type for broadcast.");
5053 switch (Op.getOpcode()) {
5055 // Unknown pattern found.
5058 case ISD::BUILD_VECTOR: {
5059 // The BUILD_VECTOR node must be a splat.
5060 if (!isSplatVector(Op.getNode()))
5063 Ld = Op.getOperand(0);
5064 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5065 Ld.getOpcode() == ISD::ConstantFP);
5067 // The suspected load node has several users. Make sure that all
5068 // of its users are from the BUILD_VECTOR node.
5069 // Constants may have multiple users.
5070 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5075 case ISD::VECTOR_SHUFFLE: {
5076 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5078 // Shuffles must have a splat mask where the first element is
5080 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5083 SDValue Sc = Op.getOperand(0);
5084 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5085 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5087 if (!Subtarget->hasAVX2())
5090 // Use the register form of the broadcast instruction available on AVX2.
5091 if (VT.is256BitVector())
5092 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5093 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5096 Ld = Sc.getOperand(0);
5097 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5098 Ld.getOpcode() == ISD::ConstantFP);
5100 // The scalar_to_vector node and the suspected
5101 // load node must have exactly one user.
5102 // Constants may have multiple users.
5103 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5109 bool Is256 = VT.is256BitVector();
5111 // Handle the broadcasting a single constant scalar from the constant pool
5112 // into a vector. On Sandybridge it is still better to load a constant vector
5113 // from the constant pool and not to broadcast it from a scalar.
5114 if (ConstSplatVal && Subtarget->hasAVX2()) {
5115 EVT CVT = Ld.getValueType();
5116 assert(!CVT.isVector() && "Must not broadcast a vector type");
5117 unsigned ScalarSize = CVT.getSizeInBits();
5119 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5120 const Constant *C = 0;
5121 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5122 C = CI->getConstantIntValue();
5123 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5124 C = CF->getConstantFPValue();
5126 assert(C && "Invalid constant type");
5128 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5129 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5130 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5131 MachinePointerInfo::getConstantPool(),
5132 false, false, false, Alignment);
5134 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5138 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5139 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5141 // Handle AVX2 in-register broadcasts.
5142 if (!IsLoad && Subtarget->hasAVX2() &&
5143 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5144 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5146 // The scalar source must be a normal load.
5150 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5151 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5153 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5154 // double since there is no vbroadcastsd xmm
5155 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5156 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5157 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5160 // Unsupported broadcast.
5164 // LowerVectorFpExtend - Recognize the scalarized FP_EXTEND from v2f32 to v2f64
5165 // and convert it into X86ISD::VFPEXT due to the current ISD::FP_EXTEND has the
5166 // constraint of matching input/output vector elements.
5168 X86TargetLowering::LowerVectorFpExtend(SDValue &Op, SelectionDAG &DAG) const {
5169 DebugLoc DL = Op.getDebugLoc();
5170 SDNode *N = Op.getNode();
5171 EVT VT = Op.getValueType();
5172 unsigned NumElts = Op.getNumOperands();
5174 // Check supported types and sub-targets.
5176 // Only v2f32 -> v2f64 needs special handling.
5177 if (VT != MVT::v2f64 || !Subtarget->hasSSE2())
5182 SmallVector<int, 8> Mask;
5183 EVT SrcVT = MVT::Other;
5185 // Check the patterns could be translated into X86vfpext.
5186 for (unsigned i = 0; i < NumElts; ++i) {
5187 SDValue In = N->getOperand(i);
5188 unsigned Opcode = In.getOpcode();
5190 // Skip if the element is undefined.
5191 if (Opcode == ISD::UNDEF) {
5196 // Quit if one of the elements is not defined from 'fpext'.
5197 if (Opcode != ISD::FP_EXTEND)
5200 // Check how the source of 'fpext' is defined.
5201 SDValue L2In = In.getOperand(0);
5202 EVT L2InVT = L2In.getValueType();
5204 // Check the original type
5205 if (SrcVT == MVT::Other)
5207 else if (SrcVT != L2InVT) // Quit if non-homogenous typed.
5210 // Check whether the value being 'fpext'ed is extracted from the same
5212 Opcode = L2In.getOpcode();
5214 // Quit if it's not extracted with a constant index.
5215 if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
5216 !isa<ConstantSDNode>(L2In.getOperand(1)))
5219 SDValue ExtractedFromVec = L2In.getOperand(0);
5221 if (VecIn.getNode() == 0) {
5222 VecIn = ExtractedFromVec;
5223 VecInVT = ExtractedFromVec.getValueType();
5224 } else if (VecIn != ExtractedFromVec) // Quit if built from more than 1 vec.
5227 Mask.push_back(cast<ConstantSDNode>(L2In.getOperand(1))->getZExtValue());
5230 // Quit if all operands of BUILD_VECTOR are undefined.
5231 if (!VecIn.getNode())
5234 // Fill the remaining mask as undef.
5235 for (unsigned i = NumElts; i < VecInVT.getVectorNumElements(); ++i)
5238 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
5239 DAG.getVectorShuffle(VecInVT, DL,
5240 VecIn, DAG.getUNDEF(VecInVT),
5245 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5246 DebugLoc dl = Op.getDebugLoc();
5248 EVT VT = Op.getValueType();
5249 EVT ExtVT = VT.getVectorElementType();
5250 unsigned NumElems = Op.getNumOperands();
5252 // Vectors containing all zeros can be matched by pxor and xorps later
5253 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5254 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5255 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5256 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5259 return getZeroVector(VT, Subtarget, DAG, dl);
5262 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5263 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5264 // vpcmpeqd on 256-bit vectors.
5265 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5266 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5269 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5272 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5273 if (Broadcast.getNode())
5276 SDValue FpExt = LowerVectorFpExtend(Op, DAG);
5277 if (FpExt.getNode())
5280 unsigned EVTBits = ExtVT.getSizeInBits();
5282 unsigned NumZero = 0;
5283 unsigned NumNonZero = 0;
5284 unsigned NonZeros = 0;
5285 bool IsAllConstants = true;
5286 SmallSet<SDValue, 8> Values;
5287 for (unsigned i = 0; i < NumElems; ++i) {
5288 SDValue Elt = Op.getOperand(i);
5289 if (Elt.getOpcode() == ISD::UNDEF)
5292 if (Elt.getOpcode() != ISD::Constant &&
5293 Elt.getOpcode() != ISD::ConstantFP)
5294 IsAllConstants = false;
5295 if (X86::isZeroNode(Elt))
5298 NonZeros |= (1 << i);
5303 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5304 if (NumNonZero == 0)
5305 return DAG.getUNDEF(VT);
5307 // Special case for single non-zero, non-undef, element.
5308 if (NumNonZero == 1) {
5309 unsigned Idx = CountTrailingZeros_32(NonZeros);
5310 SDValue Item = Op.getOperand(Idx);
5312 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5313 // the value are obviously zero, truncate the value to i32 and do the
5314 // insertion that way. Only do this if the value is non-constant or if the
5315 // value is a constant being inserted into element 0. It is cheaper to do
5316 // a constant pool load than it is to do a movd + shuffle.
5317 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5318 (!IsAllConstants || Idx == 0)) {
5319 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5321 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5322 EVT VecVT = MVT::v4i32;
5323 unsigned VecElts = 4;
5325 // Truncate the value (which may itself be a constant) to i32, and
5326 // convert it to a vector with movd (S2V+shuffle to zero extend).
5327 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5328 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5329 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5331 // Now we have our 32-bit value zero extended in the low element of
5332 // a vector. If Idx != 0, swizzle it into place.
5334 SmallVector<int, 4> Mask;
5335 Mask.push_back(Idx);
5336 for (unsigned i = 1; i != VecElts; ++i)
5338 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5341 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5345 // If we have a constant or non-constant insertion into the low element of
5346 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5347 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5348 // depending on what the source datatype is.
5351 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5353 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5354 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5355 if (VT.is256BitVector()) {
5356 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5357 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5358 Item, DAG.getIntPtrConstant(0));
5360 assert(VT.is128BitVector() && "Expected an SSE value type!");
5361 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5362 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5363 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5366 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5367 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5368 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5369 if (VT.is256BitVector()) {
5370 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5371 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5373 assert(VT.is128BitVector() && "Expected an SSE value type!");
5374 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5376 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5380 // Is it a vector logical left shift?
5381 if (NumElems == 2 && Idx == 1 &&
5382 X86::isZeroNode(Op.getOperand(0)) &&
5383 !X86::isZeroNode(Op.getOperand(1))) {
5384 unsigned NumBits = VT.getSizeInBits();
5385 return getVShift(true, VT,
5386 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5387 VT, Op.getOperand(1)),
5388 NumBits/2, DAG, *this, dl);
5391 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5394 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5395 // is a non-constant being inserted into an element other than the low one,
5396 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5397 // movd/movss) to move this into the low element, then shuffle it into
5399 if (EVTBits == 32) {
5400 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5402 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5403 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5404 SmallVector<int, 8> MaskVec;
5405 for (unsigned i = 0; i != NumElems; ++i)
5406 MaskVec.push_back(i == Idx ? 0 : 1);
5407 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5411 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5412 if (Values.size() == 1) {
5413 if (EVTBits == 32) {
5414 // Instead of a shuffle like this:
5415 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5416 // Check if it's possible to issue this instead.
5417 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5418 unsigned Idx = CountTrailingZeros_32(NonZeros);
5419 SDValue Item = Op.getOperand(Idx);
5420 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5421 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5426 // A vector full of immediates; various special cases are already
5427 // handled, so this is best done with a single constant-pool load.
5431 // For AVX-length vectors, build the individual 128-bit pieces and use
5432 // shuffles to put them in place.
5433 if (VT.is256BitVector()) {
5434 SmallVector<SDValue, 32> V;
5435 for (unsigned i = 0; i != NumElems; ++i)
5436 V.push_back(Op.getOperand(i));
5438 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5440 // Build both the lower and upper subvector.
5441 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5442 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5445 // Recreate the wider vector with the lower and upper part.
5446 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5449 // Let legalizer expand 2-wide build_vectors.
5450 if (EVTBits == 64) {
5451 if (NumNonZero == 1) {
5452 // One half is zero or undef.
5453 unsigned Idx = CountTrailingZeros_32(NonZeros);
5454 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5455 Op.getOperand(Idx));
5456 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5461 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5462 if (EVTBits == 8 && NumElems == 16) {
5463 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5465 if (V.getNode()) return V;
5468 if (EVTBits == 16 && NumElems == 8) {
5469 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5471 if (V.getNode()) return V;
5474 // If element VT is == 32 bits, turn it into a number of shuffles.
5475 SmallVector<SDValue, 8> V(NumElems);
5476 if (NumElems == 4 && NumZero > 0) {
5477 for (unsigned i = 0; i < 4; ++i) {
5478 bool isZero = !(NonZeros & (1 << i));
5480 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5482 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5485 for (unsigned i = 0; i < 2; ++i) {
5486 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5489 V[i] = V[i*2]; // Must be a zero vector.
5492 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5495 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5498 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5503 bool Reverse1 = (NonZeros & 0x3) == 2;
5504 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5508 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5509 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5511 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5514 if (Values.size() > 1 && VT.is128BitVector()) {
5515 // Check for a build vector of consecutive loads.
5516 for (unsigned i = 0; i < NumElems; ++i)
5517 V[i] = Op.getOperand(i);
5519 // Check for elements which are consecutive loads.
5520 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5524 // For SSE 4.1, use insertps to put the high elements into the low element.
5525 if (getSubtarget()->hasSSE41()) {
5527 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5528 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5530 Result = DAG.getUNDEF(VT);
5532 for (unsigned i = 1; i < NumElems; ++i) {
5533 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5534 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5535 Op.getOperand(i), DAG.getIntPtrConstant(i));
5540 // Otherwise, expand into a number of unpckl*, start by extending each of
5541 // our (non-undef) elements to the full vector width with the element in the
5542 // bottom slot of the vector (which generates no code for SSE).
5543 for (unsigned i = 0; i < NumElems; ++i) {
5544 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5545 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5547 V[i] = DAG.getUNDEF(VT);
5550 // Next, we iteratively mix elements, e.g. for v4f32:
5551 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5552 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5553 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5554 unsigned EltStride = NumElems >> 1;
5555 while (EltStride != 0) {
5556 for (unsigned i = 0; i < EltStride; ++i) {
5557 // If V[i+EltStride] is undef and this is the first round of mixing,
5558 // then it is safe to just drop this shuffle: V[i] is already in the
5559 // right place, the one element (since it's the first round) being
5560 // inserted as undef can be dropped. This isn't safe for successive
5561 // rounds because they will permute elements within both vectors.
5562 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5563 EltStride == NumElems/2)
5566 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5575 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5576 // to create 256-bit vectors from two other 128-bit ones.
5577 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5578 DebugLoc dl = Op.getDebugLoc();
5579 EVT ResVT = Op.getValueType();
5581 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5583 SDValue V1 = Op.getOperand(0);
5584 SDValue V2 = Op.getOperand(1);
5585 unsigned NumElems = ResVT.getVectorNumElements();
5587 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5590 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5591 assert(Op.getNumOperands() == 2);
5593 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5594 // from two other 128-bit ones.
5595 return LowerAVXCONCAT_VECTORS(Op, DAG);
5598 // Try to lower a shuffle node into a simple blend instruction.
5600 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5601 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5602 SDValue V1 = SVOp->getOperand(0);
5603 SDValue V2 = SVOp->getOperand(1);
5604 DebugLoc dl = SVOp->getDebugLoc();
5605 MVT VT = SVOp->getValueType(0).getSimpleVT();
5606 unsigned NumElems = VT.getVectorNumElements();
5608 if (!Subtarget->hasSSE41())
5614 switch (VT.SimpleTy) {
5615 default: return SDValue();
5617 ISDNo = X86ISD::BLENDPW;
5622 ISDNo = X86ISD::BLENDPS;
5627 ISDNo = X86ISD::BLENDPD;
5632 if (!Subtarget->hasAVX())
5634 ISDNo = X86ISD::BLENDPS;
5639 if (!Subtarget->hasAVX())
5641 ISDNo = X86ISD::BLENDPD;
5645 assert(ISDNo && "Invalid Op Number");
5647 unsigned MaskVals = 0;
5649 for (unsigned i = 0; i != NumElems; ++i) {
5650 int EltIdx = SVOp->getMaskElt(i);
5651 if (EltIdx == (int)i || EltIdx < 0)
5653 else if (EltIdx == (int)(i + NumElems))
5654 continue; // Bit is set to zero;
5659 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5660 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5661 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5662 DAG.getConstant(MaskVals, MVT::i32));
5663 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5666 // v8i16 shuffles - Prefer shuffles in the following order:
5667 // 1. [all] pshuflw, pshufhw, optional move
5668 // 2. [ssse3] 1 x pshufb
5669 // 3. [ssse3] 2 x pshufb + 1 x por
5670 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5672 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5673 SelectionDAG &DAG) {
5674 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5675 SDValue V1 = SVOp->getOperand(0);
5676 SDValue V2 = SVOp->getOperand(1);
5677 DebugLoc dl = SVOp->getDebugLoc();
5678 SmallVector<int, 8> MaskVals;
5680 // Determine if more than 1 of the words in each of the low and high quadwords
5681 // of the result come from the same quadword of one of the two inputs. Undef
5682 // mask values count as coming from any quadword, for better codegen.
5683 unsigned LoQuad[] = { 0, 0, 0, 0 };
5684 unsigned HiQuad[] = { 0, 0, 0, 0 };
5685 std::bitset<4> InputQuads;
5686 for (unsigned i = 0; i < 8; ++i) {
5687 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5688 int EltIdx = SVOp->getMaskElt(i);
5689 MaskVals.push_back(EltIdx);
5698 InputQuads.set(EltIdx / 4);
5701 int BestLoQuad = -1;
5702 unsigned MaxQuad = 1;
5703 for (unsigned i = 0; i < 4; ++i) {
5704 if (LoQuad[i] > MaxQuad) {
5706 MaxQuad = LoQuad[i];
5710 int BestHiQuad = -1;
5712 for (unsigned i = 0; i < 4; ++i) {
5713 if (HiQuad[i] > MaxQuad) {
5715 MaxQuad = HiQuad[i];
5719 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5720 // of the two input vectors, shuffle them into one input vector so only a
5721 // single pshufb instruction is necessary. If There are more than 2 input
5722 // quads, disable the next transformation since it does not help SSSE3.
5723 bool V1Used = InputQuads[0] || InputQuads[1];
5724 bool V2Used = InputQuads[2] || InputQuads[3];
5725 if (Subtarget->hasSSSE3()) {
5726 if (InputQuads.count() == 2 && V1Used && V2Used) {
5727 BestLoQuad = InputQuads[0] ? 0 : 1;
5728 BestHiQuad = InputQuads[2] ? 2 : 3;
5730 if (InputQuads.count() > 2) {
5736 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5737 // the shuffle mask. If a quad is scored as -1, that means that it contains
5738 // words from all 4 input quadwords.
5740 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5742 BestLoQuad < 0 ? 0 : BestLoQuad,
5743 BestHiQuad < 0 ? 1 : BestHiQuad
5745 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5746 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5747 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5748 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5750 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5751 // source words for the shuffle, to aid later transformations.
5752 bool AllWordsInNewV = true;
5753 bool InOrder[2] = { true, true };
5754 for (unsigned i = 0; i != 8; ++i) {
5755 int idx = MaskVals[i];
5757 InOrder[i/4] = false;
5758 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5760 AllWordsInNewV = false;
5764 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5765 if (AllWordsInNewV) {
5766 for (int i = 0; i != 8; ++i) {
5767 int idx = MaskVals[i];
5770 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5771 if ((idx != i) && idx < 4)
5773 if ((idx != i) && idx > 3)
5782 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5783 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5784 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5785 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5786 unsigned TargetMask = 0;
5787 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5788 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5789 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5790 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5791 getShufflePSHUFLWImmediate(SVOp);
5792 V1 = NewV.getOperand(0);
5793 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5797 // If we have SSSE3, and all words of the result are from 1 input vector,
5798 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5799 // is present, fall back to case 4.
5800 if (Subtarget->hasSSSE3()) {
5801 SmallVector<SDValue,16> pshufbMask;
5803 // If we have elements from both input vectors, set the high bit of the
5804 // shuffle mask element to zero out elements that come from V2 in the V1
5805 // mask, and elements that come from V1 in the V2 mask, so that the two
5806 // results can be OR'd together.
5807 bool TwoInputs = V1Used && V2Used;
5808 for (unsigned i = 0; i != 8; ++i) {
5809 int EltIdx = MaskVals[i] * 2;
5810 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5811 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5812 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5813 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5815 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5816 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5817 DAG.getNode(ISD::BUILD_VECTOR, dl,
5818 MVT::v16i8, &pshufbMask[0], 16));
5820 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5822 // Calculate the shuffle mask for the second input, shuffle it, and
5823 // OR it with the first shuffled input.
5825 for (unsigned i = 0; i != 8; ++i) {
5826 int EltIdx = MaskVals[i] * 2;
5827 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5828 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5829 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5830 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5832 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5833 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5834 DAG.getNode(ISD::BUILD_VECTOR, dl,
5835 MVT::v16i8, &pshufbMask[0], 16));
5836 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5837 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5840 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5841 // and update MaskVals with new element order.
5842 std::bitset<8> InOrder;
5843 if (BestLoQuad >= 0) {
5844 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5845 for (int i = 0; i != 4; ++i) {
5846 int idx = MaskVals[i];
5849 } else if ((idx / 4) == BestLoQuad) {
5854 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5857 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5858 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5859 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5861 getShufflePSHUFLWImmediate(SVOp), DAG);
5865 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5866 // and update MaskVals with the new element order.
5867 if (BestHiQuad >= 0) {
5868 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5869 for (unsigned i = 4; i != 8; ++i) {
5870 int idx = MaskVals[i];
5873 } else if ((idx / 4) == BestHiQuad) {
5874 MaskV[i] = (idx & 3) + 4;
5878 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5881 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5882 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5883 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5885 getShufflePSHUFHWImmediate(SVOp), DAG);
5889 // In case BestHi & BestLo were both -1, which means each quadword has a word
5890 // from each of the four input quadwords, calculate the InOrder bitvector now
5891 // before falling through to the insert/extract cleanup.
5892 if (BestLoQuad == -1 && BestHiQuad == -1) {
5894 for (int i = 0; i != 8; ++i)
5895 if (MaskVals[i] < 0 || MaskVals[i] == i)
5899 // The other elements are put in the right place using pextrw and pinsrw.
5900 for (unsigned i = 0; i != 8; ++i) {
5903 int EltIdx = MaskVals[i];
5906 SDValue ExtOp = (EltIdx < 8) ?
5907 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5908 DAG.getIntPtrConstant(EltIdx)) :
5909 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5910 DAG.getIntPtrConstant(EltIdx - 8));
5911 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5912 DAG.getIntPtrConstant(i));
5917 // v16i8 shuffles - Prefer shuffles in the following order:
5918 // 1. [ssse3] 1 x pshufb
5919 // 2. [ssse3] 2 x pshufb + 1 x por
5920 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5922 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5924 const X86TargetLowering &TLI) {
5925 SDValue V1 = SVOp->getOperand(0);
5926 SDValue V2 = SVOp->getOperand(1);
5927 DebugLoc dl = SVOp->getDebugLoc();
5928 ArrayRef<int> MaskVals = SVOp->getMask();
5930 // If we have SSSE3, case 1 is generated when all result bytes come from
5931 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5932 // present, fall back to case 3.
5934 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5935 if (TLI.getSubtarget()->hasSSSE3()) {
5936 SmallVector<SDValue,16> pshufbMask;
5938 // If all result elements are from one input vector, then only translate
5939 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5941 // Otherwise, we have elements from both input vectors, and must zero out
5942 // elements that come from V2 in the first mask, and V1 in the second mask
5943 // so that we can OR them together.
5944 for (unsigned i = 0; i != 16; ++i) {
5945 int EltIdx = MaskVals[i];
5946 if (EltIdx < 0 || EltIdx >= 16)
5948 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5950 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5951 DAG.getNode(ISD::BUILD_VECTOR, dl,
5952 MVT::v16i8, &pshufbMask[0], 16));
5954 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5955 // the 2nd operand if it's undefined or zero.
5956 if (V2.getOpcode() == ISD::UNDEF ||
5957 ISD::isBuildVectorAllZeros(V2.getNode()))
5960 // Calculate the shuffle mask for the second input, shuffle it, and
5961 // OR it with the first shuffled input.
5963 for (unsigned i = 0; i != 16; ++i) {
5964 int EltIdx = MaskVals[i];
5965 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5966 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5968 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5969 DAG.getNode(ISD::BUILD_VECTOR, dl,
5970 MVT::v16i8, &pshufbMask[0], 16));
5971 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5974 // No SSSE3 - Calculate in place words and then fix all out of place words
5975 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5976 // the 16 different words that comprise the two doublequadword input vectors.
5977 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5978 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5980 for (int i = 0; i != 8; ++i) {
5981 int Elt0 = MaskVals[i*2];
5982 int Elt1 = MaskVals[i*2+1];
5984 // This word of the result is all undef, skip it.
5985 if (Elt0 < 0 && Elt1 < 0)
5988 // This word of the result is already in the correct place, skip it.
5989 if ((Elt0 == i*2) && (Elt1 == i*2+1))
5992 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5993 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5996 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5997 // using a single extract together, load it and store it.
5998 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5999 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6000 DAG.getIntPtrConstant(Elt1 / 2));
6001 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6002 DAG.getIntPtrConstant(i));
6006 // If Elt1 is defined, extract it from the appropriate source. If the
6007 // source byte is not also odd, shift the extracted word left 8 bits
6008 // otherwise clear the bottom 8 bits if we need to do an or.
6010 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6011 DAG.getIntPtrConstant(Elt1 / 2));
6012 if ((Elt1 & 1) == 0)
6013 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6015 TLI.getShiftAmountTy(InsElt.getValueType())));
6017 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6018 DAG.getConstant(0xFF00, MVT::i16));
6020 // If Elt0 is defined, extract it from the appropriate source. If the
6021 // source byte is not also even, shift the extracted word right 8 bits. If
6022 // Elt1 was also defined, OR the extracted values together before
6023 // inserting them in the result.
6025 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6026 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6027 if ((Elt0 & 1) != 0)
6028 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6030 TLI.getShiftAmountTy(InsElt0.getValueType())));
6032 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6033 DAG.getConstant(0x00FF, MVT::i16));
6034 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6037 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6038 DAG.getIntPtrConstant(i));
6040 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6043 // v32i8 shuffles - Translate to VPSHUFB if possible.
6045 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6046 const X86Subtarget *Subtarget,
6047 SelectionDAG &DAG) {
6048 EVT VT = SVOp->getValueType(0);
6049 SDValue V1 = SVOp->getOperand(0);
6050 SDValue V2 = SVOp->getOperand(1);
6051 DebugLoc dl = SVOp->getDebugLoc();
6052 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6054 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6055 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6056 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6058 // VPSHUFB may be generated if
6059 // (1) one of input vector is undefined or zeroinitializer.
6060 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6061 // And (2) the mask indexes don't cross the 128-bit lane.
6062 if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6063 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6066 if (V1IsAllZero && !V2IsAllZero) {
6067 CommuteVectorShuffleMask(MaskVals, 32);
6070 SmallVector<SDValue, 32> pshufbMask;
6071 for (unsigned i = 0; i != 32; i++) {
6072 int EltIdx = MaskVals[i];
6073 if (EltIdx < 0 || EltIdx >= 32)
6076 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6077 // Cross lane is not allowed.
6081 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6083 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6084 DAG.getNode(ISD::BUILD_VECTOR, dl,
6085 MVT::v32i8, &pshufbMask[0], 32));
6088 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6089 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6090 /// done when every pair / quad of shuffle mask elements point to elements in
6091 /// the right sequence. e.g.
6092 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6094 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6095 SelectionDAG &DAG, DebugLoc dl) {
6096 MVT VT = SVOp->getValueType(0).getSimpleVT();
6097 unsigned NumElems = VT.getVectorNumElements();
6100 switch (VT.SimpleTy) {
6101 default: llvm_unreachable("Unexpected!");
6102 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6103 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6104 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6105 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6106 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6107 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6110 SmallVector<int, 8> MaskVec;
6111 for (unsigned i = 0; i != NumElems; i += Scale) {
6113 for (unsigned j = 0; j != Scale; ++j) {
6114 int EltIdx = SVOp->getMaskElt(i+j);
6118 StartIdx = (EltIdx / Scale);
6119 if (EltIdx != (int)(StartIdx*Scale + j))
6122 MaskVec.push_back(StartIdx);
6125 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6126 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6127 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6130 /// getVZextMovL - Return a zero-extending vector move low node.
6132 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6133 SDValue SrcOp, SelectionDAG &DAG,
6134 const X86Subtarget *Subtarget, DebugLoc dl) {
6135 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6136 LoadSDNode *LD = NULL;
6137 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6138 LD = dyn_cast<LoadSDNode>(SrcOp);
6140 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6142 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6143 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6144 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6145 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6146 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6148 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6149 return DAG.getNode(ISD::BITCAST, dl, VT,
6150 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6151 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6159 return DAG.getNode(ISD::BITCAST, dl, VT,
6160 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6161 DAG.getNode(ISD::BITCAST, dl,
6165 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6166 /// which could not be matched by any known target speficic shuffle
6168 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6170 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6171 if (NewOp.getNode())
6174 EVT VT = SVOp->getValueType(0);
6176 unsigned NumElems = VT.getVectorNumElements();
6177 unsigned NumLaneElems = NumElems / 2;
6179 DebugLoc dl = SVOp->getDebugLoc();
6180 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6181 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6184 SmallVector<int, 16> Mask;
6185 for (unsigned l = 0; l < 2; ++l) {
6186 // Build a shuffle mask for the output, discovering on the fly which
6187 // input vectors to use as shuffle operands (recorded in InputUsed).
6188 // If building a suitable shuffle vector proves too hard, then bail
6189 // out with UseBuildVector set.
6190 bool UseBuildVector = false;
6191 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6192 unsigned LaneStart = l * NumLaneElems;
6193 for (unsigned i = 0; i != NumLaneElems; ++i) {
6194 // The mask element. This indexes into the input.
6195 int Idx = SVOp->getMaskElt(i+LaneStart);
6197 // the mask element does not index into any input vector.
6202 // The input vector this mask element indexes into.
6203 int Input = Idx / NumLaneElems;
6205 // Turn the index into an offset from the start of the input vector.
6206 Idx -= Input * NumLaneElems;
6208 // Find or create a shuffle vector operand to hold this input.
6210 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6211 if (InputUsed[OpNo] == Input)
6212 // This input vector is already an operand.
6214 if (InputUsed[OpNo] < 0) {
6215 // Create a new operand for this input vector.
6216 InputUsed[OpNo] = Input;
6221 if (OpNo >= array_lengthof(InputUsed)) {
6222 // More than two input vectors used! Give up on trying to create a
6223 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6224 UseBuildVector = true;
6228 // Add the mask index for the new shuffle vector.
6229 Mask.push_back(Idx + OpNo * NumLaneElems);
6232 if (UseBuildVector) {
6233 SmallVector<SDValue, 16> SVOps;
6234 for (unsigned i = 0; i != NumLaneElems; ++i) {
6235 // The mask element. This indexes into the input.
6236 int Idx = SVOp->getMaskElt(i+LaneStart);
6238 SVOps.push_back(DAG.getUNDEF(EltVT));
6242 // The input vector this mask element indexes into.
6243 int Input = Idx / NumElems;
6245 // Turn the index into an offset from the start of the input vector.
6246 Idx -= Input * NumElems;
6248 // Extract the vector element by hand.
6249 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6250 SVOp->getOperand(Input),
6251 DAG.getIntPtrConstant(Idx)));
6254 // Construct the output using a BUILD_VECTOR.
6255 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6257 } else if (InputUsed[0] < 0) {
6258 // No input vectors were used! The result is undefined.
6259 Output[l] = DAG.getUNDEF(NVT);
6261 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6262 (InputUsed[0] % 2) * NumLaneElems,
6264 // If only one input was used, use an undefined vector for the other.
6265 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6266 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6267 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6268 // At least one input vector was used. Create a new shuffle vector.
6269 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6275 // Concatenate the result back
6276 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6279 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6280 /// 4 elements, and match them with several different shuffle types.
6282 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6283 SDValue V1 = SVOp->getOperand(0);
6284 SDValue V2 = SVOp->getOperand(1);
6285 DebugLoc dl = SVOp->getDebugLoc();
6286 EVT VT = SVOp->getValueType(0);
6288 assert(VT.is128BitVector() && "Unsupported vector size");
6290 std::pair<int, int> Locs[4];
6291 int Mask1[] = { -1, -1, -1, -1 };
6292 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6296 for (unsigned i = 0; i != 4; ++i) {
6297 int Idx = PermMask[i];
6299 Locs[i] = std::make_pair(-1, -1);
6301 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6303 Locs[i] = std::make_pair(0, NumLo);
6307 Locs[i] = std::make_pair(1, NumHi);
6309 Mask1[2+NumHi] = Idx;
6315 if (NumLo <= 2 && NumHi <= 2) {
6316 // If no more than two elements come from either vector. This can be
6317 // implemented with two shuffles. First shuffle gather the elements.
6318 // The second shuffle, which takes the first shuffle as both of its
6319 // vector operands, put the elements into the right order.
6320 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6322 int Mask2[] = { -1, -1, -1, -1 };
6324 for (unsigned i = 0; i != 4; ++i)
6325 if (Locs[i].first != -1) {
6326 unsigned Idx = (i < 2) ? 0 : 4;
6327 Idx += Locs[i].first * 2 + Locs[i].second;
6331 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6334 if (NumLo == 3 || NumHi == 3) {
6335 // Otherwise, we must have three elements from one vector, call it X, and
6336 // one element from the other, call it Y. First, use a shufps to build an
6337 // intermediate vector with the one element from Y and the element from X
6338 // that will be in the same half in the final destination (the indexes don't
6339 // matter). Then, use a shufps to build the final vector, taking the half
6340 // containing the element from Y from the intermediate, and the other half
6343 // Normalize it so the 3 elements come from V1.
6344 CommuteVectorShuffleMask(PermMask, 4);
6348 // Find the element from V2.
6350 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6351 int Val = PermMask[HiIndex];
6358 Mask1[0] = PermMask[HiIndex];
6360 Mask1[2] = PermMask[HiIndex^1];
6362 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6365 Mask1[0] = PermMask[0];
6366 Mask1[1] = PermMask[1];
6367 Mask1[2] = HiIndex & 1 ? 6 : 4;
6368 Mask1[3] = HiIndex & 1 ? 4 : 6;
6369 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6372 Mask1[0] = HiIndex & 1 ? 2 : 0;
6373 Mask1[1] = HiIndex & 1 ? 0 : 2;
6374 Mask1[2] = PermMask[2];
6375 Mask1[3] = PermMask[3];
6380 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6383 // Break it into (shuffle shuffle_hi, shuffle_lo).
6384 int LoMask[] = { -1, -1, -1, -1 };
6385 int HiMask[] = { -1, -1, -1, -1 };
6387 int *MaskPtr = LoMask;
6388 unsigned MaskIdx = 0;
6391 for (unsigned i = 0; i != 4; ++i) {
6398 int Idx = PermMask[i];
6400 Locs[i] = std::make_pair(-1, -1);
6401 } else if (Idx < 4) {
6402 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6403 MaskPtr[LoIdx] = Idx;
6406 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6407 MaskPtr[HiIdx] = Idx;
6412 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6413 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6414 int MaskOps[] = { -1, -1, -1, -1 };
6415 for (unsigned i = 0; i != 4; ++i)
6416 if (Locs[i].first != -1)
6417 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6418 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6421 static bool MayFoldVectorLoad(SDValue V) {
6422 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6423 V = V.getOperand(0);
6424 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6425 V = V.getOperand(0);
6426 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6427 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6428 // BUILD_VECTOR (load), undef
6429 V = V.getOperand(0);
6435 // FIXME: the version above should always be used. Since there's
6436 // a bug where several vector shuffles can't be folded because the
6437 // DAG is not updated during lowering and a node claims to have two
6438 // uses while it only has one, use this version, and let isel match
6439 // another instruction if the load really happens to have more than
6440 // one use. Remove this version after this bug get fixed.
6441 // rdar://8434668, PR8156
6442 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6443 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6444 V = V.getOperand(0);
6445 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6446 V = V.getOperand(0);
6447 if (ISD::isNormalLoad(V.getNode()))
6453 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6454 EVT VT = Op.getValueType();
6456 // Canonizalize to v2f64.
6457 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6458 return DAG.getNode(ISD::BITCAST, dl, VT,
6459 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6464 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6466 SDValue V1 = Op.getOperand(0);
6467 SDValue V2 = Op.getOperand(1);
6468 EVT VT = Op.getValueType();
6470 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6472 if (HasSSE2 && VT == MVT::v2f64)
6473 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6475 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6476 return DAG.getNode(ISD::BITCAST, dl, VT,
6477 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6478 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6479 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6483 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6484 SDValue V1 = Op.getOperand(0);
6485 SDValue V2 = Op.getOperand(1);
6486 EVT VT = Op.getValueType();
6488 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6489 "unsupported shuffle type");
6491 if (V2.getOpcode() == ISD::UNDEF)
6495 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6499 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6500 SDValue V1 = Op.getOperand(0);
6501 SDValue V2 = Op.getOperand(1);
6502 EVT VT = Op.getValueType();
6503 unsigned NumElems = VT.getVectorNumElements();
6505 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6506 // operand of these instructions is only memory, so check if there's a
6507 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6509 bool CanFoldLoad = false;
6511 // Trivial case, when V2 comes from a load.
6512 if (MayFoldVectorLoad(V2))
6515 // When V1 is a load, it can be folded later into a store in isel, example:
6516 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6518 // (MOVLPSmr addr:$src1, VR128:$src2)
6519 // So, recognize this potential and also use MOVLPS or MOVLPD
6520 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6523 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6525 if (HasSSE2 && NumElems == 2)
6526 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6529 // If we don't care about the second element, proceed to use movss.
6530 if (SVOp->getMaskElt(1) != -1)
6531 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6534 // movl and movlp will both match v2i64, but v2i64 is never matched by
6535 // movl earlier because we make it strict to avoid messing with the movlp load
6536 // folding logic (see the code above getMOVLP call). Match it here then,
6537 // this is horrible, but will stay like this until we move all shuffle
6538 // matching to x86 specific nodes. Note that for the 1st condition all
6539 // types are matched with movsd.
6541 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6542 // as to remove this logic from here, as much as possible
6543 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6544 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6545 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6548 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6550 // Invert the operand order and use SHUFPS to match it.
6551 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6552 getShuffleSHUFImmediate(SVOp), DAG);
6556 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6557 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6558 EVT VT = Op.getValueType();
6559 DebugLoc dl = Op.getDebugLoc();
6560 SDValue V1 = Op.getOperand(0);
6561 SDValue V2 = Op.getOperand(1);
6563 if (isZeroShuffle(SVOp))
6564 return getZeroVector(VT, Subtarget, DAG, dl);
6566 // Handle splat operations
6567 if (SVOp->isSplat()) {
6568 unsigned NumElem = VT.getVectorNumElements();
6569 int Size = VT.getSizeInBits();
6571 // Use vbroadcast whenever the splat comes from a foldable load
6572 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6573 if (Broadcast.getNode())
6576 // Handle splats by matching through known shuffle masks
6577 if ((Size == 128 && NumElem <= 4) ||
6578 (Size == 256 && NumElem < 8))
6581 // All remaning splats are promoted to target supported vector shuffles.
6582 return PromoteSplat(SVOp, DAG);
6585 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6587 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6588 VT == MVT::v16i16 || VT == MVT::v32i8) {
6589 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6590 if (NewOp.getNode())
6591 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6592 } else if ((VT == MVT::v4i32 ||
6593 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6594 // FIXME: Figure out a cleaner way to do this.
6595 // Try to make use of movq to zero out the top part.
6596 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6597 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6598 if (NewOp.getNode()) {
6599 EVT NewVT = NewOp.getValueType();
6600 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6601 NewVT, true, false))
6602 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6603 DAG, Subtarget, dl);
6605 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6606 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6607 if (NewOp.getNode()) {
6608 EVT NewVT = NewOp.getValueType();
6609 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6610 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6611 DAG, Subtarget, dl);
6619 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6620 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6621 SDValue V1 = Op.getOperand(0);
6622 SDValue V2 = Op.getOperand(1);
6623 EVT VT = Op.getValueType();
6624 DebugLoc dl = Op.getDebugLoc();
6625 unsigned NumElems = VT.getVectorNumElements();
6626 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6627 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6628 bool V1IsSplat = false;
6629 bool V2IsSplat = false;
6630 bool HasSSE2 = Subtarget->hasSSE2();
6631 bool HasAVX = Subtarget->hasAVX();
6632 bool HasAVX2 = Subtarget->hasAVX2();
6633 MachineFunction &MF = DAG.getMachineFunction();
6634 bool OptForSize = MF.getFunction()->getFnAttributes().
6635 hasAttribute(Attributes::OptimizeForSize);
6637 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6639 if (V1IsUndef && V2IsUndef)
6640 return DAG.getUNDEF(VT);
6642 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6644 // Vector shuffle lowering takes 3 steps:
6646 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6647 // narrowing and commutation of operands should be handled.
6648 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6650 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6651 // so the shuffle can be broken into other shuffles and the legalizer can
6652 // try the lowering again.
6654 // The general idea is that no vector_shuffle operation should be left to
6655 // be matched during isel, all of them must be converted to a target specific
6658 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6659 // narrowing and commutation of operands should be handled. The actual code
6660 // doesn't include all of those, work in progress...
6661 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6662 if (NewOp.getNode())
6665 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6667 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6668 // unpckh_undef). Only use pshufd if speed is more important than size.
6669 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6670 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6671 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6672 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6674 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6675 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6676 return getMOVDDup(Op, dl, V1, DAG);
6678 if (isMOVHLPS_v_undef_Mask(M, VT))
6679 return getMOVHighToLow(Op, dl, DAG);
6681 // Use to match splats
6682 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6683 (VT == MVT::v2f64 || VT == MVT::v2i64))
6684 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6686 if (isPSHUFDMask(M, VT)) {
6687 // The actual implementation will match the mask in the if above and then
6688 // during isel it can match several different instructions, not only pshufd
6689 // as its name says, sad but true, emulate the behavior for now...
6690 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6691 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6693 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6695 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6696 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6698 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6699 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6701 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6705 // Check if this can be converted into a logical shift.
6706 bool isLeft = false;
6709 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6710 if (isShift && ShVal.hasOneUse()) {
6711 // If the shifted value has multiple uses, it may be cheaper to use
6712 // v_set0 + movlhps or movhlps, etc.
6713 EVT EltVT = VT.getVectorElementType();
6714 ShAmt *= EltVT.getSizeInBits();
6715 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6718 if (isMOVLMask(M, VT)) {
6719 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6720 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6721 if (!isMOVLPMask(M, VT)) {
6722 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6723 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6725 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6726 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6730 // FIXME: fold these into legal mask.
6731 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6732 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6734 if (isMOVHLPSMask(M, VT))
6735 return getMOVHighToLow(Op, dl, DAG);
6737 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6738 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6740 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6741 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6743 if (isMOVLPMask(M, VT))
6744 return getMOVLP(Op, dl, DAG, HasSSE2);
6746 if (ShouldXformToMOVHLPS(M, VT) ||
6747 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6748 return CommuteVectorShuffle(SVOp, DAG);
6751 // No better options. Use a vshldq / vsrldq.
6752 EVT EltVT = VT.getVectorElementType();
6753 ShAmt *= EltVT.getSizeInBits();
6754 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6757 bool Commuted = false;
6758 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6759 // 1,1,1,1 -> v8i16 though.
6760 V1IsSplat = isSplatVector(V1.getNode());
6761 V2IsSplat = isSplatVector(V2.getNode());
6763 // Canonicalize the splat or undef, if present, to be on the RHS.
6764 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6765 CommuteVectorShuffleMask(M, NumElems);
6767 std::swap(V1IsSplat, V2IsSplat);
6771 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6772 // Shuffling low element of v1 into undef, just return v1.
6775 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6776 // the instruction selector will not match, so get a canonical MOVL with
6777 // swapped operands to undo the commute.
6778 return getMOVL(DAG, dl, VT, V2, V1);
6781 if (isUNPCKLMask(M, VT, HasAVX2))
6782 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6784 if (isUNPCKHMask(M, VT, HasAVX2))
6785 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6788 // Normalize mask so all entries that point to V2 points to its first
6789 // element then try to match unpck{h|l} again. If match, return a
6790 // new vector_shuffle with the corrected mask.p
6791 SmallVector<int, 8> NewMask(M.begin(), M.end());
6792 NormalizeMask(NewMask, NumElems);
6793 if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6794 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6795 if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6796 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6800 // Commute is back and try unpck* again.
6801 // FIXME: this seems wrong.
6802 CommuteVectorShuffleMask(M, NumElems);
6804 std::swap(V1IsSplat, V2IsSplat);
6807 if (isUNPCKLMask(M, VT, HasAVX2))
6808 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6810 if (isUNPCKHMask(M, VT, HasAVX2))
6811 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6814 // Normalize the node to match x86 shuffle ops if needed
6815 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6816 return CommuteVectorShuffle(SVOp, DAG);
6818 // The checks below are all present in isShuffleMaskLegal, but they are
6819 // inlined here right now to enable us to directly emit target specific
6820 // nodes, and remove one by one until they don't return Op anymore.
6822 if (isPALIGNRMask(M, VT, Subtarget))
6823 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6824 getShufflePALIGNRImmediate(SVOp),
6827 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6828 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6829 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6830 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6833 if (isPSHUFHWMask(M, VT, HasAVX2))
6834 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6835 getShufflePSHUFHWImmediate(SVOp),
6838 if (isPSHUFLWMask(M, VT, HasAVX2))
6839 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6840 getShufflePSHUFLWImmediate(SVOp),
6843 if (isSHUFPMask(M, VT, HasAVX))
6844 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6845 getShuffleSHUFImmediate(SVOp), DAG);
6847 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6848 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6849 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6850 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6852 //===--------------------------------------------------------------------===//
6853 // Generate target specific nodes for 128 or 256-bit shuffles only
6854 // supported in the AVX instruction set.
6857 // Handle VMOVDDUPY permutations
6858 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6859 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6861 // Handle VPERMILPS/D* permutations
6862 if (isVPERMILPMask(M, VT, HasAVX)) {
6863 if (HasAVX2 && VT == MVT::v8i32)
6864 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6865 getShuffleSHUFImmediate(SVOp), DAG);
6866 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6867 getShuffleSHUFImmediate(SVOp), DAG);
6870 // Handle VPERM2F128/VPERM2I128 permutations
6871 if (isVPERM2X128Mask(M, VT, HasAVX))
6872 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6873 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6875 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6876 if (BlendOp.getNode())
6879 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6880 SmallVector<SDValue, 8> permclMask;
6881 for (unsigned i = 0; i != 8; ++i) {
6882 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6884 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6886 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6887 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6888 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6891 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6892 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6893 getShuffleCLImmediate(SVOp), DAG);
6896 //===--------------------------------------------------------------------===//
6897 // Since no target specific shuffle was selected for this generic one,
6898 // lower it into other known shuffles. FIXME: this isn't true yet, but
6899 // this is the plan.
6902 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6903 if (VT == MVT::v8i16) {
6904 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6905 if (NewOp.getNode())
6909 if (VT == MVT::v16i8) {
6910 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6911 if (NewOp.getNode())
6915 if (VT == MVT::v32i8) {
6916 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
6917 if (NewOp.getNode())
6921 // Handle all 128-bit wide vectors with 4 elements, and match them with
6922 // several different shuffle types.
6923 if (NumElems == 4 && VT.is128BitVector())
6924 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6926 // Handle general 256-bit shuffles
6927 if (VT.is256BitVector())
6928 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6934 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6935 SelectionDAG &DAG) const {
6936 EVT VT = Op.getValueType();
6937 DebugLoc dl = Op.getDebugLoc();
6939 if (!Op.getOperand(0).getValueType().is128BitVector())
6942 if (VT.getSizeInBits() == 8) {
6943 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6944 Op.getOperand(0), Op.getOperand(1));
6945 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6946 DAG.getValueType(VT));
6947 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6950 if (VT.getSizeInBits() == 16) {
6951 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6952 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6954 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6955 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6956 DAG.getNode(ISD::BITCAST, dl,
6960 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6961 Op.getOperand(0), Op.getOperand(1));
6962 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6963 DAG.getValueType(VT));
6964 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6967 if (VT == MVT::f32) {
6968 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6969 // the result back to FR32 register. It's only worth matching if the
6970 // result has a single use which is a store or a bitcast to i32. And in
6971 // the case of a store, it's not worth it if the index is a constant 0,
6972 // because a MOVSSmr can be used instead, which is smaller and faster.
6973 if (!Op.hasOneUse())
6975 SDNode *User = *Op.getNode()->use_begin();
6976 if ((User->getOpcode() != ISD::STORE ||
6977 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6978 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6979 (User->getOpcode() != ISD::BITCAST ||
6980 User->getValueType(0) != MVT::i32))
6982 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6983 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6986 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6989 if (VT == MVT::i32 || VT == MVT::i64) {
6990 // ExtractPS/pextrq works with constant index.
6991 if (isa<ConstantSDNode>(Op.getOperand(1)))
6999 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7000 SelectionDAG &DAG) const {
7001 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7004 SDValue Vec = Op.getOperand(0);
7005 EVT VecVT = Vec.getValueType();
7007 // If this is a 256-bit vector result, first extract the 128-bit vector and
7008 // then extract the element from the 128-bit vector.
7009 if (VecVT.is256BitVector()) {
7010 DebugLoc dl = Op.getNode()->getDebugLoc();
7011 unsigned NumElems = VecVT.getVectorNumElements();
7012 SDValue Idx = Op.getOperand(1);
7013 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7015 // Get the 128-bit vector.
7016 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7018 if (IdxVal >= NumElems/2)
7019 IdxVal -= NumElems/2;
7020 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7021 DAG.getConstant(IdxVal, MVT::i32));
7024 assert(VecVT.is128BitVector() && "Unexpected vector length");
7026 if (Subtarget->hasSSE41()) {
7027 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7032 EVT VT = Op.getValueType();
7033 DebugLoc dl = Op.getDebugLoc();
7034 // TODO: handle v16i8.
7035 if (VT.getSizeInBits() == 16) {
7036 SDValue Vec = Op.getOperand(0);
7037 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7039 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7040 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7041 DAG.getNode(ISD::BITCAST, dl,
7044 // Transform it so it match pextrw which produces a 32-bit result.
7045 EVT EltVT = MVT::i32;
7046 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7047 Op.getOperand(0), Op.getOperand(1));
7048 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7049 DAG.getValueType(VT));
7050 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7053 if (VT.getSizeInBits() == 32) {
7054 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7058 // SHUFPS the element to the lowest double word, then movss.
7059 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7060 EVT VVT = Op.getOperand(0).getValueType();
7061 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7062 DAG.getUNDEF(VVT), Mask);
7063 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7064 DAG.getIntPtrConstant(0));
7067 if (VT.getSizeInBits() == 64) {
7068 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7069 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7070 // to match extract_elt for f64.
7071 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7075 // UNPCKHPD the element to the lowest double word, then movsd.
7076 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7077 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7078 int Mask[2] = { 1, -1 };
7079 EVT VVT = Op.getOperand(0).getValueType();
7080 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7081 DAG.getUNDEF(VVT), Mask);
7082 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7083 DAG.getIntPtrConstant(0));
7090 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7091 SelectionDAG &DAG) const {
7092 EVT VT = Op.getValueType();
7093 EVT EltVT = VT.getVectorElementType();
7094 DebugLoc dl = Op.getDebugLoc();
7096 SDValue N0 = Op.getOperand(0);
7097 SDValue N1 = Op.getOperand(1);
7098 SDValue N2 = Op.getOperand(2);
7100 if (!VT.is128BitVector())
7103 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7104 isa<ConstantSDNode>(N2)) {
7106 if (VT == MVT::v8i16)
7107 Opc = X86ISD::PINSRW;
7108 else if (VT == MVT::v16i8)
7109 Opc = X86ISD::PINSRB;
7111 Opc = X86ISD::PINSRB;
7113 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7115 if (N1.getValueType() != MVT::i32)
7116 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7117 if (N2.getValueType() != MVT::i32)
7118 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7119 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7122 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7123 // Bits [7:6] of the constant are the source select. This will always be
7124 // zero here. The DAG Combiner may combine an extract_elt index into these
7125 // bits. For example (insert (extract, 3), 2) could be matched by putting
7126 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7127 // Bits [5:4] of the constant are the destination select. This is the
7128 // value of the incoming immediate.
7129 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7130 // combine either bitwise AND or insert of float 0.0 to set these bits.
7131 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7132 // Create this as a scalar to vector..
7133 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7134 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7137 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7138 // PINSR* works with constant index.
7145 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7146 EVT VT = Op.getValueType();
7147 EVT EltVT = VT.getVectorElementType();
7149 DebugLoc dl = Op.getDebugLoc();
7150 SDValue N0 = Op.getOperand(0);
7151 SDValue N1 = Op.getOperand(1);
7152 SDValue N2 = Op.getOperand(2);
7154 // If this is a 256-bit vector result, first extract the 128-bit vector,
7155 // insert the element into the extracted half and then place it back.
7156 if (VT.is256BitVector()) {
7157 if (!isa<ConstantSDNode>(N2))
7160 // Get the desired 128-bit vector half.
7161 unsigned NumElems = VT.getVectorNumElements();
7162 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7163 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7165 // Insert the element into the desired half.
7166 bool Upper = IdxVal >= NumElems/2;
7167 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7168 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7170 // Insert the changed part back to the 256-bit vector
7171 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7174 if (Subtarget->hasSSE41())
7175 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7177 if (EltVT == MVT::i8)
7180 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7181 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7182 // as its second argument.
7183 if (N1.getValueType() != MVT::i32)
7184 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7185 if (N2.getValueType() != MVT::i32)
7186 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7187 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7192 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7193 LLVMContext *Context = DAG.getContext();
7194 DebugLoc dl = Op.getDebugLoc();
7195 EVT OpVT = Op.getValueType();
7197 // If this is a 256-bit vector result, first insert into a 128-bit
7198 // vector and then insert into the 256-bit vector.
7199 if (!OpVT.is128BitVector()) {
7200 // Insert into a 128-bit vector.
7201 EVT VT128 = EVT::getVectorVT(*Context,
7202 OpVT.getVectorElementType(),
7203 OpVT.getVectorNumElements() / 2);
7205 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7207 // Insert the 128-bit vector.
7208 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7211 if (OpVT == MVT::v1i64 &&
7212 Op.getOperand(0).getValueType() == MVT::i64)
7213 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7215 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7216 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7217 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7218 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7221 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7222 // a simple subregister reference or explicit instructions to grab
7223 // upper bits of a vector.
7224 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7225 SelectionDAG &DAG) {
7226 if (Subtarget->hasAVX()) {
7227 DebugLoc dl = Op.getNode()->getDebugLoc();
7228 SDValue Vec = Op.getNode()->getOperand(0);
7229 SDValue Idx = Op.getNode()->getOperand(1);
7231 if (Op.getNode()->getValueType(0).is128BitVector() &&
7232 Vec.getNode()->getValueType(0).is256BitVector() &&
7233 isa<ConstantSDNode>(Idx)) {
7234 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7235 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7241 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7242 // simple superregister reference or explicit instructions to insert
7243 // the upper bits of a vector.
7244 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7245 SelectionDAG &DAG) {
7246 if (Subtarget->hasAVX()) {
7247 DebugLoc dl = Op.getNode()->getDebugLoc();
7248 SDValue Vec = Op.getNode()->getOperand(0);
7249 SDValue SubVec = Op.getNode()->getOperand(1);
7250 SDValue Idx = Op.getNode()->getOperand(2);
7252 if (Op.getNode()->getValueType(0).is256BitVector() &&
7253 SubVec.getNode()->getValueType(0).is128BitVector() &&
7254 isa<ConstantSDNode>(Idx)) {
7255 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7256 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7262 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7263 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7264 // one of the above mentioned nodes. It has to be wrapped because otherwise
7265 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7266 // be used to form addressing mode. These wrapped nodes will be selected
7269 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7270 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7272 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7274 unsigned char OpFlag = 0;
7275 unsigned WrapperKind = X86ISD::Wrapper;
7276 CodeModel::Model M = getTargetMachine().getCodeModel();
7278 if (Subtarget->isPICStyleRIPRel() &&
7279 (M == CodeModel::Small || M == CodeModel::Kernel))
7280 WrapperKind = X86ISD::WrapperRIP;
7281 else if (Subtarget->isPICStyleGOT())
7282 OpFlag = X86II::MO_GOTOFF;
7283 else if (Subtarget->isPICStyleStubPIC())
7284 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7286 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7288 CP->getOffset(), OpFlag);
7289 DebugLoc DL = CP->getDebugLoc();
7290 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7291 // With PIC, the address is actually $g + Offset.
7293 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7294 DAG.getNode(X86ISD::GlobalBaseReg,
7295 DebugLoc(), getPointerTy()),
7302 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7303 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7305 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7307 unsigned char OpFlag = 0;
7308 unsigned WrapperKind = X86ISD::Wrapper;
7309 CodeModel::Model M = getTargetMachine().getCodeModel();
7311 if (Subtarget->isPICStyleRIPRel() &&
7312 (M == CodeModel::Small || M == CodeModel::Kernel))
7313 WrapperKind = X86ISD::WrapperRIP;
7314 else if (Subtarget->isPICStyleGOT())
7315 OpFlag = X86II::MO_GOTOFF;
7316 else if (Subtarget->isPICStyleStubPIC())
7317 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7319 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7321 DebugLoc DL = JT->getDebugLoc();
7322 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7324 // With PIC, the address is actually $g + Offset.
7326 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7327 DAG.getNode(X86ISD::GlobalBaseReg,
7328 DebugLoc(), getPointerTy()),
7335 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7336 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7338 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7340 unsigned char OpFlag = 0;
7341 unsigned WrapperKind = X86ISD::Wrapper;
7342 CodeModel::Model M = getTargetMachine().getCodeModel();
7344 if (Subtarget->isPICStyleRIPRel() &&
7345 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7346 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7347 OpFlag = X86II::MO_GOTPCREL;
7348 WrapperKind = X86ISD::WrapperRIP;
7349 } else if (Subtarget->isPICStyleGOT()) {
7350 OpFlag = X86II::MO_GOT;
7351 } else if (Subtarget->isPICStyleStubPIC()) {
7352 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7353 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7354 OpFlag = X86II::MO_DARWIN_NONLAZY;
7357 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7359 DebugLoc DL = Op.getDebugLoc();
7360 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7363 // With PIC, the address is actually $g + Offset.
7364 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7365 !Subtarget->is64Bit()) {
7366 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7367 DAG.getNode(X86ISD::GlobalBaseReg,
7368 DebugLoc(), getPointerTy()),
7372 // For symbols that require a load from a stub to get the address, emit the
7374 if (isGlobalStubReference(OpFlag))
7375 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7376 MachinePointerInfo::getGOT(), false, false, false, 0);
7382 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7383 // Create the TargetBlockAddressAddress node.
7384 unsigned char OpFlags =
7385 Subtarget->ClassifyBlockAddressReference();
7386 CodeModel::Model M = getTargetMachine().getCodeModel();
7387 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7388 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7389 DebugLoc dl = Op.getDebugLoc();
7390 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7393 if (Subtarget->isPICStyleRIPRel() &&
7394 (M == CodeModel::Small || M == CodeModel::Kernel))
7395 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7397 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7399 // With PIC, the address is actually $g + Offset.
7400 if (isGlobalRelativeToPICBase(OpFlags)) {
7401 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7402 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7410 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7412 SelectionDAG &DAG) const {
7413 // Create the TargetGlobalAddress node, folding in the constant
7414 // offset if it is legal.
7415 unsigned char OpFlags =
7416 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7417 CodeModel::Model M = getTargetMachine().getCodeModel();
7419 if (OpFlags == X86II::MO_NO_FLAG &&
7420 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7421 // A direct static reference to a global.
7422 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7425 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7428 if (Subtarget->isPICStyleRIPRel() &&
7429 (M == CodeModel::Small || M == CodeModel::Kernel))
7430 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7432 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7434 // With PIC, the address is actually $g + Offset.
7435 if (isGlobalRelativeToPICBase(OpFlags)) {
7436 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7437 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7441 // For globals that require a load from a stub to get the address, emit the
7443 if (isGlobalStubReference(OpFlags))
7444 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7445 MachinePointerInfo::getGOT(), false, false, false, 0);
7447 // If there was a non-zero offset that we didn't fold, create an explicit
7450 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7451 DAG.getConstant(Offset, getPointerTy()));
7457 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7458 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7459 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7460 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7464 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7465 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7466 unsigned char OperandFlags, bool LocalDynamic = false) {
7467 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7468 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7469 DebugLoc dl = GA->getDebugLoc();
7470 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7471 GA->getValueType(0),
7475 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7479 SDValue Ops[] = { Chain, TGA, *InFlag };
7480 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7482 SDValue Ops[] = { Chain, TGA };
7483 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7486 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7487 MFI->setAdjustsStack(true);
7489 SDValue Flag = Chain.getValue(1);
7490 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7493 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7495 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7498 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7499 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7500 DAG.getNode(X86ISD::GlobalBaseReg,
7501 DebugLoc(), PtrVT), InFlag);
7502 InFlag = Chain.getValue(1);
7504 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7507 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7509 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7511 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7512 X86::RAX, X86II::MO_TLSGD);
7515 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7519 DebugLoc dl = GA->getDebugLoc();
7521 // Get the start address of the TLS block for this module.
7522 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7523 .getInfo<X86MachineFunctionInfo>();
7524 MFI->incNumLocalDynamicTLSAccesses();
7528 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7529 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7532 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7533 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7534 InFlag = Chain.getValue(1);
7535 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7536 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7539 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7543 unsigned char OperandFlags = X86II::MO_DTPOFF;
7544 unsigned WrapperKind = X86ISD::Wrapper;
7545 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7546 GA->getValueType(0),
7547 GA->getOffset(), OperandFlags);
7548 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7550 // Add x@dtpoff with the base.
7551 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7554 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7555 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7556 const EVT PtrVT, TLSModel::Model model,
7557 bool is64Bit, bool isPIC) {
7558 DebugLoc dl = GA->getDebugLoc();
7560 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7561 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7562 is64Bit ? 257 : 256));
7564 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7565 DAG.getIntPtrConstant(0),
7566 MachinePointerInfo(Ptr),
7567 false, false, false, 0);
7569 unsigned char OperandFlags = 0;
7570 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7572 unsigned WrapperKind = X86ISD::Wrapper;
7573 if (model == TLSModel::LocalExec) {
7574 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7575 } else if (model == TLSModel::InitialExec) {
7577 OperandFlags = X86II::MO_GOTTPOFF;
7578 WrapperKind = X86ISD::WrapperRIP;
7580 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7583 llvm_unreachable("Unexpected model");
7586 // emit "addl x@ntpoff,%eax" (local exec)
7587 // or "addl x@indntpoff,%eax" (initial exec)
7588 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7589 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7590 GA->getValueType(0),
7591 GA->getOffset(), OperandFlags);
7592 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7594 if (model == TLSModel::InitialExec) {
7595 if (isPIC && !is64Bit) {
7596 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7597 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7601 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7602 MachinePointerInfo::getGOT(), false, false, false,
7606 // The address of the thread local variable is the add of the thread
7607 // pointer with the offset of the variable.
7608 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7612 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7614 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7615 const GlobalValue *GV = GA->getGlobal();
7617 if (Subtarget->isTargetELF()) {
7618 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7621 case TLSModel::GeneralDynamic:
7622 if (Subtarget->is64Bit())
7623 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7624 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7625 case TLSModel::LocalDynamic:
7626 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7627 Subtarget->is64Bit());
7628 case TLSModel::InitialExec:
7629 case TLSModel::LocalExec:
7630 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7631 Subtarget->is64Bit(),
7632 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7634 llvm_unreachable("Unknown TLS model.");
7637 if (Subtarget->isTargetDarwin()) {
7638 // Darwin only has one model of TLS. Lower to that.
7639 unsigned char OpFlag = 0;
7640 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7641 X86ISD::WrapperRIP : X86ISD::Wrapper;
7643 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7645 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7646 !Subtarget->is64Bit();
7648 OpFlag = X86II::MO_TLVP_PIC_BASE;
7650 OpFlag = X86II::MO_TLVP;
7651 DebugLoc DL = Op.getDebugLoc();
7652 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7653 GA->getValueType(0),
7654 GA->getOffset(), OpFlag);
7655 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7657 // With PIC32, the address is actually $g + Offset.
7659 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7660 DAG.getNode(X86ISD::GlobalBaseReg,
7661 DebugLoc(), getPointerTy()),
7664 // Lowering the machine isd will make sure everything is in the right
7666 SDValue Chain = DAG.getEntryNode();
7667 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7668 SDValue Args[] = { Chain, Offset };
7669 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7671 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7672 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7673 MFI->setAdjustsStack(true);
7675 // And our return value (tls address) is in the standard call return value
7677 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7678 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7682 if (Subtarget->isTargetWindows()) {
7683 // Just use the implicit TLS architecture
7684 // Need to generate someting similar to:
7685 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7687 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7688 // mov rcx, qword [rdx+rcx*8]
7689 // mov eax, .tls$:tlsvar
7690 // [rax+rcx] contains the address
7691 // Windows 64bit: gs:0x58
7692 // Windows 32bit: fs:__tls_array
7694 // If GV is an alias then use the aliasee for determining
7695 // thread-localness.
7696 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7697 GV = GA->resolveAliasedGlobal(false);
7698 DebugLoc dl = GA->getDebugLoc();
7699 SDValue Chain = DAG.getEntryNode();
7701 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7702 // %gs:0x58 (64-bit).
7703 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7704 ? Type::getInt8PtrTy(*DAG.getContext(),
7706 : Type::getInt32PtrTy(*DAG.getContext(),
7709 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7710 Subtarget->is64Bit()
7711 ? DAG.getIntPtrConstant(0x58)
7712 : DAG.getExternalSymbol("_tls_array",
7714 MachinePointerInfo(Ptr),
7715 false, false, false, 0);
7717 // Load the _tls_index variable
7718 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7719 if (Subtarget->is64Bit())
7720 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7721 IDX, MachinePointerInfo(), MVT::i32,
7724 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7725 false, false, false, 0);
7727 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7729 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7731 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7732 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7733 false, false, false, 0);
7735 // Get the offset of start of .tls section
7736 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7737 GA->getValueType(0),
7738 GA->getOffset(), X86II::MO_SECREL);
7739 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7741 // The address of the thread local variable is the add of the thread
7742 // pointer with the offset of the variable.
7743 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7746 llvm_unreachable("TLS not implemented for this target.");
7750 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7751 /// and take a 2 x i32 value to shift plus a shift amount.
7752 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7753 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7754 EVT VT = Op.getValueType();
7755 unsigned VTBits = VT.getSizeInBits();
7756 DebugLoc dl = Op.getDebugLoc();
7757 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7758 SDValue ShOpLo = Op.getOperand(0);
7759 SDValue ShOpHi = Op.getOperand(1);
7760 SDValue ShAmt = Op.getOperand(2);
7761 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7762 DAG.getConstant(VTBits - 1, MVT::i8))
7763 : DAG.getConstant(0, VT);
7766 if (Op.getOpcode() == ISD::SHL_PARTS) {
7767 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7768 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7770 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7771 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7774 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7775 DAG.getConstant(VTBits, MVT::i8));
7776 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7777 AndNode, DAG.getConstant(0, MVT::i8));
7780 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7781 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7782 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7784 if (Op.getOpcode() == ISD::SHL_PARTS) {
7785 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7786 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7788 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7789 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7792 SDValue Ops[2] = { Lo, Hi };
7793 return DAG.getMergeValues(Ops, 2, dl);
7796 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7797 SelectionDAG &DAG) const {
7798 EVT SrcVT = Op.getOperand(0).getValueType();
7800 if (SrcVT.isVector())
7803 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7804 "Unknown SINT_TO_FP to lower!");
7806 // These are really Legal; return the operand so the caller accepts it as
7808 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7810 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7811 Subtarget->is64Bit()) {
7815 DebugLoc dl = Op.getDebugLoc();
7816 unsigned Size = SrcVT.getSizeInBits()/8;
7817 MachineFunction &MF = DAG.getMachineFunction();
7818 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7819 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7820 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7822 MachinePointerInfo::getFixedStack(SSFI),
7824 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7827 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7829 SelectionDAG &DAG) const {
7831 DebugLoc DL = Op.getDebugLoc();
7833 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7835 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7837 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7839 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7841 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7842 MachineMemOperand *MMO;
7844 int SSFI = FI->getIndex();
7846 DAG.getMachineFunction()
7847 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7848 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7850 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7851 StackSlot = StackSlot.getOperand(1);
7853 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7854 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7856 Tys, Ops, array_lengthof(Ops),
7860 Chain = Result.getValue(1);
7861 SDValue InFlag = Result.getValue(2);
7863 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7864 // shouldn't be necessary except that RFP cannot be live across
7865 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7866 MachineFunction &MF = DAG.getMachineFunction();
7867 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7868 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7869 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7870 Tys = DAG.getVTList(MVT::Other);
7872 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7874 MachineMemOperand *MMO =
7875 DAG.getMachineFunction()
7876 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7877 MachineMemOperand::MOStore, SSFISize, SSFISize);
7879 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7880 Ops, array_lengthof(Ops),
7881 Op.getValueType(), MMO);
7882 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7883 MachinePointerInfo::getFixedStack(SSFI),
7884 false, false, false, 0);
7890 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7891 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7892 SelectionDAG &DAG) const {
7893 // This algorithm is not obvious. Here it is what we're trying to output:
7896 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7897 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7901 pshufd $0x4e, %xmm0, %xmm1
7906 DebugLoc dl = Op.getDebugLoc();
7907 LLVMContext *Context = DAG.getContext();
7909 // Build some magic constants.
7910 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7911 Constant *C0 = ConstantDataVector::get(*Context, CV0);
7912 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7914 SmallVector<Constant*,2> CV1;
7916 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7918 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7919 Constant *C1 = ConstantVector::get(CV1);
7920 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7922 // Load the 64-bit value into an XMM register.
7923 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7925 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7926 MachinePointerInfo::getConstantPool(),
7927 false, false, false, 16);
7928 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7929 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7932 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7933 MachinePointerInfo::getConstantPool(),
7934 false, false, false, 16);
7935 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7936 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7939 if (Subtarget->hasSSE3()) {
7940 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7941 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7943 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7944 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7946 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7947 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7951 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7952 DAG.getIntPtrConstant(0));
7955 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7956 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7957 SelectionDAG &DAG) const {
7958 DebugLoc dl = Op.getDebugLoc();
7959 // FP constant to bias correct the final result.
7960 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7963 // Load the 32-bit value into an XMM register.
7964 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7967 // Zero out the upper parts of the register.
7968 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7970 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7971 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7972 DAG.getIntPtrConstant(0));
7974 // Or the load with the bias.
7975 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7976 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7977 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7979 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7980 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7981 MVT::v2f64, Bias)));
7982 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7983 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7984 DAG.getIntPtrConstant(0));
7986 // Subtract the bias.
7987 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7989 // Handle final rounding.
7990 EVT DestVT = Op.getValueType();
7992 if (DestVT.bitsLT(MVT::f64))
7993 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7994 DAG.getIntPtrConstant(0));
7995 if (DestVT.bitsGT(MVT::f64))
7996 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7998 // Handle final rounding.
8002 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8003 SelectionDAG &DAG) const {
8004 SDValue N0 = Op.getOperand(0);
8005 DebugLoc dl = Op.getDebugLoc();
8007 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8008 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8009 // the optimization here.
8010 if (DAG.SignBitIsZero(N0))
8011 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8013 EVT SrcVT = N0.getValueType();
8014 EVT DstVT = Op.getValueType();
8015 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8016 return LowerUINT_TO_FP_i64(Op, DAG);
8017 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8018 return LowerUINT_TO_FP_i32(Op, DAG);
8019 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8022 // Make a 64-bit buffer, and use it to build an FILD.
8023 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8024 if (SrcVT == MVT::i32) {
8025 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8026 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8027 getPointerTy(), StackSlot, WordOff);
8028 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8029 StackSlot, MachinePointerInfo(),
8031 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8032 OffsetSlot, MachinePointerInfo(),
8034 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8038 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8039 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8040 StackSlot, MachinePointerInfo(),
8042 // For i64 source, we need to add the appropriate power of 2 if the input
8043 // was negative. This is the same as the optimization in
8044 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8045 // we must be careful to do the computation in x87 extended precision, not
8046 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8047 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8048 MachineMemOperand *MMO =
8049 DAG.getMachineFunction()
8050 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8051 MachineMemOperand::MOLoad, 8, 8);
8053 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8054 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8055 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8058 APInt FF(32, 0x5F800000ULL);
8060 // Check whether the sign bit is set.
8061 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8062 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8065 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8066 SDValue FudgePtr = DAG.getConstantPool(
8067 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8070 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8071 SDValue Zero = DAG.getIntPtrConstant(0);
8072 SDValue Four = DAG.getIntPtrConstant(4);
8073 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8075 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8077 // Load the value out, extending it from f32 to f80.
8078 // FIXME: Avoid the extend by constructing the right constant pool?
8079 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8080 FudgePtr, MachinePointerInfo::getConstantPool(),
8081 MVT::f32, false, false, 4);
8082 // Extend everything to 80 bits to force it to be done on x87.
8083 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8084 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8087 std::pair<SDValue,SDValue> X86TargetLowering::
8088 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8089 DebugLoc DL = Op.getDebugLoc();
8091 EVT DstTy = Op.getValueType();
8093 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8094 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8098 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8099 DstTy.getSimpleVT() >= MVT::i16 &&
8100 "Unknown FP_TO_INT to lower!");
8102 // These are really Legal.
8103 if (DstTy == MVT::i32 &&
8104 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8105 return std::make_pair(SDValue(), SDValue());
8106 if (Subtarget->is64Bit() &&
8107 DstTy == MVT::i64 &&
8108 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8109 return std::make_pair(SDValue(), SDValue());
8111 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8112 // stack slot, or into the FTOL runtime function.
8113 MachineFunction &MF = DAG.getMachineFunction();
8114 unsigned MemSize = DstTy.getSizeInBits()/8;
8115 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8116 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8119 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8120 Opc = X86ISD::WIN_FTOL;
8122 switch (DstTy.getSimpleVT().SimpleTy) {
8123 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8124 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8125 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8126 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8129 SDValue Chain = DAG.getEntryNode();
8130 SDValue Value = Op.getOperand(0);
8131 EVT TheVT = Op.getOperand(0).getValueType();
8132 // FIXME This causes a redundant load/store if the SSE-class value is already
8133 // in memory, such as if it is on the callstack.
8134 if (isScalarFPTypeInSSEReg(TheVT)) {
8135 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8136 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8137 MachinePointerInfo::getFixedStack(SSFI),
8139 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8141 Chain, StackSlot, DAG.getValueType(TheVT)
8144 MachineMemOperand *MMO =
8145 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8146 MachineMemOperand::MOLoad, MemSize, MemSize);
8147 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8149 Chain = Value.getValue(1);
8150 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8151 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8154 MachineMemOperand *MMO =
8155 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8156 MachineMemOperand::MOStore, MemSize, MemSize);
8158 if (Opc != X86ISD::WIN_FTOL) {
8159 // Build the FP_TO_INT*_IN_MEM
8160 SDValue Ops[] = { Chain, Value, StackSlot };
8161 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8162 Ops, 3, DstTy, MMO);
8163 return std::make_pair(FIST, StackSlot);
8165 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8166 DAG.getVTList(MVT::Other, MVT::Glue),
8168 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8169 MVT::i32, ftol.getValue(1));
8170 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8171 MVT::i32, eax.getValue(2));
8172 SDValue Ops[] = { eax, edx };
8173 SDValue pair = IsReplace
8174 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8175 : DAG.getMergeValues(Ops, 2, DL);
8176 return std::make_pair(pair, SDValue());
8180 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8181 SelectionDAG &DAG) const {
8182 if (Op.getValueType().isVector())
8185 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8186 /*IsSigned=*/ true, /*IsReplace=*/ false);
8187 SDValue FIST = Vals.first, StackSlot = Vals.second;
8188 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8189 if (FIST.getNode() == 0) return Op;
8191 if (StackSlot.getNode())
8193 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8194 FIST, StackSlot, MachinePointerInfo(),
8195 false, false, false, 0);
8197 // The node is the result.
8201 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8202 SelectionDAG &DAG) const {
8203 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8204 /*IsSigned=*/ false, /*IsReplace=*/ false);
8205 SDValue FIST = Vals.first, StackSlot = Vals.second;
8206 assert(FIST.getNode() && "Unexpected failure");
8208 if (StackSlot.getNode())
8210 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8211 FIST, StackSlot, MachinePointerInfo(),
8212 false, false, false, 0);
8214 // The node is the result.
8218 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8219 LLVMContext *Context = DAG.getContext();
8220 DebugLoc dl = Op.getDebugLoc();
8221 EVT VT = Op.getValueType();
8223 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8224 if (VT.isVector()) {
8225 EltVT = VT.getVectorElementType();
8226 NumElts = VT.getVectorNumElements();
8229 if (EltVT == MVT::f64)
8230 C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8232 C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8233 C = ConstantVector::getSplat(NumElts, C);
8234 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8235 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8236 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8237 MachinePointerInfo::getConstantPool(),
8238 false, false, false, Alignment);
8239 if (VT.isVector()) {
8240 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8241 return DAG.getNode(ISD::BITCAST, dl, VT,
8242 DAG.getNode(ISD::AND, dl, ANDVT,
8243 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8245 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8247 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8250 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8251 LLVMContext *Context = DAG.getContext();
8252 DebugLoc dl = Op.getDebugLoc();
8253 EVT VT = Op.getValueType();
8255 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8256 if (VT.isVector()) {
8257 EltVT = VT.getVectorElementType();
8258 NumElts = VT.getVectorNumElements();
8261 if (EltVT == MVT::f64)
8262 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8264 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8265 C = ConstantVector::getSplat(NumElts, C);
8266 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8267 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8268 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8269 MachinePointerInfo::getConstantPool(),
8270 false, false, false, Alignment);
8271 if (VT.isVector()) {
8272 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8273 return DAG.getNode(ISD::BITCAST, dl, VT,
8274 DAG.getNode(ISD::XOR, dl, XORVT,
8275 DAG.getNode(ISD::BITCAST, dl, XORVT,
8277 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8280 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8283 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8284 LLVMContext *Context = DAG.getContext();
8285 SDValue Op0 = Op.getOperand(0);
8286 SDValue Op1 = Op.getOperand(1);
8287 DebugLoc dl = Op.getDebugLoc();
8288 EVT VT = Op.getValueType();
8289 EVT SrcVT = Op1.getValueType();
8291 // If second operand is smaller, extend it first.
8292 if (SrcVT.bitsLT(VT)) {
8293 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8296 // And if it is bigger, shrink it first.
8297 if (SrcVT.bitsGT(VT)) {
8298 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8302 // At this point the operands and the result should have the same
8303 // type, and that won't be f80 since that is not custom lowered.
8305 // First get the sign bit of second operand.
8306 SmallVector<Constant*,4> CV;
8307 if (SrcVT == MVT::f64) {
8308 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8309 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8311 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8312 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8313 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8314 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8316 Constant *C = ConstantVector::get(CV);
8317 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8318 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8319 MachinePointerInfo::getConstantPool(),
8320 false, false, false, 16);
8321 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8323 // Shift sign bit right or left if the two operands have different types.
8324 if (SrcVT.bitsGT(VT)) {
8325 // Op0 is MVT::f32, Op1 is MVT::f64.
8326 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8327 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8328 DAG.getConstant(32, MVT::i32));
8329 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8330 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8331 DAG.getIntPtrConstant(0));
8334 // Clear first operand sign bit.
8336 if (VT == MVT::f64) {
8337 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8338 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8340 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8341 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8342 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8343 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8345 C = ConstantVector::get(CV);
8346 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8347 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8348 MachinePointerInfo::getConstantPool(),
8349 false, false, false, 16);
8350 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8352 // Or the value with the sign bit.
8353 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8356 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8357 SDValue N0 = Op.getOperand(0);
8358 DebugLoc dl = Op.getDebugLoc();
8359 EVT VT = Op.getValueType();
8361 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8362 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8363 DAG.getConstant(1, VT));
8364 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8367 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8369 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8370 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8372 if (!Subtarget->hasSSE41())
8375 if (!Op->hasOneUse())
8378 SDNode *N = Op.getNode();
8379 DebugLoc DL = N->getDebugLoc();
8381 SmallVector<SDValue, 8> Opnds;
8382 DenseMap<SDValue, unsigned> VecInMap;
8383 EVT VT = MVT::Other;
8385 // Recognize a special case where a vector is casted into wide integer to
8387 Opnds.push_back(N->getOperand(0));
8388 Opnds.push_back(N->getOperand(1));
8390 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8391 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8392 // BFS traverse all OR'd operands.
8393 if (I->getOpcode() == ISD::OR) {
8394 Opnds.push_back(I->getOperand(0));
8395 Opnds.push_back(I->getOperand(1));
8396 // Re-evaluate the number of nodes to be traversed.
8397 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8401 // Quit if a non-EXTRACT_VECTOR_ELT
8402 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8405 // Quit if without a constant index.
8406 SDValue Idx = I->getOperand(1);
8407 if (!isa<ConstantSDNode>(Idx))
8410 SDValue ExtractedFromVec = I->getOperand(0);
8411 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8412 if (M == VecInMap.end()) {
8413 VT = ExtractedFromVec.getValueType();
8414 // Quit if not 128/256-bit vector.
8415 if (!VT.is128BitVector() && !VT.is256BitVector())
8417 // Quit if not the same type.
8418 if (VecInMap.begin() != VecInMap.end() &&
8419 VT != VecInMap.begin()->first.getValueType())
8421 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8423 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8426 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8427 "Not extracted from 128-/256-bit vector.");
8429 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8430 SmallVector<SDValue, 8> VecIns;
8432 for (DenseMap<SDValue, unsigned>::const_iterator
8433 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8434 // Quit if not all elements are used.
8435 if (I->second != FullMask)
8437 VecIns.push_back(I->first);
8440 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8442 // Cast all vectors into TestVT for PTEST.
8443 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8444 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8446 // If more than one full vectors are evaluated, OR them first before PTEST.
8447 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8448 // Each iteration will OR 2 nodes and append the result until there is only
8449 // 1 node left, i.e. the final OR'd value of all vectors.
8450 SDValue LHS = VecIns[Slot];
8451 SDValue RHS = VecIns[Slot + 1];
8452 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8455 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8456 VecIns.back(), VecIns.back());
8459 /// Emit nodes that will be selected as "test Op0,Op0", or something
8461 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8462 SelectionDAG &DAG) const {
8463 DebugLoc dl = Op.getDebugLoc();
8465 // CF and OF aren't always set the way we want. Determine which
8466 // of these we need.
8467 bool NeedCF = false;
8468 bool NeedOF = false;
8471 case X86::COND_A: case X86::COND_AE:
8472 case X86::COND_B: case X86::COND_BE:
8475 case X86::COND_G: case X86::COND_GE:
8476 case X86::COND_L: case X86::COND_LE:
8477 case X86::COND_O: case X86::COND_NO:
8482 // See if we can use the EFLAGS value from the operand instead of
8483 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8484 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8485 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8486 // Emit a CMP with 0, which is the TEST pattern.
8487 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8488 DAG.getConstant(0, Op.getValueType()));
8490 unsigned Opcode = 0;
8491 unsigned NumOperands = 0;
8493 // Truncate operations may prevent the merge of the SETCC instruction
8494 // and the arithmetic intruction before it. Attempt to truncate the operands
8495 // of the arithmetic instruction and use a reduced bit-width instruction.
8496 bool NeedTruncation = false;
8497 SDValue ArithOp = Op;
8498 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8499 SDValue Arith = Op->getOperand(0);
8500 // Both the trunc and the arithmetic op need to have one user each.
8501 if (Arith->hasOneUse())
8502 switch (Arith.getOpcode()) {
8509 NeedTruncation = true;
8515 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8516 // which may be the result of a CAST. We use the variable 'Op', which is the
8517 // non-casted variable when we check for possible users.
8518 switch (ArithOp.getOpcode()) {
8520 // Due to an isel shortcoming, be conservative if this add is likely to be
8521 // selected as part of a load-modify-store instruction. When the root node
8522 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8523 // uses of other nodes in the match, such as the ADD in this case. This
8524 // leads to the ADD being left around and reselected, with the result being
8525 // two adds in the output. Alas, even if none our users are stores, that
8526 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8527 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8528 // climbing the DAG back to the root, and it doesn't seem to be worth the
8530 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8531 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8532 if (UI->getOpcode() != ISD::CopyToReg &&
8533 UI->getOpcode() != ISD::SETCC &&
8534 UI->getOpcode() != ISD::STORE)
8537 if (ConstantSDNode *C =
8538 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8539 // An add of one will be selected as an INC.
8540 if (C->getAPIntValue() == 1) {
8541 Opcode = X86ISD::INC;
8546 // An add of negative one (subtract of one) will be selected as a DEC.
8547 if (C->getAPIntValue().isAllOnesValue()) {
8548 Opcode = X86ISD::DEC;
8554 // Otherwise use a regular EFLAGS-setting add.
8555 Opcode = X86ISD::ADD;
8559 // If the primary and result isn't used, don't bother using X86ISD::AND,
8560 // because a TEST instruction will be better.
8561 bool NonFlagUse = false;
8562 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8563 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8565 unsigned UOpNo = UI.getOperandNo();
8566 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8567 // Look pass truncate.
8568 UOpNo = User->use_begin().getOperandNo();
8569 User = *User->use_begin();
8572 if (User->getOpcode() != ISD::BRCOND &&
8573 User->getOpcode() != ISD::SETCC &&
8574 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8587 // Due to the ISEL shortcoming noted above, be conservative if this op is
8588 // likely to be selected as part of a load-modify-store instruction.
8589 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8590 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8591 if (UI->getOpcode() == ISD::STORE)
8594 // Otherwise use a regular EFLAGS-setting instruction.
8595 switch (ArithOp.getOpcode()) {
8596 default: llvm_unreachable("unexpected operator!");
8597 case ISD::SUB: Opcode = X86ISD::SUB; break;
8598 case ISD::XOR: Opcode = X86ISD::XOR; break;
8599 case ISD::AND: Opcode = X86ISD::AND; break;
8601 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8602 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8603 if (EFLAGS.getNode())
8606 Opcode = X86ISD::OR;
8620 return SDValue(Op.getNode(), 1);
8626 // If we found that truncation is beneficial, perform the truncation and
8628 if (NeedTruncation) {
8629 EVT VT = Op.getValueType();
8630 SDValue WideVal = Op->getOperand(0);
8631 EVT WideVT = WideVal.getValueType();
8632 unsigned ConvertedOp = 0;
8633 // Use a target machine opcode to prevent further DAGCombine
8634 // optimizations that may separate the arithmetic operations
8635 // from the setcc node.
8636 switch (WideVal.getOpcode()) {
8638 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8639 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8640 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8641 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8642 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8646 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8647 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8648 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8649 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8650 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8656 // Emit a CMP with 0, which is the TEST pattern.
8657 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8658 DAG.getConstant(0, Op.getValueType()));
8660 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8661 SmallVector<SDValue, 4> Ops;
8662 for (unsigned i = 0; i != NumOperands; ++i)
8663 Ops.push_back(Op.getOperand(i));
8665 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8666 DAG.ReplaceAllUsesWith(Op, New);
8667 return SDValue(New.getNode(), 1);
8670 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8672 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8673 SelectionDAG &DAG) const {
8674 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8675 if (C->getAPIntValue() == 0)
8676 return EmitTest(Op0, X86CC, DAG);
8678 DebugLoc dl = Op0.getDebugLoc();
8679 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8680 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8681 // Use SUB instead of CMP to enable CSE between SUB and CMP.
8682 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8683 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8685 return SDValue(Sub.getNode(), 1);
8687 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8690 /// Convert a comparison if required by the subtarget.
8691 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8692 SelectionDAG &DAG) const {
8693 // If the subtarget does not support the FUCOMI instruction, floating-point
8694 // comparisons have to be converted.
8695 if (Subtarget->hasCMov() ||
8696 Cmp.getOpcode() != X86ISD::CMP ||
8697 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8698 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8701 // The instruction selector will select an FUCOM instruction instead of
8702 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8703 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8704 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8705 DebugLoc dl = Cmp.getDebugLoc();
8706 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8707 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8708 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8709 DAG.getConstant(8, MVT::i8));
8710 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8711 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8714 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8715 /// if it's possible.
8716 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8717 DebugLoc dl, SelectionDAG &DAG) const {
8718 SDValue Op0 = And.getOperand(0);
8719 SDValue Op1 = And.getOperand(1);
8720 if (Op0.getOpcode() == ISD::TRUNCATE)
8721 Op0 = Op0.getOperand(0);
8722 if (Op1.getOpcode() == ISD::TRUNCATE)
8723 Op1 = Op1.getOperand(0);
8726 if (Op1.getOpcode() == ISD::SHL)
8727 std::swap(Op0, Op1);
8728 if (Op0.getOpcode() == ISD::SHL) {
8729 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8730 if (And00C->getZExtValue() == 1) {
8731 // If we looked past a truncate, check that it's only truncating away
8733 unsigned BitWidth = Op0.getValueSizeInBits();
8734 unsigned AndBitWidth = And.getValueSizeInBits();
8735 if (BitWidth > AndBitWidth) {
8737 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8738 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8742 RHS = Op0.getOperand(1);
8744 } else if (Op1.getOpcode() == ISD::Constant) {
8745 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8746 uint64_t AndRHSVal = AndRHS->getZExtValue();
8747 SDValue AndLHS = Op0;
8749 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8750 LHS = AndLHS.getOperand(0);
8751 RHS = AndLHS.getOperand(1);
8754 // Use BT if the immediate can't be encoded in a TEST instruction.
8755 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8757 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8761 if (LHS.getNode()) {
8762 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8763 // instruction. Since the shift amount is in-range-or-undefined, we know
8764 // that doing a bittest on the i32 value is ok. We extend to i32 because
8765 // the encoding for the i16 version is larger than the i32 version.
8766 // Also promote i16 to i32 for performance / code size reason.
8767 if (LHS.getValueType() == MVT::i8 ||
8768 LHS.getValueType() == MVT::i16)
8769 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8771 // If the operand types disagree, extend the shift amount to match. Since
8772 // BT ignores high bits (like shifts) we can use anyextend.
8773 if (LHS.getValueType() != RHS.getValueType())
8774 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8776 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8777 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8778 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8779 DAG.getConstant(Cond, MVT::i8), BT);
8785 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8787 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8789 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8790 SDValue Op0 = Op.getOperand(0);
8791 SDValue Op1 = Op.getOperand(1);
8792 DebugLoc dl = Op.getDebugLoc();
8793 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8795 // Optimize to BT if possible.
8796 // Lower (X & (1 << N)) == 0 to BT(X, N).
8797 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8798 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8799 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8800 Op1.getOpcode() == ISD::Constant &&
8801 cast<ConstantSDNode>(Op1)->isNullValue() &&
8802 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8803 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8804 if (NewSetCC.getNode())
8808 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8810 if (Op1.getOpcode() == ISD::Constant &&
8811 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8812 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8813 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8815 // If the input is a setcc, then reuse the input setcc or use a new one with
8816 // the inverted condition.
8817 if (Op0.getOpcode() == X86ISD::SETCC) {
8818 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8819 bool Invert = (CC == ISD::SETNE) ^
8820 cast<ConstantSDNode>(Op1)->isNullValue();
8821 if (!Invert) return Op0;
8823 CCode = X86::GetOppositeBranchCondition(CCode);
8824 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8825 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8829 bool isFP = Op1.getValueType().isFloatingPoint();
8830 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8831 if (X86CC == X86::COND_INVALID)
8834 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8835 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8836 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8837 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8840 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8841 // ones, and then concatenate the result back.
8842 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8843 EVT VT = Op.getValueType();
8845 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8846 "Unsupported value type for operation");
8848 unsigned NumElems = VT.getVectorNumElements();
8849 DebugLoc dl = Op.getDebugLoc();
8850 SDValue CC = Op.getOperand(2);
8852 // Extract the LHS vectors
8853 SDValue LHS = Op.getOperand(0);
8854 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8855 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8857 // Extract the RHS vectors
8858 SDValue RHS = Op.getOperand(1);
8859 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8860 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8862 // Issue the operation on the smaller types and concatenate the result back
8863 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8864 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8865 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8866 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8867 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8871 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8873 SDValue Op0 = Op.getOperand(0);
8874 SDValue Op1 = Op.getOperand(1);
8875 SDValue CC = Op.getOperand(2);
8876 EVT VT = Op.getValueType();
8877 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8878 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8879 DebugLoc dl = Op.getDebugLoc();
8883 EVT EltVT = Op0.getValueType().getVectorElementType();
8884 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8890 // SSE Condition code mapping:
8899 switch (SetCCOpcode) {
8900 default: llvm_unreachable("Unexpected SETCC condition");
8902 case ISD::SETEQ: SSECC = 0; break;
8904 case ISD::SETGT: Swap = true; // Fallthrough
8906 case ISD::SETOLT: SSECC = 1; break;
8908 case ISD::SETGE: Swap = true; // Fallthrough
8910 case ISD::SETOLE: SSECC = 2; break;
8911 case ISD::SETUO: SSECC = 3; break;
8913 case ISD::SETNE: SSECC = 4; break;
8914 case ISD::SETULE: Swap = true; // Fallthrough
8915 case ISD::SETUGE: SSECC = 5; break;
8916 case ISD::SETULT: Swap = true; // Fallthrough
8917 case ISD::SETUGT: SSECC = 6; break;
8918 case ISD::SETO: SSECC = 7; break;
8920 case ISD::SETONE: SSECC = 8; break;
8923 std::swap(Op0, Op1);
8925 // In the two special cases we can't handle, emit two comparisons.
8928 unsigned CombineOpc;
8929 if (SetCCOpcode == ISD::SETUEQ) {
8930 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8932 assert(SetCCOpcode == ISD::SETONE);
8933 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8936 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8937 DAG.getConstant(CC0, MVT::i8));
8938 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8939 DAG.getConstant(CC1, MVT::i8));
8940 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8942 // Handle all other FP comparisons here.
8943 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8944 DAG.getConstant(SSECC, MVT::i8));
8947 // Break 256-bit integer vector compare into smaller ones.
8948 if (VT.is256BitVector() && !Subtarget->hasAVX2())
8949 return Lower256IntVSETCC(Op, DAG);
8951 // We are handling one of the integer comparisons here. Since SSE only has
8952 // GT and EQ comparisons for integer, swapping operands and multiple
8953 // operations may be required for some comparisons.
8955 bool Swap = false, Invert = false, FlipSigns = false;
8957 switch (SetCCOpcode) {
8958 default: llvm_unreachable("Unexpected SETCC condition");
8959 case ISD::SETNE: Invert = true;
8960 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
8961 case ISD::SETLT: Swap = true;
8962 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
8963 case ISD::SETGE: Swap = true;
8964 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
8965 case ISD::SETULT: Swap = true;
8966 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8967 case ISD::SETUGE: Swap = true;
8968 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8971 std::swap(Op0, Op1);
8973 // Check that the operation in question is available (most are plain SSE2,
8974 // but PCMPGTQ and PCMPEQQ have different requirements).
8975 if (VT == MVT::v2i64) {
8976 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8978 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8982 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8983 // bits of the inputs before performing those operations.
8985 EVT EltVT = VT.getVectorElementType();
8986 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8988 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8989 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8991 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8992 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8995 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8997 // If the logical-not of the result is required, perform that now.
8999 Result = DAG.getNOT(dl, Result, VT);
9004 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9005 static bool isX86LogicalCmp(SDValue Op) {
9006 unsigned Opc = Op.getNode()->getOpcode();
9007 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9008 Opc == X86ISD::SAHF)
9010 if (Op.getResNo() == 1 &&
9011 (Opc == X86ISD::ADD ||
9012 Opc == X86ISD::SUB ||
9013 Opc == X86ISD::ADC ||
9014 Opc == X86ISD::SBB ||
9015 Opc == X86ISD::SMUL ||
9016 Opc == X86ISD::UMUL ||
9017 Opc == X86ISD::INC ||
9018 Opc == X86ISD::DEC ||
9019 Opc == X86ISD::OR ||
9020 Opc == X86ISD::XOR ||
9021 Opc == X86ISD::AND))
9024 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9030 static bool isZero(SDValue V) {
9031 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9032 return C && C->isNullValue();
9035 static bool isAllOnes(SDValue V) {
9036 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9037 return C && C->isAllOnesValue();
9040 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9041 if (V.getOpcode() != ISD::TRUNCATE)
9044 SDValue VOp0 = V.getOperand(0);
9045 unsigned InBits = VOp0.getValueSizeInBits();
9046 unsigned Bits = V.getValueSizeInBits();
9047 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9050 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9051 bool addTest = true;
9052 SDValue Cond = Op.getOperand(0);
9053 SDValue Op1 = Op.getOperand(1);
9054 SDValue Op2 = Op.getOperand(2);
9055 DebugLoc DL = Op.getDebugLoc();
9058 if (Cond.getOpcode() == ISD::SETCC) {
9059 SDValue NewCond = LowerSETCC(Cond, DAG);
9060 if (NewCond.getNode())
9064 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9065 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9066 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9067 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9068 if (Cond.getOpcode() == X86ISD::SETCC &&
9069 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9070 isZero(Cond.getOperand(1).getOperand(1))) {
9071 SDValue Cmp = Cond.getOperand(1);
9073 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9075 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9076 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9077 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9079 SDValue CmpOp0 = Cmp.getOperand(0);
9080 // Apply further optimizations for special cases
9081 // (select (x != 0), -1, 0) -> neg & sbb
9082 // (select (x == 0), 0, -1) -> neg & sbb
9083 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9084 if (YC->isNullValue() &&
9085 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9086 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9087 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9088 DAG.getConstant(0, CmpOp0.getValueType()),
9090 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9091 DAG.getConstant(X86::COND_B, MVT::i8),
9092 SDValue(Neg.getNode(), 1));
9096 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9097 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9098 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9100 SDValue Res = // Res = 0 or -1.
9101 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9102 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9104 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9105 Res = DAG.getNOT(DL, Res, Res.getValueType());
9107 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9108 if (N2C == 0 || !N2C->isNullValue())
9109 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9114 // Look past (and (setcc_carry (cmp ...)), 1).
9115 if (Cond.getOpcode() == ISD::AND &&
9116 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9117 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9118 if (C && C->getAPIntValue() == 1)
9119 Cond = Cond.getOperand(0);
9122 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9123 // setting operand in place of the X86ISD::SETCC.
9124 unsigned CondOpcode = Cond.getOpcode();
9125 if (CondOpcode == X86ISD::SETCC ||
9126 CondOpcode == X86ISD::SETCC_CARRY) {
9127 CC = Cond.getOperand(0);
9129 SDValue Cmp = Cond.getOperand(1);
9130 unsigned Opc = Cmp.getOpcode();
9131 EVT VT = Op.getValueType();
9133 bool IllegalFPCMov = false;
9134 if (VT.isFloatingPoint() && !VT.isVector() &&
9135 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9136 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9138 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9139 Opc == X86ISD::BT) { // FIXME
9143 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9144 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9145 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9146 Cond.getOperand(0).getValueType() != MVT::i8)) {
9147 SDValue LHS = Cond.getOperand(0);
9148 SDValue RHS = Cond.getOperand(1);
9152 switch (CondOpcode) {
9153 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9154 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9155 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9156 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9157 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9158 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9159 default: llvm_unreachable("unexpected overflowing operator");
9161 if (CondOpcode == ISD::UMULO)
9162 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9165 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9167 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9169 if (CondOpcode == ISD::UMULO)
9170 Cond = X86Op.getValue(2);
9172 Cond = X86Op.getValue(1);
9174 CC = DAG.getConstant(X86Cond, MVT::i8);
9179 // Look pass the truncate if the high bits are known zero.
9180 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9181 Cond = Cond.getOperand(0);
9183 // We know the result of AND is compared against zero. Try to match
9185 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9186 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9187 if (NewSetCC.getNode()) {
9188 CC = NewSetCC.getOperand(0);
9189 Cond = NewSetCC.getOperand(1);
9196 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9197 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9200 // a < b ? -1 : 0 -> RES = ~setcc_carry
9201 // a < b ? 0 : -1 -> RES = setcc_carry
9202 // a >= b ? -1 : 0 -> RES = setcc_carry
9203 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9204 if (Cond.getOpcode() == X86ISD::SUB) {
9205 Cond = ConvertCmpIfNecessary(Cond, DAG);
9206 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9208 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9209 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9210 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9211 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9212 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9213 return DAG.getNOT(DL, Res, Res.getValueType());
9218 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9219 // condition is true.
9220 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9221 SDValue Ops[] = { Op2, Op1, CC, Cond };
9222 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9225 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9226 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9227 // from the AND / OR.
9228 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9229 Opc = Op.getOpcode();
9230 if (Opc != ISD::OR && Opc != ISD::AND)
9232 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9233 Op.getOperand(0).hasOneUse() &&
9234 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9235 Op.getOperand(1).hasOneUse());
9238 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9239 // 1 and that the SETCC node has a single use.
9240 static bool isXor1OfSetCC(SDValue Op) {
9241 if (Op.getOpcode() != ISD::XOR)
9243 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9244 if (N1C && N1C->getAPIntValue() == 1) {
9245 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9246 Op.getOperand(0).hasOneUse();
9251 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9252 bool addTest = true;
9253 SDValue Chain = Op.getOperand(0);
9254 SDValue Cond = Op.getOperand(1);
9255 SDValue Dest = Op.getOperand(2);
9256 DebugLoc dl = Op.getDebugLoc();
9258 bool Inverted = false;
9260 if (Cond.getOpcode() == ISD::SETCC) {
9261 // Check for setcc([su]{add,sub,mul}o == 0).
9262 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9263 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9264 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9265 Cond.getOperand(0).getResNo() == 1 &&
9266 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9267 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9268 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9269 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9270 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9271 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9273 Cond = Cond.getOperand(0);
9275 SDValue NewCond = LowerSETCC(Cond, DAG);
9276 if (NewCond.getNode())
9281 // FIXME: LowerXALUO doesn't handle these!!
9282 else if (Cond.getOpcode() == X86ISD::ADD ||
9283 Cond.getOpcode() == X86ISD::SUB ||
9284 Cond.getOpcode() == X86ISD::SMUL ||
9285 Cond.getOpcode() == X86ISD::UMUL)
9286 Cond = LowerXALUO(Cond, DAG);
9289 // Look pass (and (setcc_carry (cmp ...)), 1).
9290 if (Cond.getOpcode() == ISD::AND &&
9291 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9292 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9293 if (C && C->getAPIntValue() == 1)
9294 Cond = Cond.getOperand(0);
9297 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9298 // setting operand in place of the X86ISD::SETCC.
9299 unsigned CondOpcode = Cond.getOpcode();
9300 if (CondOpcode == X86ISD::SETCC ||
9301 CondOpcode == X86ISD::SETCC_CARRY) {
9302 CC = Cond.getOperand(0);
9304 SDValue Cmp = Cond.getOperand(1);
9305 unsigned Opc = Cmp.getOpcode();
9306 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9307 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9311 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9315 // These can only come from an arithmetic instruction with overflow,
9316 // e.g. SADDO, UADDO.
9317 Cond = Cond.getNode()->getOperand(1);
9323 CondOpcode = Cond.getOpcode();
9324 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9325 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9326 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9327 Cond.getOperand(0).getValueType() != MVT::i8)) {
9328 SDValue LHS = Cond.getOperand(0);
9329 SDValue RHS = Cond.getOperand(1);
9333 switch (CondOpcode) {
9334 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9335 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9336 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9337 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9338 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9339 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9340 default: llvm_unreachable("unexpected overflowing operator");
9343 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9344 if (CondOpcode == ISD::UMULO)
9345 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9348 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9350 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9352 if (CondOpcode == ISD::UMULO)
9353 Cond = X86Op.getValue(2);
9355 Cond = X86Op.getValue(1);
9357 CC = DAG.getConstant(X86Cond, MVT::i8);
9361 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9362 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9363 if (CondOpc == ISD::OR) {
9364 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9365 // two branches instead of an explicit OR instruction with a
9367 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9368 isX86LogicalCmp(Cmp)) {
9369 CC = Cond.getOperand(0).getOperand(0);
9370 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9371 Chain, Dest, CC, Cmp);
9372 CC = Cond.getOperand(1).getOperand(0);
9376 } else { // ISD::AND
9377 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9378 // two branches instead of an explicit AND instruction with a
9379 // separate test. However, we only do this if this block doesn't
9380 // have a fall-through edge, because this requires an explicit
9381 // jmp when the condition is false.
9382 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9383 isX86LogicalCmp(Cmp) &&
9384 Op.getNode()->hasOneUse()) {
9385 X86::CondCode CCode =
9386 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9387 CCode = X86::GetOppositeBranchCondition(CCode);
9388 CC = DAG.getConstant(CCode, MVT::i8);
9389 SDNode *User = *Op.getNode()->use_begin();
9390 // Look for an unconditional branch following this conditional branch.
9391 // We need this because we need to reverse the successors in order
9392 // to implement FCMP_OEQ.
9393 if (User->getOpcode() == ISD::BR) {
9394 SDValue FalseBB = User->getOperand(1);
9396 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9397 assert(NewBR == User);
9401 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9402 Chain, Dest, CC, Cmp);
9403 X86::CondCode CCode =
9404 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9405 CCode = X86::GetOppositeBranchCondition(CCode);
9406 CC = DAG.getConstant(CCode, MVT::i8);
9412 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9413 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9414 // It should be transformed during dag combiner except when the condition
9415 // is set by a arithmetics with overflow node.
9416 X86::CondCode CCode =
9417 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9418 CCode = X86::GetOppositeBranchCondition(CCode);
9419 CC = DAG.getConstant(CCode, MVT::i8);
9420 Cond = Cond.getOperand(0).getOperand(1);
9422 } else if (Cond.getOpcode() == ISD::SETCC &&
9423 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9424 // For FCMP_OEQ, we can emit
9425 // two branches instead of an explicit AND instruction with a
9426 // separate test. However, we only do this if this block doesn't
9427 // have a fall-through edge, because this requires an explicit
9428 // jmp when the condition is false.
9429 if (Op.getNode()->hasOneUse()) {
9430 SDNode *User = *Op.getNode()->use_begin();
9431 // Look for an unconditional branch following this conditional branch.
9432 // We need this because we need to reverse the successors in order
9433 // to implement FCMP_OEQ.
9434 if (User->getOpcode() == ISD::BR) {
9435 SDValue FalseBB = User->getOperand(1);
9437 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9438 assert(NewBR == User);
9442 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9443 Cond.getOperand(0), Cond.getOperand(1));
9444 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9445 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9446 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9447 Chain, Dest, CC, Cmp);
9448 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9453 } else if (Cond.getOpcode() == ISD::SETCC &&
9454 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9455 // For FCMP_UNE, we can emit
9456 // two branches instead of an explicit AND instruction with a
9457 // separate test. However, we only do this if this block doesn't
9458 // have a fall-through edge, because this requires an explicit
9459 // jmp when the condition is false.
9460 if (Op.getNode()->hasOneUse()) {
9461 SDNode *User = *Op.getNode()->use_begin();
9462 // Look for an unconditional branch following this conditional branch.
9463 // We need this because we need to reverse the successors in order
9464 // to implement FCMP_UNE.
9465 if (User->getOpcode() == ISD::BR) {
9466 SDValue FalseBB = User->getOperand(1);
9468 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9469 assert(NewBR == User);
9472 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9473 Cond.getOperand(0), Cond.getOperand(1));
9474 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9475 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9476 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9477 Chain, Dest, CC, Cmp);
9478 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9488 // Look pass the truncate if the high bits are known zero.
9489 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9490 Cond = Cond.getOperand(0);
9492 // We know the result of AND is compared against zero. Try to match
9494 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9495 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9496 if (NewSetCC.getNode()) {
9497 CC = NewSetCC.getOperand(0);
9498 Cond = NewSetCC.getOperand(1);
9505 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9506 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9508 Cond = ConvertCmpIfNecessary(Cond, DAG);
9509 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9510 Chain, Dest, CC, Cond);
9514 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9515 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9516 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9517 // that the guard pages used by the OS virtual memory manager are allocated in
9518 // correct sequence.
9520 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9521 SelectionDAG &DAG) const {
9522 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9523 getTargetMachine().Options.EnableSegmentedStacks) &&
9524 "This should be used only on Windows targets or when segmented stacks "
9526 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9527 DebugLoc dl = Op.getDebugLoc();
9530 SDValue Chain = Op.getOperand(0);
9531 SDValue Size = Op.getOperand(1);
9532 // FIXME: Ensure alignment here
9534 bool Is64Bit = Subtarget->is64Bit();
9535 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9537 if (getTargetMachine().Options.EnableSegmentedStacks) {
9538 MachineFunction &MF = DAG.getMachineFunction();
9539 MachineRegisterInfo &MRI = MF.getRegInfo();
9542 // The 64 bit implementation of segmented stacks needs to clobber both r10
9543 // r11. This makes it impossible to use it along with nested parameters.
9544 const Function *F = MF.getFunction();
9546 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9548 if (I->hasNestAttr())
9549 report_fatal_error("Cannot use segmented stacks with functions that "
9550 "have nested arguments.");
9553 const TargetRegisterClass *AddrRegClass =
9554 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9555 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9556 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9557 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9558 DAG.getRegister(Vreg, SPTy));
9559 SDValue Ops1[2] = { Value, Chain };
9560 return DAG.getMergeValues(Ops1, 2, dl);
9563 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9565 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9566 Flag = Chain.getValue(1);
9567 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9569 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9570 Flag = Chain.getValue(1);
9572 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9574 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9575 return DAG.getMergeValues(Ops1, 2, dl);
9579 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9580 MachineFunction &MF = DAG.getMachineFunction();
9581 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9583 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9584 DebugLoc DL = Op.getDebugLoc();
9586 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9587 // vastart just stores the address of the VarArgsFrameIndex slot into the
9588 // memory location argument.
9589 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9591 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9592 MachinePointerInfo(SV), false, false, 0);
9596 // gp_offset (0 - 6 * 8)
9597 // fp_offset (48 - 48 + 8 * 16)
9598 // overflow_arg_area (point to parameters coming in memory).
9600 SmallVector<SDValue, 8> MemOps;
9601 SDValue FIN = Op.getOperand(1);
9603 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9604 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9606 FIN, MachinePointerInfo(SV), false, false, 0);
9607 MemOps.push_back(Store);
9610 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9611 FIN, DAG.getIntPtrConstant(4));
9612 Store = DAG.getStore(Op.getOperand(0), DL,
9613 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9615 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9616 MemOps.push_back(Store);
9618 // Store ptr to overflow_arg_area
9619 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9620 FIN, DAG.getIntPtrConstant(4));
9621 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9623 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9624 MachinePointerInfo(SV, 8),
9626 MemOps.push_back(Store);
9628 // Store ptr to reg_save_area.
9629 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9630 FIN, DAG.getIntPtrConstant(8));
9631 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9633 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9634 MachinePointerInfo(SV, 16), false, false, 0);
9635 MemOps.push_back(Store);
9636 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9637 &MemOps[0], MemOps.size());
9640 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9641 assert(Subtarget->is64Bit() &&
9642 "LowerVAARG only handles 64-bit va_arg!");
9643 assert((Subtarget->isTargetLinux() ||
9644 Subtarget->isTargetDarwin()) &&
9645 "Unhandled target in LowerVAARG");
9646 assert(Op.getNode()->getNumOperands() == 4);
9647 SDValue Chain = Op.getOperand(0);
9648 SDValue SrcPtr = Op.getOperand(1);
9649 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9650 unsigned Align = Op.getConstantOperandVal(3);
9651 DebugLoc dl = Op.getDebugLoc();
9653 EVT ArgVT = Op.getNode()->getValueType(0);
9654 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9655 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9658 // Decide which area this value should be read from.
9659 // TODO: Implement the AMD64 ABI in its entirety. This simple
9660 // selection mechanism works only for the basic types.
9661 if (ArgVT == MVT::f80) {
9662 llvm_unreachable("va_arg for f80 not yet implemented");
9663 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9664 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9665 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9666 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9668 llvm_unreachable("Unhandled argument type in LowerVAARG");
9672 // Sanity Check: Make sure using fp_offset makes sense.
9673 assert(!getTargetMachine().Options.UseSoftFloat &&
9674 !(DAG.getMachineFunction()
9675 .getFunction()->getFnAttributes()
9676 .hasAttribute(Attributes::NoImplicitFloat)) &&
9677 Subtarget->hasSSE1());
9680 // Insert VAARG_64 node into the DAG
9681 // VAARG_64 returns two values: Variable Argument Address, Chain
9682 SmallVector<SDValue, 11> InstOps;
9683 InstOps.push_back(Chain);
9684 InstOps.push_back(SrcPtr);
9685 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9686 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9687 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9688 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9689 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9690 VTs, &InstOps[0], InstOps.size(),
9692 MachinePointerInfo(SV),
9697 Chain = VAARG.getValue(1);
9699 // Load the next argument and return it
9700 return DAG.getLoad(ArgVT, dl,
9703 MachinePointerInfo(),
9704 false, false, false, 0);
9707 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9708 SelectionDAG &DAG) {
9709 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9710 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9711 SDValue Chain = Op.getOperand(0);
9712 SDValue DstPtr = Op.getOperand(1);
9713 SDValue SrcPtr = Op.getOperand(2);
9714 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9715 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9716 DebugLoc DL = Op.getDebugLoc();
9718 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9719 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9721 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9724 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9725 // may or may not be a constant. Takes immediate version of shift as input.
9726 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9727 SDValue SrcOp, SDValue ShAmt,
9728 SelectionDAG &DAG) {
9729 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9731 if (isa<ConstantSDNode>(ShAmt)) {
9732 // Constant may be a TargetConstant. Use a regular constant.
9733 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9735 default: llvm_unreachable("Unknown target vector shift node");
9739 return DAG.getNode(Opc, dl, VT, SrcOp,
9740 DAG.getConstant(ShiftAmt, MVT::i32));
9744 // Change opcode to non-immediate version
9746 default: llvm_unreachable("Unknown target vector shift node");
9747 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9748 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9749 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9752 // Need to build a vector containing shift amount
9753 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9756 ShOps[1] = DAG.getConstant(0, MVT::i32);
9757 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9758 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9760 // The return type has to be a 128-bit type with the same element
9761 // type as the input type.
9762 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9763 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9765 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9766 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9769 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9770 DebugLoc dl = Op.getDebugLoc();
9771 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9773 default: return SDValue(); // Don't custom lower most intrinsics.
9774 // Comparison intrinsics.
9775 case Intrinsic::x86_sse_comieq_ss:
9776 case Intrinsic::x86_sse_comilt_ss:
9777 case Intrinsic::x86_sse_comile_ss:
9778 case Intrinsic::x86_sse_comigt_ss:
9779 case Intrinsic::x86_sse_comige_ss:
9780 case Intrinsic::x86_sse_comineq_ss:
9781 case Intrinsic::x86_sse_ucomieq_ss:
9782 case Intrinsic::x86_sse_ucomilt_ss:
9783 case Intrinsic::x86_sse_ucomile_ss:
9784 case Intrinsic::x86_sse_ucomigt_ss:
9785 case Intrinsic::x86_sse_ucomige_ss:
9786 case Intrinsic::x86_sse_ucomineq_ss:
9787 case Intrinsic::x86_sse2_comieq_sd:
9788 case Intrinsic::x86_sse2_comilt_sd:
9789 case Intrinsic::x86_sse2_comile_sd:
9790 case Intrinsic::x86_sse2_comigt_sd:
9791 case Intrinsic::x86_sse2_comige_sd:
9792 case Intrinsic::x86_sse2_comineq_sd:
9793 case Intrinsic::x86_sse2_ucomieq_sd:
9794 case Intrinsic::x86_sse2_ucomilt_sd:
9795 case Intrinsic::x86_sse2_ucomile_sd:
9796 case Intrinsic::x86_sse2_ucomigt_sd:
9797 case Intrinsic::x86_sse2_ucomige_sd:
9798 case Intrinsic::x86_sse2_ucomineq_sd: {
9802 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9803 case Intrinsic::x86_sse_comieq_ss:
9804 case Intrinsic::x86_sse2_comieq_sd:
9808 case Intrinsic::x86_sse_comilt_ss:
9809 case Intrinsic::x86_sse2_comilt_sd:
9813 case Intrinsic::x86_sse_comile_ss:
9814 case Intrinsic::x86_sse2_comile_sd:
9818 case Intrinsic::x86_sse_comigt_ss:
9819 case Intrinsic::x86_sse2_comigt_sd:
9823 case Intrinsic::x86_sse_comige_ss:
9824 case Intrinsic::x86_sse2_comige_sd:
9828 case Intrinsic::x86_sse_comineq_ss:
9829 case Intrinsic::x86_sse2_comineq_sd:
9833 case Intrinsic::x86_sse_ucomieq_ss:
9834 case Intrinsic::x86_sse2_ucomieq_sd:
9835 Opc = X86ISD::UCOMI;
9838 case Intrinsic::x86_sse_ucomilt_ss:
9839 case Intrinsic::x86_sse2_ucomilt_sd:
9840 Opc = X86ISD::UCOMI;
9843 case Intrinsic::x86_sse_ucomile_ss:
9844 case Intrinsic::x86_sse2_ucomile_sd:
9845 Opc = X86ISD::UCOMI;
9848 case Intrinsic::x86_sse_ucomigt_ss:
9849 case Intrinsic::x86_sse2_ucomigt_sd:
9850 Opc = X86ISD::UCOMI;
9853 case Intrinsic::x86_sse_ucomige_ss:
9854 case Intrinsic::x86_sse2_ucomige_sd:
9855 Opc = X86ISD::UCOMI;
9858 case Intrinsic::x86_sse_ucomineq_ss:
9859 case Intrinsic::x86_sse2_ucomineq_sd:
9860 Opc = X86ISD::UCOMI;
9865 SDValue LHS = Op.getOperand(1);
9866 SDValue RHS = Op.getOperand(2);
9867 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9868 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9869 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9870 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9871 DAG.getConstant(X86CC, MVT::i8), Cond);
9872 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9875 // Arithmetic intrinsics.
9876 case Intrinsic::x86_sse2_pmulu_dq:
9877 case Intrinsic::x86_avx2_pmulu_dq:
9878 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9879 Op.getOperand(1), Op.getOperand(2));
9881 // SSE3/AVX horizontal add/sub intrinsics
9882 case Intrinsic::x86_sse3_hadd_ps:
9883 case Intrinsic::x86_sse3_hadd_pd:
9884 case Intrinsic::x86_avx_hadd_ps_256:
9885 case Intrinsic::x86_avx_hadd_pd_256:
9886 case Intrinsic::x86_sse3_hsub_ps:
9887 case Intrinsic::x86_sse3_hsub_pd:
9888 case Intrinsic::x86_avx_hsub_ps_256:
9889 case Intrinsic::x86_avx_hsub_pd_256:
9890 case Intrinsic::x86_ssse3_phadd_w_128:
9891 case Intrinsic::x86_ssse3_phadd_d_128:
9892 case Intrinsic::x86_avx2_phadd_w:
9893 case Intrinsic::x86_avx2_phadd_d:
9894 case Intrinsic::x86_ssse3_phsub_w_128:
9895 case Intrinsic::x86_ssse3_phsub_d_128:
9896 case Intrinsic::x86_avx2_phsub_w:
9897 case Intrinsic::x86_avx2_phsub_d: {
9900 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9901 case Intrinsic::x86_sse3_hadd_ps:
9902 case Intrinsic::x86_sse3_hadd_pd:
9903 case Intrinsic::x86_avx_hadd_ps_256:
9904 case Intrinsic::x86_avx_hadd_pd_256:
9905 Opcode = X86ISD::FHADD;
9907 case Intrinsic::x86_sse3_hsub_ps:
9908 case Intrinsic::x86_sse3_hsub_pd:
9909 case Intrinsic::x86_avx_hsub_ps_256:
9910 case Intrinsic::x86_avx_hsub_pd_256:
9911 Opcode = X86ISD::FHSUB;
9913 case Intrinsic::x86_ssse3_phadd_w_128:
9914 case Intrinsic::x86_ssse3_phadd_d_128:
9915 case Intrinsic::x86_avx2_phadd_w:
9916 case Intrinsic::x86_avx2_phadd_d:
9917 Opcode = X86ISD::HADD;
9919 case Intrinsic::x86_ssse3_phsub_w_128:
9920 case Intrinsic::x86_ssse3_phsub_d_128:
9921 case Intrinsic::x86_avx2_phsub_w:
9922 case Intrinsic::x86_avx2_phsub_d:
9923 Opcode = X86ISD::HSUB;
9926 return DAG.getNode(Opcode, dl, Op.getValueType(),
9927 Op.getOperand(1), Op.getOperand(2));
9930 // AVX2 variable shift intrinsics
9931 case Intrinsic::x86_avx2_psllv_d:
9932 case Intrinsic::x86_avx2_psllv_q:
9933 case Intrinsic::x86_avx2_psllv_d_256:
9934 case Intrinsic::x86_avx2_psllv_q_256:
9935 case Intrinsic::x86_avx2_psrlv_d:
9936 case Intrinsic::x86_avx2_psrlv_q:
9937 case Intrinsic::x86_avx2_psrlv_d_256:
9938 case Intrinsic::x86_avx2_psrlv_q_256:
9939 case Intrinsic::x86_avx2_psrav_d:
9940 case Intrinsic::x86_avx2_psrav_d_256: {
9943 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9944 case Intrinsic::x86_avx2_psllv_d:
9945 case Intrinsic::x86_avx2_psllv_q:
9946 case Intrinsic::x86_avx2_psllv_d_256:
9947 case Intrinsic::x86_avx2_psllv_q_256:
9950 case Intrinsic::x86_avx2_psrlv_d:
9951 case Intrinsic::x86_avx2_psrlv_q:
9952 case Intrinsic::x86_avx2_psrlv_d_256:
9953 case Intrinsic::x86_avx2_psrlv_q_256:
9956 case Intrinsic::x86_avx2_psrav_d:
9957 case Intrinsic::x86_avx2_psrav_d_256:
9961 return DAG.getNode(Opcode, dl, Op.getValueType(),
9962 Op.getOperand(1), Op.getOperand(2));
9965 case Intrinsic::x86_ssse3_pshuf_b_128:
9966 case Intrinsic::x86_avx2_pshuf_b:
9967 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9968 Op.getOperand(1), Op.getOperand(2));
9970 case Intrinsic::x86_ssse3_psign_b_128:
9971 case Intrinsic::x86_ssse3_psign_w_128:
9972 case Intrinsic::x86_ssse3_psign_d_128:
9973 case Intrinsic::x86_avx2_psign_b:
9974 case Intrinsic::x86_avx2_psign_w:
9975 case Intrinsic::x86_avx2_psign_d:
9976 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9977 Op.getOperand(1), Op.getOperand(2));
9979 case Intrinsic::x86_sse41_insertps:
9980 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9981 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9983 case Intrinsic::x86_avx_vperm2f128_ps_256:
9984 case Intrinsic::x86_avx_vperm2f128_pd_256:
9985 case Intrinsic::x86_avx_vperm2f128_si_256:
9986 case Intrinsic::x86_avx2_vperm2i128:
9987 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9988 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9990 case Intrinsic::x86_avx2_permd:
9991 case Intrinsic::x86_avx2_permps:
9992 // Operands intentionally swapped. Mask is last operand to intrinsic,
9993 // but second operand for node/intruction.
9994 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9995 Op.getOperand(2), Op.getOperand(1));
9997 // ptest and testp intrinsics. The intrinsic these come from are designed to
9998 // return an integer value, not just an instruction so lower it to the ptest
9999 // or testp pattern and a setcc for the result.
10000 case Intrinsic::x86_sse41_ptestz:
10001 case Intrinsic::x86_sse41_ptestc:
10002 case Intrinsic::x86_sse41_ptestnzc:
10003 case Intrinsic::x86_avx_ptestz_256:
10004 case Intrinsic::x86_avx_ptestc_256:
10005 case Intrinsic::x86_avx_ptestnzc_256:
10006 case Intrinsic::x86_avx_vtestz_ps:
10007 case Intrinsic::x86_avx_vtestc_ps:
10008 case Intrinsic::x86_avx_vtestnzc_ps:
10009 case Intrinsic::x86_avx_vtestz_pd:
10010 case Intrinsic::x86_avx_vtestc_pd:
10011 case Intrinsic::x86_avx_vtestnzc_pd:
10012 case Intrinsic::x86_avx_vtestz_ps_256:
10013 case Intrinsic::x86_avx_vtestc_ps_256:
10014 case Intrinsic::x86_avx_vtestnzc_ps_256:
10015 case Intrinsic::x86_avx_vtestz_pd_256:
10016 case Intrinsic::x86_avx_vtestc_pd_256:
10017 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10018 bool IsTestPacked = false;
10021 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10022 case Intrinsic::x86_avx_vtestz_ps:
10023 case Intrinsic::x86_avx_vtestz_pd:
10024 case Intrinsic::x86_avx_vtestz_ps_256:
10025 case Intrinsic::x86_avx_vtestz_pd_256:
10026 IsTestPacked = true; // Fallthrough
10027 case Intrinsic::x86_sse41_ptestz:
10028 case Intrinsic::x86_avx_ptestz_256:
10030 X86CC = X86::COND_E;
10032 case Intrinsic::x86_avx_vtestc_ps:
10033 case Intrinsic::x86_avx_vtestc_pd:
10034 case Intrinsic::x86_avx_vtestc_ps_256:
10035 case Intrinsic::x86_avx_vtestc_pd_256:
10036 IsTestPacked = true; // Fallthrough
10037 case Intrinsic::x86_sse41_ptestc:
10038 case Intrinsic::x86_avx_ptestc_256:
10040 X86CC = X86::COND_B;
10042 case Intrinsic::x86_avx_vtestnzc_ps:
10043 case Intrinsic::x86_avx_vtestnzc_pd:
10044 case Intrinsic::x86_avx_vtestnzc_ps_256:
10045 case Intrinsic::x86_avx_vtestnzc_pd_256:
10046 IsTestPacked = true; // Fallthrough
10047 case Intrinsic::x86_sse41_ptestnzc:
10048 case Intrinsic::x86_avx_ptestnzc_256:
10050 X86CC = X86::COND_A;
10054 SDValue LHS = Op.getOperand(1);
10055 SDValue RHS = Op.getOperand(2);
10056 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10057 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10058 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10059 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10060 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10063 // SSE/AVX shift intrinsics
10064 case Intrinsic::x86_sse2_psll_w:
10065 case Intrinsic::x86_sse2_psll_d:
10066 case Intrinsic::x86_sse2_psll_q:
10067 case Intrinsic::x86_avx2_psll_w:
10068 case Intrinsic::x86_avx2_psll_d:
10069 case Intrinsic::x86_avx2_psll_q:
10070 case Intrinsic::x86_sse2_psrl_w:
10071 case Intrinsic::x86_sse2_psrl_d:
10072 case Intrinsic::x86_sse2_psrl_q:
10073 case Intrinsic::x86_avx2_psrl_w:
10074 case Intrinsic::x86_avx2_psrl_d:
10075 case Intrinsic::x86_avx2_psrl_q:
10076 case Intrinsic::x86_sse2_psra_w:
10077 case Intrinsic::x86_sse2_psra_d:
10078 case Intrinsic::x86_avx2_psra_w:
10079 case Intrinsic::x86_avx2_psra_d: {
10082 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10083 case Intrinsic::x86_sse2_psll_w:
10084 case Intrinsic::x86_sse2_psll_d:
10085 case Intrinsic::x86_sse2_psll_q:
10086 case Intrinsic::x86_avx2_psll_w:
10087 case Intrinsic::x86_avx2_psll_d:
10088 case Intrinsic::x86_avx2_psll_q:
10089 Opcode = X86ISD::VSHL;
10091 case Intrinsic::x86_sse2_psrl_w:
10092 case Intrinsic::x86_sse2_psrl_d:
10093 case Intrinsic::x86_sse2_psrl_q:
10094 case Intrinsic::x86_avx2_psrl_w:
10095 case Intrinsic::x86_avx2_psrl_d:
10096 case Intrinsic::x86_avx2_psrl_q:
10097 Opcode = X86ISD::VSRL;
10099 case Intrinsic::x86_sse2_psra_w:
10100 case Intrinsic::x86_sse2_psra_d:
10101 case Intrinsic::x86_avx2_psra_w:
10102 case Intrinsic::x86_avx2_psra_d:
10103 Opcode = X86ISD::VSRA;
10106 return DAG.getNode(Opcode, dl, Op.getValueType(),
10107 Op.getOperand(1), Op.getOperand(2));
10110 // SSE/AVX immediate shift intrinsics
10111 case Intrinsic::x86_sse2_pslli_w:
10112 case Intrinsic::x86_sse2_pslli_d:
10113 case Intrinsic::x86_sse2_pslli_q:
10114 case Intrinsic::x86_avx2_pslli_w:
10115 case Intrinsic::x86_avx2_pslli_d:
10116 case Intrinsic::x86_avx2_pslli_q:
10117 case Intrinsic::x86_sse2_psrli_w:
10118 case Intrinsic::x86_sse2_psrli_d:
10119 case Intrinsic::x86_sse2_psrli_q:
10120 case Intrinsic::x86_avx2_psrli_w:
10121 case Intrinsic::x86_avx2_psrli_d:
10122 case Intrinsic::x86_avx2_psrli_q:
10123 case Intrinsic::x86_sse2_psrai_w:
10124 case Intrinsic::x86_sse2_psrai_d:
10125 case Intrinsic::x86_avx2_psrai_w:
10126 case Intrinsic::x86_avx2_psrai_d: {
10129 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10130 case Intrinsic::x86_sse2_pslli_w:
10131 case Intrinsic::x86_sse2_pslli_d:
10132 case Intrinsic::x86_sse2_pslli_q:
10133 case Intrinsic::x86_avx2_pslli_w:
10134 case Intrinsic::x86_avx2_pslli_d:
10135 case Intrinsic::x86_avx2_pslli_q:
10136 Opcode = X86ISD::VSHLI;
10138 case Intrinsic::x86_sse2_psrli_w:
10139 case Intrinsic::x86_sse2_psrli_d:
10140 case Intrinsic::x86_sse2_psrli_q:
10141 case Intrinsic::x86_avx2_psrli_w:
10142 case Intrinsic::x86_avx2_psrli_d:
10143 case Intrinsic::x86_avx2_psrli_q:
10144 Opcode = X86ISD::VSRLI;
10146 case Intrinsic::x86_sse2_psrai_w:
10147 case Intrinsic::x86_sse2_psrai_d:
10148 case Intrinsic::x86_avx2_psrai_w:
10149 case Intrinsic::x86_avx2_psrai_d:
10150 Opcode = X86ISD::VSRAI;
10153 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10154 Op.getOperand(1), Op.getOperand(2), DAG);
10157 case Intrinsic::x86_sse42_pcmpistria128:
10158 case Intrinsic::x86_sse42_pcmpestria128:
10159 case Intrinsic::x86_sse42_pcmpistric128:
10160 case Intrinsic::x86_sse42_pcmpestric128:
10161 case Intrinsic::x86_sse42_pcmpistrio128:
10162 case Intrinsic::x86_sse42_pcmpestrio128:
10163 case Intrinsic::x86_sse42_pcmpistris128:
10164 case Intrinsic::x86_sse42_pcmpestris128:
10165 case Intrinsic::x86_sse42_pcmpistriz128:
10166 case Intrinsic::x86_sse42_pcmpestriz128: {
10170 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10171 case Intrinsic::x86_sse42_pcmpistria128:
10172 Opcode = X86ISD::PCMPISTRI;
10173 X86CC = X86::COND_A;
10175 case Intrinsic::x86_sse42_pcmpestria128:
10176 Opcode = X86ISD::PCMPESTRI;
10177 X86CC = X86::COND_A;
10179 case Intrinsic::x86_sse42_pcmpistric128:
10180 Opcode = X86ISD::PCMPISTRI;
10181 X86CC = X86::COND_B;
10183 case Intrinsic::x86_sse42_pcmpestric128:
10184 Opcode = X86ISD::PCMPESTRI;
10185 X86CC = X86::COND_B;
10187 case Intrinsic::x86_sse42_pcmpistrio128:
10188 Opcode = X86ISD::PCMPISTRI;
10189 X86CC = X86::COND_O;
10191 case Intrinsic::x86_sse42_pcmpestrio128:
10192 Opcode = X86ISD::PCMPESTRI;
10193 X86CC = X86::COND_O;
10195 case Intrinsic::x86_sse42_pcmpistris128:
10196 Opcode = X86ISD::PCMPISTRI;
10197 X86CC = X86::COND_S;
10199 case Intrinsic::x86_sse42_pcmpestris128:
10200 Opcode = X86ISD::PCMPESTRI;
10201 X86CC = X86::COND_S;
10203 case Intrinsic::x86_sse42_pcmpistriz128:
10204 Opcode = X86ISD::PCMPISTRI;
10205 X86CC = X86::COND_E;
10207 case Intrinsic::x86_sse42_pcmpestriz128:
10208 Opcode = X86ISD::PCMPESTRI;
10209 X86CC = X86::COND_E;
10212 SmallVector<SDValue, 5> NewOps;
10213 NewOps.append(Op->op_begin()+1, Op->op_end());
10214 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10215 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10216 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10217 DAG.getConstant(X86CC, MVT::i8),
10218 SDValue(PCMP.getNode(), 1));
10219 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10222 case Intrinsic::x86_sse42_pcmpistri128:
10223 case Intrinsic::x86_sse42_pcmpestri128: {
10225 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10226 Opcode = X86ISD::PCMPISTRI;
10228 Opcode = X86ISD::PCMPESTRI;
10230 SmallVector<SDValue, 5> NewOps;
10231 NewOps.append(Op->op_begin()+1, Op->op_end());
10232 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10233 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10235 case Intrinsic::x86_fma_vfmadd_ps:
10236 case Intrinsic::x86_fma_vfmadd_pd:
10237 case Intrinsic::x86_fma_vfmsub_ps:
10238 case Intrinsic::x86_fma_vfmsub_pd:
10239 case Intrinsic::x86_fma_vfnmadd_ps:
10240 case Intrinsic::x86_fma_vfnmadd_pd:
10241 case Intrinsic::x86_fma_vfnmsub_ps:
10242 case Intrinsic::x86_fma_vfnmsub_pd:
10243 case Intrinsic::x86_fma_vfmaddsub_ps:
10244 case Intrinsic::x86_fma_vfmaddsub_pd:
10245 case Intrinsic::x86_fma_vfmsubadd_ps:
10246 case Intrinsic::x86_fma_vfmsubadd_pd:
10247 case Intrinsic::x86_fma_vfmadd_ps_256:
10248 case Intrinsic::x86_fma_vfmadd_pd_256:
10249 case Intrinsic::x86_fma_vfmsub_ps_256:
10250 case Intrinsic::x86_fma_vfmsub_pd_256:
10251 case Intrinsic::x86_fma_vfnmadd_ps_256:
10252 case Intrinsic::x86_fma_vfnmadd_pd_256:
10253 case Intrinsic::x86_fma_vfnmsub_ps_256:
10254 case Intrinsic::x86_fma_vfnmsub_pd_256:
10255 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10256 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10257 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10258 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10261 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10262 case Intrinsic::x86_fma_vfmadd_ps:
10263 case Intrinsic::x86_fma_vfmadd_pd:
10264 case Intrinsic::x86_fma_vfmadd_ps_256:
10265 case Intrinsic::x86_fma_vfmadd_pd_256:
10266 Opc = X86ISD::FMADD;
10268 case Intrinsic::x86_fma_vfmsub_ps:
10269 case Intrinsic::x86_fma_vfmsub_pd:
10270 case Intrinsic::x86_fma_vfmsub_ps_256:
10271 case Intrinsic::x86_fma_vfmsub_pd_256:
10272 Opc = X86ISD::FMSUB;
10274 case Intrinsic::x86_fma_vfnmadd_ps:
10275 case Intrinsic::x86_fma_vfnmadd_pd:
10276 case Intrinsic::x86_fma_vfnmadd_ps_256:
10277 case Intrinsic::x86_fma_vfnmadd_pd_256:
10278 Opc = X86ISD::FNMADD;
10280 case Intrinsic::x86_fma_vfnmsub_ps:
10281 case Intrinsic::x86_fma_vfnmsub_pd:
10282 case Intrinsic::x86_fma_vfnmsub_ps_256:
10283 case Intrinsic::x86_fma_vfnmsub_pd_256:
10284 Opc = X86ISD::FNMSUB;
10286 case Intrinsic::x86_fma_vfmaddsub_ps:
10287 case Intrinsic::x86_fma_vfmaddsub_pd:
10288 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10289 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10290 Opc = X86ISD::FMADDSUB;
10292 case Intrinsic::x86_fma_vfmsubadd_ps:
10293 case Intrinsic::x86_fma_vfmsubadd_pd:
10294 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10295 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10296 Opc = X86ISD::FMSUBADD;
10300 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10301 Op.getOperand(2), Op.getOperand(3));
10306 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10307 DebugLoc dl = Op.getDebugLoc();
10308 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10310 default: return SDValue(); // Don't custom lower most intrinsics.
10312 // RDRAND intrinsics.
10313 case Intrinsic::x86_rdrand_16:
10314 case Intrinsic::x86_rdrand_32:
10315 case Intrinsic::x86_rdrand_64: {
10316 // Emit the node with the right value type.
10317 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10318 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10320 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10321 // return the value from Rand, which is always 0, casted to i32.
10322 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10323 DAG.getConstant(1, Op->getValueType(1)),
10324 DAG.getConstant(X86::COND_B, MVT::i32),
10325 SDValue(Result.getNode(), 1) };
10326 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10327 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10330 // Return { result, isValid, chain }.
10331 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10332 SDValue(Result.getNode(), 2));
10337 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10338 SelectionDAG &DAG) const {
10339 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10340 MFI->setReturnAddressIsTaken(true);
10342 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10343 DebugLoc dl = Op.getDebugLoc();
10346 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10348 DAG.getConstant(TD->getPointerSize(),
10349 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10350 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10351 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10352 FrameAddr, Offset),
10353 MachinePointerInfo(), false, false, false, 0);
10356 // Just load the return address.
10357 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10358 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10359 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10362 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10363 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10364 MFI->setFrameAddressIsTaken(true);
10366 EVT VT = Op.getValueType();
10367 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10368 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10369 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10370 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10372 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10373 MachinePointerInfo(),
10374 false, false, false, 0);
10378 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10379 SelectionDAG &DAG) const {
10380 return DAG.getIntPtrConstant(2*TD->getPointerSize());
10383 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10384 SDValue Chain = Op.getOperand(0);
10385 SDValue Offset = Op.getOperand(1);
10386 SDValue Handler = Op.getOperand(2);
10387 DebugLoc dl = Op.getDebugLoc();
10389 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10390 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10392 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10394 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10395 DAG.getIntPtrConstant(TD->getPointerSize()));
10396 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10397 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10399 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10401 return DAG.getNode(X86ISD::EH_RETURN, dl,
10403 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10406 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10407 return Op.getOperand(0);
10410 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10411 SelectionDAG &DAG) const {
10412 SDValue Root = Op.getOperand(0);
10413 SDValue Trmp = Op.getOperand(1); // trampoline
10414 SDValue FPtr = Op.getOperand(2); // nested function
10415 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10416 DebugLoc dl = Op.getDebugLoc();
10418 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10419 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10421 if (Subtarget->is64Bit()) {
10422 SDValue OutChains[6];
10424 // Large code-model.
10425 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10426 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10428 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10429 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10431 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10433 // Load the pointer to the nested function into R11.
10434 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10435 SDValue Addr = Trmp;
10436 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10437 Addr, MachinePointerInfo(TrmpAddr),
10440 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10441 DAG.getConstant(2, MVT::i64));
10442 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10443 MachinePointerInfo(TrmpAddr, 2),
10446 // Load the 'nest' parameter value into R10.
10447 // R10 is specified in X86CallingConv.td
10448 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10449 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10450 DAG.getConstant(10, MVT::i64));
10451 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10452 Addr, MachinePointerInfo(TrmpAddr, 10),
10455 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10456 DAG.getConstant(12, MVT::i64));
10457 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10458 MachinePointerInfo(TrmpAddr, 12),
10461 // Jump to the nested function.
10462 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10463 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10464 DAG.getConstant(20, MVT::i64));
10465 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10466 Addr, MachinePointerInfo(TrmpAddr, 20),
10469 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10470 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10471 DAG.getConstant(22, MVT::i64));
10472 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10473 MachinePointerInfo(TrmpAddr, 22),
10476 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10478 const Function *Func =
10479 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10480 CallingConv::ID CC = Func->getCallingConv();
10485 llvm_unreachable("Unsupported calling convention");
10486 case CallingConv::C:
10487 case CallingConv::X86_StdCall: {
10488 // Pass 'nest' parameter in ECX.
10489 // Must be kept in sync with X86CallingConv.td
10490 NestReg = X86::ECX;
10492 // Check that ECX wasn't needed by an 'inreg' parameter.
10493 FunctionType *FTy = Func->getFunctionType();
10494 const AttrListPtr &Attrs = Func->getAttributes();
10496 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10497 unsigned InRegCount = 0;
10500 for (FunctionType::param_iterator I = FTy->param_begin(),
10501 E = FTy->param_end(); I != E; ++I, ++Idx)
10502 if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10503 // FIXME: should only count parameters that are lowered to integers.
10504 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10506 if (InRegCount > 2) {
10507 report_fatal_error("Nest register in use - reduce number of inreg"
10513 case CallingConv::X86_FastCall:
10514 case CallingConv::X86_ThisCall:
10515 case CallingConv::Fast:
10516 // Pass 'nest' parameter in EAX.
10517 // Must be kept in sync with X86CallingConv.td
10518 NestReg = X86::EAX;
10522 SDValue OutChains[4];
10523 SDValue Addr, Disp;
10525 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10526 DAG.getConstant(10, MVT::i32));
10527 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10529 // This is storing the opcode for MOV32ri.
10530 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10531 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10532 OutChains[0] = DAG.getStore(Root, dl,
10533 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10534 Trmp, MachinePointerInfo(TrmpAddr),
10537 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10538 DAG.getConstant(1, MVT::i32));
10539 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10540 MachinePointerInfo(TrmpAddr, 1),
10543 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10544 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10545 DAG.getConstant(5, MVT::i32));
10546 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10547 MachinePointerInfo(TrmpAddr, 5),
10550 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10551 DAG.getConstant(6, MVT::i32));
10552 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10553 MachinePointerInfo(TrmpAddr, 6),
10556 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10560 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10561 SelectionDAG &DAG) const {
10563 The rounding mode is in bits 11:10 of FPSR, and has the following
10565 00 Round to nearest
10570 FLT_ROUNDS, on the other hand, expects the following:
10577 To perform the conversion, we do:
10578 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10581 MachineFunction &MF = DAG.getMachineFunction();
10582 const TargetMachine &TM = MF.getTarget();
10583 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10584 unsigned StackAlignment = TFI.getStackAlignment();
10585 EVT VT = Op.getValueType();
10586 DebugLoc DL = Op.getDebugLoc();
10588 // Save FP Control Word to stack slot
10589 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10590 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10593 MachineMemOperand *MMO =
10594 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10595 MachineMemOperand::MOStore, 2, 2);
10597 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10598 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10599 DAG.getVTList(MVT::Other),
10600 Ops, 2, MVT::i16, MMO);
10602 // Load FP Control Word from stack slot
10603 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10604 MachinePointerInfo(), false, false, false, 0);
10606 // Transform as necessary
10608 DAG.getNode(ISD::SRL, DL, MVT::i16,
10609 DAG.getNode(ISD::AND, DL, MVT::i16,
10610 CWD, DAG.getConstant(0x800, MVT::i16)),
10611 DAG.getConstant(11, MVT::i8));
10613 DAG.getNode(ISD::SRL, DL, MVT::i16,
10614 DAG.getNode(ISD::AND, DL, MVT::i16,
10615 CWD, DAG.getConstant(0x400, MVT::i16)),
10616 DAG.getConstant(9, MVT::i8));
10619 DAG.getNode(ISD::AND, DL, MVT::i16,
10620 DAG.getNode(ISD::ADD, DL, MVT::i16,
10621 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10622 DAG.getConstant(1, MVT::i16)),
10623 DAG.getConstant(3, MVT::i16));
10626 return DAG.getNode((VT.getSizeInBits() < 16 ?
10627 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10630 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10631 EVT VT = Op.getValueType();
10633 unsigned NumBits = VT.getSizeInBits();
10634 DebugLoc dl = Op.getDebugLoc();
10636 Op = Op.getOperand(0);
10637 if (VT == MVT::i8) {
10638 // Zero extend to i32 since there is not an i8 bsr.
10640 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10643 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10644 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10645 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10647 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10650 DAG.getConstant(NumBits+NumBits-1, OpVT),
10651 DAG.getConstant(X86::COND_E, MVT::i8),
10654 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10656 // Finally xor with NumBits-1.
10657 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10660 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10664 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10665 EVT VT = Op.getValueType();
10667 unsigned NumBits = VT.getSizeInBits();
10668 DebugLoc dl = Op.getDebugLoc();
10670 Op = Op.getOperand(0);
10671 if (VT == MVT::i8) {
10672 // Zero extend to i32 since there is not an i8 bsr.
10674 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10677 // Issue a bsr (scan bits in reverse).
10678 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10679 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10681 // And xor with NumBits-1.
10682 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10685 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10689 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10690 EVT VT = Op.getValueType();
10691 unsigned NumBits = VT.getSizeInBits();
10692 DebugLoc dl = Op.getDebugLoc();
10693 Op = Op.getOperand(0);
10695 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10696 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10697 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10699 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10702 DAG.getConstant(NumBits, VT),
10703 DAG.getConstant(X86::COND_E, MVT::i8),
10706 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10709 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10710 // ones, and then concatenate the result back.
10711 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10712 EVT VT = Op.getValueType();
10714 assert(VT.is256BitVector() && VT.isInteger() &&
10715 "Unsupported value type for operation");
10717 unsigned NumElems = VT.getVectorNumElements();
10718 DebugLoc dl = Op.getDebugLoc();
10720 // Extract the LHS vectors
10721 SDValue LHS = Op.getOperand(0);
10722 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10723 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10725 // Extract the RHS vectors
10726 SDValue RHS = Op.getOperand(1);
10727 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10728 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10730 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10731 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10733 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10734 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10735 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10738 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10739 assert(Op.getValueType().is256BitVector() &&
10740 Op.getValueType().isInteger() &&
10741 "Only handle AVX 256-bit vector integer operation");
10742 return Lower256IntArith(Op, DAG);
10745 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10746 assert(Op.getValueType().is256BitVector() &&
10747 Op.getValueType().isInteger() &&
10748 "Only handle AVX 256-bit vector integer operation");
10749 return Lower256IntArith(Op, DAG);
10752 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10753 SelectionDAG &DAG) {
10754 EVT VT = Op.getValueType();
10756 // Decompose 256-bit ops into smaller 128-bit ops.
10757 if (VT.is256BitVector() && !Subtarget->hasAVX2())
10758 return Lower256IntArith(Op, DAG);
10760 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10761 "Only know how to lower V2I64/V4I64 multiply");
10763 DebugLoc dl = Op.getDebugLoc();
10765 // Ahi = psrlqi(a, 32);
10766 // Bhi = psrlqi(b, 32);
10768 // AloBlo = pmuludq(a, b);
10769 // AloBhi = pmuludq(a, Bhi);
10770 // AhiBlo = pmuludq(Ahi, b);
10772 // AloBhi = psllqi(AloBhi, 32);
10773 // AhiBlo = psllqi(AhiBlo, 32);
10774 // return AloBlo + AloBhi + AhiBlo;
10776 SDValue A = Op.getOperand(0);
10777 SDValue B = Op.getOperand(1);
10779 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10781 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10782 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10784 // Bit cast to 32-bit vectors for MULUDQ
10785 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10786 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10787 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10788 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10789 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10791 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10792 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10793 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10795 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10796 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10798 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10799 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10802 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10804 EVT VT = Op.getValueType();
10805 DebugLoc dl = Op.getDebugLoc();
10806 SDValue R = Op.getOperand(0);
10807 SDValue Amt = Op.getOperand(1);
10808 LLVMContext *Context = DAG.getContext();
10810 if (!Subtarget->hasSSE2())
10813 // Optimize shl/srl/sra with constant shift amount.
10814 if (isSplatVector(Amt.getNode())) {
10815 SDValue SclrAmt = Amt->getOperand(0);
10816 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10817 uint64_t ShiftAmt = C->getZExtValue();
10819 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10820 (Subtarget->hasAVX2() &&
10821 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10822 if (Op.getOpcode() == ISD::SHL)
10823 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10824 DAG.getConstant(ShiftAmt, MVT::i32));
10825 if (Op.getOpcode() == ISD::SRL)
10826 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10827 DAG.getConstant(ShiftAmt, MVT::i32));
10828 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10829 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10830 DAG.getConstant(ShiftAmt, MVT::i32));
10833 if (VT == MVT::v16i8) {
10834 if (Op.getOpcode() == ISD::SHL) {
10835 // Make a large shift.
10836 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10837 DAG.getConstant(ShiftAmt, MVT::i32));
10838 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10839 // Zero out the rightmost bits.
10840 SmallVector<SDValue, 16> V(16,
10841 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10843 return DAG.getNode(ISD::AND, dl, VT, SHL,
10844 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10846 if (Op.getOpcode() == ISD::SRL) {
10847 // Make a large shift.
10848 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10849 DAG.getConstant(ShiftAmt, MVT::i32));
10850 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10851 // Zero out the leftmost bits.
10852 SmallVector<SDValue, 16> V(16,
10853 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10855 return DAG.getNode(ISD::AND, dl, VT, SRL,
10856 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10858 if (Op.getOpcode() == ISD::SRA) {
10859 if (ShiftAmt == 7) {
10860 // R s>> 7 === R s< 0
10861 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10862 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10865 // R s>> a === ((R u>> a) ^ m) - m
10866 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10867 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10869 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10870 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10871 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10874 llvm_unreachable("Unknown shift opcode.");
10877 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10878 if (Op.getOpcode() == ISD::SHL) {
10879 // Make a large shift.
10880 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10881 DAG.getConstant(ShiftAmt, MVT::i32));
10882 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10883 // Zero out the rightmost bits.
10884 SmallVector<SDValue, 32> V(32,
10885 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10887 return DAG.getNode(ISD::AND, dl, VT, SHL,
10888 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10890 if (Op.getOpcode() == ISD::SRL) {
10891 // Make a large shift.
10892 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10893 DAG.getConstant(ShiftAmt, MVT::i32));
10894 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10895 // Zero out the leftmost bits.
10896 SmallVector<SDValue, 32> V(32,
10897 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10899 return DAG.getNode(ISD::AND, dl, VT, SRL,
10900 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10902 if (Op.getOpcode() == ISD::SRA) {
10903 if (ShiftAmt == 7) {
10904 // R s>> 7 === R s< 0
10905 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10906 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10909 // R s>> a === ((R u>> a) ^ m) - m
10910 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10911 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10913 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10914 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10915 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10918 llvm_unreachable("Unknown shift opcode.");
10923 // Lower SHL with variable shift amount.
10924 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10925 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10926 DAG.getConstant(23, MVT::i32));
10928 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10929 Constant *C = ConstantDataVector::get(*Context, CV);
10930 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10931 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10932 MachinePointerInfo::getConstantPool(),
10933 false, false, false, 16);
10935 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10936 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10937 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10938 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10940 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10941 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10944 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10945 DAG.getConstant(5, MVT::i32));
10946 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10948 // Turn 'a' into a mask suitable for VSELECT
10949 SDValue VSelM = DAG.getConstant(0x80, VT);
10950 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10951 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10953 SDValue CM1 = DAG.getConstant(0x0f, VT);
10954 SDValue CM2 = DAG.getConstant(0x3f, VT);
10956 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10957 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10958 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10959 DAG.getConstant(4, MVT::i32), DAG);
10960 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10961 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10964 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10965 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10966 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10968 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10969 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10970 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10971 DAG.getConstant(2, MVT::i32), DAG);
10972 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10973 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10976 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10977 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10978 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10980 // return VSELECT(r, r+r, a);
10981 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10982 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10986 // Decompose 256-bit shifts into smaller 128-bit shifts.
10987 if (VT.is256BitVector()) {
10988 unsigned NumElems = VT.getVectorNumElements();
10989 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10990 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10992 // Extract the two vectors
10993 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10994 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10996 // Recreate the shift amount vectors
10997 SDValue Amt1, Amt2;
10998 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10999 // Constant shift amount
11000 SmallVector<SDValue, 4> Amt1Csts;
11001 SmallVector<SDValue, 4> Amt2Csts;
11002 for (unsigned i = 0; i != NumElems/2; ++i)
11003 Amt1Csts.push_back(Amt->getOperand(i));
11004 for (unsigned i = NumElems/2; i != NumElems; ++i)
11005 Amt2Csts.push_back(Amt->getOperand(i));
11007 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11008 &Amt1Csts[0], NumElems/2);
11009 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11010 &Amt2Csts[0], NumElems/2);
11012 // Variable shift amount
11013 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11014 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11017 // Issue new vector shifts for the smaller types
11018 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11019 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11021 // Concatenate the result back
11022 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11028 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11029 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11030 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11031 // looks for this combo and may remove the "setcc" instruction if the "setcc"
11032 // has only one use.
11033 SDNode *N = Op.getNode();
11034 SDValue LHS = N->getOperand(0);
11035 SDValue RHS = N->getOperand(1);
11036 unsigned BaseOp = 0;
11038 DebugLoc DL = Op.getDebugLoc();
11039 switch (Op.getOpcode()) {
11040 default: llvm_unreachable("Unknown ovf instruction!");
11042 // A subtract of one will be selected as a INC. Note that INC doesn't
11043 // set CF, so we can't do this for UADDO.
11044 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11046 BaseOp = X86ISD::INC;
11047 Cond = X86::COND_O;
11050 BaseOp = X86ISD::ADD;
11051 Cond = X86::COND_O;
11054 BaseOp = X86ISD::ADD;
11055 Cond = X86::COND_B;
11058 // A subtract of one will be selected as a DEC. Note that DEC doesn't
11059 // set CF, so we can't do this for USUBO.
11060 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11062 BaseOp = X86ISD::DEC;
11063 Cond = X86::COND_O;
11066 BaseOp = X86ISD::SUB;
11067 Cond = X86::COND_O;
11070 BaseOp = X86ISD::SUB;
11071 Cond = X86::COND_B;
11074 BaseOp = X86ISD::SMUL;
11075 Cond = X86::COND_O;
11077 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11078 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11080 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11083 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11084 DAG.getConstant(X86::COND_O, MVT::i32),
11085 SDValue(Sum.getNode(), 2));
11087 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11091 // Also sets EFLAGS.
11092 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11093 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11096 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11097 DAG.getConstant(Cond, MVT::i32),
11098 SDValue(Sum.getNode(), 1));
11100 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11103 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11104 SelectionDAG &DAG) const {
11105 DebugLoc dl = Op.getDebugLoc();
11106 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11107 EVT VT = Op.getValueType();
11109 if (!Subtarget->hasSSE2() || !VT.isVector())
11112 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11113 ExtraVT.getScalarType().getSizeInBits();
11114 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11116 switch (VT.getSimpleVT().SimpleTy) {
11117 default: return SDValue();
11120 if (!Subtarget->hasAVX())
11122 if (!Subtarget->hasAVX2()) {
11123 // needs to be split
11124 unsigned NumElems = VT.getVectorNumElements();
11126 // Extract the LHS vectors
11127 SDValue LHS = Op.getOperand(0);
11128 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11129 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11131 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11132 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11134 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11135 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11136 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11138 SDValue Extra = DAG.getValueType(ExtraVT);
11140 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11141 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11143 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11148 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11149 Op.getOperand(0), ShAmt, DAG);
11150 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11156 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11157 SelectionDAG &DAG) {
11158 DebugLoc dl = Op.getDebugLoc();
11160 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11161 // There isn't any reason to disable it if the target processor supports it.
11162 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11163 SDValue Chain = Op.getOperand(0);
11164 SDValue Zero = DAG.getConstant(0, MVT::i32);
11166 DAG.getRegister(X86::ESP, MVT::i32), // Base
11167 DAG.getTargetConstant(1, MVT::i8), // Scale
11168 DAG.getRegister(0, MVT::i32), // Index
11169 DAG.getTargetConstant(0, MVT::i32), // Disp
11170 DAG.getRegister(0, MVT::i32), // Segment.
11175 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11176 array_lengthof(Ops));
11177 return SDValue(Res, 0);
11180 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11182 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11184 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11185 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11186 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11187 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11189 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11190 if (!Op1 && !Op2 && !Op3 && Op4)
11191 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11193 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11194 if (Op1 && !Op2 && !Op3 && !Op4)
11195 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11197 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11199 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11202 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11203 SelectionDAG &DAG) {
11204 DebugLoc dl = Op.getDebugLoc();
11205 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11206 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11207 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11208 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11210 // The only fence that needs an instruction is a sequentially-consistent
11211 // cross-thread fence.
11212 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11213 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11214 // no-sse2). There isn't any reason to disable it if the target processor
11216 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11217 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11219 SDValue Chain = Op.getOperand(0);
11220 SDValue Zero = DAG.getConstant(0, MVT::i32);
11222 DAG.getRegister(X86::ESP, MVT::i32), // Base
11223 DAG.getTargetConstant(1, MVT::i8), // Scale
11224 DAG.getRegister(0, MVT::i32), // Index
11225 DAG.getTargetConstant(0, MVT::i32), // Disp
11226 DAG.getRegister(0, MVT::i32), // Segment.
11231 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11232 array_lengthof(Ops));
11233 return SDValue(Res, 0);
11236 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11237 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11241 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11242 SelectionDAG &DAG) {
11243 EVT T = Op.getValueType();
11244 DebugLoc DL = Op.getDebugLoc();
11247 switch(T.getSimpleVT().SimpleTy) {
11248 default: llvm_unreachable("Invalid value type!");
11249 case MVT::i8: Reg = X86::AL; size = 1; break;
11250 case MVT::i16: Reg = X86::AX; size = 2; break;
11251 case MVT::i32: Reg = X86::EAX; size = 4; break;
11253 assert(Subtarget->is64Bit() && "Node not type legal!");
11254 Reg = X86::RAX; size = 8;
11257 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11258 Op.getOperand(2), SDValue());
11259 SDValue Ops[] = { cpIn.getValue(0),
11262 DAG.getTargetConstant(size, MVT::i8),
11263 cpIn.getValue(1) };
11264 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11265 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11266 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11269 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11273 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11274 SelectionDAG &DAG) {
11275 assert(Subtarget->is64Bit() && "Result not type legalized?");
11276 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11277 SDValue TheChain = Op.getOperand(0);
11278 DebugLoc dl = Op.getDebugLoc();
11279 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11280 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11281 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11283 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11284 DAG.getConstant(32, MVT::i8));
11286 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11289 return DAG.getMergeValues(Ops, 2, dl);
11292 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11293 EVT SrcVT = Op.getOperand(0).getValueType();
11294 EVT DstVT = Op.getValueType();
11295 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11296 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11297 assert((DstVT == MVT::i64 ||
11298 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11299 "Unexpected custom BITCAST");
11300 // i64 <=> MMX conversions are Legal.
11301 if (SrcVT==MVT::i64 && DstVT.isVector())
11303 if (DstVT==MVT::i64 && SrcVT.isVector())
11305 // MMX <=> MMX conversions are Legal.
11306 if (SrcVT.isVector() && DstVT.isVector())
11308 // All other conversions need to be expanded.
11312 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11313 SDNode *Node = Op.getNode();
11314 DebugLoc dl = Node->getDebugLoc();
11315 EVT T = Node->getValueType(0);
11316 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11317 DAG.getConstant(0, T), Node->getOperand(2));
11318 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11319 cast<AtomicSDNode>(Node)->getMemoryVT(),
11320 Node->getOperand(0),
11321 Node->getOperand(1), negOp,
11322 cast<AtomicSDNode>(Node)->getSrcValue(),
11323 cast<AtomicSDNode>(Node)->getAlignment(),
11324 cast<AtomicSDNode>(Node)->getOrdering(),
11325 cast<AtomicSDNode>(Node)->getSynchScope());
11328 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11329 SDNode *Node = Op.getNode();
11330 DebugLoc dl = Node->getDebugLoc();
11331 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11333 // Convert seq_cst store -> xchg
11334 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11335 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11336 // (The only way to get a 16-byte store is cmpxchg16b)
11337 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11338 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11339 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11340 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11341 cast<AtomicSDNode>(Node)->getMemoryVT(),
11342 Node->getOperand(0),
11343 Node->getOperand(1), Node->getOperand(2),
11344 cast<AtomicSDNode>(Node)->getMemOperand(),
11345 cast<AtomicSDNode>(Node)->getOrdering(),
11346 cast<AtomicSDNode>(Node)->getSynchScope());
11347 return Swap.getValue(1);
11349 // Other atomic stores have a simple pattern.
11353 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11354 EVT VT = Op.getNode()->getValueType(0);
11356 // Let legalize expand this if it isn't a legal type yet.
11357 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11360 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11363 bool ExtraOp = false;
11364 switch (Op.getOpcode()) {
11365 default: llvm_unreachable("Invalid code");
11366 case ISD::ADDC: Opc = X86ISD::ADD; break;
11367 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11368 case ISD::SUBC: Opc = X86ISD::SUB; break;
11369 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11373 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11375 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11376 Op.getOperand(1), Op.getOperand(2));
11379 /// LowerOperation - Provide custom lowering hooks for some operations.
11381 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11382 switch (Op.getOpcode()) {
11383 default: llvm_unreachable("Should not custom lower this!");
11384 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
11385 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
11386 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11387 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
11388 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
11389 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
11390 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11391 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
11392 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11393 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11394 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11395 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11396 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11397 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11398 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11399 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11400 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11401 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
11402 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11403 case ISD::SHL_PARTS:
11404 case ISD::SRA_PARTS:
11405 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11406 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11407 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11408 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11409 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11410 case ISD::FABS: return LowerFABS(Op, DAG);
11411 case ISD::FNEG: return LowerFNEG(Op, DAG);
11412 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11413 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11414 case ISD::SETCC: return LowerSETCC(Op, DAG);
11415 case ISD::SELECT: return LowerSELECT(Op, DAG);
11416 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11417 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11418 case ISD::VASTART: return LowerVASTART(Op, DAG);
11419 case ISD::VAARG: return LowerVAARG(Op, DAG);
11420 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
11421 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11422 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11423 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11424 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11425 case ISD::FRAME_TO_ARGS_OFFSET:
11426 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11427 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11428 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11429 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11430 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11431 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11432 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11433 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11434 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11435 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
11438 case ISD::SHL: return LowerShift(Op, DAG);
11444 case ISD::UMULO: return LowerXALUO(Op, DAG);
11445 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11446 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11450 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11451 case ISD::ADD: return LowerADD(Op, DAG);
11452 case ISD::SUB: return LowerSUB(Op, DAG);
11456 static void ReplaceATOMIC_LOAD(SDNode *Node,
11457 SmallVectorImpl<SDValue> &Results,
11458 SelectionDAG &DAG) {
11459 DebugLoc dl = Node->getDebugLoc();
11460 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11462 // Convert wide load -> cmpxchg8b/cmpxchg16b
11463 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11464 // (The only way to get a 16-byte load is cmpxchg16b)
11465 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11466 SDValue Zero = DAG.getConstant(0, VT);
11467 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11468 Node->getOperand(0),
11469 Node->getOperand(1), Zero, Zero,
11470 cast<AtomicSDNode>(Node)->getMemOperand(),
11471 cast<AtomicSDNode>(Node)->getOrdering(),
11472 cast<AtomicSDNode>(Node)->getSynchScope());
11473 Results.push_back(Swap.getValue(0));
11474 Results.push_back(Swap.getValue(1));
11478 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11479 SelectionDAG &DAG, unsigned NewOp) {
11480 DebugLoc dl = Node->getDebugLoc();
11481 assert (Node->getValueType(0) == MVT::i64 &&
11482 "Only know how to expand i64 atomics");
11484 SDValue Chain = Node->getOperand(0);
11485 SDValue In1 = Node->getOperand(1);
11486 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11487 Node->getOperand(2), DAG.getIntPtrConstant(0));
11488 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11489 Node->getOperand(2), DAG.getIntPtrConstant(1));
11490 SDValue Ops[] = { Chain, In1, In2L, In2H };
11491 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11493 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11494 cast<MemSDNode>(Node)->getMemOperand());
11495 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11496 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11497 Results.push_back(Result.getValue(2));
11500 /// ReplaceNodeResults - Replace a node with an illegal result type
11501 /// with a new node built out of custom code.
11502 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11503 SmallVectorImpl<SDValue>&Results,
11504 SelectionDAG &DAG) const {
11505 DebugLoc dl = N->getDebugLoc();
11506 switch (N->getOpcode()) {
11508 llvm_unreachable("Do not know how to custom type legalize this operation!");
11509 case ISD::SIGN_EXTEND_INREG:
11514 // We don't want to expand or promote these.
11516 case ISD::FP_TO_SINT:
11517 case ISD::FP_TO_UINT: {
11518 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11520 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11523 std::pair<SDValue,SDValue> Vals =
11524 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11525 SDValue FIST = Vals.first, StackSlot = Vals.second;
11526 if (FIST.getNode() != 0) {
11527 EVT VT = N->getValueType(0);
11528 // Return a load from the stack slot.
11529 if (StackSlot.getNode() != 0)
11530 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11531 MachinePointerInfo(),
11532 false, false, false, 0));
11534 Results.push_back(FIST);
11538 case ISD::READCYCLECOUNTER: {
11539 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11540 SDValue TheChain = N->getOperand(0);
11541 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11542 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11544 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11546 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11547 SDValue Ops[] = { eax, edx };
11548 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11549 Results.push_back(edx.getValue(1));
11552 case ISD::ATOMIC_CMP_SWAP: {
11553 EVT T = N->getValueType(0);
11554 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11555 bool Regs64bit = T == MVT::i128;
11556 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11557 SDValue cpInL, cpInH;
11558 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11559 DAG.getConstant(0, HalfT));
11560 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11561 DAG.getConstant(1, HalfT));
11562 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11563 Regs64bit ? X86::RAX : X86::EAX,
11565 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11566 Regs64bit ? X86::RDX : X86::EDX,
11567 cpInH, cpInL.getValue(1));
11568 SDValue swapInL, swapInH;
11569 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11570 DAG.getConstant(0, HalfT));
11571 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11572 DAG.getConstant(1, HalfT));
11573 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11574 Regs64bit ? X86::RBX : X86::EBX,
11575 swapInL, cpInH.getValue(1));
11576 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11577 Regs64bit ? X86::RCX : X86::ECX,
11578 swapInH, swapInL.getValue(1));
11579 SDValue Ops[] = { swapInH.getValue(0),
11581 swapInH.getValue(1) };
11582 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11583 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11584 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11585 X86ISD::LCMPXCHG8_DAG;
11586 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11588 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11589 Regs64bit ? X86::RAX : X86::EAX,
11590 HalfT, Result.getValue(1));
11591 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11592 Regs64bit ? X86::RDX : X86::EDX,
11593 HalfT, cpOutL.getValue(2));
11594 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11595 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11596 Results.push_back(cpOutH.getValue(1));
11599 case ISD::ATOMIC_LOAD_ADD:
11600 case ISD::ATOMIC_LOAD_AND:
11601 case ISD::ATOMIC_LOAD_NAND:
11602 case ISD::ATOMIC_LOAD_OR:
11603 case ISD::ATOMIC_LOAD_SUB:
11604 case ISD::ATOMIC_LOAD_XOR:
11605 case ISD::ATOMIC_LOAD_MAX:
11606 case ISD::ATOMIC_LOAD_MIN:
11607 case ISD::ATOMIC_LOAD_UMAX:
11608 case ISD::ATOMIC_LOAD_UMIN:
11609 case ISD::ATOMIC_SWAP: {
11611 switch (N->getOpcode()) {
11612 default: llvm_unreachable("Unexpected opcode");
11613 case ISD::ATOMIC_LOAD_ADD:
11614 Opc = X86ISD::ATOMADD64_DAG;
11616 case ISD::ATOMIC_LOAD_AND:
11617 Opc = X86ISD::ATOMAND64_DAG;
11619 case ISD::ATOMIC_LOAD_NAND:
11620 Opc = X86ISD::ATOMNAND64_DAG;
11622 case ISD::ATOMIC_LOAD_OR:
11623 Opc = X86ISD::ATOMOR64_DAG;
11625 case ISD::ATOMIC_LOAD_SUB:
11626 Opc = X86ISD::ATOMSUB64_DAG;
11628 case ISD::ATOMIC_LOAD_XOR:
11629 Opc = X86ISD::ATOMXOR64_DAG;
11631 case ISD::ATOMIC_LOAD_MAX:
11632 Opc = X86ISD::ATOMMAX64_DAG;
11634 case ISD::ATOMIC_LOAD_MIN:
11635 Opc = X86ISD::ATOMMIN64_DAG;
11637 case ISD::ATOMIC_LOAD_UMAX:
11638 Opc = X86ISD::ATOMUMAX64_DAG;
11640 case ISD::ATOMIC_LOAD_UMIN:
11641 Opc = X86ISD::ATOMUMIN64_DAG;
11643 case ISD::ATOMIC_SWAP:
11644 Opc = X86ISD::ATOMSWAP64_DAG;
11647 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11650 case ISD::ATOMIC_LOAD:
11651 ReplaceATOMIC_LOAD(N, Results, DAG);
11655 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11657 default: return NULL;
11658 case X86ISD::BSF: return "X86ISD::BSF";
11659 case X86ISD::BSR: return "X86ISD::BSR";
11660 case X86ISD::SHLD: return "X86ISD::SHLD";
11661 case X86ISD::SHRD: return "X86ISD::SHRD";
11662 case X86ISD::FAND: return "X86ISD::FAND";
11663 case X86ISD::FOR: return "X86ISD::FOR";
11664 case X86ISD::FXOR: return "X86ISD::FXOR";
11665 case X86ISD::FSRL: return "X86ISD::FSRL";
11666 case X86ISD::FILD: return "X86ISD::FILD";
11667 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11668 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11669 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11670 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11671 case X86ISD::FLD: return "X86ISD::FLD";
11672 case X86ISD::FST: return "X86ISD::FST";
11673 case X86ISD::CALL: return "X86ISD::CALL";
11674 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11675 case X86ISD::BT: return "X86ISD::BT";
11676 case X86ISD::CMP: return "X86ISD::CMP";
11677 case X86ISD::COMI: return "X86ISD::COMI";
11678 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11679 case X86ISD::SETCC: return "X86ISD::SETCC";
11680 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11681 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11682 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11683 case X86ISD::CMOV: return "X86ISD::CMOV";
11684 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11685 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11686 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11687 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11688 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11689 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11690 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11691 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11692 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11693 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11694 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11695 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11696 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11697 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11698 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11699 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11700 case X86ISD::BLENDPW: return "X86ISD::BLENDPW";
11701 case X86ISD::BLENDPS: return "X86ISD::BLENDPS";
11702 case X86ISD::BLENDPD: return "X86ISD::BLENDPD";
11703 case X86ISD::HADD: return "X86ISD::HADD";
11704 case X86ISD::HSUB: return "X86ISD::HSUB";
11705 case X86ISD::FHADD: return "X86ISD::FHADD";
11706 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11707 case X86ISD::FMAX: return "X86ISD::FMAX";
11708 case X86ISD::FMIN: return "X86ISD::FMIN";
11709 case X86ISD::FMAXC: return "X86ISD::FMAXC";
11710 case X86ISD::FMINC: return "X86ISD::FMINC";
11711 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11712 case X86ISD::FRCP: return "X86ISD::FRCP";
11713 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11714 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
11715 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11716 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11717 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11718 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11719 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11720 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11721 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11722 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11723 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11724 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11725 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11726 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11727 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11728 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11729 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
11730 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11731 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
11732 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11733 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11734 case X86ISD::VSHL: return "X86ISD::VSHL";
11735 case X86ISD::VSRL: return "X86ISD::VSRL";
11736 case X86ISD::VSRA: return "X86ISD::VSRA";
11737 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11738 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11739 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11740 case X86ISD::CMPP: return "X86ISD::CMPP";
11741 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11742 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11743 case X86ISD::ADD: return "X86ISD::ADD";
11744 case X86ISD::SUB: return "X86ISD::SUB";
11745 case X86ISD::ADC: return "X86ISD::ADC";
11746 case X86ISD::SBB: return "X86ISD::SBB";
11747 case X86ISD::SMUL: return "X86ISD::SMUL";
11748 case X86ISD::UMUL: return "X86ISD::UMUL";
11749 case X86ISD::INC: return "X86ISD::INC";
11750 case X86ISD::DEC: return "X86ISD::DEC";
11751 case X86ISD::OR: return "X86ISD::OR";
11752 case X86ISD::XOR: return "X86ISD::XOR";
11753 case X86ISD::AND: return "X86ISD::AND";
11754 case X86ISD::ANDN: return "X86ISD::ANDN";
11755 case X86ISD::BLSI: return "X86ISD::BLSI";
11756 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11757 case X86ISD::BLSR: return "X86ISD::BLSR";
11758 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11759 case X86ISD::PTEST: return "X86ISD::PTEST";
11760 case X86ISD::TESTP: return "X86ISD::TESTP";
11761 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11762 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11763 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11764 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11765 case X86ISD::SHUFP: return "X86ISD::SHUFP";
11766 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11767 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11768 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11769 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11770 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11771 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11772 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11773 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11774 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11775 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11776 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
11777 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
11778 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11779 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
11780 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
11781 case X86ISD::VPERMV: return "X86ISD::VPERMV";
11782 case X86ISD::VPERMI: return "X86ISD::VPERMI";
11783 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
11784 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11785 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11786 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11787 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11788 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11789 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
11790 case X86ISD::SAHF: return "X86ISD::SAHF";
11791 case X86ISD::RDRAND: return "X86ISD::RDRAND";
11792 case X86ISD::FMADD: return "X86ISD::FMADD";
11793 case X86ISD::FMSUB: return "X86ISD::FMSUB";
11794 case X86ISD::FNMADD: return "X86ISD::FNMADD";
11795 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
11796 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
11797 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
11801 // isLegalAddressingMode - Return true if the addressing mode represented
11802 // by AM is legal for this target, for a load/store of the specified type.
11803 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11805 // X86 supports extremely general addressing modes.
11806 CodeModel::Model M = getTargetMachine().getCodeModel();
11807 Reloc::Model R = getTargetMachine().getRelocationModel();
11809 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11810 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11815 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11817 // If a reference to this global requires an extra load, we can't fold it.
11818 if (isGlobalStubReference(GVFlags))
11821 // If BaseGV requires a register for the PIC base, we cannot also have a
11822 // BaseReg specified.
11823 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11826 // If lower 4G is not available, then we must use rip-relative addressing.
11827 if ((M != CodeModel::Small || R != Reloc::Static) &&
11828 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11832 switch (AM.Scale) {
11838 // These scales always work.
11843 // These scales are formed with basereg+scalereg. Only accept if there is
11848 default: // Other stuff never works.
11856 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11857 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11859 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11860 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11861 if (NumBits1 <= NumBits2)
11866 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11867 return Imm == (int32_t)Imm;
11870 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11871 // Can also use sub to handle negated immediates.
11872 return Imm == (int32_t)Imm;
11875 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11876 if (!VT1.isInteger() || !VT2.isInteger())
11878 unsigned NumBits1 = VT1.getSizeInBits();
11879 unsigned NumBits2 = VT2.getSizeInBits();
11880 if (NumBits1 <= NumBits2)
11885 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11886 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11887 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11890 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11891 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11892 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11895 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11896 // i16 instructions are longer (0x66 prefix) and potentially slower.
11897 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11900 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11901 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11902 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11903 /// are assumed to be legal.
11905 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11907 // Very little shuffling can be done for 64-bit vectors right now.
11908 if (VT.getSizeInBits() == 64)
11911 // FIXME: pshufb, blends, shifts.
11912 return (VT.getVectorNumElements() == 2 ||
11913 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11914 isMOVLMask(M, VT) ||
11915 isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11916 isPSHUFDMask(M, VT) ||
11917 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11918 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11919 isPALIGNRMask(M, VT, Subtarget) ||
11920 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11921 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11922 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11923 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11927 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11929 unsigned NumElts = VT.getVectorNumElements();
11930 // FIXME: This collection of masks seems suspect.
11933 if (NumElts == 4 && VT.is128BitVector()) {
11934 return (isMOVLMask(Mask, VT) ||
11935 isCommutedMOVLMask(Mask, VT, true) ||
11936 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11937 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11942 //===----------------------------------------------------------------------===//
11943 // X86 Scheduler Hooks
11944 //===----------------------------------------------------------------------===//
11946 // private utility function
11948 // Get CMPXCHG opcode for the specified data type.
11949 static unsigned getCmpXChgOpcode(EVT VT) {
11950 switch (VT.getSimpleVT().SimpleTy) {
11951 case MVT::i8: return X86::LCMPXCHG8;
11952 case MVT::i16: return X86::LCMPXCHG16;
11953 case MVT::i32: return X86::LCMPXCHG32;
11954 case MVT::i64: return X86::LCMPXCHG64;
11958 llvm_unreachable("Invalid operand size!");
11961 // Get LOAD opcode for the specified data type.
11962 static unsigned getLoadOpcode(EVT VT) {
11963 switch (VT.getSimpleVT().SimpleTy) {
11964 case MVT::i8: return X86::MOV8rm;
11965 case MVT::i16: return X86::MOV16rm;
11966 case MVT::i32: return X86::MOV32rm;
11967 case MVT::i64: return X86::MOV64rm;
11971 llvm_unreachable("Invalid operand size!");
11974 // Get opcode of the non-atomic one from the specified atomic instruction.
11975 static unsigned getNonAtomicOpcode(unsigned Opc) {
11977 case X86::ATOMAND8: return X86::AND8rr;
11978 case X86::ATOMAND16: return X86::AND16rr;
11979 case X86::ATOMAND32: return X86::AND32rr;
11980 case X86::ATOMAND64: return X86::AND64rr;
11981 case X86::ATOMOR8: return X86::OR8rr;
11982 case X86::ATOMOR16: return X86::OR16rr;
11983 case X86::ATOMOR32: return X86::OR32rr;
11984 case X86::ATOMOR64: return X86::OR64rr;
11985 case X86::ATOMXOR8: return X86::XOR8rr;
11986 case X86::ATOMXOR16: return X86::XOR16rr;
11987 case X86::ATOMXOR32: return X86::XOR32rr;
11988 case X86::ATOMXOR64: return X86::XOR64rr;
11990 llvm_unreachable("Unhandled atomic-load-op opcode!");
11993 // Get opcode of the non-atomic one from the specified atomic instruction with
11995 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
11996 unsigned &ExtraOpc) {
11998 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
11999 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
12000 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
12001 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
12002 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
12003 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12004 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12005 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12006 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
12007 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12008 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12009 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12010 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
12011 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12012 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12013 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12014 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
12015 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12016 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12017 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12019 llvm_unreachable("Unhandled atomic-load-op opcode!");
12022 // Get opcode of the non-atomic one from the specified atomic instruction for
12023 // 64-bit data type on 32-bit target.
12024 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12026 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
12027 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
12028 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
12029 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
12030 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
12031 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12032 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
12033 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
12034 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
12035 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
12037 llvm_unreachable("Unhandled atomic-load-op opcode!");
12040 // Get opcode of the non-atomic one from the specified atomic instruction for
12041 // 64-bit data type on 32-bit target with extra opcode.
12042 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12044 unsigned &ExtraOpc) {
12046 case X86::ATOMNAND6432:
12047 ExtraOpc = X86::NOT32r;
12048 HiOpc = X86::AND32rr;
12049 return X86::AND32rr;
12051 llvm_unreachable("Unhandled atomic-load-op opcode!");
12054 // Get pseudo CMOV opcode from the specified data type.
12055 static unsigned getPseudoCMOVOpc(EVT VT) {
12056 switch (VT.getSimpleVT().SimpleTy) {
12057 case MVT::i8: return X86::CMOV_GR8;
12058 case MVT::i16: return X86::CMOV_GR16;
12059 case MVT::i32: return X86::CMOV_GR32;
12063 llvm_unreachable("Unknown CMOV opcode!");
12066 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12067 // They will be translated into a spin-loop or compare-exchange loop from
12070 // dst = atomic-fetch-op MI.addr, MI.val
12076 // EAX = LOAD MI.addr
12078 // t1 = OP MI.val, EAX
12079 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12084 MachineBasicBlock *
12085 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12086 MachineBasicBlock *MBB) const {
12087 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12088 DebugLoc DL = MI->getDebugLoc();
12090 MachineFunction *MF = MBB->getParent();
12091 MachineRegisterInfo &MRI = MF->getRegInfo();
12093 const BasicBlock *BB = MBB->getBasicBlock();
12094 MachineFunction::iterator I = MBB;
12097 assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12098 "Unexpected number of operands");
12100 assert(MI->hasOneMemOperand() &&
12101 "Expected atomic-load-op to have one memoperand");
12103 // Memory Reference
12104 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12105 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12107 unsigned DstReg, SrcReg;
12108 unsigned MemOpndSlot;
12110 unsigned CurOp = 0;
12112 DstReg = MI->getOperand(CurOp++).getReg();
12113 MemOpndSlot = CurOp;
12114 CurOp += X86::AddrNumOperands;
12115 SrcReg = MI->getOperand(CurOp++).getReg();
12117 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12118 MVT::SimpleValueType VT = *RC->vt_begin();
12119 unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12121 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12122 unsigned LOADOpc = getLoadOpcode(VT);
12124 // For the atomic load-arith operator, we generate
12127 // EAX = LOAD [MI.addr]
12129 // t1 = OP MI.val, EAX
12130 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12134 MachineBasicBlock *thisMBB = MBB;
12135 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12136 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12137 MF->insert(I, mainMBB);
12138 MF->insert(I, sinkMBB);
12140 MachineInstrBuilder MIB;
12142 // Transfer the remainder of BB and its successor edges to sinkMBB.
12143 sinkMBB->splice(sinkMBB->begin(), MBB,
12144 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12145 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12148 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12149 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12150 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12151 MIB.setMemRefs(MMOBegin, MMOEnd);
12153 thisMBB->addSuccessor(mainMBB);
12156 MachineBasicBlock *origMainMBB = mainMBB;
12157 mainMBB->addLiveIn(AccPhyReg);
12159 // Copy AccPhyReg as it is used more than once.
12160 unsigned AccReg = MRI.createVirtualRegister(RC);
12161 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12162 .addReg(AccPhyReg);
12164 unsigned t1 = MRI.createVirtualRegister(RC);
12165 unsigned Opc = MI->getOpcode();
12168 llvm_unreachable("Unhandled atomic-load-op opcode!");
12169 case X86::ATOMAND8:
12170 case X86::ATOMAND16:
12171 case X86::ATOMAND32:
12172 case X86::ATOMAND64:
12174 case X86::ATOMOR16:
12175 case X86::ATOMOR32:
12176 case X86::ATOMOR64:
12177 case X86::ATOMXOR8:
12178 case X86::ATOMXOR16:
12179 case X86::ATOMXOR32:
12180 case X86::ATOMXOR64: {
12181 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12182 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12186 case X86::ATOMNAND8:
12187 case X86::ATOMNAND16:
12188 case X86::ATOMNAND32:
12189 case X86::ATOMNAND64: {
12190 unsigned t2 = MRI.createVirtualRegister(RC);
12192 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12193 BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12195 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12198 case X86::ATOMMAX8:
12199 case X86::ATOMMAX16:
12200 case X86::ATOMMAX32:
12201 case X86::ATOMMAX64:
12202 case X86::ATOMMIN8:
12203 case X86::ATOMMIN16:
12204 case X86::ATOMMIN32:
12205 case X86::ATOMMIN64:
12206 case X86::ATOMUMAX8:
12207 case X86::ATOMUMAX16:
12208 case X86::ATOMUMAX32:
12209 case X86::ATOMUMAX64:
12210 case X86::ATOMUMIN8:
12211 case X86::ATOMUMIN16:
12212 case X86::ATOMUMIN32:
12213 case X86::ATOMUMIN64: {
12215 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12217 BuildMI(mainMBB, DL, TII->get(CMPOpc))
12221 if (Subtarget->hasCMov()) {
12222 if (VT != MVT::i8) {
12224 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12228 // Promote i8 to i32 to use CMOV32
12229 const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12230 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12231 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12232 unsigned t2 = MRI.createVirtualRegister(RC32);
12234 unsigned Undef = MRI.createVirtualRegister(RC32);
12235 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12237 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12240 .addImm(X86::sub_8bit);
12241 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12244 .addImm(X86::sub_8bit);
12246 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12250 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12251 .addReg(t2, 0, X86::sub_8bit);
12254 // Use pseudo select and lower them.
12255 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12256 "Invalid atomic-load-op transformation!");
12257 unsigned SelOpc = getPseudoCMOVOpc(VT);
12258 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12259 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12260 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12261 .addReg(SrcReg).addReg(AccReg)
12263 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12269 // Copy AccPhyReg back from virtual register.
12270 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12273 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12274 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12275 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12277 MIB.setMemRefs(MMOBegin, MMOEnd);
12279 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12281 mainMBB->addSuccessor(origMainMBB);
12282 mainMBB->addSuccessor(sinkMBB);
12285 sinkMBB->addLiveIn(AccPhyReg);
12287 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12288 TII->get(TargetOpcode::COPY), DstReg)
12289 .addReg(AccPhyReg);
12291 MI->eraseFromParent();
12295 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12296 // instructions. They will be translated into a spin-loop or compare-exchange
12300 // dst = atomic-fetch-op MI.addr, MI.val
12306 // EAX = LOAD [MI.addr + 0]
12307 // EDX = LOAD [MI.addr + 4]
12309 // EBX = OP MI.val.lo, EAX
12310 // ECX = OP MI.val.hi, EDX
12311 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12316 MachineBasicBlock *
12317 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12318 MachineBasicBlock *MBB) const {
12319 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12320 DebugLoc DL = MI->getDebugLoc();
12322 MachineFunction *MF = MBB->getParent();
12323 MachineRegisterInfo &MRI = MF->getRegInfo();
12325 const BasicBlock *BB = MBB->getBasicBlock();
12326 MachineFunction::iterator I = MBB;
12329 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12330 "Unexpected number of operands");
12332 assert(MI->hasOneMemOperand() &&
12333 "Expected atomic-load-op32 to have one memoperand");
12335 // Memory Reference
12336 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12337 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12339 unsigned DstLoReg, DstHiReg;
12340 unsigned SrcLoReg, SrcHiReg;
12341 unsigned MemOpndSlot;
12343 unsigned CurOp = 0;
12345 DstLoReg = MI->getOperand(CurOp++).getReg();
12346 DstHiReg = MI->getOperand(CurOp++).getReg();
12347 MemOpndSlot = CurOp;
12348 CurOp += X86::AddrNumOperands;
12349 SrcLoReg = MI->getOperand(CurOp++).getReg();
12350 SrcHiReg = MI->getOperand(CurOp++).getReg();
12352 const TargetRegisterClass *RC = &X86::GR32RegClass;
12353 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12355 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12356 unsigned LOADOpc = X86::MOV32rm;
12358 // For the atomic load-arith operator, we generate
12361 // EAX = LOAD [MI.addr + 0]
12362 // EDX = LOAD [MI.addr + 4]
12364 // EBX = OP MI.vallo, EAX
12365 // ECX = OP MI.valhi, EDX
12366 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12370 MachineBasicBlock *thisMBB = MBB;
12371 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12372 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12373 MF->insert(I, mainMBB);
12374 MF->insert(I, sinkMBB);
12376 MachineInstrBuilder MIB;
12378 // Transfer the remainder of BB and its successor edges to sinkMBB.
12379 sinkMBB->splice(sinkMBB->begin(), MBB,
12380 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12381 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12385 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12386 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12387 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12388 MIB.setMemRefs(MMOBegin, MMOEnd);
12390 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12391 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12392 if (i == X86::AddrDisp)
12393 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12395 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12397 MIB.setMemRefs(MMOBegin, MMOEnd);
12399 thisMBB->addSuccessor(mainMBB);
12402 MachineBasicBlock *origMainMBB = mainMBB;
12403 mainMBB->addLiveIn(X86::EAX);
12404 mainMBB->addLiveIn(X86::EDX);
12406 // Copy EDX:EAX as they are used more than once.
12407 unsigned LoReg = MRI.createVirtualRegister(RC);
12408 unsigned HiReg = MRI.createVirtualRegister(RC);
12409 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12410 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12412 unsigned t1L = MRI.createVirtualRegister(RC);
12413 unsigned t1H = MRI.createVirtualRegister(RC);
12415 unsigned Opc = MI->getOpcode();
12418 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12419 case X86::ATOMAND6432:
12420 case X86::ATOMOR6432:
12421 case X86::ATOMXOR6432:
12422 case X86::ATOMADD6432:
12423 case X86::ATOMSUB6432: {
12425 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12426 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12427 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12430 case X86::ATOMNAND6432: {
12431 unsigned HiOpc, NOTOpc;
12432 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12433 unsigned t2L = MRI.createVirtualRegister(RC);
12434 unsigned t2H = MRI.createVirtualRegister(RC);
12435 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12436 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12437 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12438 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12441 case X86::ATOMMAX6432:
12442 case X86::ATOMMIN6432:
12443 case X86::ATOMUMAX6432:
12444 case X86::ATOMUMIN6432: {
12446 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12447 unsigned cL = MRI.createVirtualRegister(RC8);
12448 unsigned cH = MRI.createVirtualRegister(RC8);
12449 unsigned cL32 = MRI.createVirtualRegister(RC);
12450 unsigned cH32 = MRI.createVirtualRegister(RC);
12451 unsigned cc = MRI.createVirtualRegister(RC);
12452 // cl := cmp src_lo, lo
12453 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12454 .addReg(SrcLoReg).addReg(LoReg);
12455 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12456 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12457 // ch := cmp src_hi, hi
12458 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12459 .addReg(SrcHiReg).addReg(HiReg);
12460 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12461 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12462 // cc := if (src_hi == hi) ? cl : ch;
12463 if (Subtarget->hasCMov()) {
12464 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12465 .addReg(cH32).addReg(cL32);
12467 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12468 .addReg(cH32).addReg(cL32)
12469 .addImm(X86::COND_E);
12470 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12472 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12473 if (Subtarget->hasCMov()) {
12474 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12475 .addReg(SrcLoReg).addReg(LoReg);
12476 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12477 .addReg(SrcHiReg).addReg(HiReg);
12479 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12480 .addReg(SrcLoReg).addReg(LoReg)
12481 .addImm(X86::COND_NE);
12482 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12483 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12484 .addReg(SrcHiReg).addReg(HiReg)
12485 .addImm(X86::COND_NE);
12486 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12490 case X86::ATOMSWAP6432: {
12492 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12493 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12494 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12499 // Copy EDX:EAX back from HiReg:LoReg
12500 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12501 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12502 // Copy ECX:EBX from t1H:t1L
12503 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12504 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12506 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12507 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12508 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12509 MIB.setMemRefs(MMOBegin, MMOEnd);
12511 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12513 mainMBB->addSuccessor(origMainMBB);
12514 mainMBB->addSuccessor(sinkMBB);
12517 sinkMBB->addLiveIn(X86::EAX);
12518 sinkMBB->addLiveIn(X86::EDX);
12520 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12521 TII->get(TargetOpcode::COPY), DstLoReg)
12523 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12524 TII->get(TargetOpcode::COPY), DstHiReg)
12527 MI->eraseFromParent();
12531 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12532 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12533 // in the .td file.
12534 MachineBasicBlock *
12535 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12536 unsigned numArgs, bool memArg) const {
12537 assert(Subtarget->hasSSE42() &&
12538 "Target must have SSE4.2 or AVX features enabled");
12540 DebugLoc dl = MI->getDebugLoc();
12541 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12543 if (!Subtarget->hasAVX()) {
12545 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12547 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12550 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12552 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12555 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12556 for (unsigned i = 0; i < numArgs; ++i) {
12557 MachineOperand &Op = MI->getOperand(i+1);
12558 if (!(Op.isReg() && Op.isImplicit()))
12559 MIB.addOperand(Op);
12561 BuildMI(*BB, MI, dl,
12562 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12563 .addReg(X86::XMM0);
12565 MI->eraseFromParent();
12569 MachineBasicBlock *
12570 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12571 DebugLoc dl = MI->getDebugLoc();
12572 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12574 // Address into RAX/EAX, other two args into ECX, EDX.
12575 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12576 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12577 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12578 for (int i = 0; i < X86::AddrNumOperands; ++i)
12579 MIB.addOperand(MI->getOperand(i));
12581 unsigned ValOps = X86::AddrNumOperands;
12582 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12583 .addReg(MI->getOperand(ValOps).getReg());
12584 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12585 .addReg(MI->getOperand(ValOps+1).getReg());
12587 // The instruction doesn't actually take any operands though.
12588 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12590 MI->eraseFromParent(); // The pseudo is gone now.
12594 MachineBasicBlock *
12595 X86TargetLowering::EmitVAARG64WithCustomInserter(
12597 MachineBasicBlock *MBB) const {
12598 // Emit va_arg instruction on X86-64.
12600 // Operands to this pseudo-instruction:
12601 // 0 ) Output : destination address (reg)
12602 // 1-5) Input : va_list address (addr, i64mem)
12603 // 6 ) ArgSize : Size (in bytes) of vararg type
12604 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12605 // 8 ) Align : Alignment of type
12606 // 9 ) EFLAGS (implicit-def)
12608 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12609 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12611 unsigned DestReg = MI->getOperand(0).getReg();
12612 MachineOperand &Base = MI->getOperand(1);
12613 MachineOperand &Scale = MI->getOperand(2);
12614 MachineOperand &Index = MI->getOperand(3);
12615 MachineOperand &Disp = MI->getOperand(4);
12616 MachineOperand &Segment = MI->getOperand(5);
12617 unsigned ArgSize = MI->getOperand(6).getImm();
12618 unsigned ArgMode = MI->getOperand(7).getImm();
12619 unsigned Align = MI->getOperand(8).getImm();
12621 // Memory Reference
12622 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12623 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12624 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12626 // Machine Information
12627 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12628 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12629 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12630 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12631 DebugLoc DL = MI->getDebugLoc();
12633 // struct va_list {
12636 // i64 overflow_area (address)
12637 // i64 reg_save_area (address)
12639 // sizeof(va_list) = 24
12640 // alignment(va_list) = 8
12642 unsigned TotalNumIntRegs = 6;
12643 unsigned TotalNumXMMRegs = 8;
12644 bool UseGPOffset = (ArgMode == 1);
12645 bool UseFPOffset = (ArgMode == 2);
12646 unsigned MaxOffset = TotalNumIntRegs * 8 +
12647 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12649 /* Align ArgSize to a multiple of 8 */
12650 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12651 bool NeedsAlign = (Align > 8);
12653 MachineBasicBlock *thisMBB = MBB;
12654 MachineBasicBlock *overflowMBB;
12655 MachineBasicBlock *offsetMBB;
12656 MachineBasicBlock *endMBB;
12658 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
12659 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
12660 unsigned OffsetReg = 0;
12662 if (!UseGPOffset && !UseFPOffset) {
12663 // If we only pull from the overflow region, we don't create a branch.
12664 // We don't need to alter control flow.
12665 OffsetDestReg = 0; // unused
12666 OverflowDestReg = DestReg;
12669 overflowMBB = thisMBB;
12672 // First emit code to check if gp_offset (or fp_offset) is below the bound.
12673 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12674 // If not, pull from overflow_area. (branch to overflowMBB)
12679 // offsetMBB overflowMBB
12684 // Registers for the PHI in endMBB
12685 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12686 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12688 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12689 MachineFunction *MF = MBB->getParent();
12690 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12691 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12692 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12694 MachineFunction::iterator MBBIter = MBB;
12697 // Insert the new basic blocks
12698 MF->insert(MBBIter, offsetMBB);
12699 MF->insert(MBBIter, overflowMBB);
12700 MF->insert(MBBIter, endMBB);
12702 // Transfer the remainder of MBB and its successor edges to endMBB.
12703 endMBB->splice(endMBB->begin(), thisMBB,
12704 llvm::next(MachineBasicBlock::iterator(MI)),
12706 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12708 // Make offsetMBB and overflowMBB successors of thisMBB
12709 thisMBB->addSuccessor(offsetMBB);
12710 thisMBB->addSuccessor(overflowMBB);
12712 // endMBB is a successor of both offsetMBB and overflowMBB
12713 offsetMBB->addSuccessor(endMBB);
12714 overflowMBB->addSuccessor(endMBB);
12716 // Load the offset value into a register
12717 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12718 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12722 .addDisp(Disp, UseFPOffset ? 4 : 0)
12723 .addOperand(Segment)
12724 .setMemRefs(MMOBegin, MMOEnd);
12726 // Check if there is enough room left to pull this argument.
12727 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12729 .addImm(MaxOffset + 8 - ArgSizeA8);
12731 // Branch to "overflowMBB" if offset >= max
12732 // Fall through to "offsetMBB" otherwise
12733 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12734 .addMBB(overflowMBB);
12737 // In offsetMBB, emit code to use the reg_save_area.
12739 assert(OffsetReg != 0);
12741 // Read the reg_save_area address.
12742 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12743 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12748 .addOperand(Segment)
12749 .setMemRefs(MMOBegin, MMOEnd);
12751 // Zero-extend the offset
12752 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12753 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12756 .addImm(X86::sub_32bit);
12758 // Add the offset to the reg_save_area to get the final address.
12759 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12760 .addReg(OffsetReg64)
12761 .addReg(RegSaveReg);
12763 // Compute the offset for the next argument
12764 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12765 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12767 .addImm(UseFPOffset ? 16 : 8);
12769 // Store it back into the va_list.
12770 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12774 .addDisp(Disp, UseFPOffset ? 4 : 0)
12775 .addOperand(Segment)
12776 .addReg(NextOffsetReg)
12777 .setMemRefs(MMOBegin, MMOEnd);
12780 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12785 // Emit code to use overflow area
12788 // Load the overflow_area address into a register.
12789 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12790 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12795 .addOperand(Segment)
12796 .setMemRefs(MMOBegin, MMOEnd);
12798 // If we need to align it, do so. Otherwise, just copy the address
12799 // to OverflowDestReg.
12801 // Align the overflow address
12802 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12803 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12805 // aligned_addr = (addr + (align-1)) & ~(align-1)
12806 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12807 .addReg(OverflowAddrReg)
12810 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12812 .addImm(~(uint64_t)(Align-1));
12814 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12815 .addReg(OverflowAddrReg);
12818 // Compute the next overflow address after this argument.
12819 // (the overflow address should be kept 8-byte aligned)
12820 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12821 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12822 .addReg(OverflowDestReg)
12823 .addImm(ArgSizeA8);
12825 // Store the new overflow address.
12826 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12831 .addOperand(Segment)
12832 .addReg(NextAddrReg)
12833 .setMemRefs(MMOBegin, MMOEnd);
12835 // If we branched, emit the PHI to the front of endMBB.
12837 BuildMI(*endMBB, endMBB->begin(), DL,
12838 TII->get(X86::PHI), DestReg)
12839 .addReg(OffsetDestReg).addMBB(offsetMBB)
12840 .addReg(OverflowDestReg).addMBB(overflowMBB);
12843 // Erase the pseudo instruction
12844 MI->eraseFromParent();
12849 MachineBasicBlock *
12850 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12852 MachineBasicBlock *MBB) const {
12853 // Emit code to save XMM registers to the stack. The ABI says that the
12854 // number of registers to save is given in %al, so it's theoretically
12855 // possible to do an indirect jump trick to avoid saving all of them,
12856 // however this code takes a simpler approach and just executes all
12857 // of the stores if %al is non-zero. It's less code, and it's probably
12858 // easier on the hardware branch predictor, and stores aren't all that
12859 // expensive anyway.
12861 // Create the new basic blocks. One block contains all the XMM stores,
12862 // and one block is the final destination regardless of whether any
12863 // stores were performed.
12864 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12865 MachineFunction *F = MBB->getParent();
12866 MachineFunction::iterator MBBIter = MBB;
12868 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12869 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12870 F->insert(MBBIter, XMMSaveMBB);
12871 F->insert(MBBIter, EndMBB);
12873 // Transfer the remainder of MBB and its successor edges to EndMBB.
12874 EndMBB->splice(EndMBB->begin(), MBB,
12875 llvm::next(MachineBasicBlock::iterator(MI)),
12877 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12879 // The original block will now fall through to the XMM save block.
12880 MBB->addSuccessor(XMMSaveMBB);
12881 // The XMMSaveMBB will fall through to the end block.
12882 XMMSaveMBB->addSuccessor(EndMBB);
12884 // Now add the instructions.
12885 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12886 DebugLoc DL = MI->getDebugLoc();
12888 unsigned CountReg = MI->getOperand(0).getReg();
12889 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12890 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12892 if (!Subtarget->isTargetWin64()) {
12893 // If %al is 0, branch around the XMM save block.
12894 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12895 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12896 MBB->addSuccessor(EndMBB);
12899 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12900 // In the XMM save block, save all the XMM argument registers.
12901 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12902 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12903 MachineMemOperand *MMO =
12904 F->getMachineMemOperand(
12905 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12906 MachineMemOperand::MOStore,
12907 /*Size=*/16, /*Align=*/16);
12908 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12909 .addFrameIndex(RegSaveFrameIndex)
12910 .addImm(/*Scale=*/1)
12911 .addReg(/*IndexReg=*/0)
12912 .addImm(/*Disp=*/Offset)
12913 .addReg(/*Segment=*/0)
12914 .addReg(MI->getOperand(i).getReg())
12915 .addMemOperand(MMO);
12918 MI->eraseFromParent(); // The pseudo instruction is gone now.
12923 // The EFLAGS operand of SelectItr might be missing a kill marker
12924 // because there were multiple uses of EFLAGS, and ISel didn't know
12925 // which to mark. Figure out whether SelectItr should have had a
12926 // kill marker, and set it if it should. Returns the correct kill
12928 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12929 MachineBasicBlock* BB,
12930 const TargetRegisterInfo* TRI) {
12931 // Scan forward through BB for a use/def of EFLAGS.
12932 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12933 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12934 const MachineInstr& mi = *miI;
12935 if (mi.readsRegister(X86::EFLAGS))
12937 if (mi.definesRegister(X86::EFLAGS))
12938 break; // Should have kill-flag - update below.
12941 // If we hit the end of the block, check whether EFLAGS is live into a
12943 if (miI == BB->end()) {
12944 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12945 sEnd = BB->succ_end();
12946 sItr != sEnd; ++sItr) {
12947 MachineBasicBlock* succ = *sItr;
12948 if (succ->isLiveIn(X86::EFLAGS))
12953 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12954 // out. SelectMI should have a kill flag on EFLAGS.
12955 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12959 MachineBasicBlock *
12960 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12961 MachineBasicBlock *BB) const {
12962 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12963 DebugLoc DL = MI->getDebugLoc();
12965 // To "insert" a SELECT_CC instruction, we actually have to insert the
12966 // diamond control-flow pattern. The incoming instruction knows the
12967 // destination vreg to set, the condition code register to branch on, the
12968 // true/false values to select between, and a branch opcode to use.
12969 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12970 MachineFunction::iterator It = BB;
12976 // cmpTY ccX, r1, r2
12978 // fallthrough --> copy0MBB
12979 MachineBasicBlock *thisMBB = BB;
12980 MachineFunction *F = BB->getParent();
12981 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12982 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12983 F->insert(It, copy0MBB);
12984 F->insert(It, sinkMBB);
12986 // If the EFLAGS register isn't dead in the terminator, then claim that it's
12987 // live into the sink and copy blocks.
12988 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12989 if (!MI->killsRegister(X86::EFLAGS) &&
12990 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12991 copy0MBB->addLiveIn(X86::EFLAGS);
12992 sinkMBB->addLiveIn(X86::EFLAGS);
12995 // Transfer the remainder of BB and its successor edges to sinkMBB.
12996 sinkMBB->splice(sinkMBB->begin(), BB,
12997 llvm::next(MachineBasicBlock::iterator(MI)),
12999 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13001 // Add the true and fallthrough blocks as its successors.
13002 BB->addSuccessor(copy0MBB);
13003 BB->addSuccessor(sinkMBB);
13005 // Create the conditional branch instruction.
13007 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13008 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13011 // %FalseValue = ...
13012 // # fallthrough to sinkMBB
13013 copy0MBB->addSuccessor(sinkMBB);
13016 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13018 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13019 TII->get(X86::PHI), MI->getOperand(0).getReg())
13020 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13021 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13023 MI->eraseFromParent(); // The pseudo instruction is gone now.
13027 MachineBasicBlock *
13028 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13029 bool Is64Bit) const {
13030 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13031 DebugLoc DL = MI->getDebugLoc();
13032 MachineFunction *MF = BB->getParent();
13033 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13035 assert(getTargetMachine().Options.EnableSegmentedStacks);
13037 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13038 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13041 // ... [Till the alloca]
13042 // If stacklet is not large enough, jump to mallocMBB
13045 // Allocate by subtracting from RSP
13046 // Jump to continueMBB
13049 // Allocate by call to runtime
13053 // [rest of original BB]
13056 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13057 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13058 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13060 MachineRegisterInfo &MRI = MF->getRegInfo();
13061 const TargetRegisterClass *AddrRegClass =
13062 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13064 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13065 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13066 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13067 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13068 sizeVReg = MI->getOperand(1).getReg(),
13069 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13071 MachineFunction::iterator MBBIter = BB;
13074 MF->insert(MBBIter, bumpMBB);
13075 MF->insert(MBBIter, mallocMBB);
13076 MF->insert(MBBIter, continueMBB);
13078 continueMBB->splice(continueMBB->begin(), BB, llvm::next
13079 (MachineBasicBlock::iterator(MI)), BB->end());
13080 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13082 // Add code to the main basic block to check if the stack limit has been hit,
13083 // and if so, jump to mallocMBB otherwise to bumpMBB.
13084 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13085 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13086 .addReg(tmpSPVReg).addReg(sizeVReg);
13087 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13088 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13089 .addReg(SPLimitVReg);
13090 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13092 // bumpMBB simply decreases the stack pointer, since we know the current
13093 // stacklet has enough space.
13094 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13095 .addReg(SPLimitVReg);
13096 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13097 .addReg(SPLimitVReg);
13098 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13100 // Calls into a routine in libgcc to allocate more space from the heap.
13101 const uint32_t *RegMask =
13102 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13104 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13106 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13107 .addExternalSymbol("__morestack_allocate_stack_space")
13108 .addRegMask(RegMask)
13109 .addReg(X86::RDI, RegState::Implicit)
13110 .addReg(X86::RAX, RegState::ImplicitDefine);
13112 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13114 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13115 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13116 .addExternalSymbol("__morestack_allocate_stack_space")
13117 .addRegMask(RegMask)
13118 .addReg(X86::EAX, RegState::ImplicitDefine);
13122 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13125 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13126 .addReg(Is64Bit ? X86::RAX : X86::EAX);
13127 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13129 // Set up the CFG correctly.
13130 BB->addSuccessor(bumpMBB);
13131 BB->addSuccessor(mallocMBB);
13132 mallocMBB->addSuccessor(continueMBB);
13133 bumpMBB->addSuccessor(continueMBB);
13135 // Take care of the PHI nodes.
13136 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13137 MI->getOperand(0).getReg())
13138 .addReg(mallocPtrVReg).addMBB(mallocMBB)
13139 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13141 // Delete the original pseudo instruction.
13142 MI->eraseFromParent();
13145 return continueMBB;
13148 MachineBasicBlock *
13149 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13150 MachineBasicBlock *BB) const {
13151 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13152 DebugLoc DL = MI->getDebugLoc();
13154 assert(!Subtarget->isTargetEnvMacho());
13156 // The lowering is pretty easy: we're just emitting the call to _alloca. The
13157 // non-trivial part is impdef of ESP.
13159 if (Subtarget->isTargetWin64()) {
13160 if (Subtarget->isTargetCygMing()) {
13161 // ___chkstk(Mingw64):
13162 // Clobbers R10, R11, RAX and EFLAGS.
13164 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13165 .addExternalSymbol("___chkstk")
13166 .addReg(X86::RAX, RegState::Implicit)
13167 .addReg(X86::RSP, RegState::Implicit)
13168 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13169 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13170 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13172 // __chkstk(MSVCRT): does not update stack pointer.
13173 // Clobbers R10, R11 and EFLAGS.
13174 // FIXME: RAX(allocated size) might be reused and not killed.
13175 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13176 .addExternalSymbol("__chkstk")
13177 .addReg(X86::RAX, RegState::Implicit)
13178 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13179 // RAX has the offset to subtracted from RSP.
13180 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13185 const char *StackProbeSymbol =
13186 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13188 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13189 .addExternalSymbol(StackProbeSymbol)
13190 .addReg(X86::EAX, RegState::Implicit)
13191 .addReg(X86::ESP, RegState::Implicit)
13192 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13193 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13194 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13197 MI->eraseFromParent(); // The pseudo instruction is gone now.
13201 MachineBasicBlock *
13202 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13203 MachineBasicBlock *BB) const {
13204 // This is pretty easy. We're taking the value that we received from
13205 // our load from the relocation, sticking it in either RDI (x86-64)
13206 // or EAX and doing an indirect call. The return value will then
13207 // be in the normal return register.
13208 const X86InstrInfo *TII
13209 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13210 DebugLoc DL = MI->getDebugLoc();
13211 MachineFunction *F = BB->getParent();
13213 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13214 assert(MI->getOperand(3).isGlobal() && "This should be a global");
13216 // Get a register mask for the lowered call.
13217 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13218 // proper register mask.
13219 const uint32_t *RegMask =
13220 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13221 if (Subtarget->is64Bit()) {
13222 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13223 TII->get(X86::MOV64rm), X86::RDI)
13225 .addImm(0).addReg(0)
13226 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13227 MI->getOperand(3).getTargetFlags())
13229 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13230 addDirectMem(MIB, X86::RDI);
13231 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13232 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13233 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13234 TII->get(X86::MOV32rm), X86::EAX)
13236 .addImm(0).addReg(0)
13237 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13238 MI->getOperand(3).getTargetFlags())
13240 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13241 addDirectMem(MIB, X86::EAX);
13242 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13244 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13245 TII->get(X86::MOV32rm), X86::EAX)
13246 .addReg(TII->getGlobalBaseReg(F))
13247 .addImm(0).addReg(0)
13248 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13249 MI->getOperand(3).getTargetFlags())
13251 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13252 addDirectMem(MIB, X86::EAX);
13253 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13256 MI->eraseFromParent(); // The pseudo instruction is gone now.
13260 MachineBasicBlock *
13261 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13262 MachineBasicBlock *BB) const {
13263 switch (MI->getOpcode()) {
13264 default: llvm_unreachable("Unexpected instr type to insert");
13265 case X86::TAILJMPd64:
13266 case X86::TAILJMPr64:
13267 case X86::TAILJMPm64:
13268 llvm_unreachable("TAILJMP64 would not be touched here.");
13269 case X86::TCRETURNdi64:
13270 case X86::TCRETURNri64:
13271 case X86::TCRETURNmi64:
13273 case X86::WIN_ALLOCA:
13274 return EmitLoweredWinAlloca(MI, BB);
13275 case X86::SEG_ALLOCA_32:
13276 return EmitLoweredSegAlloca(MI, BB, false);
13277 case X86::SEG_ALLOCA_64:
13278 return EmitLoweredSegAlloca(MI, BB, true);
13279 case X86::TLSCall_32:
13280 case X86::TLSCall_64:
13281 return EmitLoweredTLSCall(MI, BB);
13282 case X86::CMOV_GR8:
13283 case X86::CMOV_FR32:
13284 case X86::CMOV_FR64:
13285 case X86::CMOV_V4F32:
13286 case X86::CMOV_V2F64:
13287 case X86::CMOV_V2I64:
13288 case X86::CMOV_V8F32:
13289 case X86::CMOV_V4F64:
13290 case X86::CMOV_V4I64:
13291 case X86::CMOV_GR16:
13292 case X86::CMOV_GR32:
13293 case X86::CMOV_RFP32:
13294 case X86::CMOV_RFP64:
13295 case X86::CMOV_RFP80:
13296 return EmitLoweredSelect(MI, BB);
13298 case X86::FP32_TO_INT16_IN_MEM:
13299 case X86::FP32_TO_INT32_IN_MEM:
13300 case X86::FP32_TO_INT64_IN_MEM:
13301 case X86::FP64_TO_INT16_IN_MEM:
13302 case X86::FP64_TO_INT32_IN_MEM:
13303 case X86::FP64_TO_INT64_IN_MEM:
13304 case X86::FP80_TO_INT16_IN_MEM:
13305 case X86::FP80_TO_INT32_IN_MEM:
13306 case X86::FP80_TO_INT64_IN_MEM: {
13307 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13308 DebugLoc DL = MI->getDebugLoc();
13310 // Change the floating point control register to use "round towards zero"
13311 // mode when truncating to an integer value.
13312 MachineFunction *F = BB->getParent();
13313 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13314 addFrameReference(BuildMI(*BB, MI, DL,
13315 TII->get(X86::FNSTCW16m)), CWFrameIdx);
13317 // Load the old value of the high byte of the control word...
13319 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13320 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13323 // Set the high part to be round to zero...
13324 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13327 // Reload the modified control word now...
13328 addFrameReference(BuildMI(*BB, MI, DL,
13329 TII->get(X86::FLDCW16m)), CWFrameIdx);
13331 // Restore the memory image of control word to original value
13332 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13335 // Get the X86 opcode to use.
13337 switch (MI->getOpcode()) {
13338 default: llvm_unreachable("illegal opcode!");
13339 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13340 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13341 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13342 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13343 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13344 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13345 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13346 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13347 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13351 MachineOperand &Op = MI->getOperand(0);
13353 AM.BaseType = X86AddressMode::RegBase;
13354 AM.Base.Reg = Op.getReg();
13356 AM.BaseType = X86AddressMode::FrameIndexBase;
13357 AM.Base.FrameIndex = Op.getIndex();
13359 Op = MI->getOperand(1);
13361 AM.Scale = Op.getImm();
13362 Op = MI->getOperand(2);
13364 AM.IndexReg = Op.getImm();
13365 Op = MI->getOperand(3);
13366 if (Op.isGlobal()) {
13367 AM.GV = Op.getGlobal();
13369 AM.Disp = Op.getImm();
13371 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13372 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13374 // Reload the original control word now.
13375 addFrameReference(BuildMI(*BB, MI, DL,
13376 TII->get(X86::FLDCW16m)), CWFrameIdx);
13378 MI->eraseFromParent(); // The pseudo instruction is gone now.
13381 // String/text processing lowering.
13382 case X86::PCMPISTRM128REG:
13383 case X86::VPCMPISTRM128REG:
13384 case X86::PCMPISTRM128MEM:
13385 case X86::VPCMPISTRM128MEM:
13386 case X86::PCMPESTRM128REG:
13387 case X86::VPCMPESTRM128REG:
13388 case X86::PCMPESTRM128MEM:
13389 case X86::VPCMPESTRM128MEM: {
13392 switch (MI->getOpcode()) {
13393 default: llvm_unreachable("illegal opcode!");
13394 case X86::PCMPISTRM128REG:
13395 case X86::VPCMPISTRM128REG:
13396 NumArgs = 3; MemArg = false; break;
13397 case X86::PCMPISTRM128MEM:
13398 case X86::VPCMPISTRM128MEM:
13399 NumArgs = 3; MemArg = true; break;
13400 case X86::PCMPESTRM128REG:
13401 case X86::VPCMPESTRM128REG:
13402 NumArgs = 5; MemArg = false; break;
13403 case X86::PCMPESTRM128MEM:
13404 case X86::VPCMPESTRM128MEM:
13405 NumArgs = 5; MemArg = true; break;
13407 return EmitPCMP(MI, BB, NumArgs, MemArg);
13410 // Thread synchronization.
13412 return EmitMonitor(MI, BB);
13414 // Atomic Lowering.
13415 case X86::ATOMAND8:
13416 case X86::ATOMAND16:
13417 case X86::ATOMAND32:
13418 case X86::ATOMAND64:
13421 case X86::ATOMOR16:
13422 case X86::ATOMOR32:
13423 case X86::ATOMOR64:
13425 case X86::ATOMXOR16:
13426 case X86::ATOMXOR8:
13427 case X86::ATOMXOR32:
13428 case X86::ATOMXOR64:
13430 case X86::ATOMNAND8:
13431 case X86::ATOMNAND16:
13432 case X86::ATOMNAND32:
13433 case X86::ATOMNAND64:
13435 case X86::ATOMMAX8:
13436 case X86::ATOMMAX16:
13437 case X86::ATOMMAX32:
13438 case X86::ATOMMAX64:
13440 case X86::ATOMMIN8:
13441 case X86::ATOMMIN16:
13442 case X86::ATOMMIN32:
13443 case X86::ATOMMIN64:
13445 case X86::ATOMUMAX8:
13446 case X86::ATOMUMAX16:
13447 case X86::ATOMUMAX32:
13448 case X86::ATOMUMAX64:
13450 case X86::ATOMUMIN8:
13451 case X86::ATOMUMIN16:
13452 case X86::ATOMUMIN32:
13453 case X86::ATOMUMIN64:
13454 return EmitAtomicLoadArith(MI, BB);
13456 // This group does 64-bit operations on a 32-bit host.
13457 case X86::ATOMAND6432:
13458 case X86::ATOMOR6432:
13459 case X86::ATOMXOR6432:
13460 case X86::ATOMNAND6432:
13461 case X86::ATOMADD6432:
13462 case X86::ATOMSUB6432:
13463 case X86::ATOMMAX6432:
13464 case X86::ATOMMIN6432:
13465 case X86::ATOMUMAX6432:
13466 case X86::ATOMUMIN6432:
13467 case X86::ATOMSWAP6432:
13468 return EmitAtomicLoadArith6432(MI, BB);
13470 case X86::VASTART_SAVE_XMM_REGS:
13471 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13473 case X86::VAARG_64:
13474 return EmitVAARG64WithCustomInserter(MI, BB);
13478 //===----------------------------------------------------------------------===//
13479 // X86 Optimization Hooks
13480 //===----------------------------------------------------------------------===//
13482 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13485 const SelectionDAG &DAG,
13486 unsigned Depth) const {
13487 unsigned BitWidth = KnownZero.getBitWidth();
13488 unsigned Opc = Op.getOpcode();
13489 assert((Opc >= ISD::BUILTIN_OP_END ||
13490 Opc == ISD::INTRINSIC_WO_CHAIN ||
13491 Opc == ISD::INTRINSIC_W_CHAIN ||
13492 Opc == ISD::INTRINSIC_VOID) &&
13493 "Should use MaskedValueIsZero if you don't know whether Op"
13494 " is a target node!");
13496 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
13510 // These nodes' second result is a boolean.
13511 if (Op.getResNo() == 0)
13514 case X86ISD::SETCC:
13515 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13517 case ISD::INTRINSIC_WO_CHAIN: {
13518 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13519 unsigned NumLoBits = 0;
13522 case Intrinsic::x86_sse_movmsk_ps:
13523 case Intrinsic::x86_avx_movmsk_ps_256:
13524 case Intrinsic::x86_sse2_movmsk_pd:
13525 case Intrinsic::x86_avx_movmsk_pd_256:
13526 case Intrinsic::x86_mmx_pmovmskb:
13527 case Intrinsic::x86_sse2_pmovmskb_128:
13528 case Intrinsic::x86_avx2_pmovmskb: {
13529 // High bits of movmskp{s|d}, pmovmskb are known zero.
13531 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13532 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
13533 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
13534 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
13535 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
13536 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
13537 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
13538 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
13540 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13549 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13550 unsigned Depth) const {
13551 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13552 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13553 return Op.getValueType().getScalarType().getSizeInBits();
13559 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13560 /// node is a GlobalAddress + offset.
13561 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13562 const GlobalValue* &GA,
13563 int64_t &Offset) const {
13564 if (N->getOpcode() == X86ISD::Wrapper) {
13565 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13566 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13567 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13571 return TargetLowering::isGAPlusOffset(N, GA, Offset);
13574 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13575 /// same as extracting the high 128-bit part of 256-bit vector and then
13576 /// inserting the result into the low part of a new 256-bit vector
13577 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13578 EVT VT = SVOp->getValueType(0);
13579 unsigned NumElems = VT.getVectorNumElements();
13581 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13582 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13583 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13584 SVOp->getMaskElt(j) >= 0)
13590 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13591 /// same as extracting the low 128-bit part of 256-bit vector and then
13592 /// inserting the result into the high part of a new 256-bit vector
13593 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13594 EVT VT = SVOp->getValueType(0);
13595 unsigned NumElems = VT.getVectorNumElements();
13597 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13598 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13599 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13600 SVOp->getMaskElt(j) >= 0)
13606 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13607 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13608 TargetLowering::DAGCombinerInfo &DCI,
13609 const X86Subtarget* Subtarget) {
13610 DebugLoc dl = N->getDebugLoc();
13611 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13612 SDValue V1 = SVOp->getOperand(0);
13613 SDValue V2 = SVOp->getOperand(1);
13614 EVT VT = SVOp->getValueType(0);
13615 unsigned NumElems = VT.getVectorNumElements();
13617 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13618 V2.getOpcode() == ISD::CONCAT_VECTORS) {
13622 // V UNDEF BUILD_VECTOR UNDEF
13624 // CONCAT_VECTOR CONCAT_VECTOR
13627 // RESULT: V + zero extended
13629 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13630 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13631 V1.getOperand(1).getOpcode() != ISD::UNDEF)
13634 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13637 // To match the shuffle mask, the first half of the mask should
13638 // be exactly the first vector, and all the rest a splat with the
13639 // first element of the second one.
13640 for (unsigned i = 0; i != NumElems/2; ++i)
13641 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13642 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13645 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13646 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13647 if (Ld->hasNUsesOfValue(1, 0)) {
13648 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13649 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13651 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13653 Ld->getPointerInfo(),
13654 Ld->getAlignment(),
13655 false/*isVolatile*/, true/*ReadMem*/,
13656 false/*WriteMem*/);
13657 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13661 // Emit a zeroed vector and insert the desired subvector on its
13663 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13664 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13665 return DCI.CombineTo(N, InsV);
13668 //===--------------------------------------------------------------------===//
13669 // Combine some shuffles into subvector extracts and inserts:
13672 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13673 if (isShuffleHigh128VectorInsertLow(SVOp)) {
13674 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13675 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13676 return DCI.CombineTo(N, InsV);
13679 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13680 if (isShuffleLow128VectorInsertHigh(SVOp)) {
13681 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13682 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13683 return DCI.CombineTo(N, InsV);
13689 /// PerformShuffleCombine - Performs several different shuffle combines.
13690 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13691 TargetLowering::DAGCombinerInfo &DCI,
13692 const X86Subtarget *Subtarget) {
13693 DebugLoc dl = N->getDebugLoc();
13694 EVT VT = N->getValueType(0);
13696 // Don't create instructions with illegal types after legalize types has run.
13697 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13698 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13701 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13702 if (Subtarget->hasAVX() && VT.is256BitVector() &&
13703 N->getOpcode() == ISD::VECTOR_SHUFFLE)
13704 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13706 // Only handle 128 wide vector from here on.
13707 if (!VT.is128BitVector())
13710 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13711 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13712 // consecutive, non-overlapping, and in the right order.
13713 SmallVector<SDValue, 16> Elts;
13714 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13715 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13717 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13721 /// PerformTruncateCombine - Converts truncate operation to
13722 /// a sequence of vector shuffle operations.
13723 /// It is possible when we truncate 256-bit vector to 128-bit vector
13724 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13725 TargetLowering::DAGCombinerInfo &DCI,
13726 const X86Subtarget *Subtarget) {
13727 if (!DCI.isBeforeLegalizeOps())
13730 if (!Subtarget->hasAVX())
13733 EVT VT = N->getValueType(0);
13734 SDValue Op = N->getOperand(0);
13735 EVT OpVT = Op.getValueType();
13736 DebugLoc dl = N->getDebugLoc();
13738 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13740 if (Subtarget->hasAVX2()) {
13741 // AVX2: v4i64 -> v4i32
13744 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13746 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13747 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13750 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13751 DAG.getIntPtrConstant(0));
13754 // AVX: v4i64 -> v4i32
13755 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13756 DAG.getIntPtrConstant(0));
13758 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13759 DAG.getIntPtrConstant(2));
13761 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13762 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13765 static const int ShufMask1[] = {0, 2, 0, 0};
13767 SDValue Undef = DAG.getUNDEF(VT);
13768 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13769 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13772 static const int ShufMask2[] = {0, 1, 4, 5};
13774 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13777 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13779 if (Subtarget->hasAVX2()) {
13780 // AVX2: v8i32 -> v8i16
13782 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13785 SmallVector<SDValue,32> pshufbMask;
13786 for (unsigned i = 0; i < 2; ++i) {
13787 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13788 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13789 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13790 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13791 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13792 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13793 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13794 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13795 for (unsigned j = 0; j < 8; ++j)
13796 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13798 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13799 &pshufbMask[0], 32);
13800 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13802 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13804 static const int ShufMask[] = {0, 2, -1, -1};
13805 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
13808 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13809 DAG.getIntPtrConstant(0));
13811 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13814 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13815 DAG.getIntPtrConstant(0));
13817 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13818 DAG.getIntPtrConstant(4));
13820 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13821 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13824 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13825 -1, -1, -1, -1, -1, -1, -1, -1};
13827 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13828 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13829 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13831 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13832 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13835 static const int ShufMask2[] = {0, 1, 4, 5};
13837 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13838 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13844 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13845 /// specific shuffle of a load can be folded into a single element load.
13846 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13847 /// shuffles have been customed lowered so we need to handle those here.
13848 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13849 TargetLowering::DAGCombinerInfo &DCI) {
13850 if (DCI.isBeforeLegalizeOps())
13853 SDValue InVec = N->getOperand(0);
13854 SDValue EltNo = N->getOperand(1);
13856 if (!isa<ConstantSDNode>(EltNo))
13859 EVT VT = InVec.getValueType();
13861 bool HasShuffleIntoBitcast = false;
13862 if (InVec.getOpcode() == ISD::BITCAST) {
13863 // Don't duplicate a load with other uses.
13864 if (!InVec.hasOneUse())
13866 EVT BCVT = InVec.getOperand(0).getValueType();
13867 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13869 InVec = InVec.getOperand(0);
13870 HasShuffleIntoBitcast = true;
13873 if (!isTargetShuffle(InVec.getOpcode()))
13876 // Don't duplicate a load with other uses.
13877 if (!InVec.hasOneUse())
13880 SmallVector<int, 16> ShuffleMask;
13882 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13886 // Select the input vector, guarding against out of range extract vector.
13887 unsigned NumElems = VT.getVectorNumElements();
13888 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13889 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13890 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13891 : InVec.getOperand(1);
13893 // If inputs to shuffle are the same for both ops, then allow 2 uses
13894 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13896 if (LdNode.getOpcode() == ISD::BITCAST) {
13897 // Don't duplicate a load with other uses.
13898 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13901 AllowedUses = 1; // only allow 1 load use if we have a bitcast
13902 LdNode = LdNode.getOperand(0);
13905 if (!ISD::isNormalLoad(LdNode.getNode()))
13908 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13910 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13913 if (HasShuffleIntoBitcast) {
13914 // If there's a bitcast before the shuffle, check if the load type and
13915 // alignment is valid.
13916 unsigned Align = LN0->getAlignment();
13917 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13918 unsigned NewAlign = TLI.getDataLayout()->
13919 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13921 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13925 // All checks match so transform back to vector_shuffle so that DAG combiner
13926 // can finish the job
13927 DebugLoc dl = N->getDebugLoc();
13929 // Create shuffle node taking into account the case that its a unary shuffle
13930 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13931 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13932 InVec.getOperand(0), Shuffle,
13934 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13935 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13939 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13940 /// generation and convert it from being a bunch of shuffles and extracts
13941 /// to a simple store and scalar loads to extract the elements.
13942 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13943 TargetLowering::DAGCombinerInfo &DCI) {
13944 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13945 if (NewOp.getNode())
13948 SDValue InputVector = N->getOperand(0);
13950 // Only operate on vectors of 4 elements, where the alternative shuffling
13951 // gets to be more expensive.
13952 if (InputVector.getValueType() != MVT::v4i32)
13955 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13956 // single use which is a sign-extend or zero-extend, and all elements are
13958 SmallVector<SDNode *, 4> Uses;
13959 unsigned ExtractedElements = 0;
13960 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13961 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13962 if (UI.getUse().getResNo() != InputVector.getResNo())
13965 SDNode *Extract = *UI;
13966 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13969 if (Extract->getValueType(0) != MVT::i32)
13971 if (!Extract->hasOneUse())
13973 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13974 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13976 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13979 // Record which element was extracted.
13980 ExtractedElements |=
13981 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13983 Uses.push_back(Extract);
13986 // If not all the elements were used, this may not be worthwhile.
13987 if (ExtractedElements != 15)
13990 // Ok, we've now decided to do the transformation.
13991 DebugLoc dl = InputVector.getDebugLoc();
13993 // Store the value to a temporary stack slot.
13994 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13995 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13996 MachinePointerInfo(), false, false, 0);
13998 // Replace each use (extract) with a load of the appropriate element.
13999 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14000 UE = Uses.end(); UI != UE; ++UI) {
14001 SDNode *Extract = *UI;
14003 // cOMpute the element's address.
14004 SDValue Idx = Extract->getOperand(1);
14006 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14007 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14008 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14009 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14011 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14012 StackPtr, OffsetVal);
14014 // Load the scalar.
14015 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14016 ScalarAddr, MachinePointerInfo(),
14017 false, false, false, 0);
14019 // Replace the exact with the load.
14020 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14023 // The replacement was made in place; don't return anything.
14027 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14029 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14030 TargetLowering::DAGCombinerInfo &DCI,
14031 const X86Subtarget *Subtarget) {
14032 DebugLoc DL = N->getDebugLoc();
14033 SDValue Cond = N->getOperand(0);
14034 // Get the LHS/RHS of the select.
14035 SDValue LHS = N->getOperand(1);
14036 SDValue RHS = N->getOperand(2);
14037 EVT VT = LHS.getValueType();
14039 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14040 // instructions match the semantics of the common C idiom x<y?x:y but not
14041 // x<=y?x:y, because of how they handle negative zero (which can be
14042 // ignored in unsafe-math mode).
14043 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14044 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14045 (Subtarget->hasSSE2() ||
14046 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14047 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14049 unsigned Opcode = 0;
14050 // Check for x CC y ? x : y.
14051 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14052 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14056 // Converting this to a min would handle NaNs incorrectly, and swapping
14057 // the operands would cause it to handle comparisons between positive
14058 // and negative zero incorrectly.
14059 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14060 if (!DAG.getTarget().Options.UnsafeFPMath &&
14061 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14063 std::swap(LHS, RHS);
14065 Opcode = X86ISD::FMIN;
14068 // Converting this to a min would handle comparisons between positive
14069 // and negative zero incorrectly.
14070 if (!DAG.getTarget().Options.UnsafeFPMath &&
14071 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14073 Opcode = X86ISD::FMIN;
14076 // Converting this to a min would handle both negative zeros and NaNs
14077 // incorrectly, but we can swap the operands to fix both.
14078 std::swap(LHS, RHS);
14082 Opcode = X86ISD::FMIN;
14086 // Converting this to a max would handle comparisons between positive
14087 // and negative zero incorrectly.
14088 if (!DAG.getTarget().Options.UnsafeFPMath &&
14089 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14091 Opcode = X86ISD::FMAX;
14094 // Converting this to a max would handle NaNs incorrectly, and swapping
14095 // the operands would cause it to handle comparisons between positive
14096 // and negative zero incorrectly.
14097 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14098 if (!DAG.getTarget().Options.UnsafeFPMath &&
14099 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14101 std::swap(LHS, RHS);
14103 Opcode = X86ISD::FMAX;
14106 // Converting this to a max would handle both negative zeros and NaNs
14107 // incorrectly, but we can swap the operands to fix both.
14108 std::swap(LHS, RHS);
14112 Opcode = X86ISD::FMAX;
14115 // Check for x CC y ? y : x -- a min/max with reversed arms.
14116 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14117 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14121 // Converting this to a min would handle comparisons between positive
14122 // and negative zero incorrectly, and swapping the operands would
14123 // cause it to handle NaNs incorrectly.
14124 if (!DAG.getTarget().Options.UnsafeFPMath &&
14125 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14126 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14128 std::swap(LHS, RHS);
14130 Opcode = X86ISD::FMIN;
14133 // Converting this to a min would handle NaNs incorrectly.
14134 if (!DAG.getTarget().Options.UnsafeFPMath &&
14135 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14137 Opcode = X86ISD::FMIN;
14140 // Converting this to a min would handle both negative zeros and NaNs
14141 // incorrectly, but we can swap the operands to fix both.
14142 std::swap(LHS, RHS);
14146 Opcode = X86ISD::FMIN;
14150 // Converting this to a max would handle NaNs incorrectly.
14151 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14153 Opcode = X86ISD::FMAX;
14156 // Converting this to a max would handle comparisons between positive
14157 // and negative zero incorrectly, and swapping the operands would
14158 // cause it to handle NaNs incorrectly.
14159 if (!DAG.getTarget().Options.UnsafeFPMath &&
14160 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14161 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14163 std::swap(LHS, RHS);
14165 Opcode = X86ISD::FMAX;
14168 // Converting this to a max would handle both negative zeros and NaNs
14169 // incorrectly, but we can swap the operands to fix both.
14170 std::swap(LHS, RHS);
14174 Opcode = X86ISD::FMAX;
14180 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14183 // If this is a select between two integer constants, try to do some
14185 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14186 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14187 // Don't do this for crazy integer types.
14188 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14189 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14190 // so that TrueC (the true value) is larger than FalseC.
14191 bool NeedsCondInvert = false;
14193 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14194 // Efficiently invertible.
14195 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
14196 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
14197 isa<ConstantSDNode>(Cond.getOperand(1))))) {
14198 NeedsCondInvert = true;
14199 std::swap(TrueC, FalseC);
14202 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
14203 if (FalseC->getAPIntValue() == 0 &&
14204 TrueC->getAPIntValue().isPowerOf2()) {
14205 if (NeedsCondInvert) // Invert the condition if needed.
14206 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14207 DAG.getConstant(1, Cond.getValueType()));
14209 // Zero extend the condition if needed.
14210 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14212 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14213 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14214 DAG.getConstant(ShAmt, MVT::i8));
14217 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14218 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14219 if (NeedsCondInvert) // Invert the condition if needed.
14220 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14221 DAG.getConstant(1, Cond.getValueType()));
14223 // Zero extend the condition if needed.
14224 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14225 FalseC->getValueType(0), Cond);
14226 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14227 SDValue(FalseC, 0));
14230 // Optimize cases that will turn into an LEA instruction. This requires
14231 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14232 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14233 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14234 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14236 bool isFastMultiplier = false;
14238 switch ((unsigned char)Diff) {
14240 case 1: // result = add base, cond
14241 case 2: // result = lea base( , cond*2)
14242 case 3: // result = lea base(cond, cond*2)
14243 case 4: // result = lea base( , cond*4)
14244 case 5: // result = lea base(cond, cond*4)
14245 case 8: // result = lea base( , cond*8)
14246 case 9: // result = lea base(cond, cond*8)
14247 isFastMultiplier = true;
14252 if (isFastMultiplier) {
14253 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14254 if (NeedsCondInvert) // Invert the condition if needed.
14255 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14256 DAG.getConstant(1, Cond.getValueType()));
14258 // Zero extend the condition if needed.
14259 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14261 // Scale the condition by the difference.
14263 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14264 DAG.getConstant(Diff, Cond.getValueType()));
14266 // Add the base if non-zero.
14267 if (FalseC->getAPIntValue() != 0)
14268 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14269 SDValue(FalseC, 0));
14276 // Canonicalize max and min:
14277 // (x > y) ? x : y -> (x >= y) ? x : y
14278 // (x < y) ? x : y -> (x <= y) ? x : y
14279 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14280 // the need for an extra compare
14281 // against zero. e.g.
14282 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14284 // testl %edi, %edi
14286 // cmovgl %edi, %eax
14290 // cmovsl %eax, %edi
14291 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14292 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14293 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14294 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14299 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14300 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14301 Cond.getOperand(0), Cond.getOperand(1), NewCC);
14302 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14307 // If we know that this node is legal then we know that it is going to be
14308 // matched by one of the SSE/AVX BLEND instructions. These instructions only
14309 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14310 // to simplify previous instructions.
14311 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14312 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14313 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14314 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14316 // Don't optimize vector selects that map to mask-registers.
14320 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14321 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14323 APInt KnownZero, KnownOne;
14324 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14325 DCI.isBeforeLegalizeOps());
14326 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14327 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14328 DCI.CommitTargetLoweringOpt(TLO);
14334 // Check whether a boolean test is testing a boolean value generated by
14335 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14338 // Simplify the following patterns:
14339 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14340 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14341 // to (Op EFLAGS Cond)
14343 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14344 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14345 // to (Op EFLAGS !Cond)
14347 // where Op could be BRCOND or CMOV.
14349 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14350 // Quit if not CMP and SUB with its value result used.
14351 if (Cmp.getOpcode() != X86ISD::CMP &&
14352 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14355 // Quit if not used as a boolean value.
14356 if (CC != X86::COND_E && CC != X86::COND_NE)
14359 // Check CMP operands. One of them should be 0 or 1 and the other should be
14360 // an SetCC or extended from it.
14361 SDValue Op1 = Cmp.getOperand(0);
14362 SDValue Op2 = Cmp.getOperand(1);
14365 const ConstantSDNode* C = 0;
14366 bool needOppositeCond = (CC == X86::COND_E);
14368 if ((C = dyn_cast<ConstantSDNode>(Op1)))
14370 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14372 else // Quit if all operands are not constants.
14375 if (C->getZExtValue() == 1)
14376 needOppositeCond = !needOppositeCond;
14377 else if (C->getZExtValue() != 0)
14378 // Quit if the constant is neither 0 or 1.
14381 // Skip 'zext' node.
14382 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14383 SetCC = SetCC.getOperand(0);
14385 switch (SetCC.getOpcode()) {
14386 case X86ISD::SETCC:
14387 // Set the condition code or opposite one if necessary.
14388 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14389 if (needOppositeCond)
14390 CC = X86::GetOppositeBranchCondition(CC);
14391 return SetCC.getOperand(1);
14392 case X86ISD::CMOV: {
14393 // Check whether false/true value has canonical one, i.e. 0 or 1.
14394 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14395 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14396 // Quit if true value is not a constant.
14399 // Quit if false value is not a constant.
14401 // A special case for rdrand, where 0 is set if false cond is found.
14402 SDValue Op = SetCC.getOperand(0);
14403 if (Op.getOpcode() != X86ISD::RDRAND)
14406 // Quit if false value is not the constant 0 or 1.
14407 bool FValIsFalse = true;
14408 if (FVal && FVal->getZExtValue() != 0) {
14409 if (FVal->getZExtValue() != 1)
14411 // If FVal is 1, opposite cond is needed.
14412 needOppositeCond = !needOppositeCond;
14413 FValIsFalse = false;
14415 // Quit if TVal is not the constant opposite of FVal.
14416 if (FValIsFalse && TVal->getZExtValue() != 1)
14418 if (!FValIsFalse && TVal->getZExtValue() != 0)
14420 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14421 if (needOppositeCond)
14422 CC = X86::GetOppositeBranchCondition(CC);
14423 return SetCC.getOperand(3);
14430 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14431 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14432 TargetLowering::DAGCombinerInfo &DCI,
14433 const X86Subtarget *Subtarget) {
14434 DebugLoc DL = N->getDebugLoc();
14436 // If the flag operand isn't dead, don't touch this CMOV.
14437 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14440 SDValue FalseOp = N->getOperand(0);
14441 SDValue TrueOp = N->getOperand(1);
14442 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14443 SDValue Cond = N->getOperand(3);
14445 if (CC == X86::COND_E || CC == X86::COND_NE) {
14446 switch (Cond.getOpcode()) {
14450 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14451 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14452 return (CC == X86::COND_E) ? FalseOp : TrueOp;
14458 Flags = checkBoolTestSetCCCombine(Cond, CC);
14459 if (Flags.getNode() &&
14460 // Extra check as FCMOV only supports a subset of X86 cond.
14461 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14462 SDValue Ops[] = { FalseOp, TrueOp,
14463 DAG.getConstant(CC, MVT::i8), Flags };
14464 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14465 Ops, array_lengthof(Ops));
14468 // If this is a select between two integer constants, try to do some
14469 // optimizations. Note that the operands are ordered the opposite of SELECT
14471 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14472 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14473 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14474 // larger than FalseC (the false value).
14475 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14476 CC = X86::GetOppositeBranchCondition(CC);
14477 std::swap(TrueC, FalseC);
14480 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
14481 // This is efficient for any integer data type (including i8/i16) and
14483 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14484 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14485 DAG.getConstant(CC, MVT::i8), Cond);
14487 // Zero extend the condition if needed.
14488 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14490 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14491 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14492 DAG.getConstant(ShAmt, MVT::i8));
14493 if (N->getNumValues() == 2) // Dead flag value?
14494 return DCI.CombineTo(N, Cond, SDValue());
14498 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
14499 // for any integer data type, including i8/i16.
14500 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14501 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14502 DAG.getConstant(CC, MVT::i8), Cond);
14504 // Zero extend the condition if needed.
14505 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14506 FalseC->getValueType(0), Cond);
14507 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14508 SDValue(FalseC, 0));
14510 if (N->getNumValues() == 2) // Dead flag value?
14511 return DCI.CombineTo(N, Cond, SDValue());
14515 // Optimize cases that will turn into an LEA instruction. This requires
14516 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14517 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14518 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14519 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14521 bool isFastMultiplier = false;
14523 switch ((unsigned char)Diff) {
14525 case 1: // result = add base, cond
14526 case 2: // result = lea base( , cond*2)
14527 case 3: // result = lea base(cond, cond*2)
14528 case 4: // result = lea base( , cond*4)
14529 case 5: // result = lea base(cond, cond*4)
14530 case 8: // result = lea base( , cond*8)
14531 case 9: // result = lea base(cond, cond*8)
14532 isFastMultiplier = true;
14537 if (isFastMultiplier) {
14538 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14539 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14540 DAG.getConstant(CC, MVT::i8), Cond);
14541 // Zero extend the condition if needed.
14542 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14544 // Scale the condition by the difference.
14546 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14547 DAG.getConstant(Diff, Cond.getValueType()));
14549 // Add the base if non-zero.
14550 if (FalseC->getAPIntValue() != 0)
14551 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14552 SDValue(FalseC, 0));
14553 if (N->getNumValues() == 2) // Dead flag value?
14554 return DCI.CombineTo(N, Cond, SDValue());
14564 /// PerformMulCombine - Optimize a single multiply with constant into two
14565 /// in order to implement it with two cheaper instructions, e.g.
14566 /// LEA + SHL, LEA + LEA.
14567 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14568 TargetLowering::DAGCombinerInfo &DCI) {
14569 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14572 EVT VT = N->getValueType(0);
14573 if (VT != MVT::i64)
14576 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14579 uint64_t MulAmt = C->getZExtValue();
14580 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14583 uint64_t MulAmt1 = 0;
14584 uint64_t MulAmt2 = 0;
14585 if ((MulAmt % 9) == 0) {
14587 MulAmt2 = MulAmt / 9;
14588 } else if ((MulAmt % 5) == 0) {
14590 MulAmt2 = MulAmt / 5;
14591 } else if ((MulAmt % 3) == 0) {
14593 MulAmt2 = MulAmt / 3;
14596 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14597 DebugLoc DL = N->getDebugLoc();
14599 if (isPowerOf2_64(MulAmt2) &&
14600 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14601 // If second multiplifer is pow2, issue it first. We want the multiply by
14602 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14604 std::swap(MulAmt1, MulAmt2);
14607 if (isPowerOf2_64(MulAmt1))
14608 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14609 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14611 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14612 DAG.getConstant(MulAmt1, VT));
14614 if (isPowerOf2_64(MulAmt2))
14615 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14616 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14618 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14619 DAG.getConstant(MulAmt2, VT));
14621 // Do not add new nodes to DAG combiner worklist.
14622 DCI.CombineTo(N, NewMul, false);
14627 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14628 SDValue N0 = N->getOperand(0);
14629 SDValue N1 = N->getOperand(1);
14630 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14631 EVT VT = N0.getValueType();
14633 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14634 // since the result of setcc_c is all zero's or all ones.
14635 if (VT.isInteger() && !VT.isVector() &&
14636 N1C && N0.getOpcode() == ISD::AND &&
14637 N0.getOperand(1).getOpcode() == ISD::Constant) {
14638 SDValue N00 = N0.getOperand(0);
14639 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14640 ((N00.getOpcode() == ISD::ANY_EXTEND ||
14641 N00.getOpcode() == ISD::ZERO_EXTEND) &&
14642 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14643 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14644 APInt ShAmt = N1C->getAPIntValue();
14645 Mask = Mask.shl(ShAmt);
14647 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14648 N00, DAG.getConstant(Mask, VT));
14653 // Hardware support for vector shifts is sparse which makes us scalarize the
14654 // vector operations in many cases. Also, on sandybridge ADD is faster than
14656 // (shl V, 1) -> add V,V
14657 if (isSplatVector(N1.getNode())) {
14658 assert(N0.getValueType().isVector() && "Invalid vector shift type");
14659 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14660 // We shift all of the values by one. In many cases we do not have
14661 // hardware support for this operation. This is better expressed as an ADD
14663 if (N1C && (1 == N1C->getZExtValue())) {
14664 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14671 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14673 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14674 TargetLowering::DAGCombinerInfo &DCI,
14675 const X86Subtarget *Subtarget) {
14676 EVT VT = N->getValueType(0);
14677 if (N->getOpcode() == ISD::SHL) {
14678 SDValue V = PerformSHLCombine(N, DAG);
14679 if (V.getNode()) return V;
14682 // On X86 with SSE2 support, we can transform this to a vector shift if
14683 // all elements are shifted by the same amount. We can't do this in legalize
14684 // because the a constant vector is typically transformed to a constant pool
14685 // so we have no knowledge of the shift amount.
14686 if (!Subtarget->hasSSE2())
14689 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14690 (!Subtarget->hasAVX2() ||
14691 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14694 SDValue ShAmtOp = N->getOperand(1);
14695 EVT EltVT = VT.getVectorElementType();
14696 DebugLoc DL = N->getDebugLoc();
14697 SDValue BaseShAmt = SDValue();
14698 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14699 unsigned NumElts = VT.getVectorNumElements();
14701 for (; i != NumElts; ++i) {
14702 SDValue Arg = ShAmtOp.getOperand(i);
14703 if (Arg.getOpcode() == ISD::UNDEF) continue;
14707 // Handle the case where the build_vector is all undef
14708 // FIXME: Should DAG allow this?
14712 for (; i != NumElts; ++i) {
14713 SDValue Arg = ShAmtOp.getOperand(i);
14714 if (Arg.getOpcode() == ISD::UNDEF) continue;
14715 if (Arg != BaseShAmt) {
14719 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14720 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14721 SDValue InVec = ShAmtOp.getOperand(0);
14722 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14723 unsigned NumElts = InVec.getValueType().getVectorNumElements();
14725 for (; i != NumElts; ++i) {
14726 SDValue Arg = InVec.getOperand(i);
14727 if (Arg.getOpcode() == ISD::UNDEF) continue;
14731 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14732 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14733 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14734 if (C->getZExtValue() == SplatIdx)
14735 BaseShAmt = InVec.getOperand(1);
14738 if (BaseShAmt.getNode() == 0) {
14739 // Don't create instructions with illegal types after legalize
14741 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14742 !DCI.isBeforeLegalize())
14745 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14746 DAG.getIntPtrConstant(0));
14751 // The shift amount is an i32.
14752 if (EltVT.bitsGT(MVT::i32))
14753 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14754 else if (EltVT.bitsLT(MVT::i32))
14755 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14757 // The shift amount is identical so we can do a vector shift.
14758 SDValue ValOp = N->getOperand(0);
14759 switch (N->getOpcode()) {
14761 llvm_unreachable("Unknown shift opcode!");
14763 switch (VT.getSimpleVT().SimpleTy) {
14764 default: return SDValue();
14771 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14774 switch (VT.getSimpleVT().SimpleTy) {
14775 default: return SDValue();
14780 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14783 switch (VT.getSimpleVT().SimpleTy) {
14784 default: return SDValue();
14791 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14797 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
14798 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14799 // and friends. Likewise for OR -> CMPNEQSS.
14800 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14801 TargetLowering::DAGCombinerInfo &DCI,
14802 const X86Subtarget *Subtarget) {
14805 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14806 // we're requiring SSE2 for both.
14807 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14808 SDValue N0 = N->getOperand(0);
14809 SDValue N1 = N->getOperand(1);
14810 SDValue CMP0 = N0->getOperand(1);
14811 SDValue CMP1 = N1->getOperand(1);
14812 DebugLoc DL = N->getDebugLoc();
14814 // The SETCCs should both refer to the same CMP.
14815 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14818 SDValue CMP00 = CMP0->getOperand(0);
14819 SDValue CMP01 = CMP0->getOperand(1);
14820 EVT VT = CMP00.getValueType();
14822 if (VT == MVT::f32 || VT == MVT::f64) {
14823 bool ExpectingFlags = false;
14824 // Check for any users that want flags:
14825 for (SDNode::use_iterator UI = N->use_begin(),
14827 !ExpectingFlags && UI != UE; ++UI)
14828 switch (UI->getOpcode()) {
14833 ExpectingFlags = true;
14835 case ISD::CopyToReg:
14836 case ISD::SIGN_EXTEND:
14837 case ISD::ZERO_EXTEND:
14838 case ISD::ANY_EXTEND:
14842 if (!ExpectingFlags) {
14843 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14844 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14846 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14847 X86::CondCode tmp = cc0;
14852 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
14853 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14854 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14855 X86ISD::NodeType NTOperator = is64BitFP ?
14856 X86ISD::FSETCCsd : X86ISD::FSETCCss;
14857 // FIXME: need symbolic constants for these magic numbers.
14858 // See X86ATTInstPrinter.cpp:printSSECC().
14859 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14860 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14861 DAG.getConstant(x86cc, MVT::i8));
14862 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14864 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14865 DAG.getConstant(1, MVT::i32));
14866 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14867 return OneBitOfTruth;
14875 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14876 /// so it can be folded inside ANDNP.
14877 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14878 EVT VT = N->getValueType(0);
14880 // Match direct AllOnes for 128 and 256-bit vectors
14881 if (ISD::isBuildVectorAllOnes(N))
14884 // Look through a bit convert.
14885 if (N->getOpcode() == ISD::BITCAST)
14886 N = N->getOperand(0).getNode();
14888 // Sometimes the operand may come from a insert_subvector building a 256-bit
14890 if (VT.is256BitVector() &&
14891 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14892 SDValue V1 = N->getOperand(0);
14893 SDValue V2 = N->getOperand(1);
14895 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14896 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14897 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14898 ISD::isBuildVectorAllOnes(V2.getNode()))
14905 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14906 TargetLowering::DAGCombinerInfo &DCI,
14907 const X86Subtarget *Subtarget) {
14908 if (DCI.isBeforeLegalizeOps())
14911 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14915 EVT VT = N->getValueType(0);
14917 // Create ANDN, BLSI, and BLSR instructions
14918 // BLSI is X & (-X)
14919 // BLSR is X & (X-1)
14920 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14921 SDValue N0 = N->getOperand(0);
14922 SDValue N1 = N->getOperand(1);
14923 DebugLoc DL = N->getDebugLoc();
14925 // Check LHS for not
14926 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14927 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14928 // Check RHS for not
14929 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14930 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14932 // Check LHS for neg
14933 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14934 isZero(N0.getOperand(0)))
14935 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14937 // Check RHS for neg
14938 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14939 isZero(N1.getOperand(0)))
14940 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14942 // Check LHS for X-1
14943 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14944 isAllOnes(N0.getOperand(1)))
14945 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14947 // Check RHS for X-1
14948 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14949 isAllOnes(N1.getOperand(1)))
14950 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14955 // Want to form ANDNP nodes:
14956 // 1) In the hopes of then easily combining them with OR and AND nodes
14957 // to form PBLEND/PSIGN.
14958 // 2) To match ANDN packed intrinsics
14959 if (VT != MVT::v2i64 && VT != MVT::v4i64)
14962 SDValue N0 = N->getOperand(0);
14963 SDValue N1 = N->getOperand(1);
14964 DebugLoc DL = N->getDebugLoc();
14966 // Check LHS for vnot
14967 if (N0.getOpcode() == ISD::XOR &&
14968 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14969 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14970 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14972 // Check RHS for vnot
14973 if (N1.getOpcode() == ISD::XOR &&
14974 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14975 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14976 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14981 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14982 TargetLowering::DAGCombinerInfo &DCI,
14983 const X86Subtarget *Subtarget) {
14984 if (DCI.isBeforeLegalizeOps())
14987 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14991 EVT VT = N->getValueType(0);
14993 SDValue N0 = N->getOperand(0);
14994 SDValue N1 = N->getOperand(1);
14996 // look for psign/blend
14997 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14998 if (!Subtarget->hasSSSE3() ||
14999 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
15002 // Canonicalize pandn to RHS
15003 if (N0.getOpcode() == X86ISD::ANDNP)
15005 // or (and (m, y), (pandn m, x))
15006 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15007 SDValue Mask = N1.getOperand(0);
15008 SDValue X = N1.getOperand(1);
15010 if (N0.getOperand(0) == Mask)
15011 Y = N0.getOperand(1);
15012 if (N0.getOperand(1) == Mask)
15013 Y = N0.getOperand(0);
15015 // Check to see if the mask appeared in both the AND and ANDNP and
15019 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15020 // Look through mask bitcast.
15021 if (Mask.getOpcode() == ISD::BITCAST)
15022 Mask = Mask.getOperand(0);
15023 if (X.getOpcode() == ISD::BITCAST)
15024 X = X.getOperand(0);
15025 if (Y.getOpcode() == ISD::BITCAST)
15026 Y = Y.getOperand(0);
15028 EVT MaskVT = Mask.getValueType();
15030 // Validate that the Mask operand is a vector sra node.
15031 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15032 // there is no psrai.b
15033 if (Mask.getOpcode() != X86ISD::VSRAI)
15036 // Check that the SRA is all signbits.
15037 SDValue SraC = Mask.getOperand(1);
15038 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
15039 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15040 if ((SraAmt + 1) != EltBits)
15043 DebugLoc DL = N->getDebugLoc();
15045 // Now we know we at least have a plendvb with the mask val. See if
15046 // we can form a psignb/w/d.
15047 // psign = x.type == y.type == mask.type && y = sub(0, x);
15048 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15049 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15050 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15051 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15052 "Unsupported VT for PSIGN");
15053 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15054 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15056 // PBLENDVB only available on SSE 4.1
15057 if (!Subtarget->hasSSE41())
15060 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15062 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15063 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15064 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15065 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15066 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15070 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15073 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15074 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15076 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15078 if (!N0.hasOneUse() || !N1.hasOneUse())
15081 SDValue ShAmt0 = N0.getOperand(1);
15082 if (ShAmt0.getValueType() != MVT::i8)
15084 SDValue ShAmt1 = N1.getOperand(1);
15085 if (ShAmt1.getValueType() != MVT::i8)
15087 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15088 ShAmt0 = ShAmt0.getOperand(0);
15089 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15090 ShAmt1 = ShAmt1.getOperand(0);
15092 DebugLoc DL = N->getDebugLoc();
15093 unsigned Opc = X86ISD::SHLD;
15094 SDValue Op0 = N0.getOperand(0);
15095 SDValue Op1 = N1.getOperand(0);
15096 if (ShAmt0.getOpcode() == ISD::SUB) {
15097 Opc = X86ISD::SHRD;
15098 std::swap(Op0, Op1);
15099 std::swap(ShAmt0, ShAmt1);
15102 unsigned Bits = VT.getSizeInBits();
15103 if (ShAmt1.getOpcode() == ISD::SUB) {
15104 SDValue Sum = ShAmt1.getOperand(0);
15105 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15106 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15107 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15108 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15109 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15110 return DAG.getNode(Opc, DL, VT,
15112 DAG.getNode(ISD::TRUNCATE, DL,
15115 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15116 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15118 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15119 return DAG.getNode(Opc, DL, VT,
15120 N0.getOperand(0), N1.getOperand(0),
15121 DAG.getNode(ISD::TRUNCATE, DL,
15128 // Generate NEG and CMOV for integer abs.
15129 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15130 EVT VT = N->getValueType(0);
15132 // Since X86 does not have CMOV for 8-bit integer, we don't convert
15133 // 8-bit integer abs to NEG and CMOV.
15134 if (VT.isInteger() && VT.getSizeInBits() == 8)
15137 SDValue N0 = N->getOperand(0);
15138 SDValue N1 = N->getOperand(1);
15139 DebugLoc DL = N->getDebugLoc();
15141 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15142 // and change it to SUB and CMOV.
15143 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15144 N0.getOpcode() == ISD::ADD &&
15145 N0.getOperand(1) == N1 &&
15146 N1.getOpcode() == ISD::SRA &&
15147 N1.getOperand(0) == N0.getOperand(0))
15148 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15149 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15150 // Generate SUB & CMOV.
15151 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15152 DAG.getConstant(0, VT), N0.getOperand(0));
15154 SDValue Ops[] = { N0.getOperand(0), Neg,
15155 DAG.getConstant(X86::COND_GE, MVT::i8),
15156 SDValue(Neg.getNode(), 1) };
15157 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15158 Ops, array_lengthof(Ops));
15163 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15164 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15165 TargetLowering::DAGCombinerInfo &DCI,
15166 const X86Subtarget *Subtarget) {
15167 if (DCI.isBeforeLegalizeOps())
15170 if (Subtarget->hasCMov()) {
15171 SDValue RV = performIntegerAbsCombine(N, DAG);
15176 // Try forming BMI if it is available.
15177 if (!Subtarget->hasBMI())
15180 EVT VT = N->getValueType(0);
15182 if (VT != MVT::i32 && VT != MVT::i64)
15185 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15187 // Create BLSMSK instructions by finding X ^ (X-1)
15188 SDValue N0 = N->getOperand(0);
15189 SDValue N1 = N->getOperand(1);
15190 DebugLoc DL = N->getDebugLoc();
15192 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15193 isAllOnes(N0.getOperand(1)))
15194 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15196 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15197 isAllOnes(N1.getOperand(1)))
15198 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15203 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15204 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15205 TargetLowering::DAGCombinerInfo &DCI,
15206 const X86Subtarget *Subtarget) {
15207 LoadSDNode *Ld = cast<LoadSDNode>(N);
15208 EVT RegVT = Ld->getValueType(0);
15209 EVT MemVT = Ld->getMemoryVT();
15210 DebugLoc dl = Ld->getDebugLoc();
15211 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15213 ISD::LoadExtType Ext = Ld->getExtensionType();
15215 // If this is a vector EXT Load then attempt to optimize it using a
15216 // shuffle. We need SSE4 for the shuffles.
15217 // TODO: It is possible to support ZExt by zeroing the undef values
15218 // during the shuffle phase or after the shuffle.
15219 if (RegVT.isVector() && RegVT.isInteger() &&
15220 Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
15221 assert(MemVT != RegVT && "Cannot extend to the same type");
15222 assert(MemVT.isVector() && "Must load a vector from memory");
15224 unsigned NumElems = RegVT.getVectorNumElements();
15225 unsigned RegSz = RegVT.getSizeInBits();
15226 unsigned MemSz = MemVT.getSizeInBits();
15227 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15229 // All sizes must be a power of two.
15230 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15233 // Attempt to load the original value using scalar loads.
15234 // Find the largest scalar type that divides the total loaded size.
15235 MVT SclrLoadTy = MVT::i8;
15236 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15237 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15238 MVT Tp = (MVT::SimpleValueType)tp;
15239 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15244 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15245 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15247 SclrLoadTy = MVT::f64;
15249 // Calculate the number of scalar loads that we need to perform
15250 // in order to load our vector from memory.
15251 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15253 // Represent our vector as a sequence of elements which are the
15254 // largest scalar that we can load.
15255 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15256 RegSz/SclrLoadTy.getSizeInBits());
15258 // Represent the data using the same element type that is stored in
15259 // memory. In practice, we ''widen'' MemVT.
15260 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15261 RegSz/MemVT.getScalarType().getSizeInBits());
15263 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15264 "Invalid vector type");
15266 // We can't shuffle using an illegal type.
15267 if (!TLI.isTypeLegal(WideVecVT))
15270 SmallVector<SDValue, 8> Chains;
15271 SDValue Ptr = Ld->getBasePtr();
15272 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15273 TLI.getPointerTy());
15274 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15276 for (unsigned i = 0; i < NumLoads; ++i) {
15277 // Perform a single load.
15278 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15279 Ptr, Ld->getPointerInfo(),
15280 Ld->isVolatile(), Ld->isNonTemporal(),
15281 Ld->isInvariant(), Ld->getAlignment());
15282 Chains.push_back(ScalarLoad.getValue(1));
15283 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15284 // another round of DAGCombining.
15286 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15288 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15289 ScalarLoad, DAG.getIntPtrConstant(i));
15291 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15294 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15297 // Bitcast the loaded value to a vector of the original element type, in
15298 // the size of the target vector type.
15299 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15300 unsigned SizeRatio = RegSz/MemSz;
15302 // Redistribute the loaded elements into the different locations.
15303 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15304 for (unsigned i = 0; i != NumElems; ++i)
15305 ShuffleVec[i*SizeRatio] = i;
15307 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15308 DAG.getUNDEF(WideVecVT),
15311 // Bitcast to the requested type.
15312 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15313 // Replace the original load with the new sequence
15314 // and return the new chain.
15315 return DCI.CombineTo(N, Shuff, TF, true);
15321 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15322 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15323 const X86Subtarget *Subtarget) {
15324 StoreSDNode *St = cast<StoreSDNode>(N);
15325 EVT VT = St->getValue().getValueType();
15326 EVT StVT = St->getMemoryVT();
15327 DebugLoc dl = St->getDebugLoc();
15328 SDValue StoredVal = St->getOperand(1);
15329 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15331 // If we are saving a concatenation of two XMM registers, perform two stores.
15332 // On Sandy Bridge, 256-bit memory operations are executed by two
15333 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15334 // memory operation.
15335 if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15336 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15337 StoredVal.getNumOperands() == 2) {
15338 SDValue Value0 = StoredVal.getOperand(0);
15339 SDValue Value1 = StoredVal.getOperand(1);
15341 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15342 SDValue Ptr0 = St->getBasePtr();
15343 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15345 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15346 St->getPointerInfo(), St->isVolatile(),
15347 St->isNonTemporal(), St->getAlignment());
15348 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15349 St->getPointerInfo(), St->isVolatile(),
15350 St->isNonTemporal(), St->getAlignment());
15351 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15354 // Optimize trunc store (of multiple scalars) to shuffle and store.
15355 // First, pack all of the elements in one place. Next, store to memory
15356 // in fewer chunks.
15357 if (St->isTruncatingStore() && VT.isVector()) {
15358 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15359 unsigned NumElems = VT.getVectorNumElements();
15360 assert(StVT != VT && "Cannot truncate to the same type");
15361 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15362 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15364 // From, To sizes and ElemCount must be pow of two
15365 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15366 // We are going to use the original vector elt for storing.
15367 // Accumulated smaller vector elements must be a multiple of the store size.
15368 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15370 unsigned SizeRatio = FromSz / ToSz;
15372 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15374 // Create a type on which we perform the shuffle
15375 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15376 StVT.getScalarType(), NumElems*SizeRatio);
15378 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15380 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15381 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15382 for (unsigned i = 0; i != NumElems; ++i)
15383 ShuffleVec[i] = i * SizeRatio;
15385 // Can't shuffle using an illegal type.
15386 if (!TLI.isTypeLegal(WideVecVT))
15389 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15390 DAG.getUNDEF(WideVecVT),
15392 // At this point all of the data is stored at the bottom of the
15393 // register. We now need to save it to mem.
15395 // Find the largest store unit
15396 MVT StoreType = MVT::i8;
15397 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15398 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15399 MVT Tp = (MVT::SimpleValueType)tp;
15400 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15404 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15405 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15406 (64 <= NumElems * ToSz))
15407 StoreType = MVT::f64;
15409 // Bitcast the original vector into a vector of store-size units
15410 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15411 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15412 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15413 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15414 SmallVector<SDValue, 8> Chains;
15415 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15416 TLI.getPointerTy());
15417 SDValue Ptr = St->getBasePtr();
15419 // Perform one or more big stores into memory.
15420 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15421 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15422 StoreType, ShuffWide,
15423 DAG.getIntPtrConstant(i));
15424 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15425 St->getPointerInfo(), St->isVolatile(),
15426 St->isNonTemporal(), St->getAlignment());
15427 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15428 Chains.push_back(Ch);
15431 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15436 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
15437 // the FP state in cases where an emms may be missing.
15438 // A preferable solution to the general problem is to figure out the right
15439 // places to insert EMMS. This qualifies as a quick hack.
15441 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15442 if (VT.getSizeInBits() != 64)
15445 const Function *F = DAG.getMachineFunction().getFunction();
15446 bool NoImplicitFloatOps = F->getFnAttributes().
15447 hasAttribute(Attributes::NoImplicitFloat);
15448 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15449 && Subtarget->hasSSE2();
15450 if ((VT.isVector() ||
15451 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15452 isa<LoadSDNode>(St->getValue()) &&
15453 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15454 St->getChain().hasOneUse() && !St->isVolatile()) {
15455 SDNode* LdVal = St->getValue().getNode();
15456 LoadSDNode *Ld = 0;
15457 int TokenFactorIndex = -1;
15458 SmallVector<SDValue, 8> Ops;
15459 SDNode* ChainVal = St->getChain().getNode();
15460 // Must be a store of a load. We currently handle two cases: the load
15461 // is a direct child, and it's under an intervening TokenFactor. It is
15462 // possible to dig deeper under nested TokenFactors.
15463 if (ChainVal == LdVal)
15464 Ld = cast<LoadSDNode>(St->getChain());
15465 else if (St->getValue().hasOneUse() &&
15466 ChainVal->getOpcode() == ISD::TokenFactor) {
15467 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15468 if (ChainVal->getOperand(i).getNode() == LdVal) {
15469 TokenFactorIndex = i;
15470 Ld = cast<LoadSDNode>(St->getValue());
15472 Ops.push_back(ChainVal->getOperand(i));
15476 if (!Ld || !ISD::isNormalLoad(Ld))
15479 // If this is not the MMX case, i.e. we are just turning i64 load/store
15480 // into f64 load/store, avoid the transformation if there are multiple
15481 // uses of the loaded value.
15482 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15485 DebugLoc LdDL = Ld->getDebugLoc();
15486 DebugLoc StDL = N->getDebugLoc();
15487 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15488 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15490 if (Subtarget->is64Bit() || F64IsLegal) {
15491 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15492 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15493 Ld->getPointerInfo(), Ld->isVolatile(),
15494 Ld->isNonTemporal(), Ld->isInvariant(),
15495 Ld->getAlignment());
15496 SDValue NewChain = NewLd.getValue(1);
15497 if (TokenFactorIndex != -1) {
15498 Ops.push_back(NewChain);
15499 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15502 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15503 St->getPointerInfo(),
15504 St->isVolatile(), St->isNonTemporal(),
15505 St->getAlignment());
15508 // Otherwise, lower to two pairs of 32-bit loads / stores.
15509 SDValue LoAddr = Ld->getBasePtr();
15510 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15511 DAG.getConstant(4, MVT::i32));
15513 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15514 Ld->getPointerInfo(),
15515 Ld->isVolatile(), Ld->isNonTemporal(),
15516 Ld->isInvariant(), Ld->getAlignment());
15517 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15518 Ld->getPointerInfo().getWithOffset(4),
15519 Ld->isVolatile(), Ld->isNonTemporal(),
15521 MinAlign(Ld->getAlignment(), 4));
15523 SDValue NewChain = LoLd.getValue(1);
15524 if (TokenFactorIndex != -1) {
15525 Ops.push_back(LoLd);
15526 Ops.push_back(HiLd);
15527 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15531 LoAddr = St->getBasePtr();
15532 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15533 DAG.getConstant(4, MVT::i32));
15535 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15536 St->getPointerInfo(),
15537 St->isVolatile(), St->isNonTemporal(),
15538 St->getAlignment());
15539 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15540 St->getPointerInfo().getWithOffset(4),
15542 St->isNonTemporal(),
15543 MinAlign(St->getAlignment(), 4));
15544 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15549 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15550 /// and return the operands for the horizontal operation in LHS and RHS. A
15551 /// horizontal operation performs the binary operation on successive elements
15552 /// of its first operand, then on successive elements of its second operand,
15553 /// returning the resulting values in a vector. For example, if
15554 /// A = < float a0, float a1, float a2, float a3 >
15556 /// B = < float b0, float b1, float b2, float b3 >
15557 /// then the result of doing a horizontal operation on A and B is
15558 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15559 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15560 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15561 /// set to A, RHS to B, and the routine returns 'true'.
15562 /// Note that the binary operation should have the property that if one of the
15563 /// operands is UNDEF then the result is UNDEF.
15564 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15565 // Look for the following pattern: if
15566 // A = < float a0, float a1, float a2, float a3 >
15567 // B = < float b0, float b1, float b2, float b3 >
15569 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15570 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15571 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15572 // which is A horizontal-op B.
15574 // At least one of the operands should be a vector shuffle.
15575 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15576 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15579 EVT VT = LHS.getValueType();
15581 assert((VT.is128BitVector() || VT.is256BitVector()) &&
15582 "Unsupported vector type for horizontal add/sub");
15584 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15585 // operate independently on 128-bit lanes.
15586 unsigned NumElts = VT.getVectorNumElements();
15587 unsigned NumLanes = VT.getSizeInBits()/128;
15588 unsigned NumLaneElts = NumElts / NumLanes;
15589 assert((NumLaneElts % 2 == 0) &&
15590 "Vector type should have an even number of elements in each lane");
15591 unsigned HalfLaneElts = NumLaneElts/2;
15593 // View LHS in the form
15594 // LHS = VECTOR_SHUFFLE A, B, LMask
15595 // If LHS is not a shuffle then pretend it is the shuffle
15596 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15597 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15600 SmallVector<int, 16> LMask(NumElts);
15601 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15602 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15603 A = LHS.getOperand(0);
15604 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15605 B = LHS.getOperand(1);
15606 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15607 std::copy(Mask.begin(), Mask.end(), LMask.begin());
15609 if (LHS.getOpcode() != ISD::UNDEF)
15611 for (unsigned i = 0; i != NumElts; ++i)
15615 // Likewise, view RHS in the form
15616 // RHS = VECTOR_SHUFFLE C, D, RMask
15618 SmallVector<int, 16> RMask(NumElts);
15619 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15620 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15621 C = RHS.getOperand(0);
15622 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15623 D = RHS.getOperand(1);
15624 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15625 std::copy(Mask.begin(), Mask.end(), RMask.begin());
15627 if (RHS.getOpcode() != ISD::UNDEF)
15629 for (unsigned i = 0; i != NumElts; ++i)
15633 // Check that the shuffles are both shuffling the same vectors.
15634 if (!(A == C && B == D) && !(A == D && B == C))
15637 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15638 if (!A.getNode() && !B.getNode())
15641 // If A and B occur in reverse order in RHS, then "swap" them (which means
15642 // rewriting the mask).
15644 CommuteVectorShuffleMask(RMask, NumElts);
15646 // At this point LHS and RHS are equivalent to
15647 // LHS = VECTOR_SHUFFLE A, B, LMask
15648 // RHS = VECTOR_SHUFFLE A, B, RMask
15649 // Check that the masks correspond to performing a horizontal operation.
15650 for (unsigned i = 0; i != NumElts; ++i) {
15651 int LIdx = LMask[i], RIdx = RMask[i];
15653 // Ignore any UNDEF components.
15654 if (LIdx < 0 || RIdx < 0 ||
15655 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15656 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15659 // Check that successive elements are being operated on. If not, this is
15660 // not a horizontal operation.
15661 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15662 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15663 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15664 if (!(LIdx == Index && RIdx == Index + 1) &&
15665 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15669 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15670 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15674 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15675 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15676 const X86Subtarget *Subtarget) {
15677 EVT VT = N->getValueType(0);
15678 SDValue LHS = N->getOperand(0);
15679 SDValue RHS = N->getOperand(1);
15681 // Try to synthesize horizontal adds from adds of shuffles.
15682 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15683 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15684 isHorizontalBinOp(LHS, RHS, true))
15685 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15689 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15690 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15691 const X86Subtarget *Subtarget) {
15692 EVT VT = N->getValueType(0);
15693 SDValue LHS = N->getOperand(0);
15694 SDValue RHS = N->getOperand(1);
15696 // Try to synthesize horizontal subs from subs of shuffles.
15697 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15698 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15699 isHorizontalBinOp(LHS, RHS, false))
15700 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15704 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15705 /// X86ISD::FXOR nodes.
15706 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15707 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15708 // F[X]OR(0.0, x) -> x
15709 // F[X]OR(x, 0.0) -> x
15710 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15711 if (C->getValueAPF().isPosZero())
15712 return N->getOperand(1);
15713 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15714 if (C->getValueAPF().isPosZero())
15715 return N->getOperand(0);
15719 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15720 /// X86ISD::FMAX nodes.
15721 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15722 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15724 // Only perform optimizations if UnsafeMath is used.
15725 if (!DAG.getTarget().Options.UnsafeFPMath)
15728 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15729 // into FMINC and FMAXC, which are Commutative operations.
15730 unsigned NewOp = 0;
15731 switch (N->getOpcode()) {
15732 default: llvm_unreachable("unknown opcode");
15733 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
15734 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
15737 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15738 N->getOperand(0), N->getOperand(1));
15742 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15743 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15744 // FAND(0.0, x) -> 0.0
15745 // FAND(x, 0.0) -> 0.0
15746 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15747 if (C->getValueAPF().isPosZero())
15748 return N->getOperand(0);
15749 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15750 if (C->getValueAPF().isPosZero())
15751 return N->getOperand(1);
15755 static SDValue PerformBTCombine(SDNode *N,
15757 TargetLowering::DAGCombinerInfo &DCI) {
15758 // BT ignores high bits in the bit index operand.
15759 SDValue Op1 = N->getOperand(1);
15760 if (Op1.hasOneUse()) {
15761 unsigned BitWidth = Op1.getValueSizeInBits();
15762 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15763 APInt KnownZero, KnownOne;
15764 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15765 !DCI.isBeforeLegalizeOps());
15766 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15767 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15768 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15769 DCI.CommitTargetLoweringOpt(TLO);
15774 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15775 SDValue Op = N->getOperand(0);
15776 if (Op.getOpcode() == ISD::BITCAST)
15777 Op = Op.getOperand(0);
15778 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15779 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15780 VT.getVectorElementType().getSizeInBits() ==
15781 OpVT.getVectorElementType().getSizeInBits()) {
15782 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15787 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15788 TargetLowering::DAGCombinerInfo &DCI,
15789 const X86Subtarget *Subtarget) {
15790 if (!DCI.isBeforeLegalizeOps())
15793 if (!Subtarget->hasAVX())
15796 EVT VT = N->getValueType(0);
15797 SDValue Op = N->getOperand(0);
15798 EVT OpVT = Op.getValueType();
15799 DebugLoc dl = N->getDebugLoc();
15801 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15802 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15804 if (Subtarget->hasAVX2())
15805 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15807 // Optimize vectors in AVX mode
15808 // Sign extend v8i16 to v8i32 and
15811 // Divide input vector into two parts
15812 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15813 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15814 // concat the vectors to original VT
15816 unsigned NumElems = OpVT.getVectorNumElements();
15817 SDValue Undef = DAG.getUNDEF(OpVT);
15819 SmallVector<int,8> ShufMask1(NumElems, -1);
15820 for (unsigned i = 0; i != NumElems/2; ++i)
15823 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15825 SmallVector<int,8> ShufMask2(NumElems, -1);
15826 for (unsigned i = 0; i != NumElems/2; ++i)
15827 ShufMask2[i] = i + NumElems/2;
15829 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15831 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15832 VT.getVectorNumElements()/2);
15834 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15835 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15837 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15842 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15843 const X86Subtarget* Subtarget) {
15844 DebugLoc dl = N->getDebugLoc();
15845 EVT VT = N->getValueType(0);
15847 // Let legalize expand this if it isn't a legal type yet.
15848 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15851 EVT ScalarVT = VT.getScalarType();
15852 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15853 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15856 SDValue A = N->getOperand(0);
15857 SDValue B = N->getOperand(1);
15858 SDValue C = N->getOperand(2);
15860 bool NegA = (A.getOpcode() == ISD::FNEG);
15861 bool NegB = (B.getOpcode() == ISD::FNEG);
15862 bool NegC = (C.getOpcode() == ISD::FNEG);
15864 // Negative multiplication when NegA xor NegB
15865 bool NegMul = (NegA != NegB);
15867 A = A.getOperand(0);
15869 B = B.getOperand(0);
15871 C = C.getOperand(0);
15875 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15877 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15879 return DAG.getNode(Opcode, dl, VT, A, B, C);
15882 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15883 TargetLowering::DAGCombinerInfo &DCI,
15884 const X86Subtarget *Subtarget) {
15885 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
15886 // (and (i32 x86isd::setcc_carry), 1)
15887 // This eliminates the zext. This transformation is necessary because
15888 // ISD::SETCC is always legalized to i8.
15889 DebugLoc dl = N->getDebugLoc();
15890 SDValue N0 = N->getOperand(0);
15891 EVT VT = N->getValueType(0);
15892 EVT OpVT = N0.getValueType();
15894 if (N0.getOpcode() == ISD::AND &&
15896 N0.getOperand(0).hasOneUse()) {
15897 SDValue N00 = N0.getOperand(0);
15898 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15900 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15901 if (!C || C->getZExtValue() != 1)
15903 return DAG.getNode(ISD::AND, dl, VT,
15904 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15905 N00.getOperand(0), N00.getOperand(1)),
15906 DAG.getConstant(1, VT));
15909 // Optimize vectors in AVX mode:
15912 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
15913 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
15914 // Concat upper and lower parts.
15917 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
15918 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
15919 // Concat upper and lower parts.
15921 if (!DCI.isBeforeLegalizeOps())
15924 if (!Subtarget->hasAVX())
15927 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15928 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
15930 if (Subtarget->hasAVX2())
15931 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15933 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15934 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15935 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15937 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15938 VT.getVectorNumElements()/2);
15940 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15941 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15943 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15949 // Optimize x == -y --> x+y == 0
15950 // x != -y --> x+y != 0
15951 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15952 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15953 SDValue LHS = N->getOperand(0);
15954 SDValue RHS = N->getOperand(1);
15956 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15957 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15958 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15959 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15960 LHS.getValueType(), RHS, LHS.getOperand(1));
15961 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15962 addV, DAG.getConstant(0, addV.getValueType()), CC);
15964 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15965 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15966 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15967 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15968 RHS.getValueType(), LHS, RHS.getOperand(1));
15969 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15970 addV, DAG.getConstant(0, addV.getValueType()), CC);
15975 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15976 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15977 TargetLowering::DAGCombinerInfo &DCI,
15978 const X86Subtarget *Subtarget) {
15979 DebugLoc DL = N->getDebugLoc();
15980 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15981 SDValue EFLAGS = N->getOperand(1);
15983 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15984 // a zext and produces an all-ones bit which is more useful than 0/1 in some
15986 if (CC == X86::COND_B)
15987 return DAG.getNode(ISD::AND, DL, MVT::i8,
15988 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15989 DAG.getConstant(CC, MVT::i8), EFLAGS),
15990 DAG.getConstant(1, MVT::i8));
15994 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15995 if (Flags.getNode()) {
15996 SDValue Cond = DAG.getConstant(CC, MVT::i8);
15997 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16003 // Optimize branch condition evaluation.
16005 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16006 TargetLowering::DAGCombinerInfo &DCI,
16007 const X86Subtarget *Subtarget) {
16008 DebugLoc DL = N->getDebugLoc();
16009 SDValue Chain = N->getOperand(0);
16010 SDValue Dest = N->getOperand(1);
16011 SDValue EFLAGS = N->getOperand(3);
16012 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16016 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16017 if (Flags.getNode()) {
16018 SDValue Cond = DAG.getConstant(CC, MVT::i8);
16019 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16026 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
16027 SDValue Op0 = N->getOperand(0);
16028 EVT InVT = Op0->getValueType(0);
16030 // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
16031 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16032 DebugLoc dl = N->getDebugLoc();
16033 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16034 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
16035 // Notice that we use SINT_TO_FP because we know that the high bits
16036 // are zero and SINT_TO_FP is better supported by the hardware.
16037 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16043 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16044 const X86TargetLowering *XTLI) {
16045 SDValue Op0 = N->getOperand(0);
16046 EVT InVT = Op0->getValueType(0);
16048 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16049 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16050 DebugLoc dl = N->getDebugLoc();
16051 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16052 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16053 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16056 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16057 // a 32-bit target where SSE doesn't support i64->FP operations.
16058 if (Op0.getOpcode() == ISD::LOAD) {
16059 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16060 EVT VT = Ld->getValueType(0);
16061 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16062 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16063 !XTLI->getSubtarget()->is64Bit() &&
16064 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16065 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16066 Ld->getChain(), Op0, DAG);
16067 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16074 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
16075 EVT VT = N->getValueType(0);
16077 // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
16078 if (VT == MVT::v8i8 || VT == MVT::v4i8) {
16079 DebugLoc dl = N->getDebugLoc();
16080 MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16081 SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
16082 return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
16088 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16089 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16090 X86TargetLowering::DAGCombinerInfo &DCI) {
16091 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16092 // the result is either zero or one (depending on the input carry bit).
16093 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16094 if (X86::isZeroNode(N->getOperand(0)) &&
16095 X86::isZeroNode(N->getOperand(1)) &&
16096 // We don't have a good way to replace an EFLAGS use, so only do this when
16098 SDValue(N, 1).use_empty()) {
16099 DebugLoc DL = N->getDebugLoc();
16100 EVT VT = N->getValueType(0);
16101 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16102 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16103 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16104 DAG.getConstant(X86::COND_B,MVT::i8),
16106 DAG.getConstant(1, VT));
16107 return DCI.CombineTo(N, Res1, CarryOut);
16113 // fold (add Y, (sete X, 0)) -> adc 0, Y
16114 // (add Y, (setne X, 0)) -> sbb -1, Y
16115 // (sub (sete X, 0), Y) -> sbb 0, Y
16116 // (sub (setne X, 0), Y) -> adc -1, Y
16117 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16118 DebugLoc DL = N->getDebugLoc();
16120 // Look through ZExts.
16121 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16122 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16125 SDValue SetCC = Ext.getOperand(0);
16126 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16129 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16130 if (CC != X86::COND_E && CC != X86::COND_NE)
16133 SDValue Cmp = SetCC.getOperand(1);
16134 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16135 !X86::isZeroNode(Cmp.getOperand(1)) ||
16136 !Cmp.getOperand(0).getValueType().isInteger())
16139 SDValue CmpOp0 = Cmp.getOperand(0);
16140 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16141 DAG.getConstant(1, CmpOp0.getValueType()));
16143 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16144 if (CC == X86::COND_NE)
16145 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16146 DL, OtherVal.getValueType(), OtherVal,
16147 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16148 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16149 DL, OtherVal.getValueType(), OtherVal,
16150 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16153 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16154 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16155 const X86Subtarget *Subtarget) {
16156 EVT VT = N->getValueType(0);
16157 SDValue Op0 = N->getOperand(0);
16158 SDValue Op1 = N->getOperand(1);
16160 // Try to synthesize horizontal adds from adds of shuffles.
16161 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16162 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16163 isHorizontalBinOp(Op0, Op1, true))
16164 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16166 return OptimizeConditionalInDecrement(N, DAG);
16169 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16170 const X86Subtarget *Subtarget) {
16171 SDValue Op0 = N->getOperand(0);
16172 SDValue Op1 = N->getOperand(1);
16174 // X86 can't encode an immediate LHS of a sub. See if we can push the
16175 // negation into a preceding instruction.
16176 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16177 // If the RHS of the sub is a XOR with one use and a constant, invert the
16178 // immediate. Then add one to the LHS of the sub so we can turn
16179 // X-Y -> X+~Y+1, saving one register.
16180 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16181 isa<ConstantSDNode>(Op1.getOperand(1))) {
16182 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16183 EVT VT = Op0.getValueType();
16184 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16186 DAG.getConstant(~XorC, VT));
16187 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16188 DAG.getConstant(C->getAPIntValue()+1, VT));
16192 // Try to synthesize horizontal adds from adds of shuffles.
16193 EVT VT = N->getValueType(0);
16194 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16195 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16196 isHorizontalBinOp(Op0, Op1, true))
16197 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16199 return OptimizeConditionalInDecrement(N, DAG);
16202 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16203 DAGCombinerInfo &DCI) const {
16204 SelectionDAG &DAG = DCI.DAG;
16205 switch (N->getOpcode()) {
16207 case ISD::EXTRACT_VECTOR_ELT:
16208 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16210 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16211 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16212 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
16213 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
16214 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
16215 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
16218 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
16219 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
16220 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
16221 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
16222 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
16223 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
16224 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG);
16225 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
16226 case ISD::FP_TO_SINT: return PerformFP_TO_SINTCombine(N, DAG);
16227 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
16228 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
16230 case X86ISD::FOR: return PerformFORCombine(N, DAG);
16232 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
16233 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
16234 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
16235 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
16236 case ISD::ANY_EXTEND:
16237 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
16238 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
16239 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16240 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
16241 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16242 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16243 case X86ISD::SHUFP: // Handle all target specific shuffles
16244 case X86ISD::PALIGN:
16245 case X86ISD::UNPCKH:
16246 case X86ISD::UNPCKL:
16247 case X86ISD::MOVHLPS:
16248 case X86ISD::MOVLHPS:
16249 case X86ISD::PSHUFD:
16250 case X86ISD::PSHUFHW:
16251 case X86ISD::PSHUFLW:
16252 case X86ISD::MOVSS:
16253 case X86ISD::MOVSD:
16254 case X86ISD::VPERMILP:
16255 case X86ISD::VPERM2X128:
16256 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16257 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
16263 /// isTypeDesirableForOp - Return true if the target has native support for
16264 /// the specified value type and it is 'desirable' to use the type for the
16265 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16266 /// instruction encodings are longer and some i16 instructions are slow.
16267 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16268 if (!isTypeLegal(VT))
16270 if (VT != MVT::i16)
16277 case ISD::SIGN_EXTEND:
16278 case ISD::ZERO_EXTEND:
16279 case ISD::ANY_EXTEND:
16292 /// IsDesirableToPromoteOp - This method query the target whether it is
16293 /// beneficial for dag combiner to promote the specified node. If true, it
16294 /// should return the desired promotion type by reference.
16295 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16296 EVT VT = Op.getValueType();
16297 if (VT != MVT::i16)
16300 bool Promote = false;
16301 bool Commute = false;
16302 switch (Op.getOpcode()) {
16305 LoadSDNode *LD = cast<LoadSDNode>(Op);
16306 // If the non-extending load has a single use and it's not live out, then it
16307 // might be folded.
16308 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16309 Op.hasOneUse()*/) {
16310 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16311 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16312 // The only case where we'd want to promote LOAD (rather then it being
16313 // promoted as an operand is when it's only use is liveout.
16314 if (UI->getOpcode() != ISD::CopyToReg)
16321 case ISD::SIGN_EXTEND:
16322 case ISD::ZERO_EXTEND:
16323 case ISD::ANY_EXTEND:
16328 SDValue N0 = Op.getOperand(0);
16329 // Look out for (store (shl (load), x)).
16330 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16343 SDValue N0 = Op.getOperand(0);
16344 SDValue N1 = Op.getOperand(1);
16345 if (!Commute && MayFoldLoad(N1))
16347 // Avoid disabling potential load folding opportunities.
16348 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16350 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16360 //===----------------------------------------------------------------------===//
16361 // X86 Inline Assembly Support
16362 //===----------------------------------------------------------------------===//
16365 // Helper to match a string separated by whitespace.
16366 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16367 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16369 for (unsigned i = 0, e = args.size(); i != e; ++i) {
16370 StringRef piece(*args[i]);
16371 if (!s.startswith(piece)) // Check if the piece matches.
16374 s = s.substr(piece.size());
16375 StringRef::size_type pos = s.find_first_not_of(" \t");
16376 if (pos == 0) // We matched a prefix.
16384 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16387 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16388 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16390 std::string AsmStr = IA->getAsmString();
16392 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16393 if (!Ty || Ty->getBitWidth() % 16 != 0)
16396 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16397 SmallVector<StringRef, 4> AsmPieces;
16398 SplitString(AsmStr, AsmPieces, ";\n");
16400 switch (AsmPieces.size()) {
16401 default: return false;
16403 // FIXME: this should verify that we are targeting a 486 or better. If not,
16404 // we will turn this bswap into something that will be lowered to logical
16405 // ops instead of emitting the bswap asm. For now, we don't support 486 or
16406 // lower so don't worry about this.
16408 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16409 matchAsm(AsmPieces[0], "bswapl", "$0") ||
16410 matchAsm(AsmPieces[0], "bswapq", "$0") ||
16411 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16412 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16413 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16414 // No need to check constraints, nothing other than the equivalent of
16415 // "=r,0" would be valid here.
16416 return IntrinsicLowering::LowerToByteSwap(CI);
16419 // rorw $$8, ${0:w} --> llvm.bswap.i16
16420 if (CI->getType()->isIntegerTy(16) &&
16421 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16422 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16423 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16425 const std::string &ConstraintsStr = IA->getConstraintString();
16426 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16427 std::sort(AsmPieces.begin(), AsmPieces.end());
16428 if (AsmPieces.size() == 4 &&
16429 AsmPieces[0] == "~{cc}" &&
16430 AsmPieces[1] == "~{dirflag}" &&
16431 AsmPieces[2] == "~{flags}" &&
16432 AsmPieces[3] == "~{fpsr}")
16433 return IntrinsicLowering::LowerToByteSwap(CI);
16437 if (CI->getType()->isIntegerTy(32) &&
16438 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16439 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16440 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16441 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16443 const std::string &ConstraintsStr = IA->getConstraintString();
16444 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16445 std::sort(AsmPieces.begin(), AsmPieces.end());
16446 if (AsmPieces.size() == 4 &&
16447 AsmPieces[0] == "~{cc}" &&
16448 AsmPieces[1] == "~{dirflag}" &&
16449 AsmPieces[2] == "~{flags}" &&
16450 AsmPieces[3] == "~{fpsr}")
16451 return IntrinsicLowering::LowerToByteSwap(CI);
16454 if (CI->getType()->isIntegerTy(64)) {
16455 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16456 if (Constraints.size() >= 2 &&
16457 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16458 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16459 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
16460 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16461 matchAsm(AsmPieces[1], "bswap", "%edx") &&
16462 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16463 return IntrinsicLowering::LowerToByteSwap(CI);
16473 /// getConstraintType - Given a constraint letter, return the type of
16474 /// constraint it is for this target.
16475 X86TargetLowering::ConstraintType
16476 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16477 if (Constraint.size() == 1) {
16478 switch (Constraint[0]) {
16489 return C_RegisterClass;
16513 return TargetLowering::getConstraintType(Constraint);
16516 /// Examine constraint type and operand type and determine a weight value.
16517 /// This object must already have been set up with the operand type
16518 /// and the current alternative constraint selected.
16519 TargetLowering::ConstraintWeight
16520 X86TargetLowering::getSingleConstraintMatchWeight(
16521 AsmOperandInfo &info, const char *constraint) const {
16522 ConstraintWeight weight = CW_Invalid;
16523 Value *CallOperandVal = info.CallOperandVal;
16524 // If we don't have a value, we can't do a match,
16525 // but allow it at the lowest weight.
16526 if (CallOperandVal == NULL)
16528 Type *type = CallOperandVal->getType();
16529 // Look at the constraint type.
16530 switch (*constraint) {
16532 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16543 if (CallOperandVal->getType()->isIntegerTy())
16544 weight = CW_SpecificReg;
16549 if (type->isFloatingPointTy())
16550 weight = CW_SpecificReg;
16553 if (type->isX86_MMXTy() && Subtarget->hasMMX())
16554 weight = CW_SpecificReg;
16558 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16559 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16560 weight = CW_Register;
16563 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16564 if (C->getZExtValue() <= 31)
16565 weight = CW_Constant;
16569 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16570 if (C->getZExtValue() <= 63)
16571 weight = CW_Constant;
16575 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16576 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16577 weight = CW_Constant;
16581 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16582 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16583 weight = CW_Constant;
16587 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16588 if (C->getZExtValue() <= 3)
16589 weight = CW_Constant;
16593 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16594 if (C->getZExtValue() <= 0xff)
16595 weight = CW_Constant;
16600 if (dyn_cast<ConstantFP>(CallOperandVal)) {
16601 weight = CW_Constant;
16605 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16606 if ((C->getSExtValue() >= -0x80000000LL) &&
16607 (C->getSExtValue() <= 0x7fffffffLL))
16608 weight = CW_Constant;
16612 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16613 if (C->getZExtValue() <= 0xffffffff)
16614 weight = CW_Constant;
16621 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16622 /// with another that has more specific requirements based on the type of the
16623 /// corresponding operand.
16624 const char *X86TargetLowering::
16625 LowerXConstraint(EVT ConstraintVT) const {
16626 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16627 // 'f' like normal targets.
16628 if (ConstraintVT.isFloatingPoint()) {
16629 if (Subtarget->hasSSE2())
16631 if (Subtarget->hasSSE1())
16635 return TargetLowering::LowerXConstraint(ConstraintVT);
16638 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16639 /// vector. If it is invalid, don't add anything to Ops.
16640 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16641 std::string &Constraint,
16642 std::vector<SDValue>&Ops,
16643 SelectionDAG &DAG) const {
16644 SDValue Result(0, 0);
16646 // Only support length 1 constraints for now.
16647 if (Constraint.length() > 1) return;
16649 char ConstraintLetter = Constraint[0];
16650 switch (ConstraintLetter) {
16653 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16654 if (C->getZExtValue() <= 31) {
16655 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16661 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16662 if (C->getZExtValue() <= 63) {
16663 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16669 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16670 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16671 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16677 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16678 if (C->getZExtValue() <= 255) {
16679 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16685 // 32-bit signed value
16686 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16687 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16688 C->getSExtValue())) {
16689 // Widen to 64 bits here to get it sign extended.
16690 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16693 // FIXME gcc accepts some relocatable values here too, but only in certain
16694 // memory models; it's complicated.
16699 // 32-bit unsigned value
16700 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16701 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16702 C->getZExtValue())) {
16703 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16707 // FIXME gcc accepts some relocatable values here too, but only in certain
16708 // memory models; it's complicated.
16712 // Literal immediates are always ok.
16713 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16714 // Widen to 64 bits here to get it sign extended.
16715 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16719 // In any sort of PIC mode addresses need to be computed at runtime by
16720 // adding in a register or some sort of table lookup. These can't
16721 // be used as immediates.
16722 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16725 // If we are in non-pic codegen mode, we allow the address of a global (with
16726 // an optional displacement) to be used with 'i'.
16727 GlobalAddressSDNode *GA = 0;
16728 int64_t Offset = 0;
16730 // Match either (GA), (GA+C), (GA+C1+C2), etc.
16732 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16733 Offset += GA->getOffset();
16735 } else if (Op.getOpcode() == ISD::ADD) {
16736 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16737 Offset += C->getZExtValue();
16738 Op = Op.getOperand(0);
16741 } else if (Op.getOpcode() == ISD::SUB) {
16742 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16743 Offset += -C->getZExtValue();
16744 Op = Op.getOperand(0);
16749 // Otherwise, this isn't something we can handle, reject it.
16753 const GlobalValue *GV = GA->getGlobal();
16754 // If we require an extra load to get this address, as in PIC mode, we
16755 // can't accept it.
16756 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16757 getTargetMachine())))
16760 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16761 GA->getValueType(0), Offset);
16766 if (Result.getNode()) {
16767 Ops.push_back(Result);
16770 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16773 std::pair<unsigned, const TargetRegisterClass*>
16774 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16776 // First, see if this is a constraint that directly corresponds to an LLVM
16778 if (Constraint.size() == 1) {
16779 // GCC Constraint Letters
16780 switch (Constraint[0]) {
16782 // TODO: Slight differences here in allocation order and leaving
16783 // RIP in the class. Do they matter any more here than they do
16784 // in the normal allocation?
16785 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16786 if (Subtarget->is64Bit()) {
16787 if (VT == MVT::i32 || VT == MVT::f32)
16788 return std::make_pair(0U, &X86::GR32RegClass);
16789 if (VT == MVT::i16)
16790 return std::make_pair(0U, &X86::GR16RegClass);
16791 if (VT == MVT::i8 || VT == MVT::i1)
16792 return std::make_pair(0U, &X86::GR8RegClass);
16793 if (VT == MVT::i64 || VT == MVT::f64)
16794 return std::make_pair(0U, &X86::GR64RegClass);
16797 // 32-bit fallthrough
16798 case 'Q': // Q_REGS
16799 if (VT == MVT::i32 || VT == MVT::f32)
16800 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16801 if (VT == MVT::i16)
16802 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16803 if (VT == MVT::i8 || VT == MVT::i1)
16804 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16805 if (VT == MVT::i64)
16806 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16808 case 'r': // GENERAL_REGS
16809 case 'l': // INDEX_REGS
16810 if (VT == MVT::i8 || VT == MVT::i1)
16811 return std::make_pair(0U, &X86::GR8RegClass);
16812 if (VT == MVT::i16)
16813 return std::make_pair(0U, &X86::GR16RegClass);
16814 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16815 return std::make_pair(0U, &X86::GR32RegClass);
16816 return std::make_pair(0U, &X86::GR64RegClass);
16817 case 'R': // LEGACY_REGS
16818 if (VT == MVT::i8 || VT == MVT::i1)
16819 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16820 if (VT == MVT::i16)
16821 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16822 if (VT == MVT::i32 || !Subtarget->is64Bit())
16823 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16824 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16825 case 'f': // FP Stack registers.
16826 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16827 // value to the correct fpstack register class.
16828 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16829 return std::make_pair(0U, &X86::RFP32RegClass);
16830 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16831 return std::make_pair(0U, &X86::RFP64RegClass);
16832 return std::make_pair(0U, &X86::RFP80RegClass);
16833 case 'y': // MMX_REGS if MMX allowed.
16834 if (!Subtarget->hasMMX()) break;
16835 return std::make_pair(0U, &X86::VR64RegClass);
16836 case 'Y': // SSE_REGS if SSE2 allowed
16837 if (!Subtarget->hasSSE2()) break;
16839 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16840 if (!Subtarget->hasSSE1()) break;
16842 switch (VT.getSimpleVT().SimpleTy) {
16844 // Scalar SSE types.
16847 return std::make_pair(0U, &X86::FR32RegClass);
16850 return std::make_pair(0U, &X86::FR64RegClass);
16858 return std::make_pair(0U, &X86::VR128RegClass);
16866 return std::make_pair(0U, &X86::VR256RegClass);
16872 // Use the default implementation in TargetLowering to convert the register
16873 // constraint into a member of a register class.
16874 std::pair<unsigned, const TargetRegisterClass*> Res;
16875 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16877 // Not found as a standard register?
16878 if (Res.second == 0) {
16879 // Map st(0) -> st(7) -> ST0
16880 if (Constraint.size() == 7 && Constraint[0] == '{' &&
16881 tolower(Constraint[1]) == 's' &&
16882 tolower(Constraint[2]) == 't' &&
16883 Constraint[3] == '(' &&
16884 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16885 Constraint[5] == ')' &&
16886 Constraint[6] == '}') {
16888 Res.first = X86::ST0+Constraint[4]-'0';
16889 Res.second = &X86::RFP80RegClass;
16893 // GCC allows "st(0)" to be called just plain "st".
16894 if (StringRef("{st}").equals_lower(Constraint)) {
16895 Res.first = X86::ST0;
16896 Res.second = &X86::RFP80RegClass;
16901 if (StringRef("{flags}").equals_lower(Constraint)) {
16902 Res.first = X86::EFLAGS;
16903 Res.second = &X86::CCRRegClass;
16907 // 'A' means EAX + EDX.
16908 if (Constraint == "A") {
16909 Res.first = X86::EAX;
16910 Res.second = &X86::GR32_ADRegClass;
16916 // Otherwise, check to see if this is a register class of the wrong value
16917 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16918 // turn into {ax},{dx}.
16919 if (Res.second->hasType(VT))
16920 return Res; // Correct type already, nothing to do.
16922 // All of the single-register GCC register classes map their values onto
16923 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
16924 // really want an 8-bit or 32-bit register, map to the appropriate register
16925 // class and return the appropriate register.
16926 if (Res.second == &X86::GR16RegClass) {
16927 if (VT == MVT::i8) {
16928 unsigned DestReg = 0;
16929 switch (Res.first) {
16931 case X86::AX: DestReg = X86::AL; break;
16932 case X86::DX: DestReg = X86::DL; break;
16933 case X86::CX: DestReg = X86::CL; break;
16934 case X86::BX: DestReg = X86::BL; break;
16937 Res.first = DestReg;
16938 Res.second = &X86::GR8RegClass;
16940 } else if (VT == MVT::i32) {
16941 unsigned DestReg = 0;
16942 switch (Res.first) {
16944 case X86::AX: DestReg = X86::EAX; break;
16945 case X86::DX: DestReg = X86::EDX; break;
16946 case X86::CX: DestReg = X86::ECX; break;
16947 case X86::BX: DestReg = X86::EBX; break;
16948 case X86::SI: DestReg = X86::ESI; break;
16949 case X86::DI: DestReg = X86::EDI; break;
16950 case X86::BP: DestReg = X86::EBP; break;
16951 case X86::SP: DestReg = X86::ESP; break;
16954 Res.first = DestReg;
16955 Res.second = &X86::GR32RegClass;
16957 } else if (VT == MVT::i64) {
16958 unsigned DestReg = 0;
16959 switch (Res.first) {
16961 case X86::AX: DestReg = X86::RAX; break;
16962 case X86::DX: DestReg = X86::RDX; break;
16963 case X86::CX: DestReg = X86::RCX; break;
16964 case X86::BX: DestReg = X86::RBX; break;
16965 case X86::SI: DestReg = X86::RSI; break;
16966 case X86::DI: DestReg = X86::RDI; break;
16967 case X86::BP: DestReg = X86::RBP; break;
16968 case X86::SP: DestReg = X86::RSP; break;
16971 Res.first = DestReg;
16972 Res.second = &X86::GR64RegClass;
16975 } else if (Res.second == &X86::FR32RegClass ||
16976 Res.second == &X86::FR64RegClass ||
16977 Res.second == &X86::VR128RegClass) {
16978 // Handle references to XMM physical registers that got mapped into the
16979 // wrong class. This can happen with constraints like {xmm0} where the
16980 // target independent register mapper will just pick the first match it can
16981 // find, ignoring the required type.
16983 if (VT == MVT::f32 || VT == MVT::i32)
16984 Res.second = &X86::FR32RegClass;
16985 else if (VT == MVT::f64 || VT == MVT::i64)
16986 Res.second = &X86::FR64RegClass;
16987 else if (X86::VR128RegClass.hasType(VT))
16988 Res.second = &X86::VR128RegClass;
16989 else if (X86::VR256RegClass.hasType(VT))
16990 Res.second = &X86::VR256RegClass;