LLVM  8.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"
22 #include "X86TargetMachine.h"
23 #include "X86TargetObjectFile.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/IR/CallSite.h"
40 #include "llvm/IR/CallingConv.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/DiagnosticInfo.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GlobalAlias.h"
46 #include "llvm/IR/GlobalVariable.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/Intrinsics.h"
49 #include "llvm/MC/MCAsmInfo.h"
50 #include "llvm/MC/MCContext.h"
51 #include "llvm/MC/MCExpr.h"
52 #include "llvm/MC/MCSymbol.h"
54 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/KnownBits.h"
59 #include <algorithm>
60 #include <bitset>
61 #include <cctype>
62 #include <numeric>
63 using namespace llvm;
64 
65 #define DEBUG_TYPE "x86-isel"
66 
67 STATISTIC(NumTailCalls, "Number of tail calls");
68 
70  "x86-experimental-vector-widening-legalization", cl::init(false),
71  cl::desc("Enable an experimental vector type legalization through widening "
72  "rather than promotion."),
73  cl::Hidden);
74 
76  "x86-experimental-pref-loop-alignment", cl::init(4),
77  cl::desc("Sets the preferable loop alignment for experiments "
78  "(the last x86-experimental-pref-loop-alignment bits"
79  " of the loop header PC will be 0)."),
80  cl::Hidden);
81 
83  "mul-constant-optimization", cl::init(true),
84  cl::desc("Replace 'mul x, Const' with more effective instructions like "
85  "SHIFT, LEA, etc."),
86  cl::Hidden);
87 
88 /// Call this when the user attempts to do something unsupported, like
89 /// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike
90 /// report_fatal_error, so calling code should attempt to recover without
91 /// crashing.
92 static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl,
93  const char *Msg) {
95  DAG.getContext()->diagnose(
97 }
98 
100  const X86Subtarget &STI)
101  : TargetLowering(TM), Subtarget(STI) {
102  bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
103  X86ScalarSSEf64 = Subtarget.hasSSE2();
104  X86ScalarSSEf32 = Subtarget.hasSSE1();
106 
107  // Set up the TargetLowering object.
108 
109  // X86 is weird. It always uses i8 for shift amounts and setcc results.
111  // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
113 
114  // For 64-bit, since we have so many registers, use the ILP scheduler.
115  // For 32-bit, use the register pressure specific scheduling.
116  // For Atom, always use ILP scheduling.
117  if (Subtarget.isAtom())
119  else if (Subtarget.is64Bit())
121  else
123  const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
125 
126  // Bypass expensive divides and use cheaper ones.
127  if (TM.getOptLevel() >= CodeGenOpt::Default) {
128  if (Subtarget.hasSlowDivide32())
129  addBypassSlowDiv(32, 8);
130  if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
131  addBypassSlowDiv(64, 32);
132  }
133 
134  if (Subtarget.isTargetKnownWindowsMSVC() ||
135  Subtarget.isTargetWindowsItanium()) {
136  // Setup Windows compiler runtime calls.
137  setLibcallName(RTLIB::SDIV_I64, "_alldiv");
138  setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
139  setLibcallName(RTLIB::SREM_I64, "_allrem");
140  setLibcallName(RTLIB::UREM_I64, "_aullrem");
141  setLibcallName(RTLIB::MUL_I64, "_allmul");
147  }
148 
149  if (Subtarget.isTargetDarwin()) {
150  // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
151  setUseUnderscoreSetJmp(false);
153  } else if (Subtarget.isTargetWindowsGNU()) {
154  // MS runtime is weird: it exports _setjmp, but longjmp!
157  } else {
160  }
161 
162  // Set up the register classes.
163  addRegisterClass(MVT::i8, &X86::GR8RegClass);
164  addRegisterClass(MVT::i16, &X86::GR16RegClass);
165  addRegisterClass(MVT::i32, &X86::GR32RegClass);
166  if (Subtarget.is64Bit())
167  addRegisterClass(MVT::i64, &X86::GR64RegClass);
168 
169  for (MVT VT : MVT::integer_valuetypes())
171 
172  // We don't accept any truncstore of integer registers.
179 
181 
182  // SETOEQ and SETUNE require checking two conditions.
189 
190  // Integer absolute.
191  if (Subtarget.hasCMov()) {
194  if (Subtarget.is64Bit())
196  }
197 
198  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
199  // operation.
203 
204  if (Subtarget.is64Bit()) {
205  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512())
206  // f32/f64 are legal, f80 is custom.
208  else
211  } else if (!Subtarget.useSoftFloat()) {
212  // We have an algorithm for SSE2->double, and we turn this into a
213  // 64-bit FILD followed by conditional FADD for other targets.
215  // We have an algorithm for SSE2, and we turn this into a 64-bit
216  // FILD or VCVTUSI2SS/SD for other targets.
218  } else {
220  }
221 
222  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
223  // this operation.
226 
227  if (!Subtarget.useSoftFloat()) {
228  // SSE has no i16 to fp conversion, only i32.
229  if (X86ScalarSSEf32) {
231  // f32 and f64 cases are Legal, f80 case is not
233  } else {
236  }
237  } else {
240  }
241 
242  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
243  // this operation.
246 
247  if (!Subtarget.useSoftFloat()) {
248  // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
249  // are Legal, f80 is custom lowered.
252 
253  if (X86ScalarSSEf32) {
255  // f32 and f64 cases are Legal, f80 case is not
257  } else {
260  }
261  } else {
265  }
266 
267  // Handle FP_TO_UINT by promoting the destination to a larger signed
268  // conversion.
272 
273  if (Subtarget.is64Bit()) {
274  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
275  // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
278  } else {
281  }
282  } else if (!Subtarget.useSoftFloat()) {
283  // Since AVX is a superset of SSE3, only check for SSE here.
284  if (Subtarget.hasSSE1() && !Subtarget.hasSSE3())
285  // Expand FP_TO_UINT into a select.
286  // FIXME: We would like to use a Custom expander here eventually to do
287  // the optimal thing for SSE vs. the default expansion in the legalizer.
289  else
290  // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
291  // With SSE3 we can use fisttpll to convert to a signed i64; without
292  // SSE, we're stuck with a fistpll.
294 
296  }
297 
298  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
299  if (!X86ScalarSSEf64) {
302  if (Subtarget.is64Bit()) {
304  // Without SSE, i64->f64 goes through memory.
306  }
307  } else if (!Subtarget.is64Bit())
309 
310  // Scalar integer divide and remainder are lowered to use operations that
311  // produce two results, to match the available instructions. This exposes
312  // the two-result form to trivial CSE, which is able to combine x/y and x%y
313  // into a single instruction.
314  //
315  // Scalar integer multiply-high is also lowered to use two-result
316  // operations, to match the available instructions. However, plain multiply
317  // (low) operations are left as Legal, as there are single-result
318  // instructions for this in x86. Using the two-result multiply instructions
319  // when both high and low results are needed must be arranged by dagcombine.
320  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
327  }
328 
331  for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
335  }
336  if (Subtarget.is64Bit())
342 
347 
348  // Promote the i8 variants and force them on up to i32 which has a shorter
349  // encoding.
352  if (!Subtarget.hasBMI()) {
357  if (Subtarget.is64Bit()) {
360  }
361  }
362 
363  if (Subtarget.hasLZCNT()) {
364  // When promoting the i8 variants, force them to i32 for a shorter
365  // encoding.
368  } else {
375  if (Subtarget.is64Bit()) {
378  }
379  }
380 
381  // Special handling for half-precision floating point conversions.
382  // If we don't have F16C support, then lower half float conversions
383  // into library calls.
384  if (Subtarget.useSoftFloat() || !Subtarget.hasF16C()) {
387  }
388 
389  // There's never any support for operations beyond MVT::f32.
394 
401 
402  if (Subtarget.hasPOPCNT()) {
404  } else {
408  if (Subtarget.is64Bit())
410  }
411 
413 
414  if (!Subtarget.hasMOVBE())
416 
417  // These should be promoted to a larger select which is supported.
419  // X86 wants to expand cmov itself.
420  for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
423  }
424  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
425  if (VT == MVT::i64 && !Subtarget.is64Bit())
426  continue;
429  }
430 
431  // Custom action for SELECT MMX and expand action for SELECT_CC MMX
434 
436  // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
437  // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
442  setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
443 
444  // Darwin ABI issue.
445  for (auto VT : { MVT::i32, MVT::i64 }) {
446  if (VT == MVT::i64 && !Subtarget.is64Bit())
447  continue;
454  }
455 
456  // 64-bit shl, sra, srl (iff 32-bit x86)
457  for (auto VT : { MVT::i32, MVT::i64 }) {
458  if (VT == MVT::i64 && !Subtarget.is64Bit())
459  continue;
463  }
464 
465  if (Subtarget.hasSSEPrefetch() || Subtarget.has3DNow())
467 
469 
470  // Expand certain atomics
471  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
479  }
480 
481  if (Subtarget.hasCmpxchg16b()) {
483  }
484 
485  // FIXME - use subtarget debug flags
486  if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
487  !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
490  }
491 
494 
497 
500 
501  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
504  bool Is64Bit = Subtarget.is64Bit();
506  setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
507 
510 
512 
513  // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
516 
517  if (!Subtarget.useSoftFloat() && X86ScalarSSEf64) {
518  // f32 and f64 use SSE.
519  // Set up the FP register classes.
520  addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
521  : &X86::FR32RegClass);
522  addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
523  : &X86::FR64RegClass);
524 
525  for (auto VT : { MVT::f32, MVT::f64 }) {
526  // Use ANDPD to simulate FABS.
528 
529  // Use XORP to simulate FNEG.
531 
532  // Use ANDPD and ORPD to simulate FCOPYSIGN.
534 
535  // We don't support sin/cos/fmod
536  setOperationAction(ISD::FSIN , VT, Expand);
537  setOperationAction(ISD::FCOS , VT, Expand);
538  setOperationAction(ISD::FSINCOS, VT, Expand);
539  }
540 
541  // Lower this to MOVMSK plus an AND.
544 
545  } else if (!useSoftFloat() && X86ScalarSSEf32 && (UseX87 || Is64Bit)) {
546  // Use SSE for f32, x87 for f64.
547  // Set up the FP register classes.
548  addRegisterClass(MVT::f32, &X86::FR32RegClass);
549  if (UseX87)
550  addRegisterClass(MVT::f64, &X86::RFP64RegClass);
551 
552  // Use ANDPS to simulate FABS.
554 
555  // Use XORP to simulate FNEG.
557 
558  if (UseX87)
560 
561  // Use ANDPS and ORPS to simulate FCOPYSIGN.
562  if (UseX87)
565 
566  // We don't support sin/cos/fmod
570 
571  if (UseX87) {
572  // Always expand sin/cos functions even though x87 has an instruction.
576  }
577  } else if (UseX87) {
578  // f32 and f64 in x87.
579  // Set up the FP register classes.
580  addRegisterClass(MVT::f64, &X86::RFP64RegClass);
581  addRegisterClass(MVT::f32, &X86::RFP32RegClass);
582 
583  for (auto VT : { MVT::f32, MVT::f64 }) {
584  setOperationAction(ISD::UNDEF, VT, Expand);
585  setOperationAction(ISD::FCOPYSIGN, VT, Expand);
586 
587  // Always expand sin/cos functions even though x87 has an instruction.
588  setOperationAction(ISD::FSIN , VT, Expand);
589  setOperationAction(ISD::FCOS , VT, Expand);
590  setOperationAction(ISD::FSINCOS, VT, Expand);
591  }
592  }
593 
594  // Expand FP32 immediates into loads from the stack, save special cases.
595  if (isTypeLegal(MVT::f32)) {
596  if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
597  addLegalFPImmediate(APFloat(+0.0f)); // FLD0
598  addLegalFPImmediate(APFloat(+1.0f)); // FLD1
599  addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
600  addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
601  } else // SSE immediates.
602  addLegalFPImmediate(APFloat(+0.0f)); // xorps
603  }
604  // Expand FP64 immediates into loads from the stack, save special cases.
605  if (isTypeLegal(MVT::f64)) {
606  if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
607  addLegalFPImmediate(APFloat(+0.0)); // FLD0
608  addLegalFPImmediate(APFloat(+1.0)); // FLD1
609  addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
610  addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
611  } else // SSE immediates.
612  addLegalFPImmediate(APFloat(+0.0)); // xorpd
613  }
614 
615  // We don't support FMA.
618 
619  // Long double always uses X87, except f128 in MMX.
620  if (UseX87) {
621  if (Subtarget.is64Bit() && Subtarget.hasMMX()) {
622  addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
623  : &X86::VR128RegClass);
628  }
629 
630  addRegisterClass(MVT::f80, &X86::RFP80RegClass);
633  {
635  addLegalFPImmediate(TmpFlt); // FLD0
636  TmpFlt.changeSign();
637  addLegalFPImmediate(TmpFlt); // FLD0/FCHS
638 
639  bool ignored;
640  APFloat TmpFlt2(+1.0);
642  &ignored);
643  addLegalFPImmediate(TmpFlt2); // FLD1
644  TmpFlt2.changeSign();
645  addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
646  }
647 
648  // Always expand sin/cos functions even though x87 has an instruction.
652 
659  }
660 
661  // Always use a library call for pow.
665 
673 
674  // Some FP actions are always expanded for vector types.
675  for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
677  setOperationAction(ISD::FSIN, VT, Expand);
678  setOperationAction(ISD::FSINCOS, VT, Expand);
679  setOperationAction(ISD::FCOS, VT, Expand);
680  setOperationAction(ISD::FREM, VT, Expand);
681  setOperationAction(ISD::FCOPYSIGN, VT, Expand);
682  setOperationAction(ISD::FPOW, VT, Expand);
683  setOperationAction(ISD::FLOG, VT, Expand);
684  setOperationAction(ISD::FLOG2, VT, Expand);
685  setOperationAction(ISD::FLOG10, VT, Expand);
686  setOperationAction(ISD::FEXP, VT, Expand);
687  setOperationAction(ISD::FEXP2, VT, Expand);
688  }
689 
690  // First set operation action for all vector types to either promote
691  // (for widening) or expand (for scalarization). Then we will selectively
692  // turn on ones that can be effectively codegen'd.
693  for (MVT VT : MVT::vector_valuetypes()) {
694  setOperationAction(ISD::SDIV, VT, Expand);
695  setOperationAction(ISD::UDIV, VT, Expand);
696  setOperationAction(ISD::SREM, VT, Expand);
697  setOperationAction(ISD::UREM, VT, Expand);
702  setOperationAction(ISD::FMA, VT, Expand);
703  setOperationAction(ISD::FFLOOR, VT, Expand);
704  setOperationAction(ISD::FCEIL, VT, Expand);
705  setOperationAction(ISD::FTRUNC, VT, Expand);
706  setOperationAction(ISD::FRINT, VT, Expand);
707  setOperationAction(ISD::FNEARBYINT, VT, Expand);
708  setOperationAction(ISD::SMUL_LOHI, VT, Expand);
709  setOperationAction(ISD::MULHS, VT, Expand);
710  setOperationAction(ISD::UMUL_LOHI, VT, Expand);
711  setOperationAction(ISD::MULHU, VT, Expand);
712  setOperationAction(ISD::SDIVREM, VT, Expand);
713  setOperationAction(ISD::UDIVREM, VT, Expand);
714  setOperationAction(ISD::CTPOP, VT, Expand);
715  setOperationAction(ISD::CTTZ, VT, Expand);
716  setOperationAction(ISD::CTLZ, VT, Expand);
717  setOperationAction(ISD::ROTL, VT, Expand);
718  setOperationAction(ISD::ROTR, VT, Expand);
719  setOperationAction(ISD::BSWAP, VT, Expand);
720  setOperationAction(ISD::SETCC, VT, Expand);
721  setOperationAction(ISD::FP_TO_UINT, VT, Expand);
722  setOperationAction(ISD::FP_TO_SINT, VT, Expand);
723  setOperationAction(ISD::UINT_TO_FP, VT, Expand);
724  setOperationAction(ISD::SINT_TO_FP, VT, Expand);
726  setOperationAction(ISD::TRUNCATE, VT, Expand);
729  setOperationAction(ISD::ANY_EXTEND, VT, Expand);
730  setOperationAction(ISD::SELECT_CC, VT, Expand);
731  for (MVT InnerVT : MVT::vector_valuetypes()) {
732  setTruncStoreAction(InnerVT, VT, Expand);
733 
734  setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
735  setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
736 
737  // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
738  // types, we have to deal with them whether we ask for Expansion or not.
739  // Setting Expand causes its own optimisation problems though, so leave
740  // them legal.
741  if (VT.getVectorElementType() == MVT::i1)
742  setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
743 
744  // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
745  // split/scalarized right now.
746  if (VT.getVectorElementType() == MVT::f16)
747  setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
748  }
749  }
750 
751  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
752  // with -msoft-float, disable use of MMX as well.
753  if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
754  addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
755  // No operations on x86mmx supported, everything uses intrinsics.
756  }
757 
758  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
759  addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
760  : &X86::VR128RegClass);
761 
771  }
772 
773  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
774  addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
775  : &X86::VR128RegClass);
776 
777  // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
778  // registers cannot be used even for integer operations.
779  addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
780  : &X86::VR128RegClass);
781  addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
782  : &X86::VR128RegClass);
783  addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
784  : &X86::VR128RegClass);
785  addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
786  : &X86::VR128RegClass);
787 
792 
799 
813 
814  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
816  setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
817  setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
818  setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
819  }
820 
824 
825  // Provide custom widening for v2f32 setcc. This is really for VLX when
826  // setcc result type returns v2i1/v4i1 vector for v2f32/v4f32 leading to
827  // type legalization changing the result type to v4i1 during widening.
828  // It works fine for SSE2 and is probably faster so no need to qualify with
829  // VLX support.
831 
832  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
835 
836  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
837  // setcc all the way to isel and prefer SETGT in some isel patterns.
840  }
841 
842  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
848  }
849 
850  // We support custom legalizing of sext and anyext loads for specific
851  // memory vector types which we can load as a scalar (or sequence of
852  // scalars) and extend in-register to a legal 128-bit vector type. For sext
853  // loads these must work with a single scalar load.
854  for (MVT VT : MVT::integer_vector_valuetypes()) {
856  // We don't want narrow result types here when widening.
860  }
867  }
868 
870  !Subtarget.hasSSE41() && Subtarget.is64Bit()) {
871  // This lets DAG combine create sextloads that get split and scalarized.
872  // TODO: Does this make sense? What about v2i8->v2i64?
875  }
876 
877  for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
881 
882  if (VT == MVT::v2i64 && !Subtarget.is64Bit())
883  continue;
884 
887  }
888 
889  // Custom lower v2i64 and v2f64 selects.
895 
899 
900  // Custom legalize these to avoid over promotion or custom promotion.
911 
914 
916 
917  // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
919 
922 
923  for (MVT VT : MVT::fp_vector_valuetypes())
925 
926  // We want to legalize this to an f64 load rather than an i64 load on
927  // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
928  // store.
937 
941  if (!Subtarget.hasAVX512())
943 
947 
950 
957  }
958 
959  // In the customized shift lowering, the legal v4i32/v2i64 cases
960  // in AVX2 will be recognized.
961  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
965  }
966 
970  }
971 
972  if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
981  }
982 
983  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
984  for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
985  setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
986  setOperationAction(ISD::FCEIL, RoundedTy, Legal);
987  setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
988  setOperationAction(ISD::FRINT, RoundedTy, Legal);
990  }
991 
1000 
1001  // FIXME: Do we need to handle scalar-to-vector here?
1003 
1004  // We directly match byte blends in the backend as they match the VSELECT
1005  // condition form.
1007 
1008  // SSE41 brings specific instructions for doing vector sign extend even in
1009  // cases where we don't have SRA.
1010  for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1013  }
1014 
1016  // Avoid narrow result types when widening. The legal types are listed
1017  // in the next loop.
1018  for (MVT VT : MVT::integer_vector_valuetypes()) {
1022  }
1023  }
1024 
1025  // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1026  for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1035  }
1036 
1037  // i8 vectors are custom because the source register and source
1038  // source memory operand types are not the same width.
1040  }
1041 
1042  if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1043  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1046 
1047  // XOP can efficiently perform BITREVERSE with VPPERM.
1048  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1050 
1051  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1054  }
1055 
1056  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1057  bool HasInt256 = Subtarget.hasInt256();
1058 
1059  addRegisterClass(MVT::v32i8, Subtarget.hasVLX() ? &X86::VR256XRegClass
1060  : &X86::VR256RegClass);
1061  addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1062  : &X86::VR256RegClass);
1063  addRegisterClass(MVT::v8i32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1064  : &X86::VR256RegClass);
1065  addRegisterClass(MVT::v8f32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1066  : &X86::VR256RegClass);
1067  addRegisterClass(MVT::v4i64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1068  : &X86::VR256RegClass);
1069  addRegisterClass(MVT::v4f64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1070  : &X86::VR256RegClass);
1071 
1072  for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1081  }
1082 
1083  // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1084  // even though v8i16 is a legal type.
1088 
1091 
1092  if (!Subtarget.hasAVX512())
1094 
1095  for (MVT VT : MVT::fp_vector_valuetypes())
1097 
1098  // In the customized shift lowering, the legal v8i32/v4i64 cases
1099  // in AVX2 will be recognized.
1100  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1104  }
1105 
1107  // These types need custom splitting if their input is a 128-bit vector.
1112  }
1113 
1117 
1124 
1125  for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1129  }
1130 
1135 
1136  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1140 
1141  // TODO - remove this once 256-bit X86ISD::ANDNP correctly split.
1142  setOperationAction(ISD::CTTZ, VT, HasInt256 ? Expand : Custom);
1143 
1144  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1145  // setcc all the way to isel and prefer SETGT in some isel patterns.
1146  setCondCodeAction(ISD::SETLT, VT, Custom);
1147  setCondCodeAction(ISD::SETLE, VT, Custom);
1148  }
1149 
1150  if (Subtarget.hasAnyFMA()) {
1151  for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1154  }
1155 
1156  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1157  setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1158  setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1159  }
1160 
1163  setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1165 
1168  setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1169  setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1172 
1177 
1178  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1179  setOperationAction(ISD::ABS, VT, HasInt256 ? Legal : Custom);
1180  setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1181  setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1182  setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1183  setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1184  }
1185 
1186  for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1189  }
1190 
1191  if (HasInt256) {
1192  // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1193  // when we have a 256bit-wide blend with immediate.
1195 
1196  // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1197  for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1204  }
1205  }
1206 
1207  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1211  }
1212 
1213  // Extract subvector is special because the value type
1214  // (result) is 128-bit but the source is 256-bit wide.
1215  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1216  MVT::v4f32, MVT::v2f64 }) {
1218  }
1219 
1220  // Custom lower several nodes for 256-bit types.
1222  MVT::v8f32, MVT::v4f64 }) {
1225  setOperationAction(ISD::VSELECT, VT, Custom);
1231  }
1232 
1233  if (HasInt256)
1235 
1236  if (HasInt256) {
1237  // Custom legalize 2x32 to get a little better code.
1240 
1241  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1243  setOperationAction(ISD::MGATHER, VT, Custom);
1244  }
1245  }
1246 
1247  // This block controls legalization of the mask vector sizes that are
1248  // available with AVX512. 512-bit vectors are in a separate block controlled
1249  // by useAVX512Regs.
1250  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1251  addRegisterClass(MVT::v1i1, &X86::VK1RegClass);
1252  addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1253  addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1254  addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1255  addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1256 
1260 
1267 
1268  // There is no byte sized k-register load or store without AVX512DQ.
1269  if (!Subtarget.hasDQI()) {
1274 
1279  }
1280 
1281  // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1282  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1286  }
1287 
1288  for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1295 
1300  setOperationAction(ISD::VSELECT, VT, Expand);
1301  }
1302 
1310  for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1312  }
1313 
1314  // This block controls legalization for 512-bit operations with 32/64 bit
1315  // elements. 512-bits can be disabled based on prefer-vector-width and
1316  // required-vector-width function attributes.
1317  if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1318  addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1319  addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1320  addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1321  addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1322 
1323  for (MVT VT : MVT::fp_vector_valuetypes())
1325 
1326  for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1332  }
1333 
1334  for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1339  }
1340 
1351 
1357 
1358  if (!Subtarget.hasVLX()) {
1359  // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1360  // to 512-bit rather than use the AVX2 instructions so that we can use
1361  // k-masks.
1362  for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1366  }
1367  }
1368 
1377 
1379  // Need to custom widen this if we don't have AVX512BW.
1383  }
1384 
1385  for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1391  }
1392 
1393  // Without BWI we need to use custom lowering to handle MVT::v64i8 input.
1394  for (auto VT : {MVT::v16i32, MVT::v8i64, MVT::v64i8}) {
1397  }
1398 
1403 
1406 
1409 
1416 
1417  for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1430 
1431  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1432  // setcc all the way to isel and prefer SETGT in some isel patterns.
1435  }
1436 
1437  if (Subtarget.hasDQI()) {
1442 
1444  }
1445 
1446  if (Subtarget.hasCDI()) {
1447  // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1448  for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1450  }
1451  } // Subtarget.hasCDI()
1452 
1453  if (Subtarget.hasVPOPCNTDQ()) {
1454  for (auto VT : { MVT::v16i32, MVT::v8i64 })
1456  }
1457 
1458  // Extract subvector is special because the value type
1459  // (result) is 256-bit but the source is 512-bit wide.
1460  // 128-bit was made Legal under AVX1.
1461  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1464 
1465  for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1477  }
1478  // Need to custom split v32i16/v64i8 bitcasts.
1479  if (!Subtarget.hasBWI()) {
1482  }
1483  }// has AVX-512
1484 
1485  // This block controls legalization for operations that don't have
1486  // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
1487  // narrower widths.
1488  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1489  // These operations are handled on non-VLX by artificially widening in
1490  // isel patterns.
1491  // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1492 
1498 
1499  for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1505  }
1506 
1507  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1510  }
1511 
1512  // Custom legalize 2x32 to get a little better code.
1515 
1516  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1519 
1520  if (Subtarget.hasDQI()) {
1521  for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1526 
1528  }
1529  }
1530 
1531  if (Subtarget.hasCDI()) {
1532  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1534  }
1535  } // Subtarget.hasCDI()
1536 
1537  if (Subtarget.hasVPOPCNTDQ()) {
1538  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
1540  }
1541  }
1542 
1543  // This block control legalization of v32i1/v64i1 which are available with
1544  // AVX512BW. 512-bit v32i16 and v64i8 vector legalization is controlled with
1545  // useBWIRegs.
1546  if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1547  addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1548  addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1549 
1550  for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
1554  setOperationAction(ISD::VSELECT, VT, Expand);
1555 
1563  }
1564 
1569  for (auto VT : { MVT::v16i1, MVT::v32i1 })
1571 
1572  // Extends from v32i1 masks to 256-bit vectors.
1576  }
1577 
1578  // This block controls legalization for v32i16 and v64i8. 512-bits can be
1579  // disabled based on prefer-vector-width and required-vector-width function
1580  // attributes.
1581  if (!Subtarget.useSoftFloat() && Subtarget.useBWIRegs()) {
1582  addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1583  addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1584 
1585  // Extends from v64i1 masks to 512-bit vectors.
1589 
1613 
1616 
1618 
1619  for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1635 
1636  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1637  // setcc all the way to isel and prefer SETGT in some isel patterns.
1640  }
1641 
1642  for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1644  }
1645 
1646  if (Subtarget.hasBITALG()) {
1647  for (auto VT : { MVT::v64i8, MVT::v32i16 })
1649  }
1650  }
1651 
1652  if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1653  for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1654  setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1655  setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
1656  }
1657 
1658  // These operations are handled on non-VLX by artificially widening in
1659  // isel patterns.
1660  // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1661 
1662  if (Subtarget.hasBITALG()) {
1663  for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
1665  }
1666  }
1667 
1668  if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
1674 
1680 
1681  if (Subtarget.hasDQI()) {
1682  // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
1683  // v2f32 UINT_TO_FP is already custom under SSE2.
1686  "Unexpected operation action!");
1687  // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
1690  }
1691 
1692  if (Subtarget.hasBWI()) {
1695  }
1696  }
1697 
1698  // We want to custom lower some of our intrinsics.
1702  if (!Subtarget.is64Bit()) {
1705  }
1706 
1707  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1708  // handle type legalization for these operations here.
1709  //
1710  // FIXME: We really should do custom legalization for addition and
1711  // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1712  // than generic legalization for 64-bit multiplication-with-overflow, though.
1713  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1714  if (VT == MVT::i64 && !Subtarget.is64Bit())
1715  continue;
1716  // Add/Sub/Mul with overflow operations are custom lowered.
1723 
1724  // Support carry in as value rather than glue.
1728  }
1729 
1730  if (!Subtarget.is64Bit()) {
1731  // These libcalls are not available in 32-bit.
1732  setLibcallName(RTLIB::SHL_I128, nullptr);
1733  setLibcallName(RTLIB::SRL_I128, nullptr);
1734  setLibcallName(RTLIB::SRA_I128, nullptr);
1735  setLibcallName(RTLIB::MUL_I128, nullptr);
1736  }
1737 
1738  // Combine sin / cos into _sincos_stret if it is available.
1739  if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1740  getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1743  }
1744 
1745  if (Subtarget.isTargetWin64()) {
1752  }
1753 
1754  // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
1755  // is. We should promote the value to 64-bits to solve this.
1756  // This is what the CRT headers do - `fmodf` is an inline header
1757  // function casting to f64 and calling `fmod`.
1758  if (Subtarget.is32Bit() && (Subtarget.isTargetKnownWindowsMSVC() ||
1759  Subtarget.isTargetWindowsItanium()))
1760  for (ISD::NodeType Op :
1765 
1766  // We have target-specific dag combine patterns for the following nodes:
1806 
1808 
1809  MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1811  MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1813  MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1815 
1816  // TODO: These control memcmp expansion in CGP and could be raised higher, but
1817  // that needs to benchmarked and balanced with the potential use of vector
1818  // load/store types (PR33329, PR33914).
1819  MaxLoadsPerMemcmp = 2;
1821 
1822  // Set loop alignment to 2^ExperimentalPrefLoopAlignment bytes (default: 2^4).
1824 
1825  // An out-of-order CPU can speculatively execute past a predictable branch,
1826  // but a conditional move could be stalled by an expensive earlier operation.
1827  PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
1828  EnableExtLdPromotion = true;
1829  setPrefFunctionAlignment(4); // 2^4 bytes.
1830 
1832 }
1833 
1834 // This has so far only been implemented for 64-bit MachO.
1836  return Subtarget.isTargetMachO() && Subtarget.is64Bit();
1837 }
1838 
1840  // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
1841  return Subtarget.getTargetTriple().isOSMSVCRT();
1842 }
1843 
1845  const SDLoc &DL) const {
1846  EVT PtrTy = getPointerTy(DAG.getDataLayout());
1847  unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
1848  MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
1849  return SDValue(Node, 0);
1850 }
1851 
1854  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1855  return TypeSplitVector;
1856 
1858  VT.getVectorNumElements() != 1 &&
1859  VT.getVectorElementType() != MVT::i1)
1860  return TypeWidenVector;
1861 
1863 }
1864 
1866  CallingConv::ID CC,
1867  EVT VT) const {
1868  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1869  return MVT::v32i8;
1870  return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1871 }
1872 
1874  CallingConv::ID CC,
1875  EVT VT) const {
1876  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1877  return 1;
1878  return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1879 }
1880 
1883  EVT VT) const {
1884  if (!VT.isVector())
1885  return MVT::i8;
1886 
1887  if (Subtarget.hasAVX512()) {
1888  const unsigned NumElts = VT.getVectorNumElements();
1889 
1890  // Figure out what this type will be legalized to.
1891  EVT LegalVT = VT;
1892  while (getTypeAction(Context, LegalVT) != TypeLegal)
1893  LegalVT = getTypeToTransformTo(Context, LegalVT);
1894 
1895  // If we got a 512-bit vector then we'll definitely have a vXi1 compare.
1896  if (LegalVT.getSimpleVT().is512BitVector())
1897  return EVT::getVectorVT(Context, MVT::i1, NumElts);
1898 
1899  if (LegalVT.getSimpleVT().isVector() && Subtarget.hasVLX()) {
1900  // If we legalized to less than a 512-bit vector, then we will use a vXi1
1901  // compare for vXi32/vXi64 for sure. If we have BWI we will also support
1902  // vXi16/vXi8.
1903  MVT EltVT = LegalVT.getSimpleVT().getVectorElementType();
1904  if (Subtarget.hasBWI() || EltVT.getSizeInBits() >= 32)
1905  return EVT::getVectorVT(Context, MVT::i1, NumElts);
1906  }
1907  }
1908 
1910 }
1911 
1912 /// Helper for getByValTypeAlignment to determine
1913 /// the desired ByVal argument alignment.
1914 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1915  if (MaxAlign == 16)
1916  return;
1917  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1918  if (VTy->getBitWidth() == 128)
1919  MaxAlign = 16;
1920  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1921  unsigned EltAlign = 0;
1922  getMaxByValAlign(ATy->getElementType(), EltAlign);
1923  if (EltAlign > MaxAlign)
1924  MaxAlign = EltAlign;
1925  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1926  for (auto *EltTy : STy->elements()) {
1927  unsigned EltAlign = 0;
1928  getMaxByValAlign(EltTy, EltAlign);
1929  if (EltAlign > MaxAlign)
1930  MaxAlign = EltAlign;
1931  if (MaxAlign == 16)
1932  break;
1933  }
1934  }
1935 }
1936 
1937 /// Return the desired alignment for ByVal aggregate
1938 /// function arguments in the caller parameter area. For X86, aggregates
1939 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1940 /// are at 4-byte boundaries.
1942  const DataLayout &DL) const {
1943  if (Subtarget.is64Bit()) {
1944  // Max of 8 and alignment of type.
1945  unsigned TyAlign = DL.getABITypeAlignment(Ty);
1946  if (TyAlign > 8)
1947  return TyAlign;
1948  return 8;
1949  }
1950 
1951  unsigned Align = 4;
1952  if (Subtarget.hasSSE1())
1953  getMaxByValAlign(Ty, Align);
1954  return Align;
1955 }
1956 
1957 /// Returns the target specific optimal type for load
1958 /// and store operations as a result of memset, memcpy, and memmove
1959 /// lowering. If DstAlign is zero that means it's safe to destination
1960 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1961 /// means there isn't a need to check it against alignment requirement,
1962 /// probably because the source does not need to be loaded. If 'IsMemset' is
1963 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1964 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1965 /// source is constant so it does not need to be loaded.
1966 /// It returns EVT::Other if the type should be determined using generic
1967 /// target-independent logic.
1968 EVT
1970  unsigned DstAlign, unsigned SrcAlign,
1971  bool IsMemset, bool ZeroMemset,
1972  bool MemcpyStrSrc,
1973  MachineFunction &MF) const {
1974  const Function &F = MF.getFunction();
1975  if (!F.hasFnAttribute(Attribute::NoImplicitFloat)) {
1976  if (Size >= 16 &&
1977  (!Subtarget.isUnalignedMem16Slow() ||
1978  ((DstAlign == 0 || DstAlign >= 16) &&
1979  (SrcAlign == 0 || SrcAlign >= 16)))) {
1980  // FIXME: Check if unaligned 32-byte accesses are slow.
1981  if (Size >= 32 && Subtarget.hasAVX()) {
1982  // Although this isn't a well-supported type for AVX1, we'll let
1983  // legalization and shuffle lowering produce the optimal codegen. If we
1984  // choose an optimal type with a vector element larger than a byte,
1985  // getMemsetStores() may create an intermediate splat (using an integer
1986  // multiply) before we splat as a vector.
1987  return MVT::v32i8;
1988  }
1989  if (Subtarget.hasSSE2())
1990  return MVT::v16i8;
1991  // TODO: Can SSE1 handle a byte vector?
1992  // If we have SSE1 registers we should be able to use them.
1993  if (Subtarget.hasSSE1() && (Subtarget.is64Bit() || Subtarget.hasX87()))
1994  return MVT::v4f32;
1995  } else if ((!IsMemset || ZeroMemset) && !MemcpyStrSrc && Size >= 8 &&
1996  !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
1997  // Do not use f64 to lower memcpy if source is string constant. It's
1998  // better to use i32 to avoid the loads.
1999  // Also, do not use f64 to lower memset unless this is a memset of zeros.
2000  // The gymnastics of splatting a byte value into an XMM register and then
2001  // only using 8-byte stores (because this is a CPU with slow unaligned
2002  // 16-byte accesses) makes that a loser.
2003  return MVT::f64;
2004  }
2005  }
2006  // This is a compromise. If we reach here, unaligned accesses may be slow on
2007  // this target. However, creating smaller, aligned accesses could be even
2008  // slower and would certainly be a lot more code.
2009  if (Subtarget.is64Bit() && Size >= 8)
2010  return MVT::i64;
2011  return MVT::i32;
2012 }
2013 
2015  if (VT == MVT::f32)
2016  return X86ScalarSSEf32;
2017  else if (VT == MVT::f64)
2018  return X86ScalarSSEf64;
2019  return true;
2020 }
2021 
2022 bool
2024  unsigned,
2025  unsigned,
2026  bool *Fast) const {
2027  if (Fast) {
2028  switch (VT.getSizeInBits()) {
2029  default:
2030  // 8-byte and under are always assumed to be fast.
2031  *Fast = true;
2032  break;
2033  case 128:
2034  *Fast = !Subtarget.isUnalignedMem16Slow();
2035  break;
2036  case 256:
2037  *Fast = !Subtarget.isUnalignedMem32Slow();
2038  break;
2039  // TODO: What about AVX-512 (512-bit) accesses?
2040  }
2041  }
2042  // Misaligned accesses of any size are always allowed.
2043  return true;
2044 }
2045 
2046 /// Return the entry encoding for a jump table in the
2047 /// current function. The returned value is a member of the
2048 /// MachineJumpTableInfo::JTEntryKind enum.
2050  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2051  // symbol.
2052  if (isPositionIndependent() && Subtarget.isPICStyleGOT())
2054 
2055  // Otherwise, use the normal jump table encoding heuristics.
2057 }
2058 
2060  return Subtarget.useSoftFloat();
2061 }
2062 
2064  ArgListTy &Args) const {
2065 
2066  // Only relabel X86-32 for C / Stdcall CCs.
2067  if (Subtarget.is64Bit())
2068  return;
2069  if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
2070  return;
2071  unsigned ParamRegs = 0;
2072  if (auto *M = MF->getFunction().getParent())
2073  ParamRegs = M->getNumberRegisterParameters();
2074 
2075  // Mark the first N int arguments as having reg
2076  for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
2077  Type *T = Args[Idx].Ty;
2078  if (T->isIntOrPtrTy())
2079  if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
2080  unsigned numRegs = 1;
2081  if (MF->getDataLayout().getTypeAllocSize(T) > 4)
2082  numRegs = 2;
2083  if (ParamRegs < numRegs)
2084  return;
2085  ParamRegs -= numRegs;
2086  Args[Idx].IsInReg = true;
2087  }
2088  }
2089 }
2090 
2091 const MCExpr *
2093  const MachineBasicBlock *MBB,
2094  unsigned uid,MCContext &Ctx) const{
2095  assert(isPositionIndependent() && Subtarget.isPICStyleGOT());
2096  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2097  // entries.
2098  return MCSymbolRefExpr::create(MBB->getSymbol(),
2100 }
2101 
2102 /// Returns relocation base for the given PIC jumptable.
2104  SelectionDAG &DAG) const {
2105  if (!Subtarget.is64Bit())
2106  // This doesn't have SDLoc associated with it, but is not really the
2107  // same as a Register.
2108  return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2109  getPointerTy(DAG.getDataLayout()));
2110  return Table;
2111 }
2112 
2113 /// This returns the relocation base for the given PIC jumptable,
2114 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2117  MCContext &Ctx) const {
2118  // X86-64 uses RIP relative addressing based on the jump table label.
2119  if (Subtarget.isPICStyleRIPRel())
2120  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2121 
2122  // Otherwise, the reference is relative to the PIC base.
2123  return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2124 }
2125 
2126 std::pair<const TargetRegisterClass *, uint8_t>
2128  MVT VT) const {
2129  const TargetRegisterClass *RRC = nullptr;
2130  uint8_t Cost = 1;
2131  switch (VT.SimpleTy) {
2132  default:
2134  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2135  RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2136  break;
2137  case MVT::x86mmx:
2138  RRC = &X86::VR64RegClass;
2139  break;
2140  case MVT::f32: case MVT::f64:
2141  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2142  case MVT::v4f32: case MVT::v2f64:
2143  case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
2144  case MVT::v8f32: case MVT::v4f64:
2145  case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
2146  case MVT::v16f32: case MVT::v8f64:
2147  RRC = &X86::VR128XRegClass;
2148  break;
2149  }
2150  return std::make_pair(RRC, Cost);
2151 }
2152 
2153 unsigned X86TargetLowering::getAddressSpace() const {
2154  if (Subtarget.is64Bit())
2155  return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
2156  return 256;
2157 }
2158 
2159 static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2160  return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2161  (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2162 }
2163 
2165  unsigned Offset, unsigned AddressSpace) {
2168  Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2169 }
2170 
2172  // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2173  // tcbhead_t; use it instead of the usual global variable (see
2174  // sysdeps/{i386,x86_64}/nptl/tls.h)
2175  if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2176  if (Subtarget.isTargetFuchsia()) {
2177  // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2178  return SegmentOffset(IRB, 0x10, getAddressSpace());
2179  } else {
2180  // %fs:0x28, unless we're using a Kernel code model, in which case
2181  // it's %gs:0x28. gs:0x14 on i386.
2182  unsigned Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2183  return SegmentOffset(IRB, Offset, getAddressSpace());
2184  }
2185  }
2186 
2187  return TargetLowering::getIRStackGuard(IRB);
2188 }
2189 
2191  // MSVC CRT provides functionalities for stack protection.
2192  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2194  // MSVC CRT has a global variable holding security cookie.
2195  M.getOrInsertGlobal("__security_cookie",
2197 
2198  // MSVC CRT has a function to validate security cookie.
2199  auto *SecurityCheckCookie = cast<Function>(
2200  M.getOrInsertFunction("__security_check_cookie",
2203  SecurityCheckCookie->setCallingConv(CallingConv::X86_FastCall);
2204  SecurityCheckCookie->addAttribute(1, Attribute::AttrKind::InReg);
2205  return;
2206  }
2207  // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2208  if (hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2209  return;
2211 }
2212 
2214  // MSVC CRT has a global variable holding security cookie.
2215  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2217  return M.getGlobalVariable("__security_cookie");
2218  }
2220 }
2221 
2223  // MSVC CRT has a function to validate security cookie.
2224  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2226  return M.getFunction("__security_check_cookie");
2227  }
2229 }
2230 
2232  if (Subtarget.getTargetTriple().isOSContiki())
2233  return getDefaultSafeStackPointerLocation(IRB, false);
2234 
2235  // Android provides a fixed TLS slot for the SafeStack pointer. See the
2236  // definition of TLS_SLOT_SAFESTACK in
2237  // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2238  if (Subtarget.isTargetAndroid()) {
2239  // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2240  // %gs:0x24 on i386
2241  unsigned Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2242  return SegmentOffset(IRB, Offset, getAddressSpace());
2243  }
2244 
2245  // Fuchsia is similar.
2246  if (Subtarget.isTargetFuchsia()) {
2247  // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
2248  return SegmentOffset(IRB, 0x18, getAddressSpace());
2249  }
2250 
2252 }
2253 
2255  unsigned DestAS) const {
2256  assert(SrcAS != DestAS && "Expected different address spaces!");
2257 
2258  return SrcAS < 256 && DestAS < 256;
2259 }
2260 
2261 //===----------------------------------------------------------------------===//
2262 // Return Value Calling Convention Implementation
2263 //===----------------------------------------------------------------------===//
2264 
2265 #include "X86GenCallingConv.inc"
2266 
2267 bool X86TargetLowering::CanLowerReturn(
2268  CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2269  const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2271  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2272  return CCInfo.CheckReturn(Outs, RetCC_X86);
2273 }
2274 
2275 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2276  static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2277  return ScratchRegs;
2278 }
2279 
2280 /// Lowers masks values (v*i1) to the local register values
2281 /// \returns DAG node after lowering to register type
2282 static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
2283  const SDLoc &Dl, SelectionDAG &DAG) {
2284  EVT ValVT = ValArg.getValueType();
2285 
2286  if (ValVT == MVT::v1i1)
2287  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Dl, ValLoc, ValArg,
2288  DAG.getIntPtrConstant(0, Dl));
2289 
2290  if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
2291  (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
2292  // Two stage lowering might be required
2293  // bitcast: v8i1 -> i8 / v16i1 -> i16
2294  // anyextend: i8 -> i32 / i16 -> i32
2295  EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
2296  SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
2297  if (ValLoc == MVT::i32)
2298  ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
2299  return ValToCopy;
2300  }
2301 
2302  if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
2303  (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
2304  // One stage lowering is required
2305  // bitcast: v32i1 -> i32 / v64i1 -> i64
2306  return DAG.getBitcast(ValLoc, ValArg);
2307  }
2308 
2309  return DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValArg);
2310 }
2311 
2312 /// Breaks v64i1 value into two registers and adds the new node to the DAG
2314  const SDLoc &Dl, SelectionDAG &DAG, SDValue Chain, SDValue &Arg,
2315  SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, CCValAssign &VA,
2316  CCValAssign &NextVA, const X86Subtarget &Subtarget) {
2317  assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
2318  assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2319  assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value");
2320  assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2321  "The value should reside in two registers");
2322 
2323  // Before splitting the value we cast it to i64
2324  Arg = DAG.getBitcast(MVT::i64, Arg);
2325 
2326  // Splitting the value into two i32 types
2327  SDValue Lo, Hi;
2328  Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2329  DAG.getConstant(0, Dl, MVT::i32));
2330  Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2331  DAG.getConstant(1, Dl, MVT::i32));
2332 
2333  // Attach the two i32 types into corresponding registers
2334  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
2335  RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
2336 }
2337 
2338 SDValue
2339 X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2340  bool isVarArg,
2341  const SmallVectorImpl<ISD::OutputArg> &Outs,
2342  const SmallVectorImpl<SDValue> &OutVals,
2343  const SDLoc &dl, SelectionDAG &DAG) const {
2344  MachineFunction &MF = DAG.getMachineFunction();
2346 
2347  // In some cases we need to disable registers from the default CSR list.
2348  // For example, when they are used for argument passing.
2349  bool ShouldDisableCalleeSavedRegister =
2350  CallConv == CallingConv::X86_RegCall ||
2351  MF.getFunction().hasFnAttribute("no_caller_saved_registers");
2352 
2353  if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2354  report_fatal_error("X86 interrupts may not return any value");
2355 
2357  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2358  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2359 
2360  SDValue Flag;
2361  SmallVector<SDValue, 6> RetOps;
2362  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2363  // Operand #1 = Bytes To Pop
2364  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2365  MVT::i32));
2366 
2367  // Copy the result values into the output registers.
2368  for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
2369  ++I, ++OutsIndex) {
2370  CCValAssign &VA = RVLocs[I];
2371  assert(VA.isRegLoc() && "Can only return in registers!");
2372 
2373  // Add the register to the CalleeSaveDisableRegs list.
2374  if (ShouldDisableCalleeSavedRegister)
2376 
2377  SDValue ValToCopy = OutVals[OutsIndex];
2378  EVT ValVT = ValToCopy.getValueType();
2379 
2380  // Promote values to the appropriate types.
2381  if (VA.getLocInfo() == CCValAssign::SExt)
2382  ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2383  else if (VA.getLocInfo() == CCValAssign::ZExt)
2384  ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2385  else if (VA.getLocInfo() == CCValAssign::AExt) {
2386  if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2387  ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
2388  else
2389  ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2390  }
2391  else if (VA.getLocInfo() == CCValAssign::BCvt)
2392  ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2393 
2395  "Unexpected FP-extend for return value.");
2396 
2397  // If this is x86-64, and we disabled SSE, we can't return FP values,
2398  // or SSE or MMX vectors.
2399  if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2400  VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2401  (Subtarget.is64Bit() && !Subtarget.hasSSE1())) {
2402  errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2403  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2404  } else if (ValVT == MVT::f64 &&
2405  (Subtarget.is64Bit() && !Subtarget.hasSSE2())) {
2406  // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2407  // llvm-gcc has never done it right and no one has noticed, so this
2408  // should be OK for now.
2409  errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2410  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2411  }
2412 
2413  // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2414  // the RET instruction and handled by the FP Stackifier.
2415  if (VA.getLocReg() == X86::FP0 ||
2416  VA.getLocReg() == X86::FP1) {
2417  // If this is a copy from an xmm register to ST(0), use an FPExtend to
2418  // change the value to the FP stack register class.
2419  if (isScalarFPTypeInSSEReg(VA.getValVT()))
2420  ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2421  RetOps.push_back(ValToCopy);
2422  // Don't emit a copytoreg.
2423  continue;
2424  }
2425 
2426  // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2427  // which is returned in RAX / RDX.
2428  if (Subtarget.is64Bit()) {
2429  if (ValVT == MVT::x86mmx) {
2430  if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2431  ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2432  ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2433  ValToCopy);
2434  // If we don't have SSE2 available, convert to v4f32 so the generated
2435  // register is legal.
2436  if (!Subtarget.hasSSE2())
2437  ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2438  }
2439  }
2440  }
2441 
2443 
2444  if (VA.needsCustom()) {
2445  assert(VA.getValVT() == MVT::v64i1 &&
2446  "Currently the only custom case is when we split v64i1 to 2 regs");
2447 
2448  Passv64i1ArgInRegs(dl, DAG, Chain, ValToCopy, RegsToPass, VA, RVLocs[++I],
2449  Subtarget);
2450 
2451  assert(2 == RegsToPass.size() &&
2452  "Expecting two registers after Pass64BitArgInRegs");
2453 
2454  // Add the second register to the CalleeSaveDisableRegs list.
2455  if (ShouldDisableCalleeSavedRegister)
2456  MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
2457  } else {
2458  RegsToPass.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2459  }
2460 
2461  // Add nodes to the DAG and add the values into the RetOps list
2462  for (auto &Reg : RegsToPass) {
2463  Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, Flag);
2464  Flag = Chain.getValue(1);
2465  RetOps.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
2466  }
2467  }
2468 
2469  // Swift calling convention does not require we copy the sret argument
2470  // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
2471 
2472  // All x86 ABIs require that for returning structs by value we copy
2473  // the sret argument into %rax/%eax (depending on ABI) for the return.
2474  // We saved the argument into a virtual register in the entry block,
2475  // so now we copy the value out and into %rax/%eax.
2476  //
2477  // Checking Function.hasStructRetAttr() here is insufficient because the IR
2478  // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2479  // false, then an sret argument may be implicitly inserted in the SelDAG. In
2480  // either case FuncInfo->setSRetReturnReg() will have been called.
2481  if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2482  // When we have both sret and another return value, we should use the
2483  // original Chain stored in RetOps[0], instead of the current Chain updated
2484  // in the above loop. If we only have sret, RetOps[0] equals to Chain.
2485 
2486  // For the case of sret and another return value, we have
2487  // Chain_0 at the function entry
2488  // Chain_1 = getCopyToReg(Chain_0) in the above loop
2489  // If we use Chain_1 in getCopyFromReg, we will have
2490  // Val = getCopyFromReg(Chain_1)
2491  // Chain_2 = getCopyToReg(Chain_1, Val) from below
2492 
2493  // getCopyToReg(Chain_0) will be glued together with
2494  // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
2495  // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
2496  // Data dependency from Unit B to Unit A due to usage of Val in
2497  // getCopyToReg(Chain_1, Val)
2498  // Chain dependency from Unit A to Unit B
2499 
2500  // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
2501  SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
2502  getPointerTy(MF.getDataLayout()));
2503 
2504  unsigned RetValReg
2505  = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
2506  X86::RAX : X86::EAX;
2507  Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2508  Flag = Chain.getValue(1);
2509 
2510  // RAX/EAX now acts like a return value.
2511  RetOps.push_back(
2512  DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2513 
2514  // Add the returned register to the CalleeSaveDisableRegs list.
2515  if (ShouldDisableCalleeSavedRegister)
2516  MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
2517  }
2518 
2519  const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
2520  const MCPhysReg *I =
2522  if (I) {
2523  for (; *I; ++I) {
2524  if (X86::GR64RegClass.contains(*I))
2525  RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2526  else
2527  llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2528  }
2529  }
2530 
2531  RetOps[0] = Chain; // Update chain.
2532 
2533  // Add the flag if we have it.
2534  if (Flag.getNode())
2535  RetOps.push_back(Flag);
2536 
2538  if (CallConv == CallingConv::X86_INTR)
2539  opcode = X86ISD::IRET;
2540  return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2541 }
2542 
2543 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2544  if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
2545  return false;
2546 
2547  SDValue TCChain = Chain;
2548  SDNode *Copy = *N->use_begin();
2549  if (Copy->getOpcode() == ISD::CopyToReg) {
2550  // If the copy has a glue operand, we conservatively assume it isn't safe to
2551  // perform a tail call.
2552  if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2553  return false;
2554  TCChain = Copy->getOperand(0);
2555  } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2556  return false;
2557 
2558  bool HasRet = false;
2559  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2560  UI != UE; ++UI) {
2561  if (UI->getOpcode() != X86ISD::RET_FLAG)
2562  return false;
2563  // If we are returning more than one value, we can definitely
2564  // not make a tail call see PR19530
2565  if (UI->getNumOperands() > 4)
2566  return false;
2567  if (UI->getNumOperands() == 4 &&
2568  UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2569  return false;
2570  HasRet = true;
2571  }
2572 
2573  if (!HasRet)
2574  return false;
2575 
2576  Chain = TCChain;
2577  return true;
2578 }
2579 
2580 EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
2581  ISD::NodeType ExtendKind) const {
2582  MVT ReturnMVT = MVT::i32;
2583 
2584  bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
2585  if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
2586  // The ABI does not require i1, i8 or i16 to be extended.
2587  //
2588  // On Darwin, there is code in the wild relying on Clang's old behaviour of
2589  // always extending i8/i16 return values, so keep doing that for now.
2590  // (PR26665).
2591  ReturnMVT = MVT::i8;
2592  }
2593 
2594  EVT MinVT = getRegisterType(Context, ReturnMVT);
2595  return VT.bitsLT(MinVT) ? MinVT : VT;
2596 }
2597 
2598 /// Reads two 32 bit registers and creates a 64 bit mask value.
2599 /// \param VA The current 32 bit value that need to be assigned.
2600 /// \param NextVA The next 32 bit value that need to be assigned.
2601 /// \param Root The parent DAG node.
2602 /// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
2603 /// glue purposes. In the case the DAG is already using
2604 /// physical register instead of virtual, we should glue
2605 /// our new SDValue to InFlag SDvalue.
2606 /// \return a new SDvalue of size 64bit.
2608  SDValue &Root, SelectionDAG &DAG,
2609  const SDLoc &Dl, const X86Subtarget &Subtarget,
2610  SDValue *InFlag = nullptr) {
2611  assert((Subtarget.hasBWI()) && "Expected AVX512BW target!");
2612  assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2613  assert(VA.getValVT() == MVT::v64i1 &&
2614  "Expecting first location of 64 bit width type");
2615  assert(NextVA.getValVT() == VA.getValVT() &&
2616  "The locations should have the same type");
2617  assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2618  "The values should reside in two registers");
2619 
2620  SDValue Lo, Hi;
2621  unsigned Reg;
2622  SDValue ArgValueLo, ArgValueHi;
2623 
2624  MachineFunction &MF = DAG.getMachineFunction();
2625  const TargetRegisterClass *RC = &X86::GR32RegClass;
2626 
2627  // Read a 32 bit value from the registers.
2628  if (nullptr == InFlag) {
2629  // When no physical register is present,
2630  // create an intermediate virtual register.
2631  Reg = MF.addLiveIn(VA.getLocReg(), RC);
2632  ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2633  Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2634  ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2635  } else {
2636  // When a physical register is available read the value from it and glue
2637  // the reads together.
2638  ArgValueLo =
2639  DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
2640  *InFlag = ArgValueLo.getValue(2);
2641  ArgValueHi =
2642  DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
2643  *InFlag = ArgValueHi.getValue(2);
2644  }
2645 
2646  // Convert the i32 type into v32i1 type.
2647  Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
2648 
2649  // Convert the i32 type into v32i1 type.
2650  Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
2651 
2652  // Concatenate the two values together.
2653  return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
2654 }
2655 
2656 /// The function will lower a register of various sizes (8/16/32/64)
2657 /// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
2658 /// \returns a DAG node contains the operand after lowering to mask type.
2659 static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
2660  const EVT &ValLoc, const SDLoc &Dl,
2661  SelectionDAG &DAG) {
2662  SDValue ValReturned = ValArg;
2663 
2664  if (ValVT == MVT::v1i1)
2665  return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
2666 
2667  if (ValVT == MVT::v64i1) {
2668  // In 32 bit machine, this case is handled by getv64i1Argument
2669  assert(ValLoc == MVT::i64 && "Expecting only i64 locations");
2670  // In 64 bit machine, There is no need to truncate the value only bitcast
2671  } else {
2672  MVT maskLen;
2673  switch (ValVT.getSimpleVT().SimpleTy) {
2674  case MVT::v8i1:
2675  maskLen = MVT::i8;
2676  break;
2677  case MVT::v16i1:
2678  maskLen = MVT::i16;
2679  break;
2680  case MVT::v32i1:
2681  maskLen = MVT::i32;
2682  break;
2683  default:
2684  llvm_unreachable("Expecting a vector of i1 types");
2685  }
2686 
2687  ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
2688  }
2689  return DAG.getBitcast(ValVT, ValReturned);
2690 }
2691 
2692 /// Lower the result values of a call into the
2693 /// appropriate copies out of appropriate physical registers.
2694 ///
2695 SDValue X86TargetLowering::LowerCallResult(
2696  SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2697  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2698  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
2699  uint32_t *RegMask) const {
2700 
2701  const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2702  // Assign locations to each value returned by this call.
2704  bool Is64Bit = Subtarget.is64Bit();
2705  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2706  *DAG.getContext());
2707  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2708 
2709  // Copy all of the result registers out of their specified physreg.
2710  for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
2711  ++I, ++InsIndex) {
2712  CCValAssign &VA = RVLocs[I];
2713  EVT CopyVT = VA.getLocVT();
2714 
2715  // In some calling conventions we need to remove the used registers
2716  // from the register mask.
2717  if (RegMask) {
2718  for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
2719  SubRegs.isValid(); ++SubRegs)
2720  RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
2721  }
2722 
2723  // If this is x86-64, and we disabled SSE, we can't return FP values
2724  if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2725  ((Is64Bit || Ins[InsIndex].Flags.isInReg()) && !Subtarget.hasSSE1())) {
2726  errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2727  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2728  }
2729 
2730  // If we prefer to use the value in xmm registers, copy it out as f80 and
2731  // use a truncate to move it from fp stack reg to xmm reg.
2732  bool RoundAfterCopy = false;
2733  if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2735  if (!Subtarget.hasX87())
2736  report_fatal_error("X87 register return with X87 disabled");
2737  CopyVT = MVT::f80;
2738  RoundAfterCopy = (CopyVT != VA.getLocVT());
2739  }
2740 
2741  SDValue Val;
2742  if (VA.needsCustom()) {
2743  assert(VA.getValVT() == MVT::v64i1 &&
2744  "Currently the only custom case is when we split v64i1 to 2 regs");
2745  Val =
2746  getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
2747  } else {
2748  Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
2749  .getValue(1);
2750  Val = Chain.getValue(0);
2751  InFlag = Chain.getValue(2);
2752  }
2753 
2754  if (RoundAfterCopy)
2755  Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2756  // This truncation won't change the value.
2757  DAG.getIntPtrConstant(1, dl));
2758 
2759  if (VA.isExtInLoc() && (VA.getValVT().getScalarType() == MVT::i1)) {
2760  if (VA.getValVT().isVector() &&
2761  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
2762  (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
2763  // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
2764  Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
2765  } else
2766  Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2767  }
2768 
2769  InVals.push_back(Val);
2770  }
2771 
2772  return Chain;
2773 }
2774 
2775 //===----------------------------------------------------------------------===//
2776 // C & StdCall & Fast Calling Convention implementation
2777 //===----------------------------------------------------------------------===//
2778 // StdCall calling convention seems to be standard for many Windows' API
2779 // routines and around. It differs from C calling convention just a little:
2780 // callee should clean up the stack, not caller. Symbols should be also
2781 // decorated in some fancy way :) It doesn't support any vector arguments.
2782 // For info on fast calling convention see Fast Calling Convention (tail call)
2783 // implementation LowerX86_32FastCCCallTo.
2784 
2785 /// CallIsStructReturn - Determines whether a call uses struct return
2786 /// semantics.
2791 };
2792 static StructReturnType
2794  if (Outs.empty())
2795  return NotStructReturn;
2796 
2797  const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2798  if (!Flags.isSRet())
2799  return NotStructReturn;
2800  if (Flags.isInReg() || IsMCU)
2801  return RegStructReturn;
2802  return StackStructReturn;
2803 }
2804 
2805 /// Determines whether a function uses struct return semantics.
2806 static StructReturnType
2808  if (Ins.empty())
2809  return NotStructReturn;
2810 
2811  const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2812  if (!Flags.isSRet())
2813  return NotStructReturn;
2814  if (Flags.isInReg() || IsMCU)
2815  return RegStructReturn;
2816  return StackStructReturn;
2817 }
2818 
2819 /// Make a copy of an aggregate at address specified by "Src" to address
2820 /// "Dst" with size and alignment information specified by the specific
2821 /// parameter attribute. The copy will be passed as a byval function parameter.
2823  SDValue Chain, ISD::ArgFlagsTy Flags,
2824  SelectionDAG &DAG, const SDLoc &dl) {
2825  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2826 
2827  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2828  /*isVolatile*/false, /*AlwaysInline=*/true,
2829  /*isTailCall*/false,
2831 }
2832 
2833 /// Return true if the calling convention is one that we can guarantee TCO for.
2835  return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2837  CC == CallingConv::HHVM);
2838 }
2839 
2840 /// Return true if we might ever do TCO for calls with this calling convention.
2842  switch (CC) {
2843  // C calling conventions:
2844  case CallingConv::C:
2845  case CallingConv::Win64:
2847  // Callee pop conventions:
2852  return true;
2853  default:
2854  return canGuaranteeTCO(CC);
2855  }
2856 }
2857 
2858 /// Return true if the function is being made into a tailcall target by
2859 /// changing its ABI.
2860 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2861  return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2862 }
2863 
2864 bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2865  auto Attr =
2866  CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2867  if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2868  return false;
2869 
2870  ImmutableCallSite CS(CI);
2871  CallingConv::ID CalleeCC = CS.getCallingConv();
2872  if (!mayTailCallThisCC(CalleeCC))
2873  return false;
2874 
2875  return true;
2876 }
2877 
2878 SDValue
2879 X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
2880  const SmallVectorImpl<ISD::InputArg> &Ins,
2881  const SDLoc &dl, SelectionDAG &DAG,
2882  const CCValAssign &VA,
2883  MachineFrameInfo &MFI, unsigned i) const {
2884  // Create the nodes corresponding to a load from this parameter slot.
2885  ISD::ArgFlagsTy Flags = Ins[i].Flags;
2886  bool AlwaysUseMutable = shouldGuaranteeTCO(
2887  CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2888  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2889  EVT ValVT;
2890  MVT PtrVT = getPointerTy(DAG.getDataLayout());
2891 
2892  // If value is passed by pointer we have address passed instead of the value
2893  // itself. No need to extend if the mask value and location share the same
2894  // absolute size.
2895  bool ExtendedInMem =
2896  VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
2897  VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
2898 
2899  if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2900  ValVT = VA.getLocVT();
2901  else
2902  ValVT = VA.getValVT();
2903 
2904  // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2905  // taken by a return address.
2906  int Offset = 0;
2907  if (CallConv == CallingConv::X86_INTR) {
2908  // X86 interrupts may take one or two arguments.
2909  // On the stack there will be no return address as in regular call.
2910  // Offset of last argument need to be set to -4/-8 bytes.
2911  // Where offset of the first argument out of two, should be set to 0 bytes.
2912  Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2913  if (Subtarget.is64Bit() && Ins.size() == 2) {
2914  // The stack pointer needs to be realigned for 64 bit handlers with error
2915  // code, so the argument offset changes by 8 bytes.
2916  Offset += 8;
2917  }
2918  }
2919 
2920  // FIXME: For now, all byval parameter objects are marked mutable. This can be
2921  // changed with more analysis.
2922  // In case of tail call optimization mark all arguments mutable. Since they
2923  // could be overwritten by lowering of arguments in case of a tail call.
2924  if (Flags.isByVal()) {
2925  unsigned Bytes = Flags.getByValSize();
2926  if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2927 
2928  // FIXME: For now, all byval parameter objects are marked as aliasing. This
2929  // can be improved with deeper analysis.
2930  int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable,
2931  /*isAliased=*/true);
2932  // Adjust SP offset of interrupt parameter.
2933  if (CallConv == CallingConv::X86_INTR) {
2934  MFI.setObjectOffset(FI, Offset);
2935  }
2936  return DAG.getFrameIndex(FI, PtrVT);
2937  }
2938 
2939  // This is an argument in memory. We might be able to perform copy elision.
2940  if (Flags.isCopyElisionCandidate()) {
2941  EVT ArgVT = Ins[i].ArgVT;
2942  SDValue PartAddr;
2943  if (Ins[i].PartOffset == 0) {
2944  // If this is a one-part value or the first part of a multi-part value,
2945  // create a stack object for the entire argument value type and return a
2946  // load from our portion of it. This assumes that if the first part of an
2947  // argument is in memory, the rest will also be in memory.
2948  int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
2949  /*Immutable=*/false);
2950  PartAddr = DAG.getFrameIndex(FI, PtrVT);
2951  return DAG.getLoad(
2952  ValVT, dl, Chain, PartAddr,
2954  } else {
2955  // This is not the first piece of an argument in memory. See if there is
2956  // already a fixed stack object including this offset. If so, assume it
2957  // was created by the PartOffset == 0 branch above and create a load from
2958  // the appropriate offset into it.
2959  int64_t PartBegin = VA.getLocMemOffset();
2960  int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
2961  int FI = MFI.getObjectIndexBegin();
2962  for (; MFI.isFixedObjectIndex(FI); ++FI) {
2963  int64_t ObjBegin = MFI.getObjectOffset(FI);
2964  int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
2965  if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
2966  break;
2967  }
2968  if (MFI.isFixedObjectIndex(FI)) {
2969  SDValue Addr =
2970  DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
2971  DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
2972  return DAG.getLoad(
2973  ValVT, dl, Chain, Addr,
2975  Ins[i].PartOffset));
2976  }
2977  }
2978  }
2979 
2980  int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
2981  VA.getLocMemOffset(), isImmutable);
2982 
2983  // Set SExt or ZExt flag.
2984  if (VA.getLocInfo() == CCValAssign::ZExt) {
2985  MFI.setObjectZExt(FI, true);
2986  } else if (VA.getLocInfo() == CCValAssign::SExt) {
2987  MFI.setObjectSExt(FI, true);
2988  }
2989 
2990  // Adjust SP offset of interrupt parameter.
2991  if (CallConv == CallingConv::X86_INTR) {
2992  MFI.setObjectOffset(FI, Offset);
2993  }
2994 
2995  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2996  SDValue Val = DAG.getLoad(
2997  ValVT, dl, Chain, FIN,
2999  return ExtendedInMem
3000  ? (VA.getValVT().isVector()
3001  ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
3002  : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
3003  : Val;
3004 }
3005 
3006 // FIXME: Get this from tablegen.
3008  const X86Subtarget &Subtarget) {
3009  assert(Subtarget.is64Bit());
3010 
3011  if (Subtarget.isCallingConvWin64(CallConv)) {
3012  static const MCPhysReg GPR64ArgRegsWin64[] = {
3013  X86::RCX, X86::RDX, X86::R8, X86::R9
3014  };
3015  return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
3016  }
3017 
3018  static const MCPhysReg GPR64ArgRegs64Bit[] = {
3019  X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
3020  };
3021  return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
3022 }
3023 
3024 // FIXME: Get this from tablegen.
3026  CallingConv::ID CallConv,
3027  const X86Subtarget &Subtarget) {
3028  assert(Subtarget.is64Bit());
3029  if (Subtarget.isCallingConvWin64(CallConv)) {
3030  // The XMM registers which might contain var arg parameters are shadowed
3031  // in their paired GPR. So we only need to save the GPR to their home
3032  // slots.
3033  // TODO: __vectorcall will change this.
3034  return None;
3035  }
3036 
3037  const Function &F = MF.getFunction();
3038  bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
3039  bool isSoftFloat = Subtarget.useSoftFloat();
3040  assert(!(isSoftFloat && NoImplicitFloatOps) &&
3041  "SSE register cannot be used when SSE is disabled!");
3042  if (isSoftFloat || NoImplicitFloatOps || !Subtarget.hasSSE1())
3043  // Kernel mode asks for SSE to be disabled, so there are no XMM argument
3044  // registers.
3045  return None;
3046 
3047  static const MCPhysReg XMMArgRegs64Bit[] = {
3048  X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3049  X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3050  };
3051  return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
3052 }
3053 
3054 #ifndef NDEBUG
3056  return std::is_sorted(ArgLocs.begin(), ArgLocs.end(),
3057  [](const CCValAssign &A, const CCValAssign &B) -> bool {
3058  return A.getValNo() < B.getValNo();
3059  });
3060 }
3061 #endif
3062 
3063 SDValue X86TargetLowering::LowerFormalArguments(
3064  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3065  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3066  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3067  MachineFunction &MF = DAG.getMachineFunction();
3069  const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
3070 
3071  const Function &F = MF.getFunction();
3072  if (F.hasExternalLinkage() && Subtarget.isTargetCygMing() &&
3073  F.getName() == "main")
3074  FuncInfo->setForceFramePointer(true);
3075 
3076  MachineFrameInfo &MFI = MF.getFrameInfo();
3077  bool Is64Bit = Subtarget.is64Bit();
3078  bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3079 
3080  assert(
3081  !(isVarArg && canGuaranteeTCO(CallConv)) &&
3082  "Var args not supported with calling conv' regcall, fastcc, ghc or hipe");
3083 
3084  if (CallConv == CallingConv::X86_INTR) {
3085  bool isLegal = Ins.size() == 1 ||
3086  (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
3087  (!Is64Bit && Ins[1].VT == MVT::i32)));
3088  if (!isLegal)
3089  report_fatal_error("X86 interrupts may take one or two arguments");
3090  }
3091 
3092  // Assign locations to all of the incoming arguments.
3094  CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3095 
3096  // Allocate shadow area for Win64.
3097  if (IsWin64)
3098  CCInfo.AllocateStack(32, 8);
3099 
3100  CCInfo.AnalyzeArguments(Ins, CC_X86);
3101 
3102  // In vectorcall calling convention a second pass is required for the HVA
3103  // types.
3104  if (CallingConv::X86_VectorCall == CallConv) {
3105  CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
3106  }
3107 
3108  // The next loop assumes that the locations are in the same order of the
3109  // input arguments.
3110  assert(isSortedByValueNo(ArgLocs) &&
3111  "Argument Location list must be sorted before lowering");
3112 
3113  SDValue ArgValue;
3114  for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
3115  ++I, ++InsIndex) {
3116  assert(InsIndex < Ins.size() && "Invalid Ins index");
3117  CCValAssign &VA = ArgLocs[I];
3118 
3119  if (VA.isRegLoc()) {
3120  EVT RegVT = VA.getLocVT();
3121  if (VA.needsCustom()) {
3122  assert(
3123  VA.getValVT() == MVT::v64i1 &&
3124  "Currently the only custom case is when we split v64i1 to 2 regs");
3125 
3126  // v64i1 values, in regcall calling convention, that are
3127  // compiled to 32 bit arch, are split up into two registers.
3128  ArgValue =
3129  getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
3130  } else {
3131  const TargetRegisterClass *RC;
3132  if (RegVT == MVT::i8)
3133  RC = &X86::GR8RegClass;
3134  else if (RegVT == MVT::i16)
3135  RC = &X86::GR16RegClass;
3136  else if (RegVT == MVT::i32)
3137  RC = &X86::GR32RegClass;
3138  else if (Is64Bit && RegVT == MVT::i64)
3139  RC = &X86::GR64RegClass;
3140  else if (RegVT == MVT::f32)
3141  RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
3142  else if (RegVT == MVT::f64)
3143  RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
3144  else if (RegVT == MVT::f80)
3145  RC = &X86::RFP80RegClass;
3146  else if (RegVT == MVT::f128)
3147  RC = &X86::VR128RegClass;
3148  else if (RegVT.is512BitVector())
3149  RC = &X86::VR512RegClass;
3150  else if (RegVT.is256BitVector())
3151  RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
3152  else if (RegVT.is128BitVector())
3153  RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
3154  else if (RegVT == MVT::x86mmx)
3155  RC = &X86::VR64RegClass;
3156  else if (RegVT == MVT::v1i1)
3157  RC = &X86::VK1RegClass;
3158  else if (RegVT == MVT::v8i1)
3159  RC = &X86::VK8RegClass;
3160  else if (RegVT == MVT::v16i1)
3161  RC = &X86::VK16RegClass;
3162  else if (RegVT == MVT::v32i1)
3163  RC = &X86::VK32RegClass;
3164  else if (RegVT == MVT::v64i1)
3165  RC = &X86::VK64RegClass;
3166  else
3167  llvm_unreachable("Unknown argument type!");
3168 
3169  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3170  ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3171  }
3172 
3173  // If this is an 8 or 16-bit value, it is really passed promoted to 32
3174  // bits. Insert an assert[sz]ext to capture this, then truncate to the
3175  // right size.
3176  if (VA.getLocInfo() == CCValAssign::SExt)
3177  ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3178  DAG.getValueType(VA.getValVT()));
3179  else if (VA.getLocInfo() == CCValAssign::ZExt)
3180  ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3181  DAG.getValueType(VA.getValVT()));
3182  else if (VA.getLocInfo() == CCValAssign::BCvt)
3183  ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
3184 
3185  if (VA.isExtInLoc()) {
3186  // Handle MMX values passed in XMM regs.
3187  if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
3188  ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
3189  else if (VA.getValVT().isVector() &&
3190  VA.getValVT().getScalarType() == MVT::i1 &&
3191  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3192  (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3193  // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3194  ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
3195  } else
3196  ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3197  }
3198  } else {
3199  assert(VA.isMemLoc());
3200  ArgValue =
3201  LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
3202  }
3203 
3204  // If value is passed via pointer - do a load.
3205  if (VA.getLocInfo() == CCValAssign::Indirect && !Ins[I].Flags.isByVal())
3206  ArgValue =
3207  DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
3208 
3209  InVals.push_back(ArgValue);
3210  }
3211 
3212  for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3213  // Swift calling convention does not require we copy the sret argument
3214  // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
3215  if (CallConv == CallingConv::Swift)
3216  continue;
3217 
3218  // All x86 ABIs require that for returning structs by value we copy the
3219  // sret argument into %rax/%eax (depending on ABI) for the return. Save
3220  // the argument into a virtual register so that we can access it from the
3221  // return points.
3222  if (Ins[I].Flags.isSRet()) {
3223  unsigned Reg = FuncInfo->getSRetReturnReg();
3224  if (!Reg) {
3225  MVT PtrTy = getPointerTy(DAG.getDataLayout());
3226  Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3227  FuncInfo->setSRetReturnReg(Reg);
3228  }
3229  SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
3230  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3231  break;
3232  }
3233  }
3234 
3235  unsigned StackSize = CCInfo.getNextStackOffset();
3236  // Align stack specially for tail calls.
3237  if (shouldGuaranteeTCO(CallConv,
3239  StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
3240 
3241  // If the function takes variable number of arguments, make a frame index for
3242  // the start of the first vararg value... for expansion of llvm.va_start. We
3243  // can skip this if there are no va_start calls.
3244  if (MFI.hasVAStart() &&
3245  (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
3246  CallConv != CallingConv::X86_ThisCall))) {
3247  FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
3248  }
3249 
3250  // Figure out if XMM registers are in use.
3251  assert(!(Subtarget.useSoftFloat() &&
3252  F.hasFnAttribute(Attribute::NoImplicitFloat)) &&
3253  "SSE register cannot be used when SSE is disabled!");
3254 
3255  // 64-bit calling conventions support varargs and register parameters, so we
3256  // have to do extra work to spill them in the prologue.
3257  if (Is64Bit && isVarArg && MFI.hasVAStart()) {
3258  // Find the first unallocated argument registers.
3259  ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3260  ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
3261  unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3262  unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3263  assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&
3264  "SSE register cannot be used when SSE is disabled!");
3265 
3266  // Gather all the live in physical registers.
3267  SmallVector<SDValue, 6> LiveGPRs;
3268  SmallVector<SDValue, 8> LiveXMMRegs;
3269  SDValue ALVal;
3270  for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3271  unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
3272  LiveGPRs.push_back(
3273  DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
3274  }
3275  if (!ArgXMMs.empty()) {
3276  unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3277  ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
3278  for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
3279  unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
3280  LiveXMMRegs.push_back(
3281  DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
3282  }
3283  }
3284 
3285  if (IsWin64) {
3286  // Get to the caller-allocated home save location. Add 8 to account
3287  // for the return address.
3288  int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
3289  FuncInfo->setRegSaveFrameIndex(
3290  MFI.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3291  // Fixup to set vararg frame on shadow area (4 x i64).
3292  if (NumIntRegs < 4)
3293  FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3294  } else {
3295  // For X86-64, if there are vararg parameters that are passed via
3296  // registers, then we must store them to their spots on the stack so
3297  // they may be loaded by dereferencing the result of va_next.
3298  FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3299  FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3301  ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
3302  }
3303 
3304  // Store the integer parameter registers.
3305  SmallVector<SDValue, 8> MemOps;
3306  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3307  getPointerTy(DAG.getDataLayout()));
3308  unsigned Offset = FuncInfo->getVarArgsGPOffset();
3309  for (SDValue Val : LiveGPRs) {
3310  SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3311  RSFIN, DAG.getIntPtrConstant(Offset, dl));
3312  SDValue Store =
3313  DAG.getStore(Val.getValue(1), dl, Val, FIN,
3315  DAG.getMachineFunction(),
3316  FuncInfo->getRegSaveFrameIndex(), Offset));
3317  MemOps.push_back(Store);
3318  Offset += 8;
3319  }
3320 
3321  if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
3322  // Now store the XMM (fp + vector) parameter registers.
3323  SmallVector<SDValue, 12> SaveXMMOps;
3324  SaveXMMOps.push_back(Chain);
3325  SaveXMMOps.push_back(ALVal);
3326  SaveXMMOps.push_back(DAG.getIntPtrConstant(
3327  FuncInfo->getRegSaveFrameIndex(), dl));
3328  SaveXMMOps.push_back(DAG.getIntPtrConstant(
3329  FuncInfo->getVarArgsFPOffset(), dl));
3330  SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
3331  LiveXMMRegs.end());
3333  MVT::Other, SaveXMMOps));
3334  }
3335 
3336  if (!MemOps.empty())
3337  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3338  }
3339 
3340  if (isVarArg && MFI.hasMustTailInVarArgFunc()) {
3341  // Find the largest legal vector type.
3342  MVT VecVT = MVT::Other;
3343  // FIXME: Only some x86_32 calling conventions support AVX512.
3344  if (Subtarget.hasAVX512() &&
3345  (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
3346  CallConv == CallingConv::Intel_OCL_BI)))
3347  VecVT = MVT::v16f32;
3348  else if (Subtarget.hasAVX())
3349  VecVT = MVT::v8f32;
3350  else if (Subtarget.hasSSE2())
3351  VecVT = MVT::v4f32;
3352 
3353  // We forward some GPRs and some vector types.
3354  SmallVector<MVT, 2> RegParmTypes;
3355  MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
3356  RegParmTypes.push_back(IntVT);
3357  if (VecVT != MVT::Other)
3358  RegParmTypes.push_back(VecVT);
3359 
3360  // Compute the set of forwarded registers. The rest are scratch.
3362  FuncInfo->getForwardedMustTailRegParms();
3363  CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3364 
3365  // Conservatively forward AL on x86_64, since it might be used for varargs.
3366  if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
3367  unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3368  Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3369  }
3370 
3371  // Copy all forwards from physical to virtual registers.
3372  for (ForwardedRegister &F : Forwards) {
3373  // FIXME: Can we use a less constrained schedule?
3374  SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3375  F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
3376  Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
3377  }
3378  }
3379 
3380  // Some CCs need callee pop.
3381  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3383  FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
3384  } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
3385  // X86 interrupts must pop the error code (and the alignment padding) if
3386  // present.
3387  FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
3388  } else {
3389  FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
3390  // If this is an sret function, the return should pop the hidden pointer.
3391  if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3392  !Subtarget.getTargetTriple().isOSMSVCRT() &&
3393  argsAreStructReturn(Ins, Subtarget.isTargetMCU()) == StackStructReturn)
3394  FuncInfo->setBytesToPopOnReturn(4);
3395  }
3396 
3397  if (!Is64Bit) {
3398  // RegSaveFrameIndex is X86-64 only.
3399  FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3400  if (CallConv == CallingConv::X86_FastCall ||
3401  CallConv == CallingConv::X86_ThisCall)
3402  // fastcc functions can't have varargs.
3403  FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
3404  }
3405 
3406  FuncInfo->setArgumentStackSize(StackSize);
3407 
3408  if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
3410  if (Personality == EHPersonality::CoreCLR) {
3411  assert(Is64Bit);
3412  // TODO: Add a mechanism to frame lowering that will allow us to indicate
3413  // that we'd prefer this slot be allocated towards the bottom of the frame
3414  // (i.e. near the stack pointer after allocating the frame). Every
3415  // funclet needs a copy of this slot in its (mostly empty) frame, and the
3416  // offset from the bottom of this and each funclet's frame must be the
3417  // same, so the size of funclets' (mostly empty) frames is dictated by
3418  // how far this slot is from the bottom (since they allocate just enough
3419  // space to accommodate holding this slot at the correct offset).
3420  int PSPSymFI = MFI.CreateStackObject(8, 8, /*isSS=*/false);
3421  EHInfo->PSPSymFrameIdx = PSPSymFI;
3422  }
3423  }
3424 
3425  if (CallConv == CallingConv::X86_RegCall ||
3426  F.hasFnAttribute("no_caller_saved_registers")) {
3428  for (std::pair<unsigned, unsigned> Pair : MRI.liveins())
3429  MRI.disableCalleeSavedRegister(Pair.first);
3430  }
3431 
3432  return Chain;
3433 }
3434 
3435 SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
3436  SDValue Arg, const SDLoc &dl,
3437  SelectionDAG &DAG,
3438  const CCValAssign &VA,
3439  ISD::ArgFlagsTy Flags) const {
3440  unsigned LocMemOffset = VA.getLocMemOffset();
3441  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3442  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3443  StackPtr, PtrOff);
3444  if (Flags.isByVal())
3445  return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3446 
3447  return DAG.getStore(
3448  Chain, dl, Arg, PtrOff,
3449  MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
3450 }
3451 
3452 /// Emit a load of return address if tail call
3453 /// optimization is performed and it is required.
3454 SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
3455  SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
3456  bool Is64Bit, int FPDiff, const SDLoc &dl) const {
3457  // Adjust the Return address stack slot.
3458  EVT VT = getPointerTy(DAG.getDataLayout());
3459  OutRetAddr = getReturnAddressFrameIndex(DAG);
3460 
3461  // Load the "old" Return address.
3462  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
3463  return SDValue(OutRetAddr.getNode(), 1);
3464 }
3465 
3466 /// Emit a store of the return address if tail call
3467 /// optimization is performed and it is required (FPDiff!=0).
3469  SDValue Chain, SDValue RetAddrFrIdx,
3470  EVT PtrVT, unsigned SlotSize,
3471  int FPDiff, const SDLoc &dl) {
3472  // Store the return address to the appropriate stack slot.
3473  if (!FPDiff) return Chain;
3474  // Calculate the new stack slot for the return address.
3475  int NewReturnAddrFI =
3476  MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3477  false);
3478  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3479  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3481  DAG.getMachineFunction(), NewReturnAddrFI));
3482  return Chain;
3483 }
3484 
3485 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3486 /// operation of specified width.
3487 static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
3488  SDValue V2) {
3489  unsigned NumElems = VT.getVectorNumElements();
3491  Mask.push_back(NumElems);
3492  for (unsigned i = 1; i != NumElems; ++i)
3493  Mask.push_back(i);
3494  return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
3495 }
3496 
3497 SDValue
3498 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3499  SmallVectorImpl<SDValue> &InVals) const {
3500  SelectionDAG &DAG = CLI.DAG;
3501  SDLoc &dl = CLI.DL;
3503  SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3505  SDValue Chain = CLI.Chain;
3506  SDValue Callee = CLI.Callee;
3507  CallingConv::ID CallConv = CLI.CallConv;
3508  bool &isTailCall = CLI.IsTailCall;
3509  bool isVarArg = CLI.IsVarArg;
3510 
3511  MachineFunction &MF = DAG.getMachineFunction();
3512  bool Is64Bit = Subtarget.is64Bit();
3513  bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3514  StructReturnType SR = callIsStructReturn(Outs, Subtarget.isTargetMCU());
3515  bool IsSibcall = false;
3517  auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
3518  const auto *CI = dyn_cast_or_null<CallInst>(CLI.CS.getInstruction());
3519  const Function *Fn = CI ? CI->getCalledFunction() : nullptr;
3520  bool HasNCSR = (CI && CI->hasFnAttr("no_caller_saved_registers")) ||
3521  (Fn && Fn->hasFnAttribute("no_caller_saved_registers"));
3522  const auto *II = dyn_cast_or_null<InvokeInst>(CLI.CS.getInstruction());
3523  bool HasNoCfCheck =
3524  (CI && CI->doesNoCfCheck()) || (II && II->doesNoCfCheck());
3525  const Module *M = MF.getMMI().getModule();
3526  Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
3527 
3528  if (CallConv == CallingConv::X86_INTR)
3529  report_fatal_error("X86 interrupts may not be called directly");
3530 
3531  if (Attr.getValueAsString() == "true")
3532  isTailCall = false;
3533 
3534  if (Subtarget.isPICStyleGOT() &&
3536  // If we are using a GOT, disable tail calls to external symbols with
3537  // default visibility. Tail calling such a symbol requires using a GOT
3538  // relocation, which forces early binding of the symbol. This breaks code
3539  // that require lazy function symbol resolution. Using musttail or
3540  // GuaranteedTailCallOpt will override this.
3542  if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3544  isTailCall = false;
3545  }
3546 
3547  bool IsMustTail = CLI.CS && CLI.CS.isMustTailCall();
3548  if (IsMustTail) {
3549  // Force this to be a tail call. The verifier rules are enough to ensure
3550  // that we can lower this successfully without moving the return address
3551  // around.
3552  isTailCall = true;
3553  } else if (isTailCall) {
3554  // Check if it's really possible to do a tail call.
3555  isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3556  isVarArg, SR != NotStructReturn,
3557  MF.getFunction().hasStructRetAttr(), CLI.RetTy,
3558  Outs, OutVals, Ins, DAG);
3559 
3560  // Sibcalls are automatically detected tailcalls which do not require
3561  // ABI changes.
3562  if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3563  IsSibcall = true;
3564 
3565  if (isTailCall)
3566  ++NumTailCalls;
3567  }
3568 
3569  assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3570  "Var args not supported with calling convention fastcc, ghc or hipe");
3571 
3572  // Analyze operands of the call, assigning locations to each operand.
3574  CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3575 
3576  // Allocate shadow area for Win64.
3577  if (IsWin64)
3578  CCInfo.AllocateStack(32, 8);
3579 
3580  CCInfo.AnalyzeArguments(Outs, CC_X86);
3581 
3582  // In vectorcall calling convention a second pass is required for the HVA
3583  // types.
3584  if (CallingConv::X86_VectorCall == CallConv) {
3585  CCInfo.AnalyzeArgumentsSecondPass(Outs, CC_X86);
3586  }
3587 
3588  // Get a count of how many bytes are to be pushed on the stack.
3589  unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3590  if (IsSibcall)
3591  // This is a sibcall. The memory operands are available in caller's
3592  // own caller's stack.
3593  NumBytes = 0;
3594  else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3595  canGuaranteeTCO(CallConv))
3596  NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3597 
3598  int FPDiff = 0;
3599  if (isTailCall && !IsSibcall && !IsMustTail) {
3600  // Lower arguments at fp - stackoffset + fpdiff.
3601  unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3602 
3603  FPDiff = NumBytesCallerPushed - NumBytes;
3604 
3605  // Set the delta of movement of the returnaddr stackslot.
3606  // But only set if delta is greater than previous delta.
3607  if (FPDiff < X86Info->getTCReturnAddrDelta())
3608  X86Info->setTCReturnAddrDelta(FPDiff);
3609  }
3610 
3611  unsigned NumBytesToPush = NumBytes;
3612  unsigned NumBytesToPop = NumBytes;
3613 
3614  // If we have an inalloca argument, all stack space has already been allocated
3615  // for us and be right at the top of the stack. We don't support multiple
3616  // arguments passed in memory when using inalloca.
3617  if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3618  NumBytesToPush = 0;
3619  if (!ArgLocs.back().isMemLoc())
3620  report_fatal_error("cannot use inalloca attribute on a register "
3621  "parameter");
3622  if (ArgLocs.back().getLocMemOffset() != 0)
3623  report_fatal_error("any parameter with the inalloca attribute must be "
3624  "the only memory argument");
3625  }
3626 
3627  if (!IsSibcall)
3628  Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
3629  NumBytes - NumBytesToPush, dl);
3630 
3631  SDValue RetAddrFrIdx;
3632  // Load return address for tail calls.
3633  if (isTailCall && FPDiff)
3634  Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3635  Is64Bit, FPDiff, dl);
3636 
3638  SmallVector<SDValue, 8> MemOpChains;
3639  SDValue StackPtr;
3640 
3641  // The next loop assumes that the locations are in the same order of the
3642  // input arguments.
3643  assert(isSortedByValueNo(ArgLocs) &&
3644  "Argument Location list must be sorted before lowering");
3645 
3646  // Walk the register/memloc assignments, inserting copies/loads. In the case
3647  // of tail call optimization arguments are handle later.
3648  const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3649  for (unsigned I = 0, OutIndex = 0, E = ArgLocs.size(); I != E;
3650  ++I, ++OutIndex) {
3651  assert(OutIndex < Outs.size() && "Invalid Out index");
3652  // Skip inalloca arguments, they have already been written.
3653  ISD::ArgFlagsTy Flags = Outs[OutIndex].Flags;
3654  if (Flags.isInAlloca())
3655  continue;