LLVM  9.0.0svn
X86ISelLowering.cpp
Go to the documentation of this file.
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that X86 uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "X86ISelLowering.h"
15 #include "Utils/X86ShuffleDecode.h"
16 #include "X86CallingConv.h"
17 #include "X86FrameLowering.h"
18 #include "X86InstrBuilder.h"
19 #include "X86IntrinsicsInfo.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/IR/CallSite.h"
39 #include "llvm/IR/CallingConv.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/DiagnosticInfo.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/GlobalAlias.h"
45 #include "llvm/IR/GlobalVariable.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/Intrinsics.h"
48 #include "llvm/MC/MCAsmInfo.h"
49 #include "llvm/MC/MCContext.h"
50 #include "llvm/MC/MCExpr.h"
51 #include "llvm/MC/MCSymbol.h"
53 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/KnownBits.h"
58 #include <algorithm>
59 #include <bitset>
60 #include <cctype>
61 #include <numeric>
62 using namespace llvm;
63 
64 #define DEBUG_TYPE "x86-isel"
65 
66 STATISTIC(NumTailCalls, "Number of tail calls");
67 
69  "x86-experimental-vector-widening-legalization", cl::init(false),
70  cl::desc("Enable an experimental vector type legalization through widening "
71  "rather than promotion."),
72  cl::Hidden);
73 
75  "x86-experimental-pref-loop-alignment", cl::init(4),
76  cl::desc("Sets the preferable loop alignment for experiments "
77  "(the last x86-experimental-pref-loop-alignment bits"
78  " of the loop header PC will be 0)."),
79  cl::Hidden);
80 
82  "mul-constant-optimization", cl::init(true),
83  cl::desc("Replace 'mul x, Const' with more effective instructions like "
84  "SHIFT, LEA, etc."),
85  cl::Hidden);
86 
87 /// Call this when the user attempts to do something unsupported, like
88 /// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike
89 /// report_fatal_error, so calling code should attempt to recover without
90 /// crashing.
91 static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl,
92  const char *Msg) {
94  DAG.getContext()->diagnose(
96 }
97 
99  const X86Subtarget &STI)
100  : TargetLowering(TM), Subtarget(STI) {
101  bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
102  X86ScalarSSEf64 = Subtarget.hasSSE2();
103  X86ScalarSSEf32 = Subtarget.hasSSE1();
105 
106  // Set up the TargetLowering object.
107 
108  // X86 is weird. It always uses i8 for shift amounts and setcc results.
110  // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
112 
113  // For 64-bit, since we have so many registers, use the ILP scheduler.
114  // For 32-bit, use the register pressure specific scheduling.
115  // For Atom, always use ILP scheduling.
116  if (Subtarget.isAtom())
118  else if (Subtarget.is64Bit())
120  else
122  const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
124 
125  // Bypass expensive divides and use cheaper ones.
126  if (TM.getOptLevel() >= CodeGenOpt::Default) {
127  if (Subtarget.hasSlowDivide32())
128  addBypassSlowDiv(32, 8);
129  if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
130  addBypassSlowDiv(64, 32);
131  }
132 
133  if (Subtarget.isTargetKnownWindowsMSVC() ||
134  Subtarget.isTargetWindowsItanium()) {
135  // Setup Windows compiler runtime calls.
136  setLibcallName(RTLIB::SDIV_I64, "_alldiv");
137  setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
138  setLibcallName(RTLIB::SREM_I64, "_allrem");
139  setLibcallName(RTLIB::UREM_I64, "_aullrem");
140  setLibcallName(RTLIB::MUL_I64, "_allmul");
146  }
147 
148  if (Subtarget.isTargetDarwin()) {
149  // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
150  setUseUnderscoreSetJmp(false);
152  } else if (Subtarget.isTargetWindowsGNU()) {
153  // MS runtime is weird: it exports _setjmp, but longjmp!
156  } else {
159  }
160 
161  // Set up the register classes.
162  addRegisterClass(MVT::i8, &X86::GR8RegClass);
163  addRegisterClass(MVT::i16, &X86::GR16RegClass);
164  addRegisterClass(MVT::i32, &X86::GR32RegClass);
165  if (Subtarget.is64Bit())
166  addRegisterClass(MVT::i64, &X86::GR64RegClass);
167 
168  for (MVT VT : MVT::integer_valuetypes())
170 
171  // We don't accept any truncstore of integer registers.
178 
180 
181  // SETOEQ and SETUNE require checking two conditions.
188 
189  // Integer absolute.
190  if (Subtarget.hasCMov()) {
193  if (Subtarget.is64Bit())
195  }
196 
197  // Funnel shifts.
198  for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
199  setOperationAction(ShiftOp , MVT::i16 , Custom);
200  setOperationAction(ShiftOp , MVT::i32 , Custom);
201  if (Subtarget.is64Bit())
202  setOperationAction(ShiftOp , MVT::i64 , Custom);
203  }
204 
205  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
206  // operation.
210 
211  if (Subtarget.is64Bit()) {
212  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512())
213  // f32/f64 are legal, f80 is custom.
215  else
218  } else if (!Subtarget.useSoftFloat()) {
219  // We have an algorithm for SSE2->double, and we turn this into a
220  // 64-bit FILD followed by conditional FADD for other targets.
222  // We have an algorithm for SSE2, and we turn this into a 64-bit
223  // FILD or VCVTUSI2SS/SD for other targets.
225  } else {
227  }
228 
229  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
230  // this operation.
233 
234  if (!Subtarget.useSoftFloat()) {
235  // SSE has no i16 to fp conversion, only i32.
236  if (X86ScalarSSEf32) {
238  // f32 and f64 cases are Legal, f80 case is not
240  } else {
243  }
244  } else {
247  }
248 
249  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
250  // this operation.
253 
254  if (!Subtarget.useSoftFloat()) {
255  // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
256  // are Legal, f80 is custom lowered.
259 
260  if (X86ScalarSSEf32) {
262  // f32 and f64 cases are Legal, f80 case is not
264  } else {
267  }
268  } else {
272  }
273 
274  // Handle FP_TO_UINT by promoting the destination to a larger signed
275  // conversion.
279 
280  if (Subtarget.is64Bit()) {
281  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
282  // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
285  } else {
288  }
289  } else if (!Subtarget.useSoftFloat()) {
290  // Since AVX is a superset of SSE3, only check for SSE here.
291  if (Subtarget.hasSSE1() && !Subtarget.hasSSE3())
292  // Expand FP_TO_UINT into a select.
293  // FIXME: We would like to use a Custom expander here eventually to do
294  // the optimal thing for SSE vs. the default expansion in the legalizer.
296  else
297  // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
298  // With SSE3 we can use fisttpll to convert to a signed i64; without
299  // SSE, we're stuck with a fistpll.
301 
303  }
304 
305  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
306  if (!X86ScalarSSEf64) {
309  if (Subtarget.is64Bit()) {
311  // Without SSE, i64->f64 goes through memory.
313  }
314  } else if (!Subtarget.is64Bit())
316 
317  // Scalar integer divide and remainder are lowered to use operations that
318  // produce two results, to match the available instructions. This exposes
319  // the two-result form to trivial CSE, which is able to combine x/y and x%y
320  // into a single instruction.
321  //
322  // Scalar integer multiply-high is also lowered to use two-result
323  // operations, to match the available instructions. However, plain multiply
324  // (low) operations are left as Legal, as there are single-result
325  // instructions for this in x86. Using the two-result multiply instructions
326  // when both high and low results are needed must be arranged by dagcombine.
327  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
334  }
335 
338  for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
342  }
343  if (Subtarget.is64Bit())
349 
354 
355  // Promote the i8 variants and force them on up to i32 which has a shorter
356  // encoding.
359  if (!Subtarget.hasBMI()) {
364  if (Subtarget.is64Bit()) {
367  }
368  }
369 
370  if (Subtarget.hasLZCNT()) {
371  // When promoting the i8 variants, force them to i32 for a shorter
372  // encoding.
375  } else {
382  if (Subtarget.is64Bit()) {
385  }
386  }
387 
388  // Special handling for half-precision floating point conversions.
389  // If we don't have F16C support, then lower half float conversions
390  // into library calls.
391  if (Subtarget.useSoftFloat() || !Subtarget.hasF16C()) {
394  }
395 
396  // There's never any support for operations beyond MVT::f32.
401 
408 
409  if (Subtarget.hasPOPCNT()) {
411  } else {
415  if (Subtarget.is64Bit())
417  }
418 
420 
421  if (!Subtarget.hasMOVBE())
423 
424  // These should be promoted to a larger select which is supported.
426  // X86 wants to expand cmov itself.
427  for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
430  }
431  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
432  if (VT == MVT::i64 && !Subtarget.is64Bit())
433  continue;
436  }
437 
438  // Custom action for SELECT MMX and expand action for SELECT_CC MMX
441 
443  // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
444  // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
449  setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
450 
451  // Darwin ABI issue.
452  for (auto VT : { MVT::i32, MVT::i64 }) {
453  if (VT == MVT::i64 && !Subtarget.is64Bit())
454  continue;
461  }
462 
463  // 64-bit shl, sra, srl (iff 32-bit x86)
464  for (auto VT : { MVT::i32, MVT::i64 }) {
465  if (VT == MVT::i64 && !Subtarget.is64Bit())
466  continue;
470  }
471 
472  if (Subtarget.hasSSEPrefetch() || Subtarget.has3DNow())
474 
476 
477  // Expand certain atomics
478  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
486  }
487 
488  if (Subtarget.hasCmpxchg16b()) {
490  }
491 
492  // FIXME - use subtarget debug flags
493  if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
494  !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
497  }
498 
501 
504 
507 
508  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
511  bool Is64Bit = Subtarget.is64Bit();
513  setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
514 
517 
519 
520  // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
523 
524  if (!Subtarget.useSoftFloat() && X86ScalarSSEf64) {
525  // f32 and f64 use SSE.
526  // Set up the FP register classes.
527  addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
528  : &X86::FR32RegClass);
529  addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
530  : &X86::FR64RegClass);
531 
532  for (auto VT : { MVT::f32, MVT::f64 }) {
533  // Use ANDPD to simulate FABS.
535 
536  // Use XORP to simulate FNEG.
538 
539  // Use ANDPD and ORPD to simulate FCOPYSIGN.
541 
542  // These might be better off as horizontal vector ops.
545 
546  // We don't support sin/cos/fmod
547  setOperationAction(ISD::FSIN , VT, Expand);
548  setOperationAction(ISD::FCOS , VT, Expand);
549  setOperationAction(ISD::FSINCOS, VT, Expand);
550  }
551 
552  // Lower this to MOVMSK plus an AND.
555 
556  } else if (!useSoftFloat() && X86ScalarSSEf32 && (UseX87 || Is64Bit)) {
557  // Use SSE for f32, x87 for f64.
558  // Set up the FP register classes.
559  addRegisterClass(MVT::f32, &X86::FR32RegClass);
560  if (UseX87)
561  addRegisterClass(MVT::f64, &X86::RFP64RegClass);
562 
563  // Use ANDPS to simulate FABS.
565 
566  // Use XORP to simulate FNEG.
568 
569  if (UseX87)
571 
572  // Use ANDPS and ORPS to simulate FCOPYSIGN.
573  if (UseX87)
576 
577  // We don't support sin/cos/fmod
581 
582  if (UseX87) {
583  // Always expand sin/cos functions even though x87 has an instruction.
587  }
588  } else if (UseX87) {
589  // f32 and f64 in x87.
590  // Set up the FP register classes.
591  addRegisterClass(MVT::f64, &X86::RFP64RegClass);
592  addRegisterClass(MVT::f32, &X86::RFP32RegClass);
593 
594  for (auto VT : { MVT::f32, MVT::f64 }) {
595  setOperationAction(ISD::UNDEF, VT, Expand);
596  setOperationAction(ISD::FCOPYSIGN, VT, Expand);
597 
598  // Always expand sin/cos functions even though x87 has an instruction.
599  setOperationAction(ISD::FSIN , VT, Expand);
600  setOperationAction(ISD::FCOS , VT, Expand);
601  setOperationAction(ISD::FSINCOS, VT, Expand);
602  }
603  }
604 
605  // Expand FP32 immediates into loads from the stack, save special cases.
606  if (isTypeLegal(MVT::f32)) {
607  if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
608  addLegalFPImmediate(APFloat(+0.0f)); // FLD0
609  addLegalFPImmediate(APFloat(+1.0f)); // FLD1
610  addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
611  addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
612  } else // SSE immediates.
613  addLegalFPImmediate(APFloat(+0.0f)); // xorps
614  }
615  // Expand FP64 immediates into loads from the stack, save special cases.
616  if (isTypeLegal(MVT::f64)) {
617  if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
618  addLegalFPImmediate(APFloat(+0.0)); // FLD0
619  addLegalFPImmediate(APFloat(+1.0)); // FLD1
620  addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
621  addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
622  } else // SSE immediates.
623  addLegalFPImmediate(APFloat(+0.0)); // xorpd
624  }
625 
626  // We don't support FMA.
629 
630  // Long double always uses X87, except f128 in MMX.
631  if (UseX87) {
632  if (Subtarget.is64Bit() && Subtarget.hasMMX()) {
633  addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
634  : &X86::VR128RegClass);
639  }
640 
641  addRegisterClass(MVT::f80, &X86::RFP80RegClass);
644  {
646  addLegalFPImmediate(TmpFlt); // FLD0
647  TmpFlt.changeSign();
648  addLegalFPImmediate(TmpFlt); // FLD0/FCHS
649 
650  bool ignored;
651  APFloat TmpFlt2(+1.0);
653  &ignored);
654  addLegalFPImmediate(TmpFlt2); // FLD1
655  TmpFlt2.changeSign();
656  addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
657  }
658 
659  // Always expand sin/cos functions even though x87 has an instruction.
663 
670  }
671 
672  // Always use a library call for pow.
676 
684 
685  // Some FP actions are always expanded for vector types.
686  for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
688  setOperationAction(ISD::FSIN, VT, Expand);
689  setOperationAction(ISD::FSINCOS, VT, Expand);
690  setOperationAction(ISD::FCOS, VT, Expand);
691  setOperationAction(ISD::FREM, VT, Expand);
692  setOperationAction(ISD::FCOPYSIGN, VT, Expand);
693  setOperationAction(ISD::FPOW, VT, Expand);
694  setOperationAction(ISD::FLOG, VT, Expand);
695  setOperationAction(ISD::FLOG2, VT, Expand);
696  setOperationAction(ISD::FLOG10, VT, Expand);
697  setOperationAction(ISD::FEXP, VT, Expand);
698  setOperationAction(ISD::FEXP2, VT, Expand);
699  }
700 
701  // First set operation action for all vector types to either promote
702  // (for widening) or expand (for scalarization). Then we will selectively
703  // turn on ones that can be effectively codegen'd.
704  for (MVT VT : MVT::vector_valuetypes()) {
705  setOperationAction(ISD::SDIV, VT, Expand);
706  setOperationAction(ISD::UDIV, VT, Expand);
707  setOperationAction(ISD::SREM, VT, Expand);
708  setOperationAction(ISD::UREM, VT, Expand);
713  setOperationAction(ISD::FMA, VT, Expand);
714  setOperationAction(ISD::FFLOOR, VT, Expand);
715  setOperationAction(ISD::FCEIL, VT, Expand);
716  setOperationAction(ISD::FTRUNC, VT, Expand);
717  setOperationAction(ISD::FRINT, VT, Expand);
718  setOperationAction(ISD::FNEARBYINT, VT, Expand);
719  setOperationAction(ISD::SMUL_LOHI, VT, Expand);
720  setOperationAction(ISD::MULHS, VT, Expand);
721  setOperationAction(ISD::UMUL_LOHI, VT, Expand);
722  setOperationAction(ISD::MULHU, VT, Expand);
723  setOperationAction(ISD::SDIVREM, VT, Expand);
724  setOperationAction(ISD::UDIVREM, VT, Expand);
725  setOperationAction(ISD::CTPOP, VT, Expand);
726  setOperationAction(ISD::CTTZ, VT, Expand);
727  setOperationAction(ISD::CTLZ, VT, Expand);
728  setOperationAction(ISD::ROTL, VT, Expand);
729  setOperationAction(ISD::ROTR, VT, Expand);
730  setOperationAction(ISD::BSWAP, VT, Expand);
731  setOperationAction(ISD::SETCC, VT, Expand);
732  setOperationAction(ISD::FP_TO_UINT, VT, Expand);
733  setOperationAction(ISD::FP_TO_SINT, VT, Expand);
734  setOperationAction(ISD::UINT_TO_FP, VT, Expand);
735  setOperationAction(ISD::SINT_TO_FP, VT, Expand);
737  setOperationAction(ISD::TRUNCATE, VT, Expand);
740  setOperationAction(ISD::ANY_EXTEND, VT, Expand);
741  setOperationAction(ISD::SELECT_CC, VT, Expand);
742  for (MVT InnerVT : MVT::vector_valuetypes()) {
743  setTruncStoreAction(InnerVT, VT, Expand);
744 
745  setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
746  setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
747 
748  // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
749  // types, we have to deal with them whether we ask for Expansion or not.
750  // Setting Expand causes its own optimisation problems though, so leave
751  // them legal.
752  if (VT.getVectorElementType() == MVT::i1)
753  setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
754 
755  // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
756  // split/scalarized right now.
757  if (VT.getVectorElementType() == MVT::f16)
758  setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
759  }
760  }
761 
762  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
763  // with -msoft-float, disable use of MMX as well.
764  if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
765  addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
766  // No operations on x86mmx supported, everything uses intrinsics.
767  }
768 
769  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
770  addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
771  : &X86::VR128RegClass);
772 
782  }
783 
784  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
785  addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
786  : &X86::VR128RegClass);
787 
788  // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
789  // registers cannot be used even for integer operations.
790  addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
791  : &X86::VR128RegClass);
792  addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
793  : &X86::VR128RegClass);
794  addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
795  : &X86::VR128RegClass);
796  addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
797  : &X86::VR128RegClass);
798 
799  for (auto VT : { MVT::v2i8, MVT::v4i8, MVT::v8i8,
805  }
806 
813 
827 
828  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
830  setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
831  setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
832  setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
833  }
834 
843 
845  // Use widening instead of promotion.
846  for (auto VT : { MVT::v8i8, MVT::v4i8, MVT::v2i8,
847  MVT::v4i16, MVT::v2i16 }) {
852  }
853  }
854 
858 
859  // Provide custom widening for v2f32 setcc. This is really for VLX when
860  // setcc result type returns v2i1/v4i1 vector for v2f32/v4f32 leading to
861  // type legalization changing the result type to v4i1 during widening.
862  // It works fine for SSE2 and is probably faster so no need to qualify with
863  // VLX support.
865 
866  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
870 
871  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
872  // setcc all the way to isel and prefer SETGT in some isel patterns.
875  }
876 
877  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
883  }
884 
885  // We support custom legalizing of sext and anyext loads for specific
886  // memory vector types which we can load as a scalar (or sequence of
887  // scalars) and extend in-register to a legal 128-bit vector type. For sext
888  // loads these must work with a single scalar load.
889  for (MVT VT : MVT::integer_vector_valuetypes()) {
896  }
897 
898  for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
902 
903  if (VT == MVT::v2i64 && !Subtarget.is64Bit())
904  continue;
905 
908  }
909 
910  // Custom lower v2i64 and v2f64 selects.
916 
920 
921  // Custom legalize these to avoid over promotion or custom promotion.
932 
933  // By marking FP_TO_SINT v8i16 as Custom, will trick type legalization into
934  // promoting v8i8 FP_TO_UINT into FP_TO_SINT. When the v8i16 FP_TO_SINT is
935  // split again based on the input type, this will cause an AssertSExt i16 to
936  // be emitted instead of an AssertZExt. This will allow packssdw followed by
937  // packuswb to be used to truncate to v8i8. This is necessary since packusdw
938  // isn't available until sse4.1.
940 
943 
945 
946  // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
948 
951 
952  for (MVT VT : MVT::fp_vector_valuetypes())
954 
955  // We want to legalize this to an f64 load rather than an i64 load on
956  // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
957  // store.
966 
970  if (!Subtarget.hasAVX512())
972 
976 
979 
986  } else {
988  }
989 
990  // In the customized shift lowering, the legal v4i32/v2i64 cases
991  // in AVX2 will be recognized.
992  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
996  }
997 
1000 
1001  // With AVX512, expanding (and promoting the shifts) is better.
1002  if (!Subtarget.hasAVX512())
1004  }
1005 
1006  if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1015 
1016  // These might be better off as horizontal vector ops.
1021  }
1022 
1023  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1024  for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1025  setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
1026  setOperationAction(ISD::FCEIL, RoundedTy, Legal);
1027  setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
1028  setOperationAction(ISD::FRINT, RoundedTy, Legal);
1030  }
1031 
1040 
1041  // FIXME: Do we need to handle scalar-to-vector here?
1043 
1044  // We directly match byte blends in the backend as they match the VSELECT
1045  // condition form.
1047 
1048  // SSE41 brings specific instructions for doing vector sign extend even in
1049  // cases where we don't have SRA.
1050  for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1053  }
1054 
1056  // Avoid narrow result types when widening. The legal types are listed
1057  // in the next loop.
1058  for (MVT VT : MVT::integer_vector_valuetypes()) {
1062  }
1063  }
1064 
1065  // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1066  for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1075  }
1076 
1077  // i8 vectors are custom because the source register and source
1078  // source memory operand types are not the same width.
1080  }
1081 
1082  if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1083  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1086 
1087  // XOP can efficiently perform BITREVERSE with VPPERM.
1088  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1090 
1091  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1094  }
1095 
1096  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1097  bool HasInt256 = Subtarget.hasInt256();
1098 
1099  addRegisterClass(MVT::v32i8, Subtarget.hasVLX() ? &X86::VR256XRegClass
1100  : &X86::VR256RegClass);
1101  addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1102  : &X86::VR256RegClass);
1103  addRegisterClass(MVT::v8i32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1104  : &X86::VR256RegClass);
1105  addRegisterClass(MVT::v8f32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1106  : &X86::VR256RegClass);
1107  addRegisterClass(MVT::v4i64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1108  : &X86::VR256RegClass);
1109  addRegisterClass(MVT::v4f64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1110  : &X86::VR256RegClass);
1111 
1112  for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1121  }
1122 
1123  // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1124  // even though v8i16 is a legal type.
1128 
1131 
1132  if (!Subtarget.hasAVX512())
1134 
1135  for (MVT VT : MVT::fp_vector_valuetypes())
1137 
1138  // In the customized shift lowering, the legal v8i32/v4i64 cases
1139  // in AVX2 will be recognized.
1140  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1144  }
1145 
1147  // These types need custom splitting if their input is a 128-bit vector.
1152  }
1153 
1156 
1157  // With BWI, expanding (and promoting the shifts) is the better.
1158  if (!Subtarget.hasBWI())
1160 
1167 
1168  for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1172  }
1173 
1178 
1179  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1183 
1184  // TODO - remove this once 256-bit X86ISD::ANDNP correctly split.
1185  setOperationAction(ISD::CTTZ, VT, HasInt256 ? Expand : Custom);
1186 
1187  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1188  // setcc all the way to isel and prefer SETGT in some isel patterns.
1189  setCondCodeAction(ISD::SETLT, VT, Custom);
1190  setCondCodeAction(ISD::SETLE, VT, Custom);
1191  }
1192 
1193  if (Subtarget.hasAnyFMA()) {
1194  for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1197  }
1198 
1199  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1200  setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1201  setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1202  }
1203 
1206  setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1208 
1211  setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1212  setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1215 
1221 
1222  setOperationAction(ISD::UADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1223  setOperationAction(ISD::SADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1224  setOperationAction(ISD::USUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1225  setOperationAction(ISD::SSUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1226  setOperationAction(ISD::UADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1227  setOperationAction(ISD::SADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1228  setOperationAction(ISD::USUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1229  setOperationAction(ISD::SSUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1230 
1231  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1232  setOperationAction(ISD::ABS, VT, HasInt256 ? Legal : Custom);
1233  setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1234  setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1235  setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1236  setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1237  }
1238 
1239  for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1242  }
1243 
1244  if (HasInt256) {
1245  // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1246  // when we have a 256bit-wide blend with immediate.
1248 
1249  // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1250  for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1257  }
1258  }
1259 
1260  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1264  }
1265 
1266  // Extract subvector is special because the value type
1267  // (result) is 128-bit but the source is 256-bit wide.
1268  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1269  MVT::v4f32, MVT::v2f64 }) {
1271  }
1272 
1273  // Custom lower several nodes for 256-bit types.
1275  MVT::v8f32, MVT::v4f64 }) {
1278  setOperationAction(ISD::VSELECT, VT, Custom);
1284  }
1285 
1286  if (HasInt256)
1288 
1289  if (HasInt256) {
1290  // Custom legalize 2x32 to get a little better code.
1293 
1294  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1296  setOperationAction(ISD::MGATHER, VT, Custom);
1297  }
1298  }
1299 
1300  // This block controls legalization of the mask vector sizes that are
1301  // available with AVX512. 512-bit vectors are in a separate block controlled
1302  // by useAVX512Regs.
1303  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1304  addRegisterClass(MVT::v1i1, &X86::VK1RegClass);
1305  addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1306  addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1307  addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1308  addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1309 
1313 
1320 
1321  // There is no byte sized k-register load or store without AVX512DQ.
1322  if (!Subtarget.hasDQI()) {
1327 
1332  }
1333 
1334  // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1335  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1339  }
1340 
1341  for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1352 
1357  setOperationAction(ISD::VSELECT, VT, Expand);
1358  }
1359 
1367  for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1369  }
1370 
1371  // This block controls legalization for 512-bit operations with 32/64 bit
1372  // elements. 512-bits can be disabled based on prefer-vector-width and
1373  // required-vector-width function attributes.
1374  if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1375  addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1376  addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1377  addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1378  addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1379 
1380  for (MVT VT : MVT::fp_vector_valuetypes())
1382 
1383  for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1389  }
1390 
1391  for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1396  }
1397 
1408 
1414 
1415  if (!Subtarget.hasVLX()) {
1416  // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1417  // to 512-bit rather than use the AVX2 instructions so that we can use
1418  // k-masks.
1419  for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1423  }
1424  }
1425 
1434 
1436  // Need to custom widen this if we don't have AVX512BW.
1440  }
1441 
1442  for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1448  }
1449 
1450  // Without BWI we need to use custom lowering to handle MVT::v64i8 input.
1451  for (auto VT : {MVT::v16i32, MVT::v8i64, MVT::v64i8}) {
1454  }
1455 
1460 
1463 
1466 
1473 
1474  for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1487 
1488  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1489  // setcc all the way to isel and prefer SETGT in some isel patterns.
1492  }
1493 
1494  if (Subtarget.hasDQI()) {
1499 
1501  }
1502 
1503  if (Subtarget.hasCDI()) {
1504  // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1505  for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1507  }
1508  } // Subtarget.hasCDI()
1509 
1510  if (Subtarget.hasVPOPCNTDQ()) {
1511  for (auto VT : { MVT::v16i32, MVT::v8i64 })
1513  }
1514 
1515  // Extract subvector is special because the value type
1516  // (result) is 256-bit but the source is 512-bit wide.
1517  // 128-bit was made Legal under AVX1.
1518  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1521 
1522  for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1534  }
1535  // Need to custom split v32i16/v64i8 bitcasts.
1536  if (!Subtarget.hasBWI()) {
1539  }
1540 
1541  if (Subtarget.hasVBMI2()) {
1542  for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1545  }
1546  }
1547  }// has AVX-512
1548 
1549  // This block controls legalization for operations that don't have
1550  // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
1551  // narrower widths.
1552  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1553  // These operations are handled on non-VLX by artificially widening in
1554  // isel patterns.
1555  // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1556 
1562 
1563  for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1569  }
1570 
1571  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1574  }
1575 
1576  // Custom legalize 2x32 to get a little better code.
1579 
1580  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1583 
1584  if (Subtarget.hasDQI()) {
1585  for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1590 
1592  }
1593  }
1594 
1595  if (Subtarget.hasCDI()) {
1596  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1598  }
1599  } // Subtarget.hasCDI()
1600 
1601  if (Subtarget.hasVPOPCNTDQ()) {
1602  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
1604  }
1605  }
1606 
1607  // This block control legalization of v32i1/v64i1 which are available with
1608  // AVX512BW. 512-bit v32i16 and v64i8 vector legalization is controlled with
1609  // useBWIRegs.
1610  if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1611  addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1612  addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1613 
1614  for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
1618  setOperationAction(ISD::VSELECT, VT, Expand);
1623 
1631  }
1632 
1637  for (auto VT : { MVT::v16i1, MVT::v32i1 })
1639 
1640  // Extends from v32i1 masks to 256-bit vectors.
1644  }
1645 
1646  // This block controls legalization for v32i16 and v64i8. 512-bits can be
1647  // disabled based on prefer-vector-width and required-vector-width function
1648  // attributes.
1649  if (!Subtarget.useSoftFloat() && Subtarget.useBWIRegs()) {
1650  addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1651  addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1652 
1653  // Extends from v64i1 masks to 512-bit vectors.
1657 
1681 
1684 
1686 
1687  for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1707 
1708  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1709  // setcc all the way to isel and prefer SETGT in some isel patterns.
1712  }
1713 
1714  for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1716  }
1717 
1718  if (Subtarget.hasBITALG()) {
1719  for (auto VT : { MVT::v64i8, MVT::v32i16 })
1721  }
1722 
1723  if (Subtarget.hasVBMI2()) {
1726  }
1727  }
1728 
1729  if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1730  for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1731  setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1732  setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
1733  }
1734 
1735  // These operations are handled on non-VLX by artificially widening in
1736  // isel patterns.
1737  // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1738 
1739  if (Subtarget.hasBITALG()) {
1740  for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
1742  }
1743  }
1744 
1745  if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
1751 
1757 
1758  if (Subtarget.hasDQI()) {
1759  // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
1760  // v2f32 UINT_TO_FP is already custom under SSE2.
1763  "Unexpected operation action!");
1764  // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
1767  }
1768 
1769  if (Subtarget.hasBWI()) {
1772  }
1773 
1774  if (Subtarget.hasVBMI2()) {
1775  // TODO: Make these legal even without VLX?
1776  for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64,
1780  }
1781  }
1782  }
1783 
1784  // We want to custom lower some of our intrinsics.
1788  if (!Subtarget.is64Bit()) {
1791  }
1792 
1793  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1794  // handle type legalization for these operations here.
1795  //
1796  // FIXME: We really should do custom legalization for addition and
1797  // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1798  // than generic legalization for 64-bit multiplication-with-overflow, though.
1799  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1800  if (VT == MVT::i64 && !Subtarget.is64Bit())
1801  continue;
1802  // Add/Sub/Mul with overflow operations are custom lowered.
1809 
1810  // Support carry in as value rather than glue.
1814  }
1815 
1816  if (!Subtarget.is64Bit()) {
1817  // These libcalls are not available in 32-bit.
1818  setLibcallName(RTLIB::SHL_I128, nullptr);
1819  setLibcallName(RTLIB::SRL_I128, nullptr);
1820  setLibcallName(RTLIB::SRA_I128, nullptr);
1821  setLibcallName(RTLIB::MUL_I128, nullptr);
1822  }
1823 
1824  // Combine sin / cos into _sincos_stret if it is available.
1825  if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1826  getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1829  }
1830 
1831  if (Subtarget.isTargetWin64()) {
1838  }
1839 
1840  // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
1841  // is. We should promote the value to 64-bits to solve this.
1842  // This is what the CRT headers do - `fmodf` is an inline header
1843  // function casting to f64 and calling `fmod`.
1844  if (Subtarget.is32Bit() && (Subtarget.isTargetKnownWindowsMSVC() ||
1845  Subtarget.isTargetWindowsItanium()))
1846  for (ISD::NodeType Op :
1851 
1852  // We have target-specific dag combine patterns for the following nodes:
1890 
1892 
1893  MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1895  MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1897  MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1899 
1900  // TODO: These control memcmp expansion in CGP and could be raised higher, but
1901  // that needs to benchmarked and balanced with the potential use of vector
1902  // load/store types (PR33329, PR33914).
1903  MaxLoadsPerMemcmp = 2;
1905 
1906  // Set loop alignment to 2^ExperimentalPrefLoopAlignment bytes (default: 2^4).
1908 
1909  // An out-of-order CPU can speculatively execute past a predictable branch,
1910  // but a conditional move could be stalled by an expensive earlier operation.
1911  PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
1912  EnableExtLdPromotion = true;
1913  setPrefFunctionAlignment(4); // 2^4 bytes.
1914 
1916 }
1917 
1918 // This has so far only been implemented for 64-bit MachO.
1920  return Subtarget.isTargetMachO() && Subtarget.is64Bit();
1921 }
1922 
1924  // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
1925  return Subtarget.getTargetTriple().isOSMSVCRT();
1926 }
1927 
1929  const SDLoc &DL) const {
1930  EVT PtrTy = getPointerTy(DAG.getDataLayout());
1931  unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
1932  MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
1933  return SDValue(Node, 0);
1934 }
1935 
1938  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1939  return TypeSplitVector;
1940 
1942  VT.getVectorNumElements() != 1 &&
1943  VT.getVectorElementType() != MVT::i1)
1944  return TypeWidenVector;
1945 
1947 }
1948 
1950  CallingConv::ID CC,
1951  EVT VT) const {
1952  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1953  return MVT::v32i8;
1954  return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1955 }
1956 
1958  CallingConv::ID CC,
1959  EVT VT) const {
1960  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1961  return 1;
1962  return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1963 }
1964 
1967  EVT VT) const {
1968  if (!VT.isVector())
1969  return MVT::i8;
1970 
1971  if (Subtarget.hasAVX512()) {
1972  const unsigned NumElts = VT.getVectorNumElements();
1973 
1974  // Figure out what this type will be legalized to.
1975  EVT LegalVT = VT;
1976  while (getTypeAction(Context, LegalVT) != TypeLegal)
1977  LegalVT = getTypeToTransformTo(Context, LegalVT);
1978 
1979  // If we got a 512-bit vector then we'll definitely have a vXi1 compare.
1980  if (LegalVT.getSimpleVT().is512BitVector())
1981  return EVT::getVectorVT(Context, MVT::i1, NumElts);
1982 
1983  if (LegalVT.getSimpleVT().isVector() && Subtarget.hasVLX()) {
1984  // If we legalized to less than a 512-bit vector, then we will use a vXi1
1985  // compare for vXi32/vXi64 for sure. If we have BWI we will also support
1986  // vXi16/vXi8.
1987  MVT EltVT = LegalVT.getSimpleVT().getVectorElementType();
1988  if (Subtarget.hasBWI() || EltVT.getSizeInBits() >= 32)
1989  return EVT::getVectorVT(Context, MVT::i1, NumElts);
1990  }
1991  }
1992 
1994 }
1995 
1996 /// Helper for getByValTypeAlignment to determine
1997 /// the desired ByVal argument alignment.
1998 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1999  if (MaxAlign == 16)
2000  return;
2001  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
2002  if (VTy->getBitWidth() == 128)
2003  MaxAlign = 16;
2004  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2005  unsigned EltAlign = 0;
2006  getMaxByValAlign(ATy->getElementType(), EltAlign);
2007  if (EltAlign > MaxAlign)
2008  MaxAlign = EltAlign;
2009  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2010  for (auto *EltTy : STy->elements()) {
2011  unsigned EltAlign = 0;
2012  getMaxByValAlign(EltTy, EltAlign);
2013  if (EltAlign > MaxAlign)
2014  MaxAlign = EltAlign;
2015  if (MaxAlign == 16)
2016  break;
2017  }
2018  }
2019 }
2020 
2021 /// Return the desired alignment for ByVal aggregate
2022 /// function arguments in the caller parameter area. For X86, aggregates
2023 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
2024 /// are at 4-byte boundaries.
2026  const DataLayout &DL) const {
2027  if (Subtarget.is64Bit()) {
2028  // Max of 8 and alignment of type.
2029  unsigned TyAlign = DL.getABITypeAlignment(Ty);
2030  if (TyAlign > 8)
2031  return TyAlign;
2032  return 8;
2033  }
2034 
2035  unsigned Align = 4;
2036  if (Subtarget.hasSSE1())
2037  getMaxByValAlign(Ty, Align);
2038  return Align;
2039 }
2040 
2041 /// Returns the target specific optimal type for load
2042 /// and store operations as a result of memset, memcpy, and memmove
2043 /// lowering. If DstAlign is zero that means it's safe to destination
2044 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
2045 /// means there isn't a need to check it against alignment requirement,
2046 /// probably because the source does not need to be loaded. If 'IsMemset' is
2047 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
2048 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
2049 /// source is constant so it does not need to be loaded.
2050 /// It returns EVT::Other if the type should be determined using generic
2051 /// target-independent logic.
2052 EVT
2054  unsigned DstAlign, unsigned SrcAlign,
2055  bool IsMemset, bool ZeroMemset,
2056  bool MemcpyStrSrc,
2057  MachineFunction &MF) const {
2058  const Function &F = MF.getFunction();
2059  if (!F.hasFnAttribute(Attribute::NoImplicitFloat)) {
2060  if (Size >= 16 &&
2061  (!Subtarget.isUnalignedMem16Slow() ||
2062  ((DstAlign == 0 || DstAlign >= 16) &&
2063  (SrcAlign == 0 || SrcAlign >= 16)))) {
2064  // FIXME: Check if unaligned 32-byte accesses are slow.
2065  if (Size >= 32 && Subtarget.hasAVX()) {
2066  // Although this isn't a well-supported type for AVX1, we'll let
2067  // legalization and shuffle lowering produce the optimal codegen. If we
2068  // choose an optimal type with a vector element larger than a byte,
2069  // getMemsetStores() may create an intermediate splat (using an integer
2070  // multiply) before we splat as a vector.
2071  return MVT::v32i8;
2072  }
2073  if (Subtarget.hasSSE2())
2074  return MVT::v16i8;
2075  // TODO: Can SSE1 handle a byte vector?
2076  // If we have SSE1 registers we should be able to use them.
2077  if (Subtarget.hasSSE1() && (Subtarget.is64Bit() || Subtarget.hasX87()))
2078  return MVT::v4f32;
2079  } else if ((!IsMemset || ZeroMemset) && !MemcpyStrSrc && Size >= 8 &&
2080  !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
2081  // Do not use f64 to lower memcpy if source is string constant. It's
2082  // better to use i32 to avoid the loads.
2083  // Also, do not use f64 to lower memset unless this is a memset of zeros.
2084  // The gymnastics of splatting a byte value into an XMM register and then
2085  // only using 8-byte stores (because this is a CPU with slow unaligned
2086  // 16-byte accesses) makes that a loser.
2087  return MVT::f64;
2088  }
2089  }
2090  // This is a compromise. If we reach here, unaligned accesses may be slow on
2091  // this target. However, creating smaller, aligned accesses could be even
2092  // slower and would certainly be a lot more code.
2093  if (Subtarget.is64Bit() && Size >= 8)
2094  return MVT::i64;
2095  return MVT::i32;
2096 }
2097 
2099  if (VT == MVT::f32)
2100  return X86ScalarSSEf32;
2101  else if (VT == MVT::f64)
2102  return X86ScalarSSEf64;
2103  return true;
2104 }
2105 
2106 bool
2108  unsigned,
2109  unsigned,
2110  bool *Fast) const {
2111  if (Fast) {
2112  switch (VT.getSizeInBits()) {
2113  default:
2114  // 8-byte and under are always assumed to be fast.
2115  *Fast = true;
2116  break;
2117  case 128:
2118  *Fast = !Subtarget.isUnalignedMem16Slow();
2119  break;
2120  case 256:
2121  *Fast = !Subtarget.isUnalignedMem32Slow();
2122  break;
2123  // TODO: What about AVX-512 (512-bit) accesses?
2124  }
2125  }
2126  // Misaligned accesses of any size are always allowed.
2127  return true;
2128 }
2129 
2130 /// Return the entry encoding for a jump table in the
2131 /// current function. The returned value is a member of the
2132 /// MachineJumpTableInfo::JTEntryKind enum.
2134  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2135  // symbol.
2136  if (isPositionIndependent() && Subtarget.isPICStyleGOT())
2138 
2139  // Otherwise, use the normal jump table encoding heuristics.
2141 }
2142 
2144  return Subtarget.useSoftFloat();
2145 }
2146 
2148  ArgListTy &Args) const {
2149 
2150  // Only relabel X86-32 for C / Stdcall CCs.
2151  if (Subtarget.is64Bit())
2152  return;
2153  if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
2154  return;
2155  unsigned ParamRegs = 0;
2156  if (auto *M = MF->getFunction().getParent())
2157  ParamRegs = M->getNumberRegisterParameters();
2158 
2159  // Mark the first N int arguments as having reg
2160  for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
2161  Type *T = Args[Idx].Ty;
2162  if (T->isIntOrPtrTy())
2163  if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
2164  unsigned numRegs = 1;
2165  if (MF->getDataLayout().getTypeAllocSize(T) > 4)
2166  numRegs = 2;
2167  if (ParamRegs < numRegs)
2168  return;
2169  ParamRegs -= numRegs;
2170  Args[Idx].IsInReg = true;
2171  }
2172  }
2173 }
2174 
2175 const MCExpr *
2177  const MachineBasicBlock *MBB,
2178  unsigned uid,MCContext &Ctx) const{
2179  assert(isPositionIndependent() && Subtarget.isPICStyleGOT());
2180  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2181  // entries.
2182  return MCSymbolRefExpr::create(MBB->getSymbol(),
2184 }
2185 
2186 /// Returns relocation base for the given PIC jumptable.
2188  SelectionDAG &DAG) const {
2189  if (!Subtarget.is64Bit())
2190  // This doesn't have SDLoc associated with it, but is not really the
2191  // same as a Register.
2192  return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2193  getPointerTy(DAG.getDataLayout()));
2194  return Table;
2195 }
2196 
2197 /// This returns the relocation base for the given PIC jumptable,
2198 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2201  MCContext &Ctx) const {
2202  // X86-64 uses RIP relative addressing based on the jump table label.
2203  if (Subtarget.isPICStyleRIPRel())
2204  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2205 
2206  // Otherwise, the reference is relative to the PIC base.
2207  return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2208 }
2209 
2210 std::pair<const TargetRegisterClass *, uint8_t>
2212  MVT VT) const {
2213  const TargetRegisterClass *RRC = nullptr;
2214  uint8_t Cost = 1;
2215  switch (VT.SimpleTy) {
2216  default:
2218  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2219  RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2220  break;
2221  case MVT::x86mmx:
2222  RRC = &X86::VR64RegClass;
2223  break;
2224  case MVT::f32: case MVT::f64:
2225  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2226  case MVT::v4f32: case MVT::v2f64:
2227  case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
2228  case MVT::v8f32: case MVT::v4f64:
2229  case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
2230  case MVT::v16f32: case MVT::v8f64:
2231  RRC = &X86::VR128XRegClass;
2232  break;
2233  }
2234  return std::make_pair(RRC, Cost);
2235 }
2236 
2237 unsigned X86TargetLowering::getAddressSpace() const {
2238  if (Subtarget.is64Bit())
2239  return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
2240  return 256;
2241 }
2242 
2243 static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2244  return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2245  (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2246 }
2247 
2249  unsigned Offset, unsigned AddressSpace) {
2252  Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2253 }
2254 
2256  // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2257  // tcbhead_t; use it instead of the usual global variable (see
2258  // sysdeps/{i386,x86_64}/nptl/tls.h)
2259  if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2260  if (Subtarget.isTargetFuchsia()) {
2261  // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2262  return SegmentOffset(IRB, 0x10, getAddressSpace());
2263  } else {
2264  // %fs:0x28, unless we're using a Kernel code model, in which case
2265  // it's %gs:0x28. gs:0x14 on i386.
2266  unsigned Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2267  return SegmentOffset(IRB, Offset, getAddressSpace());
2268  }
2269  }
2270 
2271  return TargetLowering::getIRStackGuard(IRB);
2272 }
2273 
2275  // MSVC CRT provides functionalities for stack protection.
2276  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2278  // MSVC CRT has a global variable holding security cookie.
2279  M.getOrInsertGlobal("__security_cookie",
2281 
2282  // MSVC CRT has a function to validate security cookie.
2283  auto *SecurityCheckCookie = cast<Function>(
2284  M.getOrInsertFunction("__security_check_cookie",
2287  SecurityCheckCookie->setCallingConv(CallingConv::X86_FastCall);
2288  SecurityCheckCookie->addAttribute(1, Attribute::AttrKind::InReg);
2289  return;
2290  }
2291  // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2292  if (hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2293  return;
2295 }
2296 
2298  // MSVC CRT has a global variable holding security cookie.
2299  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2301  return M.getGlobalVariable("__security_cookie");
2302  }
2304 }
2305 
2307  // MSVC CRT has a function to validate security cookie.
2308  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2310  return M.getFunction("__security_check_cookie");
2311  }
2313 }
2314 
2316  if (Subtarget.getTargetTriple().isOSContiki())
2317  return getDefaultSafeStackPointerLocation(IRB, false);
2318 
2319  // Android provides a fixed TLS slot for the SafeStack pointer. See the
2320  // definition of TLS_SLOT_SAFESTACK in
2321  // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2322  if (Subtarget.isTargetAndroid()) {
2323  // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2324  // %gs:0x24 on i386
2325  unsigned Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2326  return SegmentOffset(IRB, Offset, getAddressSpace());
2327  }
2328 
2329  // Fuchsia is similar.
2330  if (Subtarget.isTargetFuchsia()) {
2331  // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
2332  return SegmentOffset(IRB, 0x18, getAddressSpace());
2333  }
2334 
2336 }
2337 
2339  unsigned DestAS) const {
2340  assert(SrcAS != DestAS && "Expected different address spaces!");
2341 
2342  return SrcAS < 256 && DestAS < 256;
2343 }
2344 
2345 //===----------------------------------------------------------------------===//
2346 // Return Value Calling Convention Implementation
2347 //===----------------------------------------------------------------------===//
2348 
2349 bool X86TargetLowering::CanLowerReturn(
2350  CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2351  const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2353  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2354  return CCInfo.CheckReturn(Outs, RetCC_X86);
2355 }
2356 
2357 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2358  static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2359  return ScratchRegs;
2360 }
2361 
2362 /// Lowers masks values (v*i1) to the local register values
2363 /// \returns DAG node after lowering to register type
2364 static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
2365  const SDLoc &Dl, SelectionDAG &DAG) {
2366  EVT ValVT = ValArg.getValueType();
2367 
2368  if (ValVT == MVT::v1i1)
2369  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Dl, ValLoc, ValArg,
2370  DAG.getIntPtrConstant(0, Dl));
2371 
2372  if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
2373  (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
2374  // Two stage lowering might be required
2375  // bitcast: v8i1 -> i8 / v16i1 -> i16
2376  // anyextend: i8 -> i32 / i16 -> i32
2377  EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
2378  SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
2379  if (ValLoc == MVT::i32)
2380  ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
2381  return ValToCopy;
2382  }
2383 
2384  if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
2385  (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
2386  // One stage lowering is required
2387  // bitcast: v32i1 -> i32 / v64i1 -> i64
2388  return DAG.getBitcast(ValLoc, ValArg);
2389  }
2390 
2391  return DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValArg);
2392 }
2393 
2394 /// Breaks v64i1 value into two registers and adds the new node to the DAG
2396  const SDLoc &Dl, SelectionDAG &DAG, SDValue Chain, SDValue &Arg,
2397  SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, CCValAssign &VA,
2398  CCValAssign &NextVA, const X86Subtarget &Subtarget) {
2399  assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
2400  assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2401  assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value");
2402  assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2403  "The value should reside in two registers");
2404 
2405  // Before splitting the value we cast it to i64
2406  Arg = DAG.getBitcast(MVT::i64, Arg);
2407 
2408  // Splitting the value into two i32 types
2409  SDValue Lo, Hi;
2410  Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2411  DAG.getConstant(0, Dl, MVT::i32));
2412  Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2413  DAG.getConstant(1, Dl, MVT::i32));
2414 
2415  // Attach the two i32 types into corresponding registers
2416  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
2417  RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
2418 }
2419 
2420 SDValue
2421 X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2422  bool isVarArg,
2423  const SmallVectorImpl<ISD::OutputArg> &Outs,
2424  const SmallVectorImpl<SDValue> &OutVals,
2425  const SDLoc &dl, SelectionDAG &DAG) const {
2426  MachineFunction &MF = DAG.getMachineFunction();
2428 
2429  // In some cases we need to disable registers from the default CSR list.
2430  // For example, when they are used for argument passing.
2431  bool ShouldDisableCalleeSavedRegister =
2432  CallConv == CallingConv::X86_RegCall ||
2433  MF.getFunction().hasFnAttribute("no_caller_saved_registers");
2434 
2435  if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2436  report_fatal_error("X86 interrupts may not return any value");
2437 
2439  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2440  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2441 
2442  SDValue Flag;
2443  SmallVector<SDValue, 6> RetOps;
2444  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2445  // Operand #1 = Bytes To Pop
2446  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2447  MVT::i32));
2448 
2449  // Copy the result values into the output registers.
2450  for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
2451  ++I, ++OutsIndex) {
2452  CCValAssign &VA = RVLocs[I];
2453  assert(VA.isRegLoc() && "Can only return in registers!");
2454 
2455  // Add the register to the CalleeSaveDisableRegs list.
2456  if (ShouldDisableCalleeSavedRegister)
2458 
2459  SDValue ValToCopy = OutVals[OutsIndex];
2460  EVT ValVT = ValToCopy.getValueType();
2461 
2462  // Promote values to the appropriate types.
2463  if (VA.getLocInfo() == CCValAssign::SExt)
2464  ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2465  else if (VA.getLocInfo() == CCValAssign::ZExt)
2466  ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2467  else if (VA.getLocInfo() == CCValAssign::AExt) {
2468  if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2469  ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
2470  else
2471  ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2472  }
2473  else if (VA.getLocInfo() == CCValAssign::BCvt)
2474  ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2475 
2477  "Unexpected FP-extend for return value.");
2478 
2479  // If this is x86-64, and we disabled SSE, we can't return FP values,
2480  // or SSE or MMX vectors.
2481  if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2482  VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2483  (Subtarget.is64Bit() && !Subtarget.hasSSE1())) {
2484  errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2485  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2486  } else if (ValVT == MVT::f64 &&
2487  (Subtarget.is64Bit() && !Subtarget.hasSSE2())) {
2488  // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2489  // llvm-gcc has never done it right and no one has noticed, so this
2490  // should be OK for now.
2491  errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2492  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2493  }
2494 
2495  // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2496  // the RET instruction and handled by the FP Stackifier.
2497  if (VA.getLocReg() == X86::FP0 ||
2498  VA.getLocReg() == X86::FP1) {
2499  // If this is a copy from an xmm register to ST(0), use an FPExtend to
2500  // change the value to the FP stack register class.
2501  if (isScalarFPTypeInSSEReg(VA.getValVT()))
2502  ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2503  RetOps.push_back(ValToCopy);
2504  // Don't emit a copytoreg.
2505  continue;
2506  }
2507 
2508  // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2509  // which is returned in RAX / RDX.
2510  if (Subtarget.is64Bit()) {
2511  if (ValVT == MVT::x86mmx) {
2512  if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2513  ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2514  ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2515  ValToCopy);
2516  // If we don't have SSE2 available, convert to v4f32 so the generated
2517  // register is legal.
2518  if (!Subtarget.hasSSE2())
2519  ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2520  }
2521  }
2522  }
2523 
2525 
2526  if (VA.needsCustom()) {
2527  assert(VA.getValVT() == MVT::v64i1 &&
2528  "Currently the only custom case is when we split v64i1 to 2 regs");
2529 
2530  Passv64i1ArgInRegs(dl, DAG, Chain, ValToCopy, RegsToPass, VA, RVLocs[++I],
2531  Subtarget);
2532 
2533  assert(2 == RegsToPass.size() &&
2534  "Expecting two registers after Pass64BitArgInRegs");
2535 
2536  // Add the second register to the CalleeSaveDisableRegs list.
2537  if (ShouldDisableCalleeSavedRegister)
2538  MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
2539  } else {
2540  RegsToPass.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2541  }
2542 
2543  // Add nodes to the DAG and add the values into the RetOps list
2544  for (auto &Reg : RegsToPass) {
2545  Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, Flag);
2546  Flag = Chain.getValue(1);
2547  RetOps.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
2548  }
2549  }
2550 
2551  // Swift calling convention does not require we copy the sret argument
2552  // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
2553 
2554  // All x86 ABIs require that for returning structs by value we copy
2555  // the sret argument into %rax/%eax (depending on ABI) for the return.
2556  // We saved the argument into a virtual register in the entry block,
2557  // so now we copy the value out and into %rax/%eax.
2558  //
2559  // Checking Function.hasStructRetAttr() here is insufficient because the IR
2560  // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2561  // false, then an sret argument may be implicitly inserted in the SelDAG. In
2562  // either case FuncInfo->setSRetReturnReg() will have been called.
2563  if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2564  // When we have both sret and another return value, we should use the
2565  // original Chain stored in RetOps[0], instead of the current Chain updated
2566  // in the above loop. If we only have sret, RetOps[0] equals to Chain.
2567 
2568  // For the case of sret and another return value, we have
2569  // Chain_0 at the function entry
2570  // Chain_1 = getCopyToReg(Chain_0) in the above loop
2571  // If we use Chain_1 in getCopyFromReg, we will have
2572  // Val = getCopyFromReg(Chain_1)
2573  // Chain_2 = getCopyToReg(Chain_1, Val) from below
2574 
2575  // getCopyToReg(Chain_0) will be glued together with
2576  // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
2577  // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
2578  // Data dependency from Unit B to Unit A due to usage of Val in
2579  // getCopyToReg(Chain_1, Val)
2580  // Chain dependency from Unit A to Unit B
2581 
2582  // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
2583  SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
2584  getPointerTy(MF.getDataLayout()));
2585 
2586  unsigned RetValReg
2587  = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
2588  X86::RAX : X86::EAX;
2589  Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2590  Flag = Chain.getValue(1);
2591 
2592  // RAX/EAX now acts like a return value.
2593  RetOps.push_back(
2594  DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2595 
2596  // Add the returned register to the CalleeSaveDisableRegs list.
2597  if (ShouldDisableCalleeSavedRegister)
2598  MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
2599  }
2600 
2601  const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
2602  const MCPhysReg *I =
2604  if (I) {
2605  for (; *I; ++I) {
2606  if (X86::GR64RegClass.contains(*I))
2607  RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2608  else
2609  llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2610  }
2611  }
2612 
2613  RetOps[0] = Chain; // Update chain.
2614 
2615  // Add the flag if we have it.
2616  if (Flag.getNode())
2617  RetOps.push_back(Flag);
2618 
2620  if (CallConv == CallingConv::X86_INTR)
2621  opcode = X86ISD::IRET;
2622  return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2623 }
2624 
2625 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2626  if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
2627  return false;
2628 
2629  SDValue TCChain = Chain;
2630  SDNode *Copy = *N->use_begin();
2631  if (Copy->getOpcode() == ISD::CopyToReg) {
2632  // If the copy has a glue operand, we conservatively assume it isn't safe to
2633  // perform a tail call.
2634  if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2635  return false;
2636  TCChain = Copy->getOperand(0);
2637  } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2638  return false;
2639 
2640  bool HasRet = false;
2641  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2642  UI != UE; ++UI) {
2643  if (UI->getOpcode() != X86ISD::RET_FLAG)
2644  return false;
2645  // If we are returning more than one value, we can definitely
2646  // not make a tail call see PR19530
2647  if (UI->getNumOperands() > 4)
2648  return false;
2649  if (UI->getNumOperands() == 4 &&
2650  UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2651  return false;
2652  HasRet = true;
2653  }
2654 
2655  if (!HasRet)
2656  return false;
2657 
2658  Chain = TCChain;
2659  return true;
2660 }
2661 
2662 EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
2663  ISD::NodeType ExtendKind) const {
2664  MVT ReturnMVT = MVT::i32;
2665 
2666  bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
2667  if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
2668  // The ABI does not require i1, i8 or i16 to be extended.
2669  //
2670  // On Darwin, there is code in the wild relying on Clang's old behaviour of
2671  // always extending i8/i16 return values, so keep doing that for now.
2672  // (PR26665).
2673  ReturnMVT = MVT::i8;
2674  }
2675 
2676  EVT MinVT = getRegisterType(Context, ReturnMVT);
2677  return VT.bitsLT(MinVT) ? MinVT : VT;
2678 }
2679 
2680 /// Reads two 32 bit registers and creates a 64 bit mask value.
2681 /// \param VA The current 32 bit value that need to be assigned.
2682 /// \param NextVA The next 32 bit value that need to be assigned.
2683 /// \param Root The parent DAG node.
2684 /// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
2685 /// glue purposes. In the case the DAG is already using
2686 /// physical register instead of virtual, we should glue
2687 /// our new SDValue to InFlag SDvalue.
2688 /// \return a new SDvalue of size 64bit.
2690  SDValue &Root, SelectionDAG &DAG,
2691  const SDLoc &Dl, const X86Subtarget &Subtarget,
2692  SDValue *InFlag = nullptr) {
2693  assert((Subtarget.hasBWI()) && "Expected AVX512BW target!");
2694  assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2695  assert(VA.getValVT() == MVT::v64i1 &&
2696  "Expecting first location of 64 bit width type");
2697  assert(NextVA.getValVT() == VA.getValVT() &&
2698  "The locations should have the same type");
2699  assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2700  "The values should reside in two registers");
2701 
2702  SDValue Lo, Hi;
2703  unsigned Reg;
2704  SDValue ArgValueLo, ArgValueHi;
2705 
2706  MachineFunction &MF = DAG.getMachineFunction();
2707  const TargetRegisterClass *RC = &X86::GR32RegClass;
2708 
2709  // Read a 32 bit value from the registers.
2710  if (nullptr == InFlag) {
2711  // When no physical register is present,
2712  // create an intermediate virtual register.
2713  Reg = MF.addLiveIn(VA.getLocReg(), RC);
2714  ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2715  Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2716  ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2717  } else {
2718  // When a physical register is available read the value from it and glue
2719  // the reads together.
2720  ArgValueLo =
2721  DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
2722  *InFlag = ArgValueLo.getValue(2);
2723  ArgValueHi =
2724  DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
2725  *InFlag = ArgValueHi.getValue(2);
2726  }
2727 
2728  // Convert the i32 type into v32i1 type.
2729  Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
2730 
2731  // Convert the i32 type into v32i1 type.
2732  Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
2733 
2734  // Concatenate the two values together.
2735  return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
2736 }
2737 
2738 /// The function will lower a register of various sizes (8/16/32/64)
2739 /// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
2740 /// \returns a DAG node contains the operand after lowering to mask type.
2741 static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
2742  const EVT &ValLoc, const SDLoc &Dl,
2743  SelectionDAG &DAG) {
2744  SDValue ValReturned = ValArg;
2745 
2746  if (ValVT == MVT::v1i1)
2747  return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
2748 
2749  if (ValVT == MVT::v64i1) {
2750  // In 32 bit machine, this case is handled by getv64i1Argument
2751  assert(ValLoc == MVT::i64 && "Expecting only i64 locations");
2752  // In 64 bit machine, There is no need to truncate the value only bitcast
2753  } else {
2754  MVT maskLen;
2755  switch (ValVT.getSimpleVT().SimpleTy) {
2756  case MVT::v8i1:
2757  maskLen = MVT::i8;
2758  break;
2759  case MVT::v16i1:
2760  maskLen = MVT::i16;
2761  break;
2762  case MVT::v32i1:
2763  maskLen = MVT::i32;
2764  break;
2765  default:
2766  llvm_unreachable("Expecting a vector of i1 types");
2767  }
2768 
2769  ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
2770  }
2771  return DAG.getBitcast(ValVT, ValReturned);
2772 }
2773 
2774 /// Lower the result values of a call into the
2775 /// appropriate copies out of appropriate physical registers.
2776 ///
2777 SDValue X86TargetLowering::LowerCallResult(
2778  SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2779  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2780  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
2781  uint32_t *RegMask) const {
2782 
2783  const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2784  // Assign locations to each value returned by this call.
2786  bool Is64Bit = Subtarget.is64Bit();
2787  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2788  *DAG.getContext());
2789  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2790 
2791  // Copy all of the result registers out of their specified physreg.
2792  for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
2793  ++I, ++InsIndex) {
2794  CCValAssign &VA = RVLocs[I];
2795  EVT CopyVT = VA.getLocVT();
2796 
2797  // In some calling conventions we need to remove the used registers
2798  // from the register mask.
2799  if (RegMask) {
2800  for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
2801  SubRegs.isValid(); ++SubRegs)
2802  RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
2803  }
2804 
2805  // If this is x86-64, and we disabled SSE, we can't return FP values
2806  if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2807  ((Is64Bit || Ins[InsIndex].Flags.isInReg()) && !Subtarget.hasSSE1())) {
2808  errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2809  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2810  }
2811 
2812  // If we prefer to use the value in xmm registers, copy it out as f80 and
2813  // use a truncate to move it from fp stack reg to xmm reg.
2814  bool RoundAfterCopy = false;
2815  if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2817  if (!Subtarget.hasX87())
2818  report_fatal_error("X87 register return with X87 disabled");
2819  CopyVT = MVT::f80;
2820  RoundAfterCopy = (CopyVT != VA.getLocVT());
2821  }
2822 
2823  SDValue Val;
2824  if (VA.needsCustom()) {
2825  assert(VA.getValVT() == MVT::v64i1 &&
2826  "Currently the only custom case is when we split v64i1 to 2 regs");
2827  Val =
2828  getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
2829  } else {
2830  Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
2831  .getValue(1);
2832  Val = Chain.getValue(0);
2833  InFlag = Chain.getValue(2);
2834  }
2835 
2836  if (RoundAfterCopy)
2837  Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2838  // This truncation won't change the value.
2839  DAG.getIntPtrConstant(1, dl));
2840 
2841  if (VA.isExtInLoc() && (VA.getValVT().getScalarType() == MVT::i1)) {
2842  if (VA.getValVT().isVector() &&
2843  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
2844  (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
2845  // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
2846  Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
2847  } else
2848  Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2849  }
2850 
2851  InVals.push_back(Val);
2852  }
2853 
2854  return Chain;
2855 }
2856 
2857 //===----------------------------------------------------------------------===//
2858 // C & StdCall & Fast Calling Convention implementation
2859 //===----------------------------------------------------------------------===//
2860 // StdCall calling convention seems to be standard for many Windows' API
2861 // routines and around. It differs from C calling convention just a little:
2862 // callee should clean up the stack, not caller. Symbols should be also
2863 // decorated in some fancy way :) It doesn't support any vector arguments.
2864 // For info on fast calling convention see Fast Calling Convention (tail call)
2865 // implementation LowerX86_32FastCCCallTo.
2866 
2867 /// CallIsStructReturn - Determines whether a call uses struct return
2868 /// semantics.
2873 };
2874 static StructReturnType
2876  if (Outs.empty())
2877  return NotStructReturn;
2878 
2879  const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2880  if (!Flags.isSRet())
2881  return NotStructReturn;
2882  if (Flags.isInReg() || IsMCU)
2883  return RegStructReturn;
2884  return StackStructReturn;
2885 }
2886 
2887 /// Determines whether a function uses struct return semantics.
2888 static StructReturnType
2890  if (Ins.empty())
2891  return NotStructReturn;
2892 
2893  const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2894  if (!Flags.isSRet())
2895  return NotStructReturn;
2896  if (Flags.isInReg() || IsMCU)
2897  return RegStructReturn;
2898  return StackStructReturn;
2899 }
2900 
2901 /// Make a copy of an aggregate at address specified by "Src" to address
2902 /// "Dst" with size and alignment information specified by the specific
2903 /// parameter attribute. The copy will be passed as a byval function parameter.
2905  SDValue Chain, ISD::ArgFlagsTy Flags,
2906  SelectionDAG &DAG, const SDLoc &dl) {
2907  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2908 
2909  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2910  /*isVolatile*/false, /*AlwaysInline=*/true,
2911  /*isTailCall*/false,
2913 }
2914 
2915 /// Return true if the calling convention is one that we can guarantee TCO for.
2917  return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2919  CC == CallingConv::HHVM);
2920 }
2921 
2922 /// Return true if we might ever do TCO for calls with this calling convention.
2924  switch (CC) {
2925  // C calling conventions:
2926  case CallingConv::C:
2927  case CallingConv::Win64:
2929  // Callee pop conventions:
2934  return true;
2935  default:
2936  return canGuaranteeTCO(CC);
2937  }
2938 }
2939 
2940 /// Return true if the function is being made into a tailcall target by
2941 /// changing its ABI.
2942 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2943  return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2944 }
2945 
2946 bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2947  auto Attr =
2948  CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2949  if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2950  return false;
2951 
2952  ImmutableCallSite CS(CI);
2953  CallingConv::ID CalleeCC = CS.getCallingConv();
2954  if (!mayTailCallThisCC(CalleeCC))
2955  return false;
2956 
2957  return true;
2958 }
2959 
2960 SDValue
2961 X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
2962  const SmallVectorImpl<ISD::InputArg> &Ins,
2963  const SDLoc &dl, SelectionDAG &DAG,
2964  const CCValAssign &VA,
2965  MachineFrameInfo &MFI, unsigned i) const {
2966  // Create the nodes corresponding to a load from this parameter slot.
2967  ISD::ArgFlagsTy Flags = Ins[i].Flags;
2968  bool AlwaysUseMutable = shouldGuaranteeTCO(
2969  CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2970  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2971  EVT ValVT;
2972  MVT PtrVT = getPointerTy(DAG.getDataLayout());
2973 
2974  // If value is passed by pointer we have address passed instead of the value
2975  // itself. No need to extend if the mask value and location share the same
2976  // absolute size.
2977  bool ExtendedInMem =
2978  VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
2979  VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
2980 
2981  if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2982  ValVT = VA.getLocVT();
2983  else
2984  ValVT = VA.getValVT();
2985 
2986  // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2987  // taken by a return address.
2988  int Offset = 0;
2989  if (CallConv == CallingConv::X86_INTR) {
2990  // X86 interrupts may take one or two arguments.
2991  // On the stack there will be no return address as in regular call.
2992  // Offset of last argument need to be set to -4/-8 bytes.
2993  // Where offset of the first argument out of two, should be set to 0 bytes.
2994  Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2995  if (Subtarget.is64Bit() && Ins.size() == 2) {
2996  // The stack pointer needs to be realigned for 64 bit handlers with error
2997  // code, so the argument offset changes by 8 bytes.
2998  Offset += 8;
2999  }
3000  }
3001 
3002  // FIXME: For now, all byval parameter objects are marked mutable. This can be
3003  // changed with more analysis.
3004  // In case of tail call optimization mark all arguments mutable. Since they
3005  // could be overwritten by lowering of arguments in case of a tail call.
3006  if (Flags.isByVal()) {
3007  unsigned Bytes = Flags.getByValSize();
3008  if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
3009 
3010  // FIXME: For now, all byval parameter objects are marked as aliasing. This
3011  // can be improved with deeper analysis.
3012  int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable,
3013  /*isAliased=*/true);
3014  // Adjust SP offset of interrupt parameter.
3015  if (CallConv == CallingConv::X86_INTR) {
3016  MFI.setObjectOffset(FI, Offset);
3017  }
3018  return DAG.getFrameIndex(FI, PtrVT);
3019  }
3020 
3021  // This is an argument in memory. We might be able to perform copy elision.
3022  if (Flags.isCopyElisionCandidate()) {
3023  EVT ArgVT = Ins[i].ArgVT;
3024  SDValue PartAddr;
3025  if (Ins[i].PartOffset == 0) {
3026  // If this is a one-part value or the first part of a multi-part value,
3027  // create a stack object for the entire argument value type and return a
3028  // load from our portion of it. This assumes that if the first part of an
3029  // argument is in memory, the rest will also be in memory.
3030  int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
3031  /*Immutable=*/false);
3032  PartAddr = DAG.getFrameIndex(FI, PtrVT);
3033  return DAG.getLoad(
3034  ValVT, dl, Chain, PartAddr,
3036  } else {
3037  // This is not the first piece of an argument in memory. See if there is
3038  // already a fixed stack object including this offset. If so, assume it
3039  // was created by the PartOffset == 0 branch above and create a load from
3040  // the appropriate offset into it.
3041  int64_t PartBegin = VA.getLocMemOffset();
3042  int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
3043  int FI = MFI.getObjectIndexBegin();
3044  for (; MFI.isFixedObjectIndex(FI); ++FI) {
3045  int64_t ObjBegin = MFI.getObjectOffset(FI);
3046  int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
3047  if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
3048  break;
3049  }
3050  if (MFI.isFixedObjectIndex(FI)) {
3051  SDValue Addr =
3052  DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
3053  DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
3054  return DAG.getLoad(
3055  ValVT, dl, Chain, Addr,
3057  Ins[i].PartOffset));
3058  }
3059  }
3060  }
3061 
3062  int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
3063  VA.getLocMemOffset(), isImmutable);
3064 
3065  // Set SExt or ZExt flag.
3066  if (VA.getLocInfo() == CCValAssign::ZExt) {
3067  MFI.setObjectZExt(FI, true);
3068  } else if (VA.getLocInfo() == CCValAssign::SExt) {
3069  MFI.setObjectSExt(FI, true);
3070  }
3071 
3072  // Adjust SP offset of interrupt parameter.
3073  if (CallConv == CallingConv::X86_INTR) {
3074  MFI.setObjectOffset(FI, Offset);
3075  }
3076 
3077  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3078  SDValue Val = DAG.getLoad(
3079  ValVT, dl, Chain, FIN,
3081  return ExtendedInMem
3082  ? (VA.getValVT().isVector()
3083  ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
3084  : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
3085  : Val;
3086 }
3087 
3088 // FIXME: Get this from tablegen.
3090  const X86Subtarget &Subtarget) {
3091  assert(Subtarget.is64Bit());
3092 
3093  if (Subtarget.isCallingConvWin64(CallConv)) {
3094  static const MCPhysReg GPR64ArgRegsWin64[] = {
3095  X86::RCX, X86::RDX, X86::R8, X86::R9
3096  };
3097  return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
3098  }
3099 
3100  static const MCPhysReg GPR64ArgRegs64Bit[] = {
3101  X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
3102  };
3103  return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
3104 }
3105 
3106 // FIXME: Get this from tablegen.
3108  CallingConv::ID CallConv,
3109  const X86Subtarget &Subtarget) {
3110  assert(Subtarget.is64Bit());
3111  if (Subtarget.isCallingConvWin64(CallConv)) {
3112  // The XMM registers which might contain var arg parameters are shadowed
3113  // in their paired GPR. So we only need to save the GPR to their home
3114  // slots.
3115  // TODO: __vectorcall will change this.
3116  return None;
3117  }
3118 
3119  const Function &F = MF.getFunction();
3120  bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
3121  bool isSoftFloat = Subtarget.useSoftFloat();
3122  assert(!(isSoftFloat && NoImplicitFloatOps) &&
3123  "SSE register cannot be used when SSE is disabled!");
3124  if (isSoftFloat || NoImplicitFloatOps || !Subtarget.hasSSE1())
3125  // Kernel mode asks for SSE to be disabled, so there are no XMM argument
3126  // registers.
3127  return None;
3128 
3129  static const MCPhysReg XMMArgRegs64Bit[] = {
3130  X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3131  X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3132  };
3133  return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
3134 }
3135 
3136 #ifndef NDEBUG
3138  return std::is_sorted(ArgLocs.begin(), ArgLocs.end(),
3139  [](const CCValAssign &A, const CCValAssign &B) -> bool {
3140  return A.getValNo() < B.getValNo();
3141  });
3142 }
3143 #endif
3144 
3145 SDValue X86TargetLowering::LowerFormalArguments(
3146  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3147  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3148  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3149  MachineFunction &MF = DAG.getMachineFunction();
3151  const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
3152 
3153  const Function &F = MF.getFunction();
3154  if (F.hasExternalLinkage() && Subtarget.isTargetCygMing() &&
3155  F.getName() == "main")
3156  FuncInfo->setForceFramePointer(true);
3157 
3158  MachineFrameInfo &MFI = MF.getFrameInfo();
3159  bool Is64Bit = Subtarget.is64Bit();
3160  bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3161 
3162  assert(
3163  !(isVarArg && canGuaranteeTCO(CallConv)) &&
3164  "Var args not supported with calling conv' regcall, fastcc, ghc or hipe");
3165 
3166  if (CallConv == CallingConv::X86_INTR) {
3167  bool isLegal = Ins.size() == 1 ||
3168  (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
3169  (!Is64Bit && Ins[1].VT == MVT::i32)));
3170  if (!isLegal)
3171  report_fatal_error("X86 interrupts may take one or two arguments");
3172  }
3173 
3174  // Assign locations to all of the incoming arguments.
3176  CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3177 
3178  // Allocate shadow area for Win64.
3179  if (IsWin64)
3180  CCInfo.AllocateStack(32, 8);
3181 
3182  CCInfo.AnalyzeArguments(Ins, CC_X86);
3183 
3184  // In vectorcall calling convention a second pass is required for the HVA
3185  // types.
3186  if (CallingConv::X86_VectorCall == CallConv) {
3187  CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
3188  }
3189 
3190  // The next loop assumes that the locations are in the same order of the
3191  // input arguments.
3192  assert(isSortedByValueNo(ArgLocs) &&
3193  "Argument Location list must be sorted before lowering");
3194 
3195  SDValue ArgValue;
3196  for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
3197  ++I, ++InsIndex) {
3198  assert(InsIndex < Ins.size() && "Invalid Ins index");
3199  CCValAssign &VA = ArgLocs[I];
3200 
3201  if (VA.isRegLoc()) {
3202  EVT RegVT = VA.getLocVT();
3203  if (VA.needsCustom()) {
3204  assert(
3205  VA.getValVT() == MVT::v64i1 &&
3206  "Currently the only custom case is when we split v64i1 to 2 regs");
3207 
3208  // v64i1 values, in regcall calling convention, that are
3209  // compiled to 32 bit arch, are split up into two registers.
3210  ArgValue =
3211  getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
3212  } else {
3213  const TargetRegisterClass *RC;
3214  if (RegVT == MVT::i8)
3215  RC = &X86::GR8RegClass;
3216  else if (RegVT == MVT::i16)
3217  RC = &X86::GR16RegClass;
3218  else if (RegVT == MVT::i32)
3219  RC = &X86::GR32RegClass;
3220  else if (Is64Bit && RegVT == MVT::i64)
3221  RC = &X86::GR64RegClass;
3222  else if (RegVT == MVT::f32)
3223  RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
3224  else if (RegVT == MVT::f64)
3225  RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
3226  else if (RegVT == MVT::f80)
3227  RC = &X86::RFP80RegClass;
3228  else if (RegVT == MVT::f128)
3229  RC = &X86::VR128RegClass;
3230  else if (RegVT.is512BitVector())
3231  RC = &X86::VR512RegClass;
3232  else if (RegVT.is256BitVector())
3233  RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
3234  else if (RegVT.is128BitVector())
3235  RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
3236  else if (RegVT == MVT::x86mmx)
3237  RC = &X86::VR64RegClass;
3238  else if (RegVT == MVT::v1i1)
3239  RC = &X86::VK1RegClass;
3240  else if (RegVT == MVT::v8i1)
3241  RC = &X86::VK8RegClass;
3242  else if (RegVT == MVT::v16i1)
3243  RC = &X86::VK16RegClass;
3244  else if (RegVT == MVT::v32i1)
3245  RC = &X86::VK32RegClass;
3246  else if (RegVT == MVT::v64i1)
3247  RC = &X86::VK64RegClass;
3248  else
3249  llvm_unreachable("Unknown argument type!");
3250 
3251  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3252  ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3253  }
3254 
3255  // If this is an 8 or 16-bit value, it is really passed promoted to 32
3256  // bits. Insert an assert[sz]ext to capture this, then truncate to the
3257  // right size.
3258  if (VA.getLocInfo() == CCValAssign::SExt)
3259  ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3260  DAG.getValueType(VA.getValVT()));
3261  else if (VA.getLocInfo() == CCValAssign::ZExt)
3262  ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3263  DAG.getValueType(VA.getValVT()));
3264  else if (VA.getLocInfo() == CCValAssign::BCvt)
3265  ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
3266 
3267  if (VA.isExtInLoc()) {
3268  // Handle MMX values passed in XMM regs.
3269  if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
3270  ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
3271  else if (VA.getValVT().isVector() &&
3272  VA.getValVT().getScalarType() == MVT::i1 &&
3273  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3274  (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3275  // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3276  ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
3277  } else
3278  ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3279  }
3280  } else {
3281  assert(VA.isMemLoc());
3282  ArgValue =
3283  LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
3284  }
3285 
3286  // If value is passed via pointer - do a load.
3287  if (VA.getLocInfo() == CCValAssign::Indirect && !Ins[I].Flags.isByVal())
3288  ArgValue =
3289  DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
3290 
3291  InVals.push_back(ArgValue);
3292  }
3293 
3294  for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3295  // Swift calling convention does not require we copy the sret argument
3296  // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
3297  if (CallConv == CallingConv::Swift)
3298  continue;
3299 
3300  // All x86 ABIs require that for returning structs by value we copy the
3301  // sret argument into %rax/%eax (depending on ABI) for the return. Save
3302  // the argument into a virtual register so that we can access it from the
3303  // return points.
3304  if (Ins[I].Flags.isSRet()) {
3305  unsigned Reg = FuncInfo->getSRetReturnReg();
3306  if (!Reg) {
3307  MVT PtrTy = getPointerTy(DAG.getDataLayout());
3308  Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3309  FuncInfo->setSRetReturnReg(Reg);
3310  }
3311  SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
3312  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3313  break;
3314  }
3315  }
3316 
3317  unsigned StackSize = CCInfo.getNextStackOffset();
3318  // Align stack specially for tail calls.
3319  if (shouldGuaranteeTCO(CallConv,
3321  StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
3322 
3323  // If the function takes variable number of arguments, make a frame index for
3324  // the start of the first vararg value... for expansion of llvm.va_start. We
3325  // can skip this if there are no va_start calls.
3326  if (MFI.hasVAStart() &&
3327  (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
3328  CallConv != CallingConv::X86_ThisCall))) {
3329  FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
3330  }
3331 
3332  // Figure out if XMM registers are in use.
3333  assert(!(Subtarget.useSoftFloat() &&
3334  F.hasFnAttribute(Attribute::NoImplicitFloat)) &&
3335  "SSE register cannot be used when SSE is disabled!");
3336 
3337  // 64-bit calling conventions support varargs and register parameters, so we
3338  // have to do extra work to spill them in the prologue.
3339  if (Is64Bit && isVarArg && MFI.hasVAStart()) {
3340  // Find the first unallocated argument registers.
3341  ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3342  ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
3343  unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3344  unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3345  assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&
3346  "SSE register cannot be used when SSE is disabled!");
3347 
3348  // Gather all the live in physical registers.
3349  SmallVector<SDValue, 6> LiveGPRs;
3350  SmallVector<SDValue, 8> LiveXMMRegs;
3351  SDValue ALVal;
3352  for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3353  unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
3354  LiveGPRs.push_back(
3355  DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
3356  }
3357  if (!ArgXMMs.empty()) {
3358  unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3359  ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
3360  for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
3361  unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
3362  LiveXMMRegs.push_back(
3363  DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
3364  }
3365  }
3366 
3367  if (IsWin64) {
3368  // Get to the caller-allocated home save location. Add 8 to account
3369  // for the return address.
3370  int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
3371  FuncInfo->setRegSaveFrameIndex(
3372  MFI.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3373  // Fixup to set vararg frame on shadow area (4 x i64).
3374  if (NumIntRegs < 4)
3375  FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3376  } else {
3377  // For X86-64, if there are vararg parameters that are passed via
3378  // registers, then we must store them to their spots on the stack so
3379  // they may be loaded by dereferencing the result of va_next.
3380  FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3381  FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3383  ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
3384  }
3385 
3386  // Store the integer parameter registers.
3387  SmallVector<SDValue, 8> MemOps;
3388  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3389  getPointerTy(DAG.getDataLayout()));
3390  unsigned Offset = FuncInfo->getVarArgsGPOffset();
3391  for (SDValue Val : LiveGPRs) {
3392  SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3393  RSFIN, DAG.getIntPtrConstant(Offset, dl));
3394  SDValue Store =
3395  DAG.getStore(Val.getValue(1), dl, Val, FIN,
3397  DAG.getMachineFunction(),
3398  FuncInfo->getRegSaveFrameIndex(), Offset));
3399  MemOps.push_back(Store);
3400  Offset += 8;
3401  }
3402 
3403  if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
3404  // Now store the XMM (fp + vector) parameter registers.
3405  SmallVector<SDValue, 12> SaveXMMOps;
3406  SaveXMMOps.push_back(Chain);
3407  SaveXMMOps.push_back(ALVal);
3408  SaveXMMOps.push_back(DAG.getIntPtrConstant(
3409  FuncInfo->getRegSaveFrameIndex(), dl));
3410  SaveXMMOps.push_back(DAG.getIntPtrConstant(
3411  FuncInfo->getVarArgsFPOffset(), dl));
3412  SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
3413  LiveXMMRegs.end());
3415  MVT::Other, SaveXMMOps));
3416  }
3417 
3418  if (!MemOps.empty())
3419  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3420  }
3421 
3422  if (isVarArg && MFI.hasMustTailInVarArgFunc()) {
3423  // Find the largest legal vector type.
3424  MVT VecVT = MVT::Other;
3425  // FIXME: Only some x86_32 calling conventions support AVX512.
3426  if (Subtarget.hasAVX512() &&
3427  (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
3428  CallConv == CallingConv::Intel_OCL_BI)))
3429  VecVT = MVT::v16f32;
3430  else if (Subtarget.hasAVX())
3431  VecVT = MVT::v8f32;
3432  else if (Subtarget.hasSSE2())
3433  VecVT = MVT::v4f32;
3434 
3435  // We forward some GPRs and some vector types.
3436  SmallVector<MVT, 2> RegParmTypes;
3437  MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
3438  RegParmTypes.push_back(IntVT);
3439  if (VecVT != MVT::Other)
3440  RegParmTypes.push_back(VecVT);
3441 
3442  // Compute the set of forwarded registers. The rest are scratch.
3444  FuncInfo->getForwardedMustTailRegParms();
3445  CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3446 
3447  // Conservatively forward AL on x86_64, since it might be used for varargs.
3448  if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
3449  unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3450  Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3451  }
3452 
3453  // Copy all forwards from physical to virtual registers.
3454  for (ForwardedRegister &F : Forwards) {
3455  // FIXME: Can we use a less constrained schedule?
3456  SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3457  F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
3458  Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
3459  }
3460  }
3461 
3462  // Some CCs need callee pop.
3463  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3465  FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
3466  } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
3467  // X86 interrupts must pop the error code (and the alignment padding) if
3468  // present.
3469  FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
3470  } else {
3471  FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
3472  // If this is an sret function, the return should pop the hidden pointer.
3473  if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3474  !Subtarget.getTargetTriple().isOSMSVCRT() &&
3475  argsAreStructReturn(Ins, Subtarget.isTargetMCU()) == StackStructReturn)
3476  FuncInfo->setBytesToPopOnReturn(4);
3477  }
3478 
3479  if (!Is64Bit) {
3480  // RegSaveFrameIndex is X86-64 only.
3481  FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3482  if (CallConv == CallingConv::X86_FastCall ||
3483  CallConv == CallingConv::X86_ThisCall)
3484  // fastcc functions can't have varargs.
3485  FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
3486  }
3487 
3488  FuncInfo->setArgumentStackSize(StackSize);
3489 
3490  if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
3492  if (Personality == EHPersonality::CoreCLR) {
3493  assert(Is64Bit);
3494  // TODO: Add a mechanism to frame lowering that will allow us to indicate
3495  // that we'd prefer this slot be allocated towards the bottom of the frame
3496  // (i.e. near the stack pointer after allocating the frame). Every
3497  // funclet needs a copy of this slot in its (mostly empty) frame, and the
3498  // offset from the bottom of this and each funclet's frame must be the
3499  // same, so the size of funclets' (mostly empty) frames is dictated by
3500  // how far this slot is from the bottom (since they allocate just enough
3501  // space to accommodate holding this slot at the correct offset).
3502  int PSPSymFI = MFI.CreateStackObject(8, 8, /*isSS=*/false);
3503  EHInfo->PSPSymFrameIdx = PSPSymFI;
3504  }
3505  }
3506 
3507  if (CallConv == CallingConv::X86_RegCall ||
3508  F.hasFnAttribute("no_caller_saved_registers")) {
3510  for (std::pair<unsigned, unsigned> Pair : MRI.liveins())
3511  MRI.disableCalleeSavedRegister(Pair.first);
3512  }
3513 
3514  return Chain;
3515 }
3516 
3517 SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
3518  SDValue Arg, const SDLoc &dl,
3519  SelectionDAG &DAG,
3520  const CCValAssign &VA,
3521  ISD::ArgFlagsTy Flags) const {
3522  unsigned LocMemOffset = VA.getLocMemOffset();
3523  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3524  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3525  StackPtr, PtrOff);
3526  if (Flags.isByVal())
3527  return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3528 
3529  return DAG.getStore(
3530  Chain, dl, Arg, PtrOff,
3531  MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
3532 }
3533 
3534 /// Emit a load of return address if tail call
3535 /// optimization is performed and it is required.
3536 SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
3537  SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
3538  bool Is64Bit, int FPDiff, const SDLoc &dl) const {
3539  // Adjust the Return address stack slot.
3540  EVT VT = getPointerTy(DAG.getDataLayout());
3541  OutRetAddr = getReturnAddressFrameIndex(DAG);
3542 
3543  // Load the "old" Return address.
3544  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
3545  return SDValue(OutRetAddr.getNode(), 1);
3546 }
3547 
3548 /// Emit a store of the return address if tail call
3549 /// optimization is performed and it is required (FPDiff!=0).
3551  SDValue Chain, SDValue RetAddrFrIdx,
3552  EVT PtrVT, unsigned SlotSize,
3553  int FPDiff, const SDLoc &dl) {
3554  // Store the return address to the appropriate stack slot.
3555  if (!FPDiff) return Chain;
3556  // Calculate the new stack slot for the return address.
3557  int NewReturnAddrFI =
3558  MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3559  false);
3560  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3561  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3563  DAG.getMachineFunction(), NewReturnAddrFI));
3564  return Chain;
3565 }
3566 
3567 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3568 /// operation of specified width.
3569 static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
3570  SDValue V2) {
3571  unsigned NumElems = VT.getVectorNumElements();
3573  Mask.push_back(NumElems);
3574  for (unsigned i = 1; i != NumElems; ++i)
3575  Mask.push_back(i);
3576  return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
3577 }
3578 
3579 SDValue
3580 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3581  SmallVectorImpl<SDValue> &InVals) const {
3582  SelectionDAG &DAG = CLI.DAG;
3583  SDLoc &dl = CLI.DL;