LLVM  6.0.0svn
X86ISelLowering.cpp
Go to the documentation of this file.
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86IntrinsicsInfo.h"
21 #include "X86MachineFunctionInfo.h"
23 #include "X86TargetMachine.h"
24 #include "X86TargetObjectFile.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringSwitch.h"
40 #include "llvm/IR/CallSite.h"
41 #include "llvm/IR/CallingConv.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/DiagnosticInfo.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/GlobalAlias.h"
47 #include "llvm/IR/GlobalVariable.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/MC/MCAsmInfo.h"
51 #include "llvm/MC/MCContext.h"
52 #include "llvm/MC/MCExpr.h"
53 #include "llvm/MC/MCSymbol.h"
55 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/KnownBits.h"
60 #include <algorithm>
61 #include <bitset>
62 #include <cctype>
63 #include <numeric>
64 using namespace llvm;
65 
66 #define DEBUG_TYPE "x86-isel"
67 
68 STATISTIC(NumTailCalls, "Number of tail calls");
69 
71  "x86-experimental-vector-widening-legalization", cl::init(false),
72  cl::desc("Enable an experimental vector type legalization through widening "
73  "rather than promotion."),
74  cl::Hidden);
75 
77  "x86-experimental-pref-loop-alignment", cl::init(4),
78  cl::desc("Sets the preferable loop alignment for experiments "
79  "(the last x86-experimental-pref-loop-alignment bits"
80  " of the loop header PC will be 0)."),
81  cl::Hidden);
82 
84  "mul-constant-optimization", cl::init(true),
85  cl::desc("Replace 'mul x, Const' with more effective instructions like "
86  "SHIFT, LEA, etc."),
87  cl::Hidden);
88 
89 /// Call this when the user attempts to do something unsupported, like
90 /// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike
91 /// report_fatal_error, so calling code should attempt to recover without
92 /// crashing.
93 static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl,
94  const char *Msg) {
96  DAG.getContext()->diagnose(
98 }
99 
101  const X86Subtarget &STI)
102  : TargetLowering(TM), Subtarget(STI) {
103  bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
104  X86ScalarSSEf64 = Subtarget.hasSSE2();
105  X86ScalarSSEf32 = Subtarget.hasSSE1();
106  MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
107 
108  // Set up the TargetLowering object.
109 
110  // X86 is weird. It always uses i8 for shift amounts and setcc results.
112  // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
114 
115  // For 64-bit, since we have so many registers, use the ILP scheduler.
116  // For 32-bit, use the register pressure specific scheduling.
117  // For Atom, always use ILP scheduling.
118  if (Subtarget.isAtom())
120  else if (Subtarget.is64Bit())
122  else
124  const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
126 
127  // Bypass expensive divides and use cheaper ones.
128  if (TM.getOptLevel() >= CodeGenOpt::Default) {
129  if (Subtarget.hasSlowDivide32())
130  addBypassSlowDiv(32, 8);
131  if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
132  addBypassSlowDiv(64, 32);
133  }
134 
135  if (Subtarget.isTargetKnownWindowsMSVC() ||
136  Subtarget.isTargetWindowsItanium()) {
137  // Setup Windows compiler runtime calls.
138  setLibcallName(RTLIB::SDIV_I64, "_alldiv");
139  setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
140  setLibcallName(RTLIB::SREM_I64, "_allrem");
141  setLibcallName(RTLIB::UREM_I64, "_aullrem");
142  setLibcallName(RTLIB::MUL_I64, "_allmul");
148  }
149 
150  if (Subtarget.isTargetDarwin()) {
151  // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
152  setUseUnderscoreSetJmp(false);
154  } else if (Subtarget.isTargetWindowsGNU()) {
155  // MS runtime is weird: it exports _setjmp, but longjmp!
158  } else {
161  }
162 
163  // Set up the register classes.
164  addRegisterClass(MVT::i8, &X86::GR8RegClass);
165  addRegisterClass(MVT::i16, &X86::GR16RegClass);
166  addRegisterClass(MVT::i32, &X86::GR32RegClass);
167  if (Subtarget.is64Bit())
168  addRegisterClass(MVT::i64, &X86::GR64RegClass);
169 
170  for (MVT VT : MVT::integer_valuetypes())
172 
173  // We don't accept any truncstore of integer registers.
180 
182 
183  // SETOEQ and SETUNE require checking two conditions.
190 
191  // Integer absolute.
192  if (Subtarget.hasCMov()) {
195  if (Subtarget.is64Bit())
197  }
198 
199  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
200  // operation.
204 
205  if (Subtarget.is64Bit()) {
206  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512())
207  // f32/f64 are legal, f80 is custom.
209  else
212  } else if (!Subtarget.useSoftFloat()) {
213  // We have an algorithm for SSE2->double, and we turn this into a
214  // 64-bit FILD followed by conditional FADD for other targets.
216  // We have an algorithm for SSE2, and we turn this into a 64-bit
217  // FILD or VCVTUSI2SS/SD for other targets.
219  }
220 
221  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
222  // this operation.
225 
226  if (!Subtarget.useSoftFloat()) {
227  // SSE has no i16 to fp conversion, only i32.
228  if (X86ScalarSSEf32) {
230  // f32 and f64 cases are Legal, f80 case is not
232  } else {
235  }
236  } else {
239  }
240 
241  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
242  // this operation.
245 
246  if (!Subtarget.useSoftFloat()) {
247  // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
248  // are Legal, f80 is custom lowered.
251 
252  if (X86ScalarSSEf32) {
254  // f32 and f64 cases are Legal, f80 case is not
256  } else {
259  }
260  } else {
264  }
265 
266  // Handle FP_TO_UINT by promoting the destination to a larger signed
267  // conversion.
271 
272  if (Subtarget.is64Bit()) {
273  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
274  // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
277  } else {
280  }
281  } else if (!Subtarget.useSoftFloat()) {
282  // Since AVX is a superset of SSE3, only check for SSE here.
283  if (Subtarget.hasSSE1() && !Subtarget.hasSSE3())
284  // Expand FP_TO_UINT into a select.
285  // FIXME: We would like to use a Custom expander here eventually to do
286  // the optimal thing for SSE vs. the default expansion in the legalizer.
288  else
289  // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
290  // With SSE3 we can use fisttpll to convert to a signed i64; without
291  // SSE, we're stuck with a fistpll.
293 
295  }
296 
297  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
298  if (!X86ScalarSSEf64) {
301  if (Subtarget.is64Bit()) {
303  // Without SSE, i64->f64 goes through memory.
305  }
306  } else if (!Subtarget.is64Bit())
308 
309  // Scalar integer divide and remainder are lowered to use operations that
310  // produce two results, to match the available instructions. This exposes
311  // the two-result form to trivial CSE, which is able to combine x/y and x%y
312  // into a single instruction.
313  //
314  // Scalar integer multiply-high is also lowered to use two-result
315  // operations, to match the available instructions. However, plain multiply
316  // (low) operations are left as Legal, as there are single-result
317  // instructions for this in x86. Using the two-result multiply instructions
318  // when both high and low results are needed must be arranged by dagcombine.
319  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
326  }
327 
330  for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
334  }
335  if (Subtarget.is64Bit())
341 
346 
347  // Promote the i8 variants and force them on up to i32 which has a shorter
348  // encoding.
351  if (!Subtarget.hasBMI()) {
356  if (Subtarget.is64Bit()) {
359  }
360  }
361 
362  if (Subtarget.hasLZCNT()) {
363  // When promoting the i8 variants, force them to i32 for a shorter
364  // encoding.
367  } else {
374  if (Subtarget.is64Bit()) {
377  }
378  }
379 
380  // Special handling for half-precision floating point conversions.
381  // If we don't have F16C support, then lower half float conversions
382  // into library calls.
383  if (Subtarget.useSoftFloat() || !Subtarget.hasF16C()) {
386  }
387 
388  // There's never any support for operations beyond MVT::f32.
393 
400 
401  if (Subtarget.hasPOPCNT()) {
403  } else {
407  if (Subtarget.is64Bit())
409  }
410 
412 
413  if (!Subtarget.hasMOVBE())
415 
416  // These should be promoted to a larger select which is supported.
418  // X86 wants to expand cmov itself.
419  for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
422  }
423  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
424  if (VT == MVT::i64 && !Subtarget.is64Bit())
425  continue;
428  }
429 
430  // Custom action for SELECT MMX and expand action for SELECT_CC MMX
433 
435  // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
436  // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
441  setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
442 
443  // Darwin ABI issue.
444  for (auto VT : { MVT::i32, MVT::i64 }) {
445  if (VT == MVT::i64 && !Subtarget.is64Bit())
446  continue;
453  }
454 
455  // 64-bit shl, sra, srl (iff 32-bit x86)
456  for (auto VT : { MVT::i32, MVT::i64 }) {
457  if (VT == MVT::i64 && !Subtarget.is64Bit())
458  continue;
462  }
463 
464  if (Subtarget.hasSSE1())
466 
468 
469  // Expand certain atomics
470  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
478  }
479 
480  if (Subtarget.hasCmpxchg16b()) {
482  }
483 
484  // FIXME - use subtarget debug flags
485  if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
486  !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
489  }
490 
493 
496 
499 
500  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
503  bool Is64Bit = Subtarget.is64Bit();
505  setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
506 
509 
511 
512  // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
515 
516  if (!Subtarget.useSoftFloat() && X86ScalarSSEf64) {
517  // f32 and f64 use SSE.
518  // Set up the FP register classes.
519  addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
520  : &X86::FR32RegClass);
521  addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
522  : &X86::FR64RegClass);
523 
524  for (auto VT : { MVT::f32, MVT::f64 }) {
525  // Use ANDPD to simulate FABS.
527 
528  // Use XORP to simulate FNEG.
530 
531  // Use ANDPD and ORPD to simulate FCOPYSIGN.
533 
534  // We don't support sin/cos/fmod
535  setOperationAction(ISD::FSIN , VT, Expand);
536  setOperationAction(ISD::FCOS , VT, Expand);
537  setOperationAction(ISD::FSINCOS, VT, Expand);
538  }
539 
540  // Lower this to MOVMSK plus an AND.
543 
544  // Expand FP immediates into loads from the stack, except for the special
545  // cases we handle.
546  addLegalFPImmediate(APFloat(+0.0)); // xorpd
547  addLegalFPImmediate(APFloat(+0.0f)); // xorps
548  } else if (UseX87 && X86ScalarSSEf32) {
549  // Use SSE for f32, x87 for f64.
550  // Set up the FP register classes.
551  addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
552  : &X86::FR32RegClass);
553  addRegisterClass(MVT::f64, &X86::RFP64RegClass);
554 
555  // Use ANDPS to simulate FABS.
557 
558  // Use XORP to simulate FNEG.
560 
562 
563  // Use ANDPS and ORPS to simulate FCOPYSIGN.
566 
567  // We don't support sin/cos/fmod
571 
572  // Special cases we handle for FP constants.
573  addLegalFPImmediate(APFloat(+0.0f)); // xorps
574  addLegalFPImmediate(APFloat(+0.0)); // FLD0
575  addLegalFPImmediate(APFloat(+1.0)); // FLD1
576  addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
577  addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
578 
579  // Always expand sin/cos functions even though x87 has an instruction.
583  } else if (UseX87) {
584  // f32 and f64 in x87.
585  // Set up the FP register classes.
586  addRegisterClass(MVT::f64, &X86::RFP64RegClass);
587  addRegisterClass(MVT::f32, &X86::RFP32RegClass);
588 
589  for (auto VT : { MVT::f32, MVT::f64 }) {
590  setOperationAction(ISD::UNDEF, VT, Expand);
591  setOperationAction(ISD::FCOPYSIGN, VT, Expand);
592 
593  // Always expand sin/cos functions even though x87 has an instruction.
594  setOperationAction(ISD::FSIN , VT, Expand);
595  setOperationAction(ISD::FCOS , VT, Expand);
596  setOperationAction(ISD::FSINCOS, VT, Expand);
597  }
598  addLegalFPImmediate(APFloat(+0.0)); // FLD0
599  addLegalFPImmediate(APFloat(+1.0)); // FLD1
600  addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
601  addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
602  addLegalFPImmediate(APFloat(+0.0f)); // FLD0
603  addLegalFPImmediate(APFloat(+1.0f)); // FLD1
604  addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
605  addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
606  }
607 
608  // We don't support FMA.
611 
612  // Long double always uses X87, except f128 in MMX.
613  if (UseX87) {
614  if (Subtarget.is64Bit() && Subtarget.hasMMX()) {
615  addRegisterClass(MVT::f128, &X86::FR128RegClass);
620  }
621 
622  addRegisterClass(MVT::f80, &X86::RFP80RegClass);
625  {
627  addLegalFPImmediate(TmpFlt); // FLD0
628  TmpFlt.changeSign();
629  addLegalFPImmediate(TmpFlt); // FLD0/FCHS
630 
631  bool ignored;
632  APFloat TmpFlt2(+1.0);
634  &ignored);
635  addLegalFPImmediate(TmpFlt2); // FLD1
636  TmpFlt2.changeSign();
637  addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
638  }
639 
640  // Always expand sin/cos functions even though x87 has an instruction.
644 
651  }
652 
653  // Always use a library call for pow.
657 
665 
666  // Some FP actions are always expanded for vector types.
667  for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
669  setOperationAction(ISD::FSIN, VT, Expand);
670  setOperationAction(ISD::FSINCOS, VT, Expand);
671  setOperationAction(ISD::FCOS, VT, Expand);
672  setOperationAction(ISD::FREM, VT, Expand);
673  setOperationAction(ISD::FCOPYSIGN, VT, Expand);
674  setOperationAction(ISD::FPOW, VT, Expand);
675  setOperationAction(ISD::FLOG, VT, Expand);
676  setOperationAction(ISD::FLOG2, VT, Expand);
677  setOperationAction(ISD::FLOG10, VT, Expand);
678  setOperationAction(ISD::FEXP, VT, Expand);
679  setOperationAction(ISD::FEXP2, VT, Expand);
680  }
681 
682  // First set operation action for all vector types to either promote
683  // (for widening) or expand (for scalarization). Then we will selectively
684  // turn on ones that can be effectively codegen'd.
685  for (MVT VT : MVT::vector_valuetypes()) {
686  setOperationAction(ISD::SDIV, VT, Expand);
687  setOperationAction(ISD::UDIV, VT, Expand);
688  setOperationAction(ISD::SREM, VT, Expand);
689  setOperationAction(ISD::UREM, VT, Expand);
694  setOperationAction(ISD::FMA, VT, Expand);
695  setOperationAction(ISD::FFLOOR, VT, Expand);
696  setOperationAction(ISD::FCEIL, VT, Expand);
697  setOperationAction(ISD::FTRUNC, VT, Expand);
698  setOperationAction(ISD::FRINT, VT, Expand);
699  setOperationAction(ISD::FNEARBYINT, VT, Expand);
700  setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701  setOperationAction(ISD::MULHS, VT, Expand);
702  setOperationAction(ISD::UMUL_LOHI, VT, Expand);
703  setOperationAction(ISD::MULHU, VT, Expand);
704  setOperationAction(ISD::SDIVREM, VT, Expand);
705  setOperationAction(ISD::UDIVREM, VT, Expand);
706  setOperationAction(ISD::CTPOP, VT, Expand);
707  setOperationAction(ISD::CTTZ, VT, Expand);
708  setOperationAction(ISD::CTLZ, VT, Expand);
709  setOperationAction(ISD::ROTL, VT, Expand);
710  setOperationAction(ISD::ROTR, VT, Expand);
711  setOperationAction(ISD::BSWAP, VT, Expand);
712  setOperationAction(ISD::SETCC, VT, Expand);
713  setOperationAction(ISD::FP_TO_UINT, VT, Expand);
714  setOperationAction(ISD::FP_TO_SINT, VT, Expand);
715  setOperationAction(ISD::UINT_TO_FP, VT, Expand);
716  setOperationAction(ISD::SINT_TO_FP, VT, Expand);
718  setOperationAction(ISD::TRUNCATE, VT, Expand);
721  setOperationAction(ISD::ANY_EXTEND, VT, Expand);
722  setOperationAction(ISD::SELECT_CC, VT, Expand);
723  for (MVT InnerVT : MVT::vector_valuetypes()) {
724  setTruncStoreAction(InnerVT, VT, Expand);
725 
726  setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
727  setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
728 
729  // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
730  // types, we have to deal with them whether we ask for Expansion or not.
731  // Setting Expand causes its own optimisation problems though, so leave
732  // them legal.
733  if (VT.getVectorElementType() == MVT::i1)
734  setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
735 
736  // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
737  // split/scalarized right now.
738  if (VT.getVectorElementType() == MVT::f16)
739  setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
740  }
741  }
742 
743  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
744  // with -msoft-float, disable use of MMX as well.
745  if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
746  addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
747  // No operations on x86mmx supported, everything uses intrinsics.
748  }
749 
750  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
751  addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
752  : &X86::VR128RegClass);
753 
763  }
764 
765  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
766  addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
767  : &X86::VR128RegClass);
768 
769  // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
770  // registers cannot be used even for integer operations.
771  addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
772  : &X86::VR128RegClass);
773  addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
774  : &X86::VR128RegClass);
775  addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
776  : &X86::VR128RegClass);
777  addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
778  : &X86::VR128RegClass);
779 
793 
798 
802 
803  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
807  }
808 
809  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
815  }
816 
817  // We support custom legalizing of sext and anyext loads for specific
818  // memory vector types which we can load as a scalar (or sequence of
819  // scalars) and extend in-register to a legal 128-bit vector type. For sext
820  // loads these must work with a single scalar load.
821  for (MVT VT : MVT::integer_vector_valuetypes()) {
831  }
832 
833  for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
837 
838  if (VT == MVT::v2i64 && !Subtarget.is64Bit())
839  continue;
840 
843  }
844 
845  // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
846  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
852  }
853 
854  // Custom lower v2i64 and v2f64 selects.
857 
860 
863 
867 
868  // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
870 
873 
874  for (MVT VT : MVT::fp_vector_valuetypes())
876 
880 
884 
885  // In the customized shift lowering, the legal v4i32/v2i64 cases
886  // in AVX2 will be recognized.
887  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
891  }
892  }
893 
894  if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
903  }
904 
905  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
906  for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
907  setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
908  setOperationAction(ISD::FCEIL, RoundedTy, Legal);
909  setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
910  setOperationAction(ISD::FRINT, RoundedTy, Legal);
912  }
913 
922 
923  // FIXME: Do we need to handle scalar-to-vector here?
925 
926  // We directly match byte blends in the backend as they match the VSELECT
927  // condition form.
929 
930  // SSE41 brings specific instructions for doing vector sign extend even in
931  // cases where we don't have SRA.
932  for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
935  }
936 
937  for (MVT VT : MVT::integer_vector_valuetypes()) {
941  }
942 
943  // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
944  for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
952  }
953 
954  // i8 vectors are custom because the source register and source
955  // source memory operand types are not the same width.
957  }
958 
959  if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
960  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
963 
964  // XOP can efficiently perform BITREVERSE with VPPERM.
965  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
967 
968  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
971  }
972 
973  if (!Subtarget.useSoftFloat() && Subtarget.hasFp256()) {
974  bool HasInt256 = Subtarget.hasInt256();
975 
976  addRegisterClass(MVT::v32i8, Subtarget.hasVLX() ? &X86::VR256XRegClass
977  : &X86::VR256RegClass);
978  addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
979  : &X86::VR256RegClass);
980  addRegisterClass(MVT::v8i32, Subtarget.hasVLX() ? &X86::VR256XRegClass
981  : &X86::VR256RegClass);
982  addRegisterClass(MVT::v8f32, Subtarget.hasVLX() ? &X86::VR256XRegClass
983  : &X86::VR256RegClass);
984  addRegisterClass(MVT::v4i64, Subtarget.hasVLX() ? &X86::VR256XRegClass
985  : &X86::VR256RegClass);
986  addRegisterClass(MVT::v4f64, Subtarget.hasVLX() ? &X86::VR256XRegClass
987  : &X86::VR256RegClass);
988 
989  for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
998  }
999 
1000  // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1001  // even though v8i16 is a legal type.
1005 
1009 
1012 
1013  for (MVT VT : MVT::fp_vector_valuetypes())
1015 
1016  // In the customized shift lowering, the legal v8i32/v4i64 cases
1017  // in AVX2 will be recognized.
1018  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1022  }
1023 
1027 
1028  for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1032  }
1033 
1038 
1039  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1044  }
1045 
1046  if (Subtarget.hasAnyFMA()) {
1047  for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1050  }
1051 
1052  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1053  setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1054  setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1055  }
1056 
1059  setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1061 
1064 
1065  setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1066  setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1069 
1070  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1071  setOperationAction(ISD::ABS, VT, HasInt256 ? Legal : Custom);
1072  setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1073  setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1074  setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1075  setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1076  }
1077 
1078  if (HasInt256) {
1082 
1083  // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1084  // when we have a 256bit-wide blend with immediate.
1086 
1087  // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1088  for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1095  }
1096  }
1097 
1098  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1102  }
1103 
1104  // Extract subvector is special because the value type
1105  // (result) is 128-bit but the source is 256-bit wide.
1106  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1107  MVT::v4f32, MVT::v2f64 }) {
1109  }
1110 
1111  // Custom lower several nodes for 256-bit types.
1113  MVT::v8f32, MVT::v4f64 }) {
1116  setOperationAction(ISD::VSELECT, VT, Custom);
1122  }
1123 
1124  if (HasInt256)
1126 
1127  // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1128  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1134  }
1135  }
1136 
1137  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1138  addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1139  addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1140  addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1141  addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1142 
1143  addRegisterClass(MVT::v1i1, &X86::VK1RegClass);
1144  addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1145  addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1146 
1147  for (MVT VT : MVT::fp_vector_valuetypes())
1149 
1150  for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1156  }
1157 
1161  MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
1162  setLoadExtAction(ISD::SEXTLOAD, VT, MaskVT, Custom);
1163  setLoadExtAction(ISD::ZEXTLOAD, VT, MaskVT, Custom);
1164  setLoadExtAction(ISD::EXTLOAD, VT, MaskVT, Custom);
1165  setTruncStoreAction(VT, MaskVT, Custom);
1166  }
1167 
1168  for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1173  }
1174 
1202 
1208  if (Subtarget.hasVLX()){
1214 
1220  } else {
1221  for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1225  }
1226  }
1227 
1228  if (Subtarget.hasDQI()) {
1229  for (auto VT : { MVT::v2i64, MVT::v4i64, MVT::v8i64 }) {
1234  }
1235  if (Subtarget.hasVLX()) {
1236  // Fast v2f32 SINT_TO_FP( v2i32 ) custom conversion.
1240  }
1241  }
1242  if (Subtarget.hasVLX()) {
1254  }
1255 
1267 
1268  for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1274  }
1275 
1278 
1279  // Without BWI we need to use custom lowering to handle MVT::v64i8 input.
1282 
1288 
1291 
1294 
1301 
1302 
1303  // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1306 
1307  for (auto VT : { MVT::v8i1, MVT::v16i1 }) {
1314 
1319  setOperationAction(ISD::VSELECT, VT, Expand);
1320  }
1321 
1322  for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1333  }
1334 
1335  // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1337  MVT::v8i64}) {
1340  }
1341 
1342  // Need to promote to 64-bit even though we have 32-bit masked instructions
1343  // because the IR optimizers rearrange bitcasts around logic ops leaving
1344  // too many variations to handle if we don't promote them.
1348 
1349  if (Subtarget.hasCDI()) {
1350  // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1351  for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v16i32, MVT::v2i64,
1352  MVT::v4i64, MVT::v8i64}) {
1355  }
1356  } // Subtarget.hasCDI()
1357 
1358  if (Subtarget.hasDQI()) {
1359  // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1363  }
1364 
1365  if (Subtarget.hasVPOPCNTDQ()) {
1366  // VPOPCNTDQ sub-targets extend 128/256 vectors to use the avx512
1367  // version of popcntd/q.
1368  for (auto VT : {MVT::v16i32, MVT::v8i64, MVT::v8i32, MVT::v4i64,
1371  }
1372 
1373  // Custom legalize 2x32 to get a little better code.
1374  if (Subtarget.hasVLX()) {
1376  }
1377 
1378  // Custom lower several nodes.
1379  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1383  }
1384 
1386 
1387  // Extract subvector is special because the value type
1388  // (result) is 256-bit but the source is 512-bit wide.
1389  // 128-bit was made Legal under AVX1.
1390  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1393  for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1,
1396 
1397  for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1409  }
1410  for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1413  }
1414  }// has AVX-512
1415 
1416  if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1417  addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1418  addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1419 
1420  addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1421  addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1422 
1429 
1477 
1479 
1481  if (Subtarget.hasVLX()) {
1484  }
1485 
1486  LegalizeAction Action = Subtarget.hasVLX() ? Legal : Custom;
1487  for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1488  setOperationAction(ISD::MLOAD, VT, Action);
1489  setOperationAction(ISD::MSTORE, VT, Action);
1490  }
1491 
1492  if (Subtarget.hasCDI()) {
1495  }
1496 
1497  for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1512 
1516  }
1517 
1518  for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1520  }
1521  }
1522 
1523  if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
1524  addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1525  addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1526 
1527  for (auto VT : { MVT::v2i1, MVT::v4i1 }) {
1531  setOperationAction(ISD::VSELECT, VT, Expand);
1532 
1540  }
1541 
1546 
1547  for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1552  }
1553  }
1554 
1555  // We want to custom lower some of our intrinsics.
1559  if (!Subtarget.is64Bit()) {
1562  }
1563 
1564  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1565  // handle type legalization for these operations here.
1566  //
1567  // FIXME: We really should do custom legalization for addition and
1568  // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1569  // than generic legalization for 64-bit multiplication-with-overflow, though.
1570  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1571  if (VT == MVT::i64 && !Subtarget.is64Bit())
1572  continue;
1573  // Add/Sub/Mul with overflow operations are custom lowered.
1580 
1581  // Support carry in as value rather than glue.
1585  }
1586 
1587  if (!Subtarget.is64Bit()) {
1588  // These libcalls are not available in 32-bit.
1589  setLibcallName(RTLIB::SHL_I128, nullptr);
1590  setLibcallName(RTLIB::SRL_I128, nullptr);
1591  setLibcallName(RTLIB::SRA_I128, nullptr);
1592  setLibcallName(RTLIB::MUL_I128, nullptr);
1593  }
1594 
1595  // Combine sin / cos into one node or libcall if possible.
1596  if (Subtarget.hasSinCos()) {
1597  setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1598  setLibcallName(RTLIB::SINCOS_F64, "sincos");
1599  if (Subtarget.isTargetDarwin()) {
1600  // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1601  // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1604  }
1605  }
1606 
1607  if (Subtarget.isTargetWin64()) {
1614  }
1615 
1616  // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
1617  // is. We should promote the value to 64-bits to solve this.
1618  // This is what the CRT headers do - `fmodf` is an inline header
1619  // function casting to f64 and calling `fmod`.
1620  if (Subtarget.is32Bit() && (Subtarget.isTargetKnownWindowsMSVC() ||
1621  Subtarget.isTargetWindowsItanium()))
1622  for (ISD::NodeType Op :
1627 
1628  // We have target-specific dag combine patterns for the following nodes:
1667 
1669 
1670  MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1672  MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1674  MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1676 
1677  // TODO: These control memcmp expansion in CGP and could be raised higher, but
1678  // that needs to benchmarked and balanced with the potential use of vector
1679  // load/store types (PR33329, PR33914).
1680  MaxLoadsPerMemcmp = 2;
1682 
1683  // Set loop alignment to 2^ExperimentalPrefLoopAlignment bytes (default: 2^4).
1685 
1686  // An out-of-order CPU can speculatively execute past a predictable branch,
1687  // but a conditional move could be stalled by an expensive earlier operation.
1688  PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
1689  EnableExtLdPromotion = true;
1690  setPrefFunctionAlignment(4); // 2^4 bytes.
1691 
1693 }
1694 
1695 // This has so far only been implemented for 64-bit MachO.
1697  return Subtarget.isTargetMachO() && Subtarget.is64Bit();
1698 }
1699 
1703  VT.getVectorNumElements() != 1 &&
1705  return TypeWidenVector;
1706 
1708 }
1709 
1712  EVT VT) const {
1713  if (!VT.isVector())
1714  return MVT::i8;
1715 
1716  if (VT.isSimple()) {
1717  MVT VVT = VT.getSimpleVT();
1718  const unsigned NumElts = VVT.getVectorNumElements();
1719  MVT EltVT = VVT.getVectorElementType();
1720  if (VVT.is512BitVector()) {
1721  if (Subtarget.hasAVX512())
1722  if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1723  EltVT == MVT::f32 || EltVT == MVT::f64)
1724  switch(NumElts) {
1725  case 8: return MVT::v8i1;
1726  case 16: return MVT::v16i1;
1727  }
1728  if (Subtarget.hasBWI())
1729  if (EltVT == MVT::i8 || EltVT == MVT::i16)
1730  switch(NumElts) {
1731  case 32: return MVT::v32i1;
1732  case 64: return MVT::v64i1;
1733  }
1734  }
1735 
1736  if (Subtarget.hasBWI() && Subtarget.hasVLX())
1737  return MVT::getVectorVT(MVT::i1, NumElts);
1738 
1739  if (!isTypeLegal(VT) && getTypeAction(Context, VT) == TypePromoteInteger) {
1740  EVT LegalVT = getTypeToTransformTo(Context, VT);
1741  EltVT = LegalVT.getVectorElementType().getSimpleVT();
1742  }
1743 
1744  if (Subtarget.hasVLX() && EltVT.getSizeInBits() >= 32)
1745  switch(NumElts) {
1746  case 2: return MVT::v2i1;
1747  case 4: return MVT::v4i1;
1748  case 8: return MVT::v8i1;
1749  }
1750  }
1751 
1753 }
1754 
1755 /// Helper for getByValTypeAlignment to determine
1756 /// the desired ByVal argument alignment.
1757 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1758  if (MaxAlign == 16)
1759  return;
1760  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1761  if (VTy->getBitWidth() == 128)
1762  MaxAlign = 16;
1763  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1764  unsigned EltAlign = 0;
1765  getMaxByValAlign(ATy->getElementType(), EltAlign);
1766  if (EltAlign > MaxAlign)
1767  MaxAlign = EltAlign;
1768  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1769  for (auto *EltTy : STy->elements()) {
1770  unsigned EltAlign = 0;
1771  getMaxByValAlign(EltTy, EltAlign);
1772  if (EltAlign > MaxAlign)
1773  MaxAlign = EltAlign;
1774  if (MaxAlign == 16)
1775  break;
1776  }
1777  }
1778 }
1779 
1780 /// Return the desired alignment for ByVal aggregate
1781 /// function arguments in the caller parameter area. For X86, aggregates
1782 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1783 /// are at 4-byte boundaries.
1785  const DataLayout &DL) const {
1786  if (Subtarget.is64Bit()) {
1787  // Max of 8 and alignment of type.
1788  unsigned TyAlign = DL.getABITypeAlignment(Ty);
1789  if (TyAlign > 8)
1790  return TyAlign;
1791  return 8;
1792  }
1793 
1794  unsigned Align = 4;
1795  if (Subtarget.hasSSE1())
1796  getMaxByValAlign(Ty, Align);
1797  return Align;
1798 }
1799 
1800 /// Returns the target specific optimal type for load
1801 /// and store operations as a result of memset, memcpy, and memmove
1802 /// lowering. If DstAlign is zero that means it's safe to destination
1803 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1804 /// means there isn't a need to check it against alignment requirement,
1805 /// probably because the source does not need to be loaded. If 'IsMemset' is
1806 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1807 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1808 /// source is constant so it does not need to be loaded.
1809 /// It returns EVT::Other if the type should be determined using generic
1810 /// target-independent logic.
1811 EVT
1813  unsigned DstAlign, unsigned SrcAlign,
1814  bool IsMemset, bool ZeroMemset,
1815  bool MemcpyStrSrc,
1816  MachineFunction &MF) const {
1817  const Function *F = MF.getFunction();
1818  if (!F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1819  if (Size >= 16 &&
1820  (!Subtarget.isUnalignedMem16Slow() ||
1821  ((DstAlign == 0 || DstAlign >= 16) &&
1822  (SrcAlign == 0 || SrcAlign >= 16)))) {
1823  // FIXME: Check if unaligned 32-byte accesses are slow.
1824  if (Size >= 32 && Subtarget.hasAVX()) {
1825  // Although this isn't a well-supported type for AVX1, we'll let
1826  // legalization and shuffle lowering produce the optimal codegen. If we
1827  // choose an optimal type with a vector element larger than a byte,
1828  // getMemsetStores() may create an intermediate splat (using an integer
1829  // multiply) before we splat as a vector.
1830  return MVT::v32i8;
1831  }
1832  if (Subtarget.hasSSE2())
1833  return MVT::v16i8;
1834  // TODO: Can SSE1 handle a byte vector?
1835  if (Subtarget.hasSSE1())
1836  return MVT::v4f32;
1837  } else if ((!IsMemset || ZeroMemset) && !MemcpyStrSrc && Size >= 8 &&
1838  !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
1839  // Do not use f64 to lower memcpy if source is string constant. It's
1840  // better to use i32 to avoid the loads.
1841  // Also, do not use f64 to lower memset unless this is a memset of zeros.
1842  // The gymnastics of splatting a byte value into an XMM register and then
1843  // only using 8-byte stores (because this is a CPU with slow unaligned
1844  // 16-byte accesses) makes that a loser.
1845  return MVT::f64;
1846  }
1847  }
1848  // This is a compromise. If we reach here, unaligned accesses may be slow on
1849  // this target. However, creating smaller, aligned accesses could be even
1850  // slower and would certainly be a lot more code.
1851  if (Subtarget.is64Bit() && Size >= 8)
1852  return MVT::i64;
1853  return MVT::i32;
1854 }
1855 
1857  if (VT == MVT::f32)
1858  return X86ScalarSSEf32;
1859  else if (VT == MVT::f64)
1860  return X86ScalarSSEf64;
1861  return true;
1862 }
1863 
1864 bool
1866  unsigned,
1867  unsigned,
1868  bool *Fast) const {
1869  if (Fast) {
1870  switch (VT.getSizeInBits()) {
1871  default:
1872  // 8-byte and under are always assumed to be fast.
1873  *Fast = true;
1874  break;
1875  case 128:
1876  *Fast = !Subtarget.isUnalignedMem16Slow();
1877  break;
1878  case 256:
1879  *Fast = !Subtarget.isUnalignedMem32Slow();
1880  break;
1881  // TODO: What about AVX-512 (512-bit) accesses?
1882  }
1883  }
1884  // Misaligned accesses of any size are always allowed.
1885  return true;
1886 }
1887 
1888 /// Return the entry encoding for a jump table in the
1889 /// current function. The returned value is a member of the
1890 /// MachineJumpTableInfo::JTEntryKind enum.
1892  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1893  // symbol.
1894  if (isPositionIndependent() && Subtarget.isPICStyleGOT())
1896 
1897  // Otherwise, use the normal jump table encoding heuristics.
1899 }
1900 
1902  return Subtarget.useSoftFloat();
1903 }
1904 
1906  ArgListTy &Args) const {
1907 
1908  // Only relabel X86-32 for C / Stdcall CCs.
1909  if (Subtarget.is64Bit())
1910  return;
1911  if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
1912  return;
1913  unsigned ParamRegs = 0;
1914  if (auto *M = MF->getFunction()->getParent())
1915  ParamRegs = M->getNumberRegisterParameters();
1916 
1917  // Mark the first N int arguments as having reg
1918  for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
1919  Type *T = Args[Idx].Ty;
1920  if (T->isPointerTy() || T->isIntegerTy())
1921  if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
1922  unsigned numRegs = 1;
1923  if (MF->getDataLayout().getTypeAllocSize(T) > 4)
1924  numRegs = 2;
1925  if (ParamRegs < numRegs)
1926  return;
1927  ParamRegs -= numRegs;
1928  Args[Idx].IsInReg = true;
1929  }
1930  }
1931 }
1932 
1933 const MCExpr *
1935  const MachineBasicBlock *MBB,
1936  unsigned uid,MCContext &Ctx) const{
1937  assert(isPositionIndependent() && Subtarget.isPICStyleGOT());
1938  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1939  // entries.
1940  return MCSymbolRefExpr::create(MBB->getSymbol(),
1942 }
1943 
1944 /// Returns relocation base for the given PIC jumptable.
1946  SelectionDAG &DAG) const {
1947  if (!Subtarget.is64Bit())
1948  // This doesn't have SDLoc associated with it, but is not really the
1949  // same as a Register.
1950  return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1951  getPointerTy(DAG.getDataLayout()));
1952  return Table;
1953 }
1954 
1955 /// This returns the relocation base for the given PIC jumptable,
1956 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1959  MCContext &Ctx) const {
1960  // X86-64 uses RIP relative addressing based on the jump table label.
1961  if (Subtarget.isPICStyleRIPRel())
1962  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1963 
1964  // Otherwise, the reference is relative to the PIC base.
1965  return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1966 }
1967 
1968 std::pair<const TargetRegisterClass *, uint8_t>
1970  MVT VT) const {
1971  const TargetRegisterClass *RRC = nullptr;
1972  uint8_t Cost = 1;
1973  switch (VT.SimpleTy) {
1974  default:
1976  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1977  RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1978  break;
1979  case MVT::x86mmx:
1980  RRC = &X86::VR64RegClass;
1981  break;
1982  case MVT::f32: case MVT::f64:
1983  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1984  case MVT::v4f32: case MVT::v2f64:
1985  case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
1986  case MVT::v8f32: case MVT::v4f64:
1987  case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
1988  case MVT::v16f32: case MVT::v8f64:
1989  RRC = &X86::VR128XRegClass;
1990  break;
1991  }
1992  return std::make_pair(RRC, Cost);
1993 }
1994 
1995 unsigned X86TargetLowering::getAddressSpace() const {
1996  if (Subtarget.is64Bit())
1997  return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
1998  return 256;
1999 }
2000 
2001 static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2002  return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2003  (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2004 }
2005 
2007  unsigned Offset, unsigned AddressSpace) {
2010  Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2011 }
2012 
2014  // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2015  // tcbhead_t; use it instead of the usual global variable (see
2016  // sysdeps/{i386,x86_64}/nptl/tls.h)
2017  if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2018  if (Subtarget.isTargetFuchsia()) {
2019  // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2020  return SegmentOffset(IRB, 0x10, getAddressSpace());
2021  } else {
2022  // %fs:0x28, unless we're using a Kernel code model, in which case
2023  // it's %gs:0x28. gs:0x14 on i386.
2024  unsigned Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2025  return SegmentOffset(IRB, Offset, getAddressSpace());
2026  }
2027  }
2028 
2029  return TargetLowering::getIRStackGuard(IRB);
2030 }
2031 
2033  // MSVC CRT provides functionalities for stack protection.
2034  if (Subtarget.getTargetTriple().isOSMSVCRT()) {
2035  // MSVC CRT has a global variable holding security cookie.
2036  M.getOrInsertGlobal("__security_cookie",
2038 
2039  // MSVC CRT has a function to validate security cookie.
2040  auto *SecurityCheckCookie = cast<Function>(
2041  M.getOrInsertFunction("__security_check_cookie",
2044  SecurityCheckCookie->setCallingConv(CallingConv::X86_FastCall);
2045  SecurityCheckCookie->addAttribute(1, Attribute::AttrKind::InReg);
2046  return;
2047  }
2048  // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2049  if (hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2050  return;
2052 }
2053 
2055  // MSVC CRT has a global variable holding security cookie.
2056  if (Subtarget.getTargetTriple().isOSMSVCRT())
2057  return M.getGlobalVariable("__security_cookie");
2059 }
2060 
2062  // MSVC CRT has a function to validate security cookie.
2063  if (Subtarget.getTargetTriple().isOSMSVCRT())
2064  return M.getFunction("__security_check_cookie");
2066 }
2067 
2069  if (Subtarget.getTargetTriple().isOSContiki())
2070  return getDefaultSafeStackPointerLocation(IRB, false);
2071 
2072  // Android provides a fixed TLS slot for the SafeStack pointer. See the
2073  // definition of TLS_SLOT_SAFESTACK in
2074  // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2075  if (Subtarget.isTargetAndroid()) {
2076  // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2077  // %gs:0x24 on i386
2078  unsigned Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2079  return SegmentOffset(IRB, Offset, getAddressSpace());
2080  }
2081 
2082  // Fuchsia is similar.
2083  if (Subtarget.isTargetFuchsia()) {
2084  // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
2085  return SegmentOffset(IRB, 0x18, getAddressSpace());
2086  }
2087 
2089 }
2090 
2092  unsigned DestAS) const {
2093  assert(SrcAS != DestAS && "Expected different address spaces!");
2094 
2095  return SrcAS < 256 && DestAS < 256;
2096 }
2097 
2098 //===----------------------------------------------------------------------===//
2099 // Return Value Calling Convention Implementation
2100 //===----------------------------------------------------------------------===//
2101 
2102 #include "X86GenCallingConv.inc"
2103 
2104 bool X86TargetLowering::CanLowerReturn(
2105  CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2106  const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2108  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2109  return CCInfo.CheckReturn(Outs, RetCC_X86);
2110 }
2111 
2112 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2113  static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2114  return ScratchRegs;
2115 }
2116 
2117 /// Lowers masks values (v*i1) to the local register values
2118 /// \returns DAG node after lowering to register type
2119 static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
2120  const SDLoc &Dl, SelectionDAG &DAG) {
2121  EVT ValVT = ValArg.getValueType();
2122 
2123  if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
2124  (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
2125  // Two stage lowering might be required
2126  // bitcast: v8i1 -> i8 / v16i1 -> i16
2127  // anyextend: i8 -> i32 / i16 -> i32
2128  EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
2129  SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
2130  if (ValLoc == MVT::i32)
2131  ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
2132  return ValToCopy;
2133  } else if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
2134  (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
2135  // One stage lowering is required
2136  // bitcast: v32i1 -> i32 / v64i1 -> i64
2137  return DAG.getBitcast(ValLoc, ValArg);
2138  } else
2139  return DAG.getNode(ISD::SIGN_EXTEND, Dl, ValLoc, ValArg);
2140 }
2141 
2142 /// Breaks v64i1 value into two registers and adds the new node to the DAG
2144  const SDLoc &Dl, SelectionDAG &DAG, SDValue Chain, SDValue &Arg,
2145  SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, CCValAssign &VA,
2146  CCValAssign &NextVA, const X86Subtarget &Subtarget) {
2147  assert((Subtarget.hasBWI() || Subtarget.hasBMI()) &&
2148  "Expected AVX512BW or AVX512BMI target!");
2149  assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2150  assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value");
2151  assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2152  "The value should reside in two registers");
2153 
2154  // Before splitting the value we cast it to i64
2155  Arg = DAG.getBitcast(MVT::i64, Arg);
2156 
2157  // Splitting the value into two i32 types
2158  SDValue Lo, Hi;
2159  Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2160  DAG.getConstant(0, Dl, MVT::i32));
2161  Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2162  DAG.getConstant(1, Dl, MVT::i32));
2163 
2164  // Attach the two i32 types into corresponding registers
2165  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
2166  RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
2167 }
2168 
2169 SDValue
2170 X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2171  bool isVarArg,
2172  const SmallVectorImpl<ISD::OutputArg> &Outs,
2173  const SmallVectorImpl<SDValue> &OutVals,
2174  const SDLoc &dl, SelectionDAG &DAG) const {
2175  MachineFunction &MF = DAG.getMachineFunction();
2177 
2178  // In some cases we need to disable registers from the default CSR list.
2179  // For example, when they are used for argument passing.
2180  bool ShouldDisableCalleeSavedRegister =
2181  CallConv == CallingConv::X86_RegCall ||
2182  MF.getFunction()->hasFnAttribute("no_caller_saved_registers");
2183 
2184  if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2185  report_fatal_error("X86 interrupts may not return any value");
2186 
2188  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2189  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2190 
2191  SDValue Flag;
2192  SmallVector<SDValue, 6> RetOps;
2193  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2194  // Operand #1 = Bytes To Pop
2195  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2196  MVT::i32));
2197 
2198  // Copy the result values into the output registers.
2199  for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
2200  ++I, ++OutsIndex) {
2201  CCValAssign &VA = RVLocs[I];
2202  assert(VA.isRegLoc() && "Can only return in registers!");
2203 
2204  // Add the register to the CalleeSaveDisableRegs list.
2205  if (ShouldDisableCalleeSavedRegister)
2207 
2208  SDValue ValToCopy = OutVals[OutsIndex];
2209  EVT ValVT = ValToCopy.getValueType();
2210 
2211  // Promote values to the appropriate types.
2212  if (VA.getLocInfo() == CCValAssign::SExt)
2213  ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2214  else if (VA.getLocInfo() == CCValAssign::ZExt)
2215  ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2216  else if (VA.getLocInfo() == CCValAssign::AExt) {
2217  if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2218  ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
2219  else
2220  ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2221  }
2222  else if (VA.getLocInfo() == CCValAssign::BCvt)
2223  ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2224 
2226  "Unexpected FP-extend for return value.");
2227 
2228  // If this is x86-64, and we disabled SSE, we can't return FP values,
2229  // or SSE or MMX vectors.
2230  if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2231  VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2232  (Subtarget.is64Bit() && !Subtarget.hasSSE1())) {
2233  errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2234  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2235  } else if (ValVT == MVT::f64 &&
2236  (Subtarget.is64Bit() && !Subtarget.hasSSE2())) {
2237  // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2238  // llvm-gcc has never done it right and no one has noticed, so this
2239  // should be OK for now.
2240  errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2241  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2242  }
2243 
2244  // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2245  // the RET instruction and handled by the FP Stackifier.
2246  if (VA.getLocReg() == X86::FP0 ||
2247  VA.getLocReg() == X86::FP1) {
2248  // If this is a copy from an xmm register to ST(0), use an FPExtend to
2249  // change the value to the FP stack register class.
2250  if (isScalarFPTypeInSSEReg(VA.getValVT()))
2251  ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2252  RetOps.push_back(ValToCopy);
2253  // Don't emit a copytoreg.
2254  continue;
2255  }
2256 
2257  // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2258  // which is returned in RAX / RDX.
2259  if (Subtarget.is64Bit()) {
2260  if (ValVT == MVT::x86mmx) {
2261  if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2262  ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2263  ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2264  ValToCopy);
2265  // If we don't have SSE2 available, convert to v4f32 so the generated
2266  // register is legal.
2267  if (!Subtarget.hasSSE2())
2268  ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2269  }
2270  }
2271  }
2272 
2274 
2275  if (VA.needsCustom()) {
2276  assert(VA.getValVT() == MVT::v64i1 &&
2277  "Currently the only custom case is when we split v64i1 to 2 regs");
2278 
2279  Passv64i1ArgInRegs(dl, DAG, Chain, ValToCopy, RegsToPass, VA, RVLocs[++I],
2280  Subtarget);
2281 
2282  assert(2 == RegsToPass.size() &&
2283  "Expecting two registers after Pass64BitArgInRegs");
2284 
2285  // Add the second register to the CalleeSaveDisableRegs list.
2286  if (ShouldDisableCalleeSavedRegister)
2287  MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
2288  } else {
2289  RegsToPass.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2290  }
2291 
2292  // Add nodes to the DAG and add the values into the RetOps list
2293  for (auto &Reg : RegsToPass) {
2294  Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, Flag);
2295  Flag = Chain.getValue(1);
2296  RetOps.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
2297  }
2298  }
2299 
2300  // Swift calling convention does not require we copy the sret argument
2301  // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
2302 
2303  // All x86 ABIs require that for returning structs by value we copy
2304  // the sret argument into %rax/%eax (depending on ABI) for the return.
2305  // We saved the argument into a virtual register in the entry block,
2306  // so now we copy the value out and into %rax/%eax.
2307  //
2308  // Checking Function.hasStructRetAttr() here is insufficient because the IR
2309  // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2310  // false, then an sret argument may be implicitly inserted in the SelDAG. In
2311  // either case FuncInfo->setSRetReturnReg() will have been called.
2312  if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2313  // When we have both sret and another return value, we should use the
2314  // original Chain stored in RetOps[0], instead of the current Chain updated
2315  // in the above loop. If we only have sret, RetOps[0] equals to Chain.
2316 
2317  // For the case of sret and another return value, we have
2318  // Chain_0 at the function entry
2319  // Chain_1 = getCopyToReg(Chain_0) in the above loop
2320  // If we use Chain_1 in getCopyFromReg, we will have
2321  // Val = getCopyFromReg(Chain_1)
2322  // Chain_2 = getCopyToReg(Chain_1, Val) from below
2323 
2324  // getCopyToReg(Chain_0) will be glued together with
2325  // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
2326  // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
2327  // Data dependency from Unit B to Unit A due to usage of Val in
2328  // getCopyToReg(Chain_1, Val)
2329  // Chain dependency from Unit A to Unit B
2330 
2331  // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
2332  SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
2333  getPointerTy(MF.getDataLayout()));
2334 
2335  unsigned RetValReg
2336  = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
2337  X86::RAX : X86::EAX;
2338  Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2339  Flag = Chain.getValue(1);
2340 
2341  // RAX/EAX now acts like a return value.
2342  RetOps.push_back(
2343  DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2344 
2345  // Add the returned register to the CalleeSaveDisableRegs list.
2346  if (ShouldDisableCalleeSavedRegister)
2347  MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
2348  }
2349 
2350  const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
2351  const MCPhysReg *I =
2353  if (I) {
2354  for (; *I; ++I) {
2355  if (X86::GR64RegClass.contains(*I))
2356  RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2357  else
2358  llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2359  }
2360  }
2361 
2362  RetOps[0] = Chain; // Update chain.
2363 
2364  // Add the flag if we have it.
2365  if (Flag.getNode())
2366  RetOps.push_back(Flag);
2367 
2369  if (CallConv == CallingConv::X86_INTR)
2370  opcode = X86ISD::IRET;
2371  return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2372 }
2373 
2374 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2375  if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
2376  return false;
2377 
2378  SDValue TCChain = Chain;
2379  SDNode *Copy = *N->use_begin();
2380  if (Copy->getOpcode() == ISD::CopyToReg) {
2381  // If the copy has a glue operand, we conservatively assume it isn't safe to
2382  // perform a tail call.
2383  if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2384  return false;
2385  TCChain = Copy->getOperand(0);
2386  } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2387  return false;
2388 
2389  bool HasRet = false;
2390  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2391  UI != UE; ++UI) {
2392  if (UI->getOpcode() != X86ISD::RET_FLAG)
2393  return false;
2394  // If we are returning more than one value, we can definitely
2395  // not make a tail call see PR19530
2396  if (UI->getNumOperands() > 4)
2397  return false;
2398  if (UI->getNumOperands() == 4 &&
2399  UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2400  return false;
2401  HasRet = true;
2402  }
2403 
2404  if (!HasRet)
2405  return false;
2406 
2407  Chain = TCChain;
2408  return true;
2409 }
2410 
2411 EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
2412  ISD::NodeType ExtendKind) const {
2413  MVT ReturnMVT = MVT::i32;
2414 
2415  bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
2416  if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
2417  // The ABI does not require i1, i8 or i16 to be extended.
2418  //
2419  // On Darwin, there is code in the wild relying on Clang's old behaviour of
2420  // always extending i8/i16 return values, so keep doing that for now.
2421  // (PR26665).
2422  ReturnMVT = MVT::i8;
2423  }
2424 
2425  EVT MinVT = getRegisterType(Context, ReturnMVT);
2426  return VT.bitsLT(MinVT) ? MinVT : VT;
2427 }
2428 
2429 /// Reads two 32 bit registers and creates a 64 bit mask value.
2430 /// \param VA The current 32 bit value that need to be assigned.
2431 /// \param NextVA The next 32 bit value that need to be assigned.
2432 /// \param Root The parent DAG node.
2433 /// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
2434 /// glue purposes. In the case the DAG is already using
2435 /// physical register instead of virtual, we should glue
2436 /// our new SDValue to InFlag SDvalue.
2437 /// \return a new SDvalue of size 64bit.
2439  SDValue &Root, SelectionDAG &DAG,
2440  const SDLoc &Dl, const X86Subtarget &Subtarget,
2441  SDValue *InFlag = nullptr) {
2442  assert((Subtarget.hasBWI()) && "Expected AVX512BW target!");
2443  assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2444  assert(VA.getValVT() == MVT::v64i1 &&
2445  "Expecting first location of 64 bit width type");
2446  assert(NextVA.getValVT() == VA.getValVT() &&
2447  "The locations should have the same type");
2448  assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2449  "The values should reside in two registers");
2450 
2451  SDValue Lo, Hi;
2452  unsigned Reg;
2453  SDValue ArgValueLo, ArgValueHi;
2454 
2455  MachineFunction &MF = DAG.getMachineFunction();
2456  const TargetRegisterClass *RC = &X86::GR32RegClass;
2457 
2458  // Read a 32 bit value from the registers
2459  if (nullptr == InFlag) {
2460  // When no physical register is present,
2461  // create an intermediate virtual register
2462  Reg = MF.addLiveIn(VA.getLocReg(), RC);
2463  ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2464  Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2465  ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2466  } else {
2467  // When a physical register is available read the value from it and glue
2468  // the reads together.
2469  ArgValueLo =
2470  DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
2471  *InFlag = ArgValueLo.getValue(2);
2472  ArgValueHi =
2473  DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
2474  *InFlag = ArgValueHi.getValue(2);
2475  }
2476 
2477  // Convert the i32 type into v32i1 type
2478  Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
2479 
2480  // Convert the i32 type into v32i1 type
2481  Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
2482 
2483  // Concatenate the two values together
2484  return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
2485 }
2486 
2487 /// The function will lower a register of various sizes (8/16/32/64)
2488 /// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
2489 /// \returns a DAG node contains the operand after lowering to mask type.
2490 static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
2491  const EVT &ValLoc, const SDLoc &Dl,
2492  SelectionDAG &DAG) {
2493  SDValue ValReturned = ValArg;
2494 
2495  if (ValVT == MVT::v1i1)
2496  return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
2497 
2498  if (ValVT == MVT::v64i1) {
2499  // In 32 bit machine, this case is handled by getv64i1Argument
2500  assert(ValLoc == MVT::i64 && "Expecting only i64 locations");
2501  // In 64 bit machine, There is no need to truncate the value only bitcast
2502  } else {
2503  MVT maskLen;
2504  switch (ValVT.getSimpleVT().SimpleTy) {
2505  case MVT::v8i1:
2506  maskLen = MVT::i8;
2507  break;
2508  case MVT::v16i1:
2509  maskLen = MVT::i16;
2510  break;
2511  case MVT::v32i1:
2512  maskLen = MVT::i32;
2513  break;
2514  default:
2515  llvm_unreachable("Expecting a vector of i1 types");
2516  }
2517 
2518  ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
2519  }
2520  return DAG.getBitcast(ValVT, ValReturned);
2521 }
2522 
2523 /// Lower the result values of a call into the
2524 /// appropriate copies out of appropriate physical registers.
2525 ///
2526 SDValue X86TargetLowering::LowerCallResult(
2527  SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2528  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2529  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
2530  uint32_t *RegMask) const {
2531 
2532  const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2533  // Assign locations to each value returned by this call.
2535  bool Is64Bit = Subtarget.is64Bit();
2536  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2537  *DAG.getContext());
2538  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2539 
2540  // Copy all of the result registers out of their specified physreg.
2541  for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
2542  ++I, ++InsIndex) {
2543  CCValAssign &VA = RVLocs[I];
2544  EVT CopyVT = VA.getLocVT();
2545 
2546  // In some calling conventions we need to remove the used registers
2547  // from the register mask.
2548  if (RegMask) {
2549  for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
2550  SubRegs.isValid(); ++SubRegs)
2551  RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
2552  }
2553 
2554  // If this is x86-64, and we disabled SSE, we can't return FP values
2555  if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2556  ((Is64Bit || Ins[InsIndex].Flags.isInReg()) && !Subtarget.hasSSE1())) {
2557  errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2558  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2559  }
2560 
2561  // If we prefer to use the value in xmm registers, copy it out as f80 and
2562  // use a truncate to move it from fp stack reg to xmm reg.
2563  bool RoundAfterCopy = false;
2564  if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2566  if (!Subtarget.hasX87())
2567  report_fatal_error("X87 register return with X87 disabled");
2568  CopyVT = MVT::f80;
2569  RoundAfterCopy = (CopyVT != VA.getLocVT());
2570  }
2571 
2572  SDValue Val;
2573  if (VA.needsCustom()) {
2574  assert(VA.getValVT() == MVT::v64i1 &&
2575  "Currently the only custom case is when we split v64i1 to 2 regs");
2576  Val =
2577  getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
2578  } else {
2579  Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
2580  .getValue(1);
2581  Val = Chain.getValue(0);
2582  InFlag = Chain.getValue(2);
2583  }
2584 
2585  if (RoundAfterCopy)
2586  Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2587  // This truncation won't change the value.
2588  DAG.getIntPtrConstant(1, dl));
2589 
2590  if (VA.isExtInLoc() && (VA.getValVT().getScalarType() == MVT::i1)) {
2591  if (VA.getValVT().isVector() &&
2592  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
2593  (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
2594  // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
2595  Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
2596  } else
2597  Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2598  }
2599 
2600  InVals.push_back(Val);
2601  }
2602 
2603  return Chain;
2604 }
2605 
2606 //===----------------------------------------------------------------------===//
2607 // C & StdCall & Fast Calling Convention implementation
2608 //===----------------------------------------------------------------------===//
2609 // StdCall calling convention seems to be standard for many Windows' API
2610 // routines and around. It differs from C calling convention just a little:
2611 // callee should clean up the stack, not caller. Symbols should be also
2612 // decorated in some fancy way :) It doesn't support any vector arguments.
2613 // For info on fast calling convention see Fast Calling Convention (tail call)
2614 // implementation LowerX86_32FastCCCallTo.
2615 
2616 /// CallIsStructReturn - Determines whether a call uses struct return
2617 /// semantics.
2622 };
2623 static StructReturnType
2625  if (Outs.empty())
2626  return NotStructReturn;
2627 
2628  const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2629  if (!Flags.isSRet())
2630  return NotStructReturn;
2631  if (Flags.isInReg() || IsMCU)
2632  return RegStructReturn;
2633  return StackStructReturn;
2634 }
2635 
2636 /// Determines whether a function uses struct return semantics.
2637 static StructReturnType
2639  if (Ins.empty())
2640  return NotStructReturn;
2641 
2642  const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2643  if (!Flags.isSRet())
2644  return NotStructReturn;
2645  if (Flags.isInReg() || IsMCU)
2646  return RegStructReturn;
2647  return StackStructReturn;
2648 }
2649 
2650 /// Make a copy of an aggregate at address specified by "Src" to address
2651 /// "Dst" with size and alignment information specified by the specific
2652 /// parameter attribute. The copy will be passed as a byval function parameter.
2654  SDValue Chain, ISD::ArgFlagsTy Flags,
2655  SelectionDAG &DAG, const SDLoc &dl) {
2656  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2657 
2658  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2659  /*isVolatile*/false, /*AlwaysInline=*/true,
2660  /*isTailCall*/false,
2662 }
2663 
2664 /// Return true if the calling convention is one that we can guarantee TCO for.
2666  return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2668  CC == CallingConv::HHVM);
2669 }
2670 
2671 /// Return true if we might ever do TCO for calls with this calling convention.
2673  switch (CC) {
2674  // C calling conventions:
2675  case CallingConv::C:
2676  case CallingConv::Win64:
2678  // Callee pop conventions:
2683  return true;
2684  default:
2685  return canGuaranteeTCO(CC);
2686  }
2687 }
2688 
2689 /// Return true if the function is being made into a tailcall target by
2690 /// changing its ABI.
2691 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2692  return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2693 }
2694 
2695 bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2696  auto Attr =
2697  CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2698  if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2699  return false;
2700 
2701  ImmutableCallSite CS(CI);
2702  CallingConv::ID CalleeCC = CS.getCallingConv();
2703  if (!mayTailCallThisCC(CalleeCC))
2704  return false;
2705 
2706  return true;
2707 }
2708 
2709 SDValue
2710 X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
2711  const SmallVectorImpl<ISD::InputArg> &Ins,
2712  const SDLoc &dl, SelectionDAG &DAG,
2713  const CCValAssign &VA,
2714  MachineFrameInfo &MFI, unsigned i) const {
2715  // Create the nodes corresponding to a load from this parameter slot.
2716  ISD::ArgFlagsTy Flags = Ins[i].Flags;
2717  bool AlwaysUseMutable = shouldGuaranteeTCO(
2718  CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2719  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2720  EVT ValVT;
2721  MVT PtrVT = getPointerTy(DAG.getDataLayout());
2722 
2723  // If value is passed by pointer we have address passed instead of the value
2724  // itself. No need to extend if the mask value and location share the same
2725  // absolute size.
2726  bool ExtendedInMem =
2727  VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
2728  VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
2729 
2730  if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2731  ValVT = VA.getLocVT();
2732  else
2733  ValVT = VA.getValVT();
2734 
2735  // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2736  // taken by a return address.
2737  int Offset = 0;
2738  if (CallConv == CallingConv::X86_INTR) {
2739  // X86 interrupts may take one or two arguments.
2740  // On the stack there will be no return address as in regular call.
2741  // Offset of last argument need to be set to -4/-8 bytes.
2742  // Where offset of the first argument out of two, should be set to 0 bytes.
2743  Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2744  if (Subtarget.is64Bit() && Ins.size() == 2) {
2745  // The stack pointer needs to be realigned for 64 bit handlers with error
2746  // code, so the argument offset changes by 8 bytes.
2747  Offset += 8;
2748  }
2749  }
2750 
2751  // FIXME: For now, all byval parameter objects are marked mutable. This can be
2752  // changed with more analysis.
2753  // In case of tail call optimization mark all arguments mutable. Since they
2754  // could be overwritten by lowering of arguments in case of a tail call.
2755  if (Flags.isByVal()) {
2756  unsigned Bytes = Flags.getByValSize();
2757  if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2758  int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2759  // Adjust SP offset of interrupt parameter.
2760  if (CallConv == CallingConv::X86_INTR) {
2761  MFI.setObjectOffset(FI, Offset);
2762  }
2763  return DAG.getFrameIndex(FI, PtrVT);
2764  }
2765 
2766  // This is an argument in memory. We might be able to perform copy elision.
2767  if (Flags.isCopyElisionCandidate()) {
2768  EVT ArgVT = Ins[i].ArgVT;
2769  SDValue PartAddr;
2770  if (Ins[i].PartOffset == 0) {
2771  // If this is a one-part value or the first part of a multi-part value,
2772  // create a stack object for the entire argument value type and return a
2773  // load from our portion of it. This assumes that if the first part of an
2774  // argument is in memory, the rest will also be in memory.
2775  int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
2776  /*Immutable=*/false);
2777  PartAddr = DAG.getFrameIndex(FI, PtrVT);
2778  return DAG.getLoad(
2779  ValVT, dl, Chain, PartAddr,
2781  } else {
2782  // This is not the first piece of an argument in memory. See if there is
2783  // already a fixed stack object including this offset. If so, assume it
2784  // was created by the PartOffset == 0 branch above and create a load from
2785  // the appropriate offset into it.
2786  int64_t PartBegin = VA.getLocMemOffset();
2787  int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
2788  int FI = MFI.getObjectIndexBegin();
2789  for (; MFI.isFixedObjectIndex(FI); ++FI) {
2790  int64_t ObjBegin = MFI.getObjectOffset(FI);
2791  int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
2792  if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
2793  break;
2794  }
2795  if (MFI.isFixedObjectIndex(FI)) {
2796  SDValue Addr =
2797  DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
2798  DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
2799  return DAG.getLoad(
2800  ValVT, dl, Chain, Addr,
2802  Ins[i].PartOffset));
2803  }
2804  }
2805  }
2806 
2807  int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
2808  VA.getLocMemOffset(), isImmutable);
2809 
2810  // Set SExt or ZExt flag.
2811  if (VA.getLocInfo() == CCValAssign::ZExt) {
2812  MFI.setObjectZExt(FI, true);
2813  } else if (VA.getLocInfo() == CCValAssign::SExt) {
2814  MFI.setObjectSExt(FI, true);
2815  }
2816 
2817  // Adjust SP offset of interrupt parameter.
2818  if (CallConv == CallingConv::X86_INTR) {
2819  MFI.setObjectOffset(FI, Offset);
2820  }
2821 
2822  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2823  SDValue Val = DAG.getLoad(
2824  ValVT, dl, Chain, FIN,
2826  return ExtendedInMem
2827  ? (VA.getValVT().isVector()
2828  ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
2829  : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
2830  : Val;
2831 }
2832 
2833 // FIXME: Get this from tablegen.
2835  const X86Subtarget &Subtarget) {
2836  assert(Subtarget.is64Bit());
2837 
2838  if (Subtarget.isCallingConvWin64(CallConv)) {
2839  static const MCPhysReg GPR64ArgRegsWin64[] = {
2840  X86::RCX, X86::RDX, X86::R8, X86::R9
2841  };
2842  return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2843  }
2844 
2845  static const MCPhysReg GPR64ArgRegs64Bit[] = {
2846  X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2847  };
2848  return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2849 }
2850 
2851 // FIXME: Get this from tablegen.
2853  CallingConv::ID CallConv,
2854  const X86Subtarget &Subtarget) {
2855  assert(Subtarget.is64Bit());
2856  if (Subtarget.isCallingConvWin64(CallConv)) {
2857  // The XMM registers which might contain var arg parameters are shadowed
2858  // in their paired GPR. So we only need to save the GPR to their home
2859  // slots.
2860  // TODO: __vectorcall will change this.
2861  return None;
2862  }
2863 
2864  const Function *Fn = MF.getFunction();
2865  bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2866  bool isSoftFloat = Subtarget.useSoftFloat();
2867  assert(!(isSoftFloat && NoImplicitFloatOps) &&
2868  "SSE register cannot be used when SSE is disabled!");
2869  if (isSoftFloat || NoImplicitFloatOps || !Subtarget.hasSSE1())
2870  // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2871  // registers.
2872  return None;
2873 
2874  static const MCPhysReg XMMArgRegs64Bit[] = {
2875  X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2876  X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2877  };
2878  return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2879 }
2880 
2881 #ifndef NDEBUG
2883  return std::is_sorted(ArgLocs.begin(), ArgLocs.end(),
2884  [](const CCValAssign &A, const CCValAssign &B) -> bool {
2885  return A.getValNo() < B.getValNo();
2886  });
2887 }
2888 #endif
2889 
2890 SDValue X86TargetLowering::LowerFormalArguments(
2891  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2892  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2893  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2894  MachineFunction &MF = DAG.getMachineFunction();
2896  const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
2897 
2898  const Function *Fn = MF.getFunction();
2899  if (Fn->hasExternalLinkage() &&
2900  Subtarget.isTargetCygMing() &&
2901  Fn->getName() == "main")
2902  FuncInfo->setForceFramePointer(true);
2903 
2904  MachineFrameInfo &MFI = MF.getFrameInfo();
2905  bool Is64Bit = Subtarget.is64Bit();
2906  bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
2907 
2908  assert(
2909  !(isVarArg && canGuaranteeTCO(CallConv)) &&
2910  "Var args not supported with calling conv' regcall, fastcc, ghc or hipe");
2911 
2912  if (CallConv == CallingConv::X86_INTR) {
2913  bool isLegal = Ins.size() == 1 ||
2914  (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
2915  (!Is64Bit && Ins[1].VT == MVT::i32)));
2916  if (!isLegal)
2917  report_fatal_error("X86 interrupts may take one or two arguments");
2918  }
2919 
2920  // Assign locations to all of the incoming arguments.
2922  CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2923 
2924  // Allocate shadow area for Win64.
2925  if (IsWin64)
2926  CCInfo.AllocateStack(32, 8);
2927 
2928  CCInfo.AnalyzeArguments(Ins, CC_X86);
2929 
2930  // In vectorcall calling convention a second pass is required for the HVA
2931  // types.
2932  if (CallingConv::X86_VectorCall == CallConv) {
2933  CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
2934  }
2935 
2936  // The next loop assumes that the locations are in the same order of the
2937  // input arguments.
2938  assert(isSortedByValueNo(ArgLocs) &&
2939  "Argument Location list must be sorted before lowering");
2940 
2941  SDValue ArgValue;
2942  for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
2943  ++I, ++InsIndex) {
2944  assert(InsIndex < Ins.size() && "Invalid Ins index");
2945  CCValAssign &VA = ArgLocs[I];
2946 
2947  if (VA.isRegLoc()) {
2948  EVT RegVT = VA.getLocVT();
2949  if (VA.needsCustom()) {
2950  assert(
2951  VA.getValVT() == MVT::v64i1 &&
2952  "Currently the only custom case is when we split v64i1 to 2 regs");
2953 
2954  // v64i1 values, in regcall calling convention, that are
2955  // compiled to 32 bit arch, are split up into two registers.
2956  ArgValue =
2957  getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
2958  } else {
2959  const TargetRegisterClass *RC;
2960  if (RegVT == MVT::i32)
2961  RC = &X86::GR32RegClass;
2962  else if (Is64Bit && RegVT == MVT::i64)
2963  RC = &X86::GR64RegClass;
2964  else if (RegVT == MVT::f32)
2965  RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
2966  else if (RegVT == MVT::f64)
2967  RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
2968  else if (RegVT == MVT::f80)
2969  RC = &X86::RFP80RegClass;
2970  else if (RegVT == MVT::f128)
2971  RC = &X86::FR128RegClass;
2972  else if (RegVT.is512BitVector())
2973  RC = &X86::VR512RegClass;
2974  else if (RegVT.is256BitVector())
2975  RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
2976  else if (RegVT.is128BitVector())
2977  RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
2978  else if (RegVT == MVT::x86mmx)
2979  RC = &X86::VR64RegClass;
2980  else if (RegVT == MVT::v1i1)
2981  RC = &X86::VK1RegClass;
2982  else if (RegVT == MVT::v8i1)
2983  RC = &X86::VK8RegClass;
2984  else if (RegVT == MVT::v16i1)
2985  RC = &X86::VK16RegClass;
2986  else if (RegVT == MVT::v32i1)
2987  RC = &X86::VK32RegClass;
2988  else if (RegVT == MVT::v64i1)
2989  RC = &X86::VK64RegClass;
2990  else
2991  llvm_unreachable("Unknown argument type!");
2992 
2993  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2994  ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2995  }
2996 
2997  // If this is an 8 or 16-bit value, it is really passed promoted to 32
2998  // bits. Insert an assert[sz]ext to capture this, then truncate to the
2999  // right size.
3000  if (VA.getLocInfo() == CCValAssign::SExt)
3001  ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3002  DAG.getValueType(VA.getValVT()));
3003  else if (VA.getLocInfo() == CCValAssign::ZExt)
3004  ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3005  DAG.getValueType(VA.getValVT()));
3006  else if (VA.getLocInfo() == CCValAssign::BCvt)
3007  ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
3008 
3009  if (VA.isExtInLoc()) {
3010  // Handle MMX values passed in XMM regs.
3011  if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
3012  ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
3013  else if (VA.getValVT().isVector() &&
3014  VA.getValVT().getScalarType() == MVT::i1 &&
3015  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3016  (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3017  // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3018  ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
3019  } else
3020  ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3021  }
3022  } else {
3023  assert(VA.isMemLoc());
3024  ArgValue =
3025  LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
3026  }
3027 
3028  // If value is passed via pointer - do a load.
3029  if (VA.getLocInfo() == CCValAssign::Indirect)
3030  ArgValue =
3031  DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
3032 
3033  InVals.push_back(ArgValue);
3034  }
3035 
3036  for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3037  // Swift calling convention does not require we copy the sret argument
3038  // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
3039  if (CallConv == CallingConv::Swift)
3040  continue;
3041 
3042  // All x86 ABIs require that for returning structs by value we copy the
3043  // sret argument into %rax/%eax (depending on ABI) for the return. Save
3044  // the argument into a virtual register so that we can access it from the
3045  // return points.
3046  if (Ins[I].Flags.isSRet()) {
3047  unsigned Reg = FuncInfo->getSRetReturnReg();
3048  if (!Reg) {
3049  MVT PtrTy = getPointerTy(DAG.getDataLayout());
3050  Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3051  FuncInfo->setSRetReturnReg(Reg);
3052  }
3053  SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
3054  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3055  break;
3056  }
3057  }
3058 
3059  unsigned StackSize = CCInfo.getNextStackOffset();
3060  // Align stack specially for tail calls.
3061  if (shouldGuaranteeTCO(CallConv,
3063  StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
3064 
3065  // If the function takes variable number of arguments, make a frame index for
3066  // the start of the first vararg value... for expansion of llvm.va_start. We
3067  // can skip this if there are no va_start calls.
3068  if (MFI.hasVAStart() &&
3069  (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
3070  CallConv != CallingConv::X86_ThisCall))) {
3071  FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
3072  }
3073 
3074  // Figure out if XMM registers are in use.
3075  assert(!(Subtarget.useSoftFloat() &&
3076  Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
3077  "SSE register cannot be used when SSE is disabled!");
3078 
3079  // 64-bit calling conventions support varargs and register parameters, so we
3080  // have to do extra work to spill them in the prologue.
3081  if (Is64Bit && isVarArg && MFI.hasVAStart()) {
3082  // Find the first unallocated argument registers.
3083  ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3084  ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
3085  unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3086  unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3087  assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&
3088  "SSE register cannot be used when SSE is disabled!");
3089 
3090  // Gather all the live in physical registers.
3091  SmallVector<SDValue, 6> LiveGPRs;
3092  SmallVector<SDValue, 8> LiveXMMRegs;
3093  SDValue ALVal;
3094  for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3095  unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
3096  LiveGPRs.push_back(
3097  DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
3098  }
3099  if (!ArgXMMs.empty()) {
3100  unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3101  ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
3102  for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
3103  unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
3104  LiveXMMRegs.push_back(
3105  DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
3106  }
3107  }
3108 
3109  if (IsWin64) {
3110  // Get to the caller-allocated home save location. Add 8 to account
3111  // for the return address.
3112  int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
3113  FuncInfo->setRegSaveFrameIndex(
3114  MFI.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3115  // Fixup to set vararg frame on shadow area (4 x i64).
3116  if (NumIntRegs < 4)
3117  FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3118  } else {
3119  // For X86-64, if there are vararg parameters that are passed via
3120  // registers, then we must store them to their spots on the stack so
3121  // they may be loaded by dereferencing the result of va_next.
3122  FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3123  FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3125  ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
3126  }
3127 
3128  // Store the integer parameter registers.
3129  SmallVector<SDValue, 8> MemOps;
3130  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3131  getPointerTy(DAG.getDataLayout()));
3132  unsigned Offset = FuncInfo->getVarArgsGPOffset();
3133  for (SDValue Val : LiveGPRs) {
3134  SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3135  RSFIN, DAG.getIntPtrConstant(Offset, dl));
3136  SDValue Store =
3137  DAG.getStore(Val.getValue(1), dl, Val, FIN,
3139  DAG.getMachineFunction(),
3140  FuncInfo->getRegSaveFrameIndex(), Offset));
3141  MemOps.push_back(Store);
3142  Offset += 8;
3143  }
3144 
3145  if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
3146  // Now store the XMM (fp + vector) parameter registers.
3147  SmallVector<SDValue, 12> SaveXMMOps;
3148  SaveXMMOps.push_back(Chain);
3149  SaveXMMOps.push_back(ALVal);
3150  SaveXMMOps.push_back(DAG.getIntPtrConstant(
3151  FuncInfo->getRegSaveFrameIndex(), dl));
3152  SaveXMMOps.push_back(DAG.getIntPtrConstant(
3153  FuncInfo->getVarArgsFPOffset(), dl));
3154  SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
3155  LiveXMMRegs.end());
3157  MVT::Other, SaveXMMOps));
3158  }
3159 
3160  if (!MemOps.empty())
3161  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3162  }
3163 
3164  if (isVarArg && MFI.hasMustTailInVarArgFunc()) {
3165  // Find the largest legal vector type.
3166  MVT VecVT = MVT::Other;
3167  // FIXME: Only some x86_32 calling conventions support AVX512.
3168  if (Subtarget.hasAVX512() &&
3169  (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
3170  CallConv == CallingConv::Intel_OCL_BI)))
3171  VecVT = MVT::v16f32;
3172  else if (Subtarget.hasAVX())
3173  VecVT = MVT::v8f32;
3174  else if (Subtarget.hasSSE2())
3175  VecVT = MVT::v4f32;
3176 
3177  // We forward some GPRs and some vector types.
3178  SmallVector<MVT, 2> RegParmTypes;
3179  MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
3180  RegParmTypes.push_back(IntVT);
3181  if (VecVT != MVT::Other)
3182  RegParmTypes.push_back(VecVT);
3183 
3184  // Compute the set of forwarded registers. The rest are scratch.
3186  FuncInfo->getForwardedMustTailRegParms();
3187  CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3188 
3189  // Conservatively forward AL on x86_64, since it might be used for varargs.
3190  if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
3191  unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3192  Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3193  }
3194 
3195  // Copy all forwards from physical to virtual registers.
3196  for (ForwardedRegister &F : Forwards) {
3197  // FIXME: Can we use a less constrained schedule?
3198  SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3200  Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
3201  }
3202  }
3203 
3204  // Some CCs need callee pop.
3205  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3207  FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
3208  } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
3209  // X86 interrupts must pop the error code (and the alignment padding) if
3210  // present.
3211  FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
3212  } else {
3213  FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
3214  // If this is an sret function, the return should pop the hidden pointer.
3215  if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3216  !Subtarget.getTargetTriple().isOSMSVCRT() &&
3217  argsAreStructReturn(Ins, Subtarget.isTargetMCU()) == StackStructReturn)
3218  FuncInfo->setBytesToPopOnReturn(4);
3219  }
3220 
3221  if (!Is64Bit) {
3222  // RegSaveFrameIndex is X86-64 only.
3223  FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3224  if (CallConv == CallingConv::X86_FastCall ||
3225  CallConv == CallingConv::X86_ThisCall)
3226  // fastcc functions can't have varargs.
3227  FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
3228  }
3229 
3230  FuncInfo->setArgumentStackSize(StackSize);
3231 
3232  if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
3234  if (Personality == EHPersonality::CoreCLR) {
3235  assert(Is64Bit);
3236  // TODO: Add a mechanism to frame lowering that will allow us to indicate
3237  // that we'd prefer this slot be allocated towards the bottom of the frame
3238  // (i.e. near the stack pointer after allocating the frame). Every
3239  // funclet needs a copy of this slot in its (mostly empty) frame, and the
3240  // offset from the bottom of this and each funclet's frame must be the
3241  // same, so the size of funclets' (mostly empty) frames is dictated by
3242  // how far this slot is from the bottom (since they allocate just enough
3243  // space to accommodate holding this slot at the correct offset).
3244  int PSPSymFI = MFI.CreateStackObject(8, 8, /*isSS=*/false);
3245  EHInfo->PSPSymFrameIdx = PSPSymFI;
3246  }
3247  }
3248 
3249  if (CallConv == CallingConv::X86_RegCall ||
3250  Fn->hasFnAttribute("no_caller_saved_registers")) {
3252  for (std::pair<unsigned, unsigned> Pair : MRI.liveins())
3253  MRI.disableCalleeSavedRegister(Pair.first);
3254  }
3255 
3256  return Chain;
3257 }
3258 
3259 SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
3260  SDValue Arg, const SDLoc &dl,
3261  SelectionDAG &DAG,
3262  const CCValAssign &VA,
3263  ISD::ArgFlagsTy Flags) const {
3264  unsigned LocMemOffset = VA.getLocMemOffset();
3265  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3266  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3267  StackPtr, PtrOff);
3268  if (Flags.isByVal())
3269  return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3270 
3271  return DAG.getStore(
3272  Chain, dl, Arg, PtrOff,
3273  MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
3274 }
3275 
3276 /// Emit a load of return address if tail call
3277 /// optimization is performed and it is required.
3278 SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
3279  SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
3280  bool Is64Bit, int FPDiff, const SDLoc &dl) const {
3281  // Adjust the Return address stack slot.
3282  EVT VT = getPointerTy(DAG.getDataLayout());
3283  OutRetAddr = getReturnAddressFrameIndex(DAG);
3284 
3285  // Load the "old" Return address.
3286  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
3287  return SDValue(OutRetAddr.getNode(), 1);
3288 }
3289 
3290 /// Emit a store of the return address if tail call
3291 /// optimization is performed and it is required (FPDiff!=0).
3293  SDValue Chain, SDValue RetAddrFrIdx,
3294  EVT PtrVT, unsigned SlotSize,
3295  int FPDiff, const SDLoc &dl) {
3296  // Store the return address to the appropriate stack slot.
3297  if (!FPDiff) return Chain;
3298  // Calculate the new stack slot for the return address.
3299  int NewReturnAddrFI =
3300  MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3301  false);
3302  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3303  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3305  DAG.getMachineFunction(), NewReturnAddrFI));
3306  return Chain;
3307 }
3308 
3309 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3310 /// operation of specified width.
3311 static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
3312  SDValue V2) {
3313  unsigned NumElems = VT.getVectorNumElements();
3315  Mask.push_back(NumElems);
3316  for (unsigned i = 1; i != NumElems; ++i)
3317  Mask.push_back(i);
3318  return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
3319 }
3320 
3321 SDValue
3322 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3323  SmallVectorImpl<SDValue> &InVals) const {
3324  SelectionDAG &DAG = CLI.DAG;
3325  SDLoc &dl = CLI.DL;
3327  SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3329  SDValue Chain = CLI.Chain;
3330  SDValue Callee = CLI.Callee;
3331  CallingConv::ID CallConv = CLI.CallConv;
3332  bool &isTailCall = CLI.IsTailCall;
3333  bool isVarArg = CLI.IsVarArg;
3334 
3335  MachineFunction &MF = DAG.getMachineFunction();
3336  bool Is64Bit = Subtarget.is64Bit();
3337  bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3338  StructReturnType SR = callIsStructReturn(Outs, Subtarget.isTargetMCU());
3339  bool IsSibcall = false;
3341  auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3342  const auto *CI = dyn_cast_or_null<CallInst>(CLI.CS.getInstruction());
3343  const Function *Fn = CI ? CI->getCalledFunction() : nullptr;
3344  bool HasNCSR = (CI && CI->hasFnAttr("no_caller_saved_registers")) ||
3345  (Fn && Fn->hasFnAttribute("no_caller_saved_registers"));
3346 
3347  if (CallConv == CallingConv::X86_INTR)
3348  report_fatal_error("X86 interrupts may not be called directly");
3349 
3350  if (Attr.getValueAsString() == "true")
3351  isTailCall = false;
3352 
3353  if (Subtarget.isPICStyleGOT() &&
3355  // If we are using a GOT, disable tail calls to external symbols with
3356  // default visibility. Tail calling such a symbol requires using a GOT
3357  // relocation, which forces early binding of the symbol. This breaks code
3358  // that require lazy function symbol resolution. Using musttail or
3359  // GuaranteedTailCallOpt will override this.
3361  if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3363  isTailCall = false;
3364  }
3365 
3366  bool IsMustTail = CLI.CS && CLI.CS.isMustTailCall();
3367  if (IsMustTail) {
3368  // Force this to be a tail call. The verifier rules are enough to ensure
3369  // that we can lower this successfully without moving the return address
3370  // around.
3371  isTailCall = true;
3372  } else if (isTailCall) {
3373  // Check if it's really possible to do a tail call.
3374  isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3375  isVarArg, SR != NotStructReturn,
3376  MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3377  Outs, OutVals, Ins, DAG);
3378 
3379  // Sibcalls are automatically detected tailcalls which do not require
3380  // ABI changes.
3381  if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3382  IsSibcall = true;
3383 
3384  if (isTailCall)
3385  ++NumTailCalls;
3386  }
3387 
3388  assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3389  "Var args not supported with calling convention fastcc, ghc or hipe");
3390 
3391  // Analyze operands of the call, assigning locations to each operand.
3393  CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3394 
3395  // Allocate shadow area for Win64.
3396  if (IsWin64)
3397  CCInfo.AllocateStack(32, 8);
3398 
3399  CCInfo.AnalyzeArguments(Outs, CC_X86);
3400 
3401  // In vectorcall calling convention a second pass is required for the HVA
3402  // types.
3403  if (CallingConv::X86_VectorCall == CallConv) {
3404  CCInfo.AnalyzeArgumentsSecondPass(Outs, CC_X86);
3405  }
3406 
3407  // Get a count of how many bytes are to be pushed on the stack.
3408  unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3409  if (IsSibcall)
3410  // This is a sibcall. The memory operands are available in caller's
3411  // own caller's stack.
3412  NumBytes = 0;
3413  else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3414  canGuaranteeTCO(CallConv))
3415  NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3416 
3417  int FPDiff = 0;
3418  if (isTailCall && !IsSibcall && !IsMustTail) {
3419  // Lower arguments at fp - stackoffset + fpdiff.
3420  unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3421 
3422  FPDiff = NumBytesCallerPushed - NumBytes;
3423 
3424  // Set the delta of movement of the returnaddr stackslot.
3425  // But only set if delta is greater than previous delta.
3426  if (FPDiff < X86Info->getTCReturnAddrDelta())
3427  X86Info->setTCReturnAddrDelta(FPDiff);
3428  }
3429 
3430  unsigned NumBytesToPush = NumBytes;
3431  unsigned NumBytesToPop = NumBytes;
3432 
3433  // If we have an inalloca argument, all stack space has already been allocated
3434  // for us and be right at the top of the stack. We don't support multiple
3435  // arguments passed in memory when using inalloca.
3436  if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3437  NumBytesToPush = 0;
3438  if (!ArgLocs.back().isMemLoc())
3439  report_fatal_error("cannot use inalloca attribute on a register "
3440  "parameter");
3441  if (ArgLocs.back().getLocMemOffset() != 0)
3442  report_fatal_error("any parameter with the inalloca attribute must be "
3443  "the only memory argument");
3444  }
3445 
3446  if (!IsSibcall)
3447  Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
3448  NumBytes - NumBytesToPush, dl);
3449 
3450  SDValue RetAddrFrIdx;
3451  // Load return address for tail calls.
3452  if (isTailCall && FPDiff)
3453  Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3454  Is64Bit, FPDiff, dl);
3455 
3457  SmallVector<SDValue, 8> MemOpChains;
3458  SDValue StackPtr;
3459 
3460  // The next loop assumes that the locations are in the same order of the
3461  // input arguments.
3462  assert(isSortedByValueNo(ArgLocs) &&
3463  "Argument Location list must be sorted before lowering");
3464 
3465  // Walk the register/memloc assignments, inserting copies/loads. In the case
3466  // of tail call optimization arguments are handle later.
3467  const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3468  for (unsigned I = 0, OutIndex = 0, E = ArgLocs.size(); I != E;
3469  ++I, ++OutIndex) {
3470  assert(OutIndex < Outs.size() && "Invalid Out index");
3471  // Skip inalloca arguments, they have already been written.
3472  ISD::ArgFlagsTy Flags = Outs[OutIndex].Flags;
3473  if (Flags.isInAlloca())
3474  continue;
3475 
3476  CCValAssign &VA = ArgLocs[I];
3477  EVT RegVT = VA.getLocVT();
3478  SDValue Arg = OutVals[OutIndex];
3479  bool isByVal = Flags.isByVal();
3480 
3481  // Promote the value if needed.
3482  switch (VA.getLocInfo()) {
3483  default: llvm_unreachable("Unknown loc info!");
3484  case CCValAssign::Full: break;
3485  case CCValAssign::SExt:
3486  Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3487  break;
3488  case CCValAssign::ZExt:
3489  Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3490  break;
3491  case CCValAssign::AExt:
3492  if (Arg.getValueType().isVector() &&
3494  Arg = lowerMasksToReg(Arg, RegVT, dl, DAG);
3495  else if (RegVT.is128BitVector()) {
3496  // Special case: passing MMX values in XMM registers.
3497  Arg = DAG.getBitcast(MVT::i64, Arg);
3498  Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3499  Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3500  } else
3501  Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3502  break;
3503  case CCValAssign::BCvt:
3504  Arg = DAG.getBitcast(RegVT, Arg);
3505  break;
3506  case CCValAssign::Indirect: {
3507  // Store the argument.
3508  SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3509  int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3510  Chain = DAG.getStore(
3511  Chain, dl, Arg, SpillSlot,
3513  Arg = SpillSlot;
3514  break;
3515  }
3516  }
3517 
3518  if (VA.needsCustom()) {
3519  assert(VA.getValVT() == MVT::v64i1 &&
3520  "Currently the only custom case is when we split v64i1 to 2 regs");
3521  // Split v64i1 value into two registers
3522  Passv64i1ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++I],
3523  Subtarget);
3524  } else if (VA.isRegLoc()) {
3525  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3526  if (isVarArg && IsWin64) {
3527  // Win64 ABI requires argument XMM reg to be copied to the corresponding
3528  // shadow reg if callee is a varargs function.
3529  unsigned ShadowReg = 0;
3530  switch (VA.getLocReg()) {
3531  case X86::XMM0: ShadowReg = X86::RCX; break;
3532  case X86::XMM1: ShadowReg = X86::RDX; break;
3533  case X86::XMM2: ShadowReg = X86::R8; break;
3534  case X86::XMM3: ShadowReg = X86::R9; break;
3535  }
3536  if (ShadowReg)
3537  RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3538  }
3539  } else if (!IsSibcall && (!isTailCall || isByVal)) {
3540  assert(VA.isMemLoc());
3541  if (!StackPtr.getNode())
3542  StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3543  getPointerTy(DAG.getDataLayout()));
3544  MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3545  dl, DAG, VA, Flags));
3546  }
3547  }
3548 
3549  if (!MemOpChains.empty())
3550  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3551 
3552  if (Subtarget.isPICStyleGOT()) {
3553  // ELF / PIC requires GOT in the EBX register before function calls via PLT
3554  // GOT pointer.
3555  if (!isTailCall) {
3556  RegsToPass.push_back(std::make_pair(
3557  unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3558  getPointerTy(DAG.getDataLayout()))));
3559  } else {
3560  // If we are tail calling and generating PIC/GOT style code load the
3561  // address of the callee into ECX. The value in ecx is used as target of
3562  // the tail jump. This is done to circumvent the ebx/callee-saved problem
3563  // for tail calls on PIC/GOT architectures. Normally we would just put the
3564  // address of GOT into ebx and then call target@PLT. But for tail calls
3565  // ebx would be restored (since ebx is callee saved) before jumping to the
3566  // target@PLT.
3567 
3568  // Note: The actual moving to ECX is done further down.
3570  if (G && !G->getGlobal()->hasLocalLinkage() &&
3572  Callee = LowerGlobalAddress(Callee, DAG);
3573  else if (isa<ExternalSymbolSDNode>(Callee))
3574  Callee = LowerExternalSymbol(Callee, DAG);
3575  }
3576  }
3577 
3578  if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3579  // From AMD64 ABI document:
3580  // For calls that may call functions that use varargs or stdargs
3581  // (prototype-less calls or calls to functions containing ellipsis (...) in
3582  // the declaration) %al is used as hidden argument to specify the number
3583  // of SSE registers used. The contents of %al do not need to match exactly
3584  // the number of registers, but must be an ubound on the number of SSE
3585  // registers used and is in the range 0 - 8 inclusive.
3586 
3587  // Count the number of XMM registers allocated.
3588  static const MCPhysReg XMMArgRegs[] = {
3589  X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3590  X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3591  };
3592  unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3593  assert((Subtarget.hasSSE1() || !NumXMMRegs)
3594  && "SSE registers cannot be used when SSE is disabled");
3595 
3596  RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3597  DAG.getConstant(NumXMMRegs, dl,
3598  MVT::i8)));
3599  }
3600 
3601  if (isVarArg && IsMustTail) {
3602  const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3603  for (const auto &F : Forwards) {
3604  SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3605  RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3606  }
3607  }
3608 
3609  // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3610  // don't need this because the eligibility check rejects calls that require
3611  // shuffling arguments passed in memory.
3612  if (!IsSibcall && isTailCall) {
3613  // Force all the incoming stack arguments to be loaded from the stack
3614  // before any new outgoing arguments are stored to the stack, because the
3615  // outgoing stack slots may alias the incoming argument stack slots, and
3616  // the alias isn't otherwise explicit. This is slightly more conservative
3617  // than necessary, because it means that each store effectively depends
3618  // on every argument instead of just those arguments it would clobber.
3619  SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3620 
3621  SmallVector<SDValue, 8> MemOpChains2;
3622  SDValue FIN;
3623  int FI = 0;
3624  for (unsigned I = 0, OutsIndex = 0, E = ArgLocs.size(); I != E;
3625  ++I, ++OutsIndex) {
3626  CCValAssign &VA = ArgLocs[I];
3627 
3628  if (VA.isRegLoc()) {
3629  if (VA.needsCustom()) {
3630  assert((CallConv == CallingConv::X86_RegCall) &&
3631  "Expecting custom case only in regcall calling convention");
3632  // This means that we are in special case where one argument was
3633  // passed through two register locations - Skip the next location
3634  ++I;
3635  }
3636 
3637  continue;
3638  }
3639 
3640  assert(VA.isMemLoc());
3641  SDValue Arg = OutVals[OutsIndex];
3642  ISD::ArgFlagsTy Flags = Outs[OutsIndex].Flags;
3643  // Skip inalloca arguments. They don't require any work.
3644  if (Flags.isInAlloca())
3645  continue;
3646  // Create frame index.
3647  int32_t Offset = VA.getLocMemOffset()+FPDiff;
3648  uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3649  FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3650  FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3651 
3652  if (Flags.isByVal()) {
3653  // Copy relative to framepointer.
3655  if (!StackPtr.getNode())
3656  StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3657  getPointerTy(DAG.getDataLayout()));
3658  Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3659  StackPtr, Source);
3660 
3661  MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3662  ArgChain,
3663  Flags, DAG, dl));
3664  } else {
3665  // Store relative to framepointer.
3666  MemOpChains2.push_back(DAG.getStore(
3667  ArgChain, dl, Arg, FIN,
3669  }
3670  }
3671 
3672  if (!MemOpChains2.empty())
3673  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3674 
3675  // Store the return address to the appropriate stack slot.
3676  Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3677  getPointerTy(DAG.getDataLayout()),
3678  RegInfo->getSlotSize(), FPDiff, dl);
3679  }
3680 
3681  // Build a sequence of copy-to-reg nodes chained together with token chain
3682  // and flag operands which copy the outgoing args into registers.
3683  SDValue InFlag;
3684  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3685  Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3686  RegsToPass[i].second, InFlag);
3687  InFlag = Chain.getValue(1);
3688  }
3689 
3690  if (DAG.getTarget().