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