[X86] Make some for loops over MVTs more explicit (and shorter) by just mentioning...
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.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"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
71                                      const X86Subtarget &STI)
72     : TargetLowering(TM), Subtarget(&STI) {
73   X86ScalarSSEf64 = Subtarget->hasSSE2();
74   X86ScalarSSEf32 = Subtarget->hasSSE1();
75   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
76
77   // Set up the TargetLowering object.
78
79   // X86 is weird. It always uses i8 for shift amounts and setcc results.
80   setBooleanContents(ZeroOrOneBooleanContent);
81   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
82   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
83
84   // For 64-bit, since we have so many registers, use the ILP scheduler.
85   // For 32-bit, use the register pressure specific scheduling.
86   // For Atom, always use ILP scheduling.
87   if (Subtarget->isAtom())
88     setSchedulingPreference(Sched::ILP);
89   else if (Subtarget->is64Bit())
90     setSchedulingPreference(Sched::ILP);
91   else
92     setSchedulingPreference(Sched::RegPressure);
93   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
94   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
95
96   // Bypass expensive divides on Atom when compiling with O2.
97   if (TM.getOptLevel() >= CodeGenOpt::Default) {
98     if (Subtarget->hasSlowDivide32())
99       addBypassSlowDiv(32, 8);
100     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
101       addBypassSlowDiv(64, 16);
102   }
103
104   if (Subtarget->isTargetKnownWindowsMSVC()) {
105     // Setup Windows compiler runtime calls.
106     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
107     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
108     setLibcallName(RTLIB::SREM_I64, "_allrem");
109     setLibcallName(RTLIB::UREM_I64, "_aullrem");
110     setLibcallName(RTLIB::MUL_I64, "_allmul");
111     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
112     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
113     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
114     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
115     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
116   }
117
118   if (Subtarget->isTargetDarwin()) {
119     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
120     setUseUnderscoreSetJmp(false);
121     setUseUnderscoreLongJmp(false);
122   } else if (Subtarget->isTargetWindowsGNU()) {
123     // MS runtime is weird: it exports _setjmp, but longjmp!
124     setUseUnderscoreSetJmp(true);
125     setUseUnderscoreLongJmp(false);
126   } else {
127     setUseUnderscoreSetJmp(true);
128     setUseUnderscoreLongJmp(true);
129   }
130
131   // Set up the register classes.
132   addRegisterClass(MVT::i8, &X86::GR8RegClass);
133   addRegisterClass(MVT::i16, &X86::GR16RegClass);
134   addRegisterClass(MVT::i32, &X86::GR32RegClass);
135   if (Subtarget->is64Bit())
136     addRegisterClass(MVT::i64, &X86::GR64RegClass);
137
138   for (MVT VT : MVT::integer_valuetypes())
139     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
140
141   // We don't accept any truncstore of integer registers.
142   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
143   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
144   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
145   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
146   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
147   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
148
149   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
150
151   // SETOEQ and SETUNE require checking two conditions.
152   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
153   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
154   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
155   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
156   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
157   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
158
159   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
160   // operation.
161   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
162   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
163   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
164
165   if (Subtarget->is64Bit()) {
166     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
167       // f32/f64 are legal, f80 is custom.
168       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
169     else
170       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
171     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
172   } else if (!Subtarget->useSoftFloat()) {
173     // We have an algorithm for SSE2->double, and we turn this into a
174     // 64-bit FILD followed by conditional FADD for other targets.
175     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
176     // We have an algorithm for SSE2, and we turn this into a 64-bit
177     // FILD or VCVTUSI2SS/SD for other targets.
178     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
179   }
180
181   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
182   // this operation.
183   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
184   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
185
186   if (!Subtarget->useSoftFloat()) {
187     // SSE has no i16 to fp conversion, only i32
188     if (X86ScalarSSEf32) {
189       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
190       // f32 and f64 cases are Legal, f80 case is not
191       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
192     } else {
193       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
194       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
195     }
196   } else {
197     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
198     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
199   }
200
201   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
202   // are Legal, f80 is custom lowered.
203   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
204   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
205
206   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
207   // this operation.
208   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
209   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
210
211   if (X86ScalarSSEf32) {
212     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
213     // f32 and f64 cases are Legal, f80 case is not
214     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
215   } else {
216     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
217     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
218   }
219
220   // Handle FP_TO_UINT by promoting the destination to a larger signed
221   // conversion.
222   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
223   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
224   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
225
226   if (Subtarget->is64Bit()) {
227     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
228       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
229       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
230       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
231     } else {
232       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
233       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
234     }
235   } else if (!Subtarget->useSoftFloat()) {
236     // Since AVX is a superset of SSE3, only check for SSE here.
237     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
238       // Expand FP_TO_UINT into a select.
239       // FIXME: We would like to use a Custom expander here eventually to do
240       // the optimal thing for SSE vs. the default expansion in the legalizer.
241       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
242     else
243       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
244       // With SSE3 we can use fisttpll to convert to a signed i64; without
245       // SSE, we're stuck with a fistpll.
246       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
247
248     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
249   }
250
251   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
252   if (!X86ScalarSSEf64) {
253     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
254     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
255     if (Subtarget->is64Bit()) {
256       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
257       // Without SSE, i64->f64 goes through memory.
258       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
259     }
260   }
261
262   // Scalar integer divide and remainder are lowered to use operations that
263   // produce two results, to match the available instructions. This exposes
264   // the two-result form to trivial CSE, which is able to combine x/y and x%y
265   // into a single instruction.
266   //
267   // Scalar integer multiply-high is also lowered to use two-result
268   // operations, to match the available instructions. However, plain multiply
269   // (low) operations are left as Legal, as there are single-result
270   // instructions for this in x86. Using the two-result multiply instructions
271   // when both high and low results are needed must be arranged by dagcombine.
272   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
273     setOperationAction(ISD::MULHS, VT, Expand);
274     setOperationAction(ISD::MULHU, VT, Expand);
275     setOperationAction(ISD::SDIV, VT, Expand);
276     setOperationAction(ISD::UDIV, VT, Expand);
277     setOperationAction(ISD::SREM, VT, Expand);
278     setOperationAction(ISD::UREM, VT, Expand);
279
280     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
281     setOperationAction(ISD::ADDC, VT, Custom);
282     setOperationAction(ISD::ADDE, VT, Custom);
283     setOperationAction(ISD::SUBC, VT, Custom);
284     setOperationAction(ISD::SUBE, VT, Custom);
285   }
286
287   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
288   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
289   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
290   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
291   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
292   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
293   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
294   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
295   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
296   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
297   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
298   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
299   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
300   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
301   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
303   if (Subtarget->is64Bit())
304     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
305   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
306   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
307   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
308   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
309
310   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
311     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
312     // is. We should promote the value to 64-bits to solve this.
313     // This is what the CRT headers do - `fmodf` is an inline header
314     // function casting to f64 and calling `fmod`.
315     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
316   } else {
317     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
318   }
319
320   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
321   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
322   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
323
324   // Promote the i8 variants and force them on up to i32 which has a shorter
325   // encoding.
326   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
327   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
328   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
329   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
330   if (Subtarget->hasBMI()) {
331     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
332     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
333     if (Subtarget->is64Bit())
334       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
335   } else {
336     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
337     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
338     if (Subtarget->is64Bit())
339       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
340   }
341
342   if (Subtarget->hasLZCNT()) {
343     // When promoting the i8 variants, force them to i32 for a shorter
344     // encoding.
345     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
346     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
347     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
348     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
349     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
350     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
351     if (Subtarget->is64Bit())
352       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
353   } else {
354     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
355     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
356     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
357     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
358     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
360     if (Subtarget->is64Bit()) {
361       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
362       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
363     }
364   }
365
366   // Special handling for half-precision floating point conversions.
367   // If we don't have F16C support, then lower half float conversions
368   // into library calls.
369   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
370     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
371     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
372   }
373
374   // There's never any support for operations beyond MVT::f32.
375   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
376   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
377   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
378   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
379
380   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
381   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
382   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
383   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
384   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
386
387   if (Subtarget->hasPOPCNT()) {
388     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
389   } else {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
391     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
392     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
393     if (Subtarget->is64Bit())
394       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
395   }
396
397   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
398
399   if (!Subtarget->hasMOVBE())
400     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
401
402   // These should be promoted to a larger select which is supported.
403   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
404   // X86 wants to expand cmov itself.
405   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
406   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
407   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
408   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
412   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
414   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
417   if (Subtarget->is64Bit()) {
418     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
419     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
420   }
421   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
422   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
423   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
424   // support continuation, user-level threading, and etc.. As a result, no
425   // other SjLj exception interfaces are implemented and please don't build
426   // your own exception handling based on them.
427   // LLVM/Clang supports zero-cost DWARF exception handling.
428   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
429   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
430
431   // Darwin ABI issue.
432   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
433   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
434   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
435   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
436   if (Subtarget->is64Bit())
437     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
438   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
439   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
440   if (Subtarget->is64Bit()) {
441     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
442     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
443     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
444     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
445     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
446   }
447   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
448   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
449   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
450   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
451   if (Subtarget->is64Bit()) {
452     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
453     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
454     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
455   }
456
457   if (Subtarget->hasSSE1())
458     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
459
460   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
461
462   // Expand certain atomics
463   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
464     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
465     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
466     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
467   }
468
469   if (Subtarget->hasCmpxchg16b()) {
470     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
471   }
472
473   // FIXME - use subtarget debug flags
474   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
475       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
476     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
477   }
478
479   if (Subtarget->isTarget64BitLP64()) {
480     setExceptionPointerRegister(X86::RAX);
481     setExceptionSelectorRegister(X86::RDX);
482   } else {
483     setExceptionPointerRegister(X86::EAX);
484     setExceptionSelectorRegister(X86::EDX);
485   }
486   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
487   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
488
489   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
490   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
491
492   setOperationAction(ISD::TRAP, MVT::Other, Legal);
493   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
494
495   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
496   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
497   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
498   if (Subtarget->is64Bit()) {
499     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
500     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
501   } else {
502     // TargetInfo::CharPtrBuiltinVaList
503     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
504     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
505   }
506
507   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
508   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
509
510   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
511
512   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
513   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
514   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
515
516   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
517     // f32 and f64 use SSE.
518     // Set up the FP register classes.
519     addRegisterClass(MVT::f32, &X86::FR32RegClass);
520     addRegisterClass(MVT::f64, &X86::FR64RegClass);
521
522     // Use ANDPD to simulate FABS.
523     setOperationAction(ISD::FABS , MVT::f64, Custom);
524     setOperationAction(ISD::FABS , MVT::f32, Custom);
525
526     // Use XORP to simulate FNEG.
527     setOperationAction(ISD::FNEG , MVT::f64, Custom);
528     setOperationAction(ISD::FNEG , MVT::f32, Custom);
529
530     // Use ANDPD and ORPD to simulate FCOPYSIGN.
531     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
532     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
533
534     // Lower this to FGETSIGNx86 plus an AND.
535     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
536     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
537
538     // We don't support sin/cos/fmod
539     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
540     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
541     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
542     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
543     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
544     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
545
546     // Expand FP immediates into loads from the stack, except for the special
547     // cases we handle.
548     addLegalFPImmediate(APFloat(+0.0)); // xorpd
549     addLegalFPImmediate(APFloat(+0.0f)); // xorps
550   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
551     // Use SSE for f32, x87 for f64.
552     // Set up the FP register classes.
553     addRegisterClass(MVT::f32, &X86::FR32RegClass);
554     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
555
556     // Use ANDPS to simulate FABS.
557     setOperationAction(ISD::FABS , MVT::f32, Custom);
558
559     // Use XORP to simulate FNEG.
560     setOperationAction(ISD::FNEG , MVT::f32, Custom);
561
562     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
563
564     // Use ANDPS and ORPS to simulate FCOPYSIGN.
565     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
566     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
567
568     // We don't support sin/cos/fmod
569     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
570     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
571     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
572
573     // Special cases we handle for FP constants.
574     addLegalFPImmediate(APFloat(+0.0f)); // xorps
575     addLegalFPImmediate(APFloat(+0.0)); // FLD0
576     addLegalFPImmediate(APFloat(+1.0)); // FLD1
577     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
578     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
579
580     if (!TM.Options.UnsafeFPMath) {
581       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
582       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
583       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
584     }
585   } else if (!Subtarget->useSoftFloat()) {
586     // f32 and f64 in x87.
587     // Set up the FP register classes.
588     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
589     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
590
591     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
592     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
593     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
594     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
595
596     if (!TM.Options.UnsafeFPMath) {
597       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
598       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
599       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
600       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
601       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
602       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
603     }
604     addLegalFPImmediate(APFloat(+0.0)); // FLD0
605     addLegalFPImmediate(APFloat(+1.0)); // FLD1
606     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
607     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
608     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
612   }
613
614   // We don't support FMA.
615   setOperationAction(ISD::FMA, MVT::f64, Expand);
616   setOperationAction(ISD::FMA, MVT::f32, Expand);
617
618   // Long double always uses X87.
619   if (!Subtarget->useSoftFloat()) {
620     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
621     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
622     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
623     {
624       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
625       addLegalFPImmediate(TmpFlt);  // FLD0
626       TmpFlt.changeSign();
627       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
628
629       bool ignored;
630       APFloat TmpFlt2(+1.0);
631       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
632                       &ignored);
633       addLegalFPImmediate(TmpFlt2);  // FLD1
634       TmpFlt2.changeSign();
635       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
636     }
637
638     if (!TM.Options.UnsafeFPMath) {
639       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
640       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
641       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
642     }
643
644     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
645     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
646     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
647     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
648     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
649     setOperationAction(ISD::FMA, MVT::f80, Expand);
650   }
651
652   // Always use a library call for pow.
653   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
654   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
655   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
656
657   setOperationAction(ISD::FLOG, MVT::f80, Expand);
658   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
659   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
660   setOperationAction(ISD::FEXP, MVT::f80, Expand);
661   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
662   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
663   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
664
665   // First set operation action for all vector types to either promote
666   // (for widening) or expand (for scalarization). Then we will selectively
667   // turn on ones that can be effectively codegen'd.
668   for (MVT VT : MVT::vector_valuetypes()) {
669     setOperationAction(ISD::ADD , VT, Expand);
670     setOperationAction(ISD::SUB , VT, Expand);
671     setOperationAction(ISD::FADD, VT, Expand);
672     setOperationAction(ISD::FNEG, VT, Expand);
673     setOperationAction(ISD::FSUB, VT, Expand);
674     setOperationAction(ISD::MUL , VT, Expand);
675     setOperationAction(ISD::FMUL, VT, Expand);
676     setOperationAction(ISD::SDIV, VT, Expand);
677     setOperationAction(ISD::UDIV, VT, Expand);
678     setOperationAction(ISD::FDIV, VT, Expand);
679     setOperationAction(ISD::SREM, VT, Expand);
680     setOperationAction(ISD::UREM, VT, Expand);
681     setOperationAction(ISD::LOAD, VT, Expand);
682     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
683     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
684     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
685     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
686     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
687     setOperationAction(ISD::FABS, VT, Expand);
688     setOperationAction(ISD::FSIN, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FCOS, VT, Expand);
691     setOperationAction(ISD::FSINCOS, VT, Expand);
692     setOperationAction(ISD::FREM, VT, Expand);
693     setOperationAction(ISD::FMA,  VT, Expand);
694     setOperationAction(ISD::FPOWI, VT, Expand);
695     setOperationAction(ISD::FSQRT, VT, Expand);
696     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
697     setOperationAction(ISD::FFLOOR, VT, Expand);
698     setOperationAction(ISD::FCEIL, VT, Expand);
699     setOperationAction(ISD::FTRUNC, VT, Expand);
700     setOperationAction(ISD::FRINT, VT, Expand);
701     setOperationAction(ISD::FNEARBYINT, VT, Expand);
702     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHS, VT, Expand);
704     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
705     setOperationAction(ISD::MULHU, VT, Expand);
706     setOperationAction(ISD::SDIVREM, VT, Expand);
707     setOperationAction(ISD::UDIVREM, VT, Expand);
708     setOperationAction(ISD::FPOW, VT, Expand);
709     setOperationAction(ISD::CTPOP, VT, Expand);
710     setOperationAction(ISD::CTTZ, VT, Expand);
711     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::CTLZ, VT, Expand);
713     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
714     setOperationAction(ISD::SHL, VT, Expand);
715     setOperationAction(ISD::SRA, VT, Expand);
716     setOperationAction(ISD::SRL, VT, Expand);
717     setOperationAction(ISD::ROTL, VT, Expand);
718     setOperationAction(ISD::ROTR, VT, Expand);
719     setOperationAction(ISD::BSWAP, VT, Expand);
720     setOperationAction(ISD::SETCC, VT, Expand);
721     setOperationAction(ISD::FLOG, VT, Expand);
722     setOperationAction(ISD::FLOG2, VT, Expand);
723     setOperationAction(ISD::FLOG10, VT, Expand);
724     setOperationAction(ISD::FEXP, VT, Expand);
725     setOperationAction(ISD::FEXP2, 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);
730     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
731     setOperationAction(ISD::TRUNCATE, VT, Expand);
732     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
733     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
734     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
735     setOperationAction(ISD::VSELECT, VT, Expand);
736     setOperationAction(ISD::SELECT_CC, VT, Expand);
737     for (MVT InnerVT : MVT::vector_valuetypes()) {
738       setTruncStoreAction(InnerVT, VT, Expand);
739
740       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
741       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
742
743       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
744       // types, we have to deal with them whether we ask for Expansion or not.
745       // Setting Expand causes its own optimisation problems though, so leave
746       // them legal.
747       if (VT.getVectorElementType() == MVT::i1)
748         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
749
750       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
751       // split/scalarized right now.
752       if (VT.getVectorElementType() == MVT::f16)
753         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
754     }
755   }
756
757   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
758   // with -msoft-float, disable use of MMX as well.
759   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
760     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
761     // No operations on x86mmx supported, everything uses intrinsics.
762   }
763
764   // MMX-sized vectors (other than x86mmx) are expected to be expanded
765   // into smaller operations.
766   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
767     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
768     setOperationAction(ISD::AND,                MMXTy,      Expand);
769     setOperationAction(ISD::OR,                 MMXTy,      Expand);
770     setOperationAction(ISD::XOR,                MMXTy,      Expand);
771     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
772     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
773     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
774   }
775   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
776
777   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
778     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
779
780     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
783     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
784     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
785     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
786     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
787     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
788     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
789     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
790     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
791     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
792     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
793     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
794   }
795
796   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
797     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
798
799     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
800     // registers cannot be used even for integer operations.
801     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
802     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
803     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
804     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
805
806     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
807     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
808     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
809     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
810     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
811     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
812     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
813     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
814     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
815     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
816     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
817     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
818     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
819     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
820     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
821     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
822     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
825     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
826     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
827     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
828     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
829
830     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
831     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
832     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
833     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
834
835     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
837     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
838     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
839
840     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
841     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
843     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
844     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
845
846     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
847     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
848     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
849     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
850
851     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
852     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
853     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
854     // ISD::CTTZ v2i64 - scalarization is faster.
855     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
856     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
857     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
858     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
859
860     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
861     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
862       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
863       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
864       setOperationAction(ISD::VSELECT,            VT, Custom);
865       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
866     }
867
868     // We support custom legalizing of sext and anyext loads for specific
869     // memory vector types which we can load as a scalar (or sequence of
870     // scalars) and extend in-register to a legal 128-bit vector type. For sext
871     // loads these must work with a single scalar load.
872     for (MVT VT : MVT::integer_vector_valuetypes()) {
873       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
874       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
875       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
878       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
879       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
880       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
881       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
882     }
883
884     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
885     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
886     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
887     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
888     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
889     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
891     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
892
893     if (Subtarget->is64Bit()) {
894       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
895       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
896     }
897
898     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
899     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
900       setOperationAction(ISD::AND,    VT, Promote);
901       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
902       setOperationAction(ISD::OR,     VT, Promote);
903       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
904       setOperationAction(ISD::XOR,    VT, Promote);
905       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
906       setOperationAction(ISD::LOAD,   VT, Promote);
907       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
908       setOperationAction(ISD::SELECT, VT, Promote);
909       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
910     }
911
912     // Custom lower v2i64 and v2f64 selects.
913     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
914     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
915     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
916     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
917
918     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
919     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
920
921     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
922
923     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
924     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
925     // As there is no 64-bit GPR available, we need build a special custom
926     // sequence to convert from v2i32 to v2f32.
927     if (!Subtarget->is64Bit())
928       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
929
930     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
931     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
932
933     for (MVT VT : MVT::fp_vector_valuetypes())
934       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
935
936     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
937     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
938     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
939   }
940
941   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
942     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
943       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
944       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
945       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
946       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
947       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
948     }
949
950     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
951     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
952     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
953     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
954     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
955     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
956     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
957     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
958
959     // FIXME: Do we need to handle scalar-to-vector here?
960     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
961
962     // We directly match byte blends in the backend as they match the VSELECT
963     // condition form.
964     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
965
966     // SSE41 brings specific instructions for doing vector sign extend even in
967     // cases where we don't have SRA.
968     for (MVT VT : MVT::integer_vector_valuetypes()) {
969       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
970       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
971       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
972     }
973
974     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
975     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
976     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
977     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
978     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
981
982     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
983     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
984     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
985     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
988
989     // i8 and i16 vectors are custom because the source register and source
990     // source memory operand types are not the same width.  f32 vectors are
991     // custom since the immediate controlling the insert encodes additional
992     // information.
993     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
994     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
997
998     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
999     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1000     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1001     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1002
1003     // FIXME: these should be Legal, but that's only for the case where
1004     // the index is constant.  For now custom expand to deal with that.
1005     if (Subtarget->is64Bit()) {
1006       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1007       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1008     }
1009   }
1010
1011   if (Subtarget->hasSSE2()) {
1012     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1013     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1014     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1015
1016     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1017     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1018
1019     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1020     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1021
1022     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1023     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1024
1025     // In the customized shift lowering, the legal cases in AVX2 will be
1026     // recognized.
1027     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1028     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1029
1030     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1031     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1032
1033     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1034     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1035   }
1036
1037   if (Subtarget->hasXOP()) {
1038     setOperationAction(ISD::ROTL,              MVT::v16i8, Custom);
1039     setOperationAction(ISD::ROTL,              MVT::v8i16, Custom);
1040     setOperationAction(ISD::ROTL,              MVT::v4i32, Custom);
1041     setOperationAction(ISD::ROTL,              MVT::v2i64, Custom);
1042     setOperationAction(ISD::ROTL,              MVT::v32i8, Custom);
1043     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1044     setOperationAction(ISD::ROTL,              MVT::v8i32, Custom);
1045     setOperationAction(ISD::ROTL,              MVT::v4i64, Custom);
1046   }
1047
1048   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1049     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1050     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1051     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1052     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1053     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1054     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1055
1056     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1057     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1058     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1059
1060     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1061     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1062     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1063     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1064     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1065     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1066     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1067     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1068     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1069     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1070     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1071     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1072
1073     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1074     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1075     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1076     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1077     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1078     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1079     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1080     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1081     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1082     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1083     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1084     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1085
1086     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1087     // even though v8i16 is a legal type.
1088     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1089     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1090     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1091
1092     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1093     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1094     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1095
1096     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1097     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1098
1099     for (MVT VT : MVT::fp_vector_valuetypes())
1100       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1101
1102     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1103     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1104
1105     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1106     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1107
1108     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1109     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1110
1111     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1112     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1113     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1114     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1115
1116     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1117     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1118     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1119
1120     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1121     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1122     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1123     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1124     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1125     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1126     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1127     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1128     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1129     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1130     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1131     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1132
1133     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1134     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1135     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1136     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1137
1138     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1139     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1140     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1141     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1142     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1143     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1144     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1145     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1146
1147     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1148       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1149       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1150       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1151       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1152       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1153       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1154     }
1155
1156     if (Subtarget->hasInt256()) {
1157       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1158       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1159       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1160       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1161
1162       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1163       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1164       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1165       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1166
1167       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1168       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1169       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1170       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1171
1172       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1173       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1174       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1175       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1176
1177       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1178       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1179       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1180       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1181       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1182       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1183       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1184       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1185       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1186       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1187       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1188       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1189
1190       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1191       // when we have a 256bit-wide blend with immediate.
1192       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1193
1194       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1195       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1196       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1197       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1198       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1199       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1200       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1201
1202       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1203       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1204       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1205       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1206       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1207       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1208     } else {
1209       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1210       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1211       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1212       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1213
1214       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1215       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1216       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1217       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1218
1219       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1220       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1221       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1222       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1223
1224       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1225       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1226       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1227       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1228       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1229       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1230       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1231       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1232       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1233       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1234       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1235       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1236     }
1237
1238     // In the customized shift lowering, the legal cases in AVX2 will be
1239     // recognized.
1240     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1241     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1242
1243     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1244     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1245
1246     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1247     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1248
1249     // Custom lower several nodes for 256-bit types.
1250     for (MVT VT : MVT::vector_valuetypes()) {
1251       if (VT.getScalarSizeInBits() >= 32) {
1252         setOperationAction(ISD::MLOAD,  VT, Legal);
1253         setOperationAction(ISD::MSTORE, VT, Legal);
1254       }
1255       // Extract subvector is special because the value type
1256       // (result) is 128-bit but the source is 256-bit wide.
1257       if (VT.is128BitVector()) {
1258         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1259       }
1260       // Do not attempt to custom lower other non-256-bit vectors
1261       if (!VT.is256BitVector())
1262         continue;
1263
1264       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1265       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1266       setOperationAction(ISD::VSELECT,            VT, Custom);
1267       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1268       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1269       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1270       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1271       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1272     }
1273
1274     if (Subtarget->hasInt256())
1275       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1276
1277     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1278     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1279       setOperationAction(ISD::AND,    VT, Promote);
1280       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1281       setOperationAction(ISD::OR,     VT, Promote);
1282       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1283       setOperationAction(ISD::XOR,    VT, Promote);
1284       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1285       setOperationAction(ISD::LOAD,   VT, Promote);
1286       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1287       setOperationAction(ISD::SELECT, VT, Promote);
1288       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1289     }
1290   }
1291
1292   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1293     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1294     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1295     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1296     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1297
1298     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1299     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1300     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1301
1302     for (MVT VT : MVT::fp_vector_valuetypes())
1303       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1304
1305     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1306     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1307     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1308     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1309     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1310     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1311     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1312     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1313     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1314     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1315     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1316     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1317
1318     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1319     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1320     setOperationAction(ISD::SELECT_CC,          MVT::i1,    Expand);
1321     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1322     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1323     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1324     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1325     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1326     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1327     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1328     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1329     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1330     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1331     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1332
1333     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1334     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1335     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1336     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1337     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1338     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1339
1340     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1341     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1342     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1343     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1344     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1345     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1346     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1347     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1348
1349     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1350     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1351     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1352     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1353     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1354     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1355     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1356     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1357     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1358     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1359     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1360     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1361     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1362     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1363     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1364     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1365
1366     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1367     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1368     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1369     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1370     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1371     if (Subtarget->hasVLX()){
1372       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1373       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1374       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1375       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1376       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1377
1378       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1379       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1380       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1381       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1382       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1383     }
1384     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1385     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1386     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1387     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1388     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1389     if (Subtarget->hasDQI()) {
1390       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1391       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1392
1393       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1394       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1395       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1396       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1397       if (Subtarget->hasVLX()) {
1398         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1399         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1400         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1401         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1402         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1403         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1404         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1405         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1406       }
1407     }
1408     if (Subtarget->hasVLX()) {
1409       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1410       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1411       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1412       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1413       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1414       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1415       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1416       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1417     }
1418     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1419     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1420     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1421     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1422     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1423     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1424     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1425     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1426     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1427     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1428     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1429     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1430     if (Subtarget->hasDQI()) {
1431       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1432       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1433     }
1434     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1435     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1436     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1437     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1438     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1439     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1440     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1441     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1442     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1443     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1444
1445     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1446     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1447     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1448     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1449     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1450
1451     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1452     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1453
1454     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1455
1456     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1457     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1458     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1459     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1460     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1461     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1462     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1463     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1464     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1465     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1466     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1467
1468     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1469     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1470     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1471     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1472     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1473     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1474     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1475     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1476
1477     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1478     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1479
1480     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1481     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1482
1483     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1484
1485     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1486     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1487
1488     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1489     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1490
1491     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1492     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1493
1494     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1495     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1496     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1497     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1498     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1499     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1500
1501     if (Subtarget->hasCDI()) {
1502       setOperationAction(ISD::CTLZ,             MVT::v8i64,  Legal);
1503       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1504       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64,  Legal);
1505       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1506
1507       setOperationAction(ISD::CTLZ,             MVT::v8i16,  Custom);
1508       setOperationAction(ISD::CTLZ,             MVT::v16i8,  Custom);
1509       setOperationAction(ISD::CTLZ,             MVT::v16i16, Custom);
1510       setOperationAction(ISD::CTLZ,             MVT::v32i8,  Custom);
1511       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i16,  Custom);
1512       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i8,  Custom);
1513       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i16, Custom);
1514       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v32i8,  Custom);
1515
1516       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64,  Custom);
1517       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1518
1519       if (Subtarget->hasVLX()) {
1520         setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1521         setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1522         setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1523         setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1524         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1525         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1526         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1527         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1528
1529         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1530         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1531         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1532         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1533       } else {
1534         setOperationAction(ISD::CTLZ,             MVT::v4i64, Custom);
1535         setOperationAction(ISD::CTLZ,             MVT::v8i32, Custom);
1536         setOperationAction(ISD::CTLZ,             MVT::v2i64, Custom);
1537         setOperationAction(ISD::CTLZ,             MVT::v4i32, Custom);
1538         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1539         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1540         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1541         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1542       }
1543     } // Subtarget->hasCDI()
1544
1545     if (Subtarget->hasDQI()) {
1546       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1547       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1548       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1549     }
1550     // Custom lower several nodes.
1551     for (MVT VT : MVT::vector_valuetypes()) {
1552       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1553       if (EltSize == 1) {
1554         setOperationAction(ISD::AND, VT, Legal);
1555         setOperationAction(ISD::OR,  VT, Legal);
1556         setOperationAction(ISD::XOR,  VT, Legal);
1557       }
1558       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1559         setOperationAction(ISD::MGATHER,  VT, Custom);
1560         setOperationAction(ISD::MSCATTER, VT, Custom);
1561       }
1562       // Extract subvector is special because the value type
1563       // (result) is 256/128-bit but the source is 512-bit wide.
1564       if (VT.is128BitVector() || VT.is256BitVector()) {
1565         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1566       }
1567       if (VT.getVectorElementType() == MVT::i1)
1568         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1569
1570       // Do not attempt to custom lower other non-512-bit vectors
1571       if (!VT.is512BitVector())
1572         continue;
1573
1574       if (EltSize >= 32) {
1575         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1576         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1577         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1578         setOperationAction(ISD::VSELECT,             VT, Legal);
1579         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1580         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1581         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1582         setOperationAction(ISD::MLOAD,               VT, Legal);
1583         setOperationAction(ISD::MSTORE,              VT, Legal);
1584       }
1585     }
1586     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1587       setOperationAction(ISD::SELECT, VT, Promote);
1588       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1589     }
1590   }// has  AVX-512
1591
1592   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1593     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1594     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1595
1596     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1597     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1598
1599     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1600     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1601     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1602     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1603     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1604     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1605     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1606     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1607     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1608     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1609     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1610     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Legal);
1611     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Legal);
1612     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1613     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1614     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1615     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1616     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Custom);
1617     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Custom);
1618     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1619     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1620     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1621     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1622     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1623     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1624     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1625     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1626     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1627     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1628     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1629     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1630     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1631     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1632     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1633     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1634     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1635     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1636     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1637     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1638     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1639     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1640     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1641
1642     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1643     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1644     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1645     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1646     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1647     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1648     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1649     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1650
1651     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1652     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1653     if (Subtarget->hasVLX())
1654       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1655
1656     if (Subtarget->hasCDI()) {
1657       setOperationAction(ISD::CTLZ,            MVT::v32i16, Custom);
1658       setOperationAction(ISD::CTLZ,            MVT::v64i8,  Custom);
1659       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Custom);
1660       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8,  Custom);
1661     }
1662
1663     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1664       setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1665       setOperationAction(ISD::VSELECT,             VT, Legal);
1666     }
1667   }
1668
1669   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1670     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1671     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1672
1673     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1674     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1675     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1676     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1677     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1678     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1679     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1680     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1681     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1682     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1683     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1684     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1685
1686     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1687     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1688     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1689     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1690     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1691     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1692     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1693     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1694
1695     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1696     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1697     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1698     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1699     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1700     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1701     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1702     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1703   }
1704
1705   // We want to custom lower some of our intrinsics.
1706   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1707   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1708   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1709   if (!Subtarget->is64Bit())
1710     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1711
1712   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1713   // handle type legalization for these operations here.
1714   //
1715   // FIXME: We really should do custom legalization for addition and
1716   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1717   // than generic legalization for 64-bit multiplication-with-overflow, though.
1718   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1719     if (VT == MVT::i64 && !Subtarget->is64Bit())
1720       continue;
1721     // Add/Sub/Mul with overflow operations are custom lowered.
1722     setOperationAction(ISD::SADDO, VT, Custom);
1723     setOperationAction(ISD::UADDO, VT, Custom);
1724     setOperationAction(ISD::SSUBO, VT, Custom);
1725     setOperationAction(ISD::USUBO, VT, Custom);
1726     setOperationAction(ISD::SMULO, VT, Custom);
1727     setOperationAction(ISD::UMULO, VT, Custom);
1728   }
1729
1730   if (!Subtarget->is64Bit()) {
1731     // These libcalls are not available in 32-bit.
1732     setLibcallName(RTLIB::SHL_I128, nullptr);
1733     setLibcallName(RTLIB::SRL_I128, nullptr);
1734     setLibcallName(RTLIB::SRA_I128, nullptr);
1735   }
1736
1737   // Combine sin / cos into one node or libcall if possible.
1738   if (Subtarget->hasSinCos()) {
1739     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1740     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1741     if (Subtarget->isTargetDarwin()) {
1742       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1743       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1744       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1745       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1746     }
1747   }
1748
1749   if (Subtarget->isTargetWin64()) {
1750     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1751     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1752     setOperationAction(ISD::SREM, MVT::i128, Custom);
1753     setOperationAction(ISD::UREM, MVT::i128, Custom);
1754     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1755     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1756   }
1757
1758   // We have target-specific dag combine patterns for the following nodes:
1759   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1760   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1761   setTargetDAGCombine(ISD::BITCAST);
1762   setTargetDAGCombine(ISD::VSELECT);
1763   setTargetDAGCombine(ISD::SELECT);
1764   setTargetDAGCombine(ISD::SHL);
1765   setTargetDAGCombine(ISD::SRA);
1766   setTargetDAGCombine(ISD::SRL);
1767   setTargetDAGCombine(ISD::OR);
1768   setTargetDAGCombine(ISD::AND);
1769   setTargetDAGCombine(ISD::ADD);
1770   setTargetDAGCombine(ISD::FADD);
1771   setTargetDAGCombine(ISD::FSUB);
1772   setTargetDAGCombine(ISD::FMA);
1773   setTargetDAGCombine(ISD::SUB);
1774   setTargetDAGCombine(ISD::LOAD);
1775   setTargetDAGCombine(ISD::MLOAD);
1776   setTargetDAGCombine(ISD::STORE);
1777   setTargetDAGCombine(ISD::MSTORE);
1778   setTargetDAGCombine(ISD::ZERO_EXTEND);
1779   setTargetDAGCombine(ISD::ANY_EXTEND);
1780   setTargetDAGCombine(ISD::SIGN_EXTEND);
1781   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1782   setTargetDAGCombine(ISD::SINT_TO_FP);
1783   setTargetDAGCombine(ISD::UINT_TO_FP);
1784   setTargetDAGCombine(ISD::SETCC);
1785   setTargetDAGCombine(ISD::BUILD_VECTOR);
1786   setTargetDAGCombine(ISD::MUL);
1787   setTargetDAGCombine(ISD::XOR);
1788
1789   computeRegisterProperties(Subtarget->getRegisterInfo());
1790
1791   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1792   MaxStoresPerMemsetOptSize = 8;
1793   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1794   MaxStoresPerMemcpyOptSize = 4;
1795   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1796   MaxStoresPerMemmoveOptSize = 4;
1797   setPrefLoopAlignment(4); // 2^4 bytes.
1798
1799   // A predictable cmov does not hurt on an in-order CPU.
1800   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1801   PredictableSelectIsExpensive = !Subtarget->isAtom();
1802   EnableExtLdPromotion = true;
1803   setPrefFunctionAlignment(4); // 2^4 bytes.
1804
1805   verifyIntrinsicTables();
1806 }
1807
1808 // This has so far only been implemented for 64-bit MachO.
1809 bool X86TargetLowering::useLoadStackGuardNode() const {
1810   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1811 }
1812
1813 TargetLoweringBase::LegalizeTypeAction
1814 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1815   if (ExperimentalVectorWideningLegalization &&
1816       VT.getVectorNumElements() != 1 &&
1817       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1818     return TypeWidenVector;
1819
1820   return TargetLoweringBase::getPreferredVectorAction(VT);
1821 }
1822
1823 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1824                                           EVT VT) const {
1825   if (!VT.isVector())
1826     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1827
1828   const unsigned NumElts = VT.getVectorNumElements();
1829   const EVT EltVT = VT.getVectorElementType();
1830   if (VT.is512BitVector()) {
1831     if (Subtarget->hasAVX512())
1832       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1833           EltVT == MVT::f32 || EltVT == MVT::f64)
1834         switch(NumElts) {
1835         case  8: return MVT::v8i1;
1836         case 16: return MVT::v16i1;
1837       }
1838     if (Subtarget->hasBWI())
1839       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1840         switch(NumElts) {
1841         case 32: return MVT::v32i1;
1842         case 64: return MVT::v64i1;
1843       }
1844   }
1845
1846   if (VT.is256BitVector() || VT.is128BitVector()) {
1847     if (Subtarget->hasVLX())
1848       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1849           EltVT == MVT::f32 || EltVT == MVT::f64)
1850         switch(NumElts) {
1851         case 2: return MVT::v2i1;
1852         case 4: return MVT::v4i1;
1853         case 8: return MVT::v8i1;
1854       }
1855     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1856       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1857         switch(NumElts) {
1858         case  8: return MVT::v8i1;
1859         case 16: return MVT::v16i1;
1860         case 32: return MVT::v32i1;
1861       }
1862   }
1863
1864   return VT.changeVectorElementTypeToInteger();
1865 }
1866
1867 /// Helper for getByValTypeAlignment to determine
1868 /// the desired ByVal argument alignment.
1869 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1870   if (MaxAlign == 16)
1871     return;
1872   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1873     if (VTy->getBitWidth() == 128)
1874       MaxAlign = 16;
1875   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1876     unsigned EltAlign = 0;
1877     getMaxByValAlign(ATy->getElementType(), EltAlign);
1878     if (EltAlign > MaxAlign)
1879       MaxAlign = EltAlign;
1880   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1881     for (auto *EltTy : STy->elements()) {
1882       unsigned EltAlign = 0;
1883       getMaxByValAlign(EltTy, EltAlign);
1884       if (EltAlign > MaxAlign)
1885         MaxAlign = EltAlign;
1886       if (MaxAlign == 16)
1887         break;
1888     }
1889   }
1890 }
1891
1892 /// Return the desired alignment for ByVal aggregate
1893 /// function arguments in the caller parameter area. For X86, aggregates
1894 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1895 /// are at 4-byte boundaries.
1896 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1897                                                   const DataLayout &DL) const {
1898   if (Subtarget->is64Bit()) {
1899     // Max of 8 and alignment of type.
1900     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1901     if (TyAlign > 8)
1902       return TyAlign;
1903     return 8;
1904   }
1905
1906   unsigned Align = 4;
1907   if (Subtarget->hasSSE1())
1908     getMaxByValAlign(Ty, Align);
1909   return Align;
1910 }
1911
1912 /// Returns the target specific optimal type for load
1913 /// and store operations as a result of memset, memcpy, and memmove
1914 /// lowering. If DstAlign is zero that means it's safe to destination
1915 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1916 /// means there isn't a need to check it against alignment requirement,
1917 /// probably because the source does not need to be loaded. If 'IsMemset' is
1918 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1919 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1920 /// source is constant so it does not need to be loaded.
1921 /// It returns EVT::Other if the type should be determined using generic
1922 /// target-independent logic.
1923 EVT
1924 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1925                                        unsigned DstAlign, unsigned SrcAlign,
1926                                        bool IsMemset, bool ZeroMemset,
1927                                        bool MemcpyStrSrc,
1928                                        MachineFunction &MF) const {
1929   const Function *F = MF.getFunction();
1930   if ((!IsMemset || ZeroMemset) &&
1931       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1932     if (Size >= 16 &&
1933         (!Subtarget->isUnalignedMem16Slow() ||
1934          ((DstAlign == 0 || DstAlign >= 16) &&
1935           (SrcAlign == 0 || SrcAlign >= 16)))) {
1936       if (Size >= 32) {
1937         // FIXME: Check if unaligned 32-byte accesses are slow.
1938         if (Subtarget->hasInt256())
1939           return MVT::v8i32;
1940         if (Subtarget->hasFp256())
1941           return MVT::v8f32;
1942       }
1943       if (Subtarget->hasSSE2())
1944         return MVT::v4i32;
1945       if (Subtarget->hasSSE1())
1946         return MVT::v4f32;
1947     } else if (!MemcpyStrSrc && Size >= 8 &&
1948                !Subtarget->is64Bit() &&
1949                Subtarget->hasSSE2()) {
1950       // Do not use f64 to lower memcpy if source is string constant. It's
1951       // better to use i32 to avoid the loads.
1952       return MVT::f64;
1953     }
1954   }
1955   // This is a compromise. If we reach here, unaligned accesses may be slow on
1956   // this target. However, creating smaller, aligned accesses could be even
1957   // slower and would certainly be a lot more code.
1958   if (Subtarget->is64Bit() && Size >= 8)
1959     return MVT::i64;
1960   return MVT::i32;
1961 }
1962
1963 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1964   if (VT == MVT::f32)
1965     return X86ScalarSSEf32;
1966   else if (VT == MVT::f64)
1967     return X86ScalarSSEf64;
1968   return true;
1969 }
1970
1971 bool
1972 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1973                                                   unsigned,
1974                                                   unsigned,
1975                                                   bool *Fast) const {
1976   if (Fast) {
1977     switch (VT.getSizeInBits()) {
1978     default:
1979       // 8-byte and under are always assumed to be fast.
1980       *Fast = true;
1981       break;
1982     case 128:
1983       *Fast = !Subtarget->isUnalignedMem16Slow();
1984       break;
1985     case 256:
1986       *Fast = !Subtarget->isUnalignedMem32Slow();
1987       break;
1988     // TODO: What about AVX-512 (512-bit) accesses?
1989     }
1990   }
1991   // Misaligned accesses of any size are always allowed.
1992   return true;
1993 }
1994
1995 /// Return the entry encoding for a jump table in the
1996 /// current function.  The returned value is a member of the
1997 /// MachineJumpTableInfo::JTEntryKind enum.
1998 unsigned X86TargetLowering::getJumpTableEncoding() const {
1999   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2000   // symbol.
2001   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2002       Subtarget->isPICStyleGOT())
2003     return MachineJumpTableInfo::EK_Custom32;
2004
2005   // Otherwise, use the normal jump table encoding heuristics.
2006   return TargetLowering::getJumpTableEncoding();
2007 }
2008
2009 bool X86TargetLowering::useSoftFloat() const {
2010   return Subtarget->useSoftFloat();
2011 }
2012
2013 const MCExpr *
2014 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2015                                              const MachineBasicBlock *MBB,
2016                                              unsigned uid,MCContext &Ctx) const{
2017   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2018          Subtarget->isPICStyleGOT());
2019   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2020   // entries.
2021   return MCSymbolRefExpr::create(MBB->getSymbol(),
2022                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2023 }
2024
2025 /// Returns relocation base for the given PIC jumptable.
2026 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2027                                                     SelectionDAG &DAG) const {
2028   if (!Subtarget->is64Bit())
2029     // This doesn't have SDLoc associated with it, but is not really the
2030     // same as a Register.
2031     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2032                        getPointerTy(DAG.getDataLayout()));
2033   return Table;
2034 }
2035
2036 /// This returns the relocation base for the given PIC jumptable,
2037 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2038 const MCExpr *X86TargetLowering::
2039 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2040                              MCContext &Ctx) const {
2041   // X86-64 uses RIP relative addressing based on the jump table label.
2042   if (Subtarget->isPICStyleRIPRel())
2043     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2044
2045   // Otherwise, the reference is relative to the PIC base.
2046   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2047 }
2048
2049 std::pair<const TargetRegisterClass *, uint8_t>
2050 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2051                                            MVT VT) const {
2052   const TargetRegisterClass *RRC = nullptr;
2053   uint8_t Cost = 1;
2054   switch (VT.SimpleTy) {
2055   default:
2056     return TargetLowering::findRepresentativeClass(TRI, VT);
2057   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2058     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2059     break;
2060   case MVT::x86mmx:
2061     RRC = &X86::VR64RegClass;
2062     break;
2063   case MVT::f32: case MVT::f64:
2064   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2065   case MVT::v4f32: case MVT::v2f64:
2066   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2067   case MVT::v4f64:
2068     RRC = &X86::VR128RegClass;
2069     break;
2070   }
2071   return std::make_pair(RRC, Cost);
2072 }
2073
2074 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2075                                                unsigned &Offset) const {
2076   if (!Subtarget->isTargetLinux())
2077     return false;
2078
2079   if (Subtarget->is64Bit()) {
2080     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2081     Offset = 0x28;
2082     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2083       AddressSpace = 256;
2084     else
2085       AddressSpace = 257;
2086   } else {
2087     // %gs:0x14 on i386
2088     Offset = 0x14;
2089     AddressSpace = 256;
2090   }
2091   return true;
2092 }
2093
2094 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2095   if (!Subtarget->isTargetAndroid())
2096     return TargetLowering::getSafeStackPointerLocation(IRB);
2097
2098   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2099   // definition of TLS_SLOT_SAFESTACK in
2100   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2101   unsigned AddressSpace, Offset;
2102   if (Subtarget->is64Bit()) {
2103     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2104     Offset = 0x48;
2105     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2106       AddressSpace = 256;
2107     else
2108       AddressSpace = 257;
2109   } else {
2110     // %gs:0x24 on i386
2111     Offset = 0x24;
2112     AddressSpace = 256;
2113   }
2114
2115   return ConstantExpr::getIntToPtr(
2116       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2117       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2118 }
2119
2120 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2121                                             unsigned DestAS) const {
2122   assert(SrcAS != DestAS && "Expected different address spaces!");
2123
2124   return SrcAS < 256 && DestAS < 256;
2125 }
2126
2127 //===----------------------------------------------------------------------===//
2128 //               Return Value Calling Convention Implementation
2129 //===----------------------------------------------------------------------===//
2130
2131 #include "X86GenCallingConv.inc"
2132
2133 bool X86TargetLowering::CanLowerReturn(
2134     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2135     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2136   SmallVector<CCValAssign, 16> RVLocs;
2137   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2138   return CCInfo.CheckReturn(Outs, RetCC_X86);
2139 }
2140
2141 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2142   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2143   return ScratchRegs;
2144 }
2145
2146 SDValue
2147 X86TargetLowering::LowerReturn(SDValue Chain,
2148                                CallingConv::ID CallConv, bool isVarArg,
2149                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2150                                const SmallVectorImpl<SDValue> &OutVals,
2151                                SDLoc dl, SelectionDAG &DAG) const {
2152   MachineFunction &MF = DAG.getMachineFunction();
2153   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2154
2155   SmallVector<CCValAssign, 16> RVLocs;
2156   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2157   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2158
2159   SDValue Flag;
2160   SmallVector<SDValue, 6> RetOps;
2161   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2162   // Operand #1 = Bytes To Pop
2163   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2164                    MVT::i16));
2165
2166   // Copy the result values into the output registers.
2167   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2168     CCValAssign &VA = RVLocs[i];
2169     assert(VA.isRegLoc() && "Can only return in registers!");
2170     SDValue ValToCopy = OutVals[i];
2171     EVT ValVT = ValToCopy.getValueType();
2172
2173     // Promote values to the appropriate types.
2174     if (VA.getLocInfo() == CCValAssign::SExt)
2175       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2176     else if (VA.getLocInfo() == CCValAssign::ZExt)
2177       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2178     else if (VA.getLocInfo() == CCValAssign::AExt) {
2179       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2180         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2181       else
2182         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2183     }
2184     else if (VA.getLocInfo() == CCValAssign::BCvt)
2185       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2186
2187     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2188            "Unexpected FP-extend for return value.");
2189
2190     // If this is x86-64, and we disabled SSE, we can't return FP values,
2191     // or SSE or MMX vectors.
2192     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2193          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2194           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2195       report_fatal_error("SSE register return with SSE disabled");
2196     }
2197     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2198     // llvm-gcc has never done it right and no one has noticed, so this
2199     // should be OK for now.
2200     if (ValVT == MVT::f64 &&
2201         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2202       report_fatal_error("SSE2 register return with SSE2 disabled");
2203
2204     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2205     // the RET instruction and handled by the FP Stackifier.
2206     if (VA.getLocReg() == X86::FP0 ||
2207         VA.getLocReg() == X86::FP1) {
2208       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2209       // change the value to the FP stack register class.
2210       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2211         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2212       RetOps.push_back(ValToCopy);
2213       // Don't emit a copytoreg.
2214       continue;
2215     }
2216
2217     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2218     // which is returned in RAX / RDX.
2219     if (Subtarget->is64Bit()) {
2220       if (ValVT == MVT::x86mmx) {
2221         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2222           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2223           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2224                                   ValToCopy);
2225           // If we don't have SSE2 available, convert to v4f32 so the generated
2226           // register is legal.
2227           if (!Subtarget->hasSSE2())
2228             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2229         }
2230       }
2231     }
2232
2233     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2234     Flag = Chain.getValue(1);
2235     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2236   }
2237
2238   // All x86 ABIs require that for returning structs by value we copy
2239   // the sret argument into %rax/%eax (depending on ABI) for the return.
2240   // We saved the argument into a virtual register in the entry block,
2241   // so now we copy the value out and into %rax/%eax.
2242   //
2243   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2244   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2245   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2246   // either case FuncInfo->setSRetReturnReg() will have been called.
2247   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2248     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2249                                      getPointerTy(MF.getDataLayout()));
2250
2251     unsigned RetValReg
2252         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2253           X86::RAX : X86::EAX;
2254     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2255     Flag = Chain.getValue(1);
2256
2257     // RAX/EAX now acts like a return value.
2258     RetOps.push_back(
2259         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2260   }
2261
2262   RetOps[0] = Chain;  // Update chain.
2263
2264   // Add the flag if we have it.
2265   if (Flag.getNode())
2266     RetOps.push_back(Flag);
2267
2268   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2269 }
2270
2271 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2272   if (N->getNumValues() != 1)
2273     return false;
2274   if (!N->hasNUsesOfValue(1, 0))
2275     return false;
2276
2277   SDValue TCChain = Chain;
2278   SDNode *Copy = *N->use_begin();
2279   if (Copy->getOpcode() == ISD::CopyToReg) {
2280     // If the copy has a glue operand, we conservatively assume it isn't safe to
2281     // perform a tail call.
2282     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2283       return false;
2284     TCChain = Copy->getOperand(0);
2285   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2286     return false;
2287
2288   bool HasRet = false;
2289   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2290        UI != UE; ++UI) {
2291     if (UI->getOpcode() != X86ISD::RET_FLAG)
2292       return false;
2293     // If we are returning more than one value, we can definitely
2294     // not make a tail call see PR19530
2295     if (UI->getNumOperands() > 4)
2296       return false;
2297     if (UI->getNumOperands() == 4 &&
2298         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2299       return false;
2300     HasRet = true;
2301   }
2302
2303   if (!HasRet)
2304     return false;
2305
2306   Chain = TCChain;
2307   return true;
2308 }
2309
2310 EVT
2311 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2312                                             ISD::NodeType ExtendKind) const {
2313   MVT ReturnMVT;
2314   // TODO: Is this also valid on 32-bit?
2315   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2316     ReturnMVT = MVT::i8;
2317   else
2318     ReturnMVT = MVT::i32;
2319
2320   EVT MinVT = getRegisterType(Context, ReturnMVT);
2321   return VT.bitsLT(MinVT) ? MinVT : VT;
2322 }
2323
2324 /// Lower the result values of a call into the
2325 /// appropriate copies out of appropriate physical registers.
2326 ///
2327 SDValue
2328 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2329                                    CallingConv::ID CallConv, bool isVarArg,
2330                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2331                                    SDLoc dl, SelectionDAG &DAG,
2332                                    SmallVectorImpl<SDValue> &InVals) const {
2333
2334   // Assign locations to each value returned by this call.
2335   SmallVector<CCValAssign, 16> RVLocs;
2336   bool Is64Bit = Subtarget->is64Bit();
2337   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2338                  *DAG.getContext());
2339   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2340
2341   // Copy all of the result registers out of their specified physreg.
2342   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2343     CCValAssign &VA = RVLocs[i];
2344     EVT CopyVT = VA.getLocVT();
2345
2346     // If this is x86-64, and we disabled SSE, we can't return FP values
2347     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2348         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2349       report_fatal_error("SSE register return with SSE disabled");
2350     }
2351
2352     // If we prefer to use the value in xmm registers, copy it out as f80 and
2353     // use a truncate to move it from fp stack reg to xmm reg.
2354     bool RoundAfterCopy = false;
2355     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2356         isScalarFPTypeInSSEReg(VA.getValVT())) {
2357       CopyVT = MVT::f80;
2358       RoundAfterCopy = (CopyVT != VA.getLocVT());
2359     }
2360
2361     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2362                                CopyVT, InFlag).getValue(1);
2363     SDValue Val = Chain.getValue(0);
2364
2365     if (RoundAfterCopy)
2366       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2367                         // This truncation won't change the value.
2368                         DAG.getIntPtrConstant(1, dl));
2369
2370     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2371       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2372
2373     InFlag = Chain.getValue(2);
2374     InVals.push_back(Val);
2375   }
2376
2377   return Chain;
2378 }
2379
2380 //===----------------------------------------------------------------------===//
2381 //                C & StdCall & Fast Calling Convention implementation
2382 //===----------------------------------------------------------------------===//
2383 //  StdCall calling convention seems to be standard for many Windows' API
2384 //  routines and around. It differs from C calling convention just a little:
2385 //  callee should clean up the stack, not caller. Symbols should be also
2386 //  decorated in some fancy way :) It doesn't support any vector arguments.
2387 //  For info on fast calling convention see Fast Calling Convention (tail call)
2388 //  implementation LowerX86_32FastCCCallTo.
2389
2390 /// CallIsStructReturn - Determines whether a call uses struct return
2391 /// semantics.
2392 enum StructReturnType {
2393   NotStructReturn,
2394   RegStructReturn,
2395   StackStructReturn
2396 };
2397 static StructReturnType
2398 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2399   if (Outs.empty())
2400     return NotStructReturn;
2401
2402   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2403   if (!Flags.isSRet())
2404     return NotStructReturn;
2405   if (Flags.isInReg())
2406     return RegStructReturn;
2407   return StackStructReturn;
2408 }
2409
2410 /// Determines whether a function uses struct return semantics.
2411 static StructReturnType
2412 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2413   if (Ins.empty())
2414     return NotStructReturn;
2415
2416   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2417   if (!Flags.isSRet())
2418     return NotStructReturn;
2419   if (Flags.isInReg())
2420     return RegStructReturn;
2421   return StackStructReturn;
2422 }
2423
2424 /// Make a copy of an aggregate at address specified by "Src" to address
2425 /// "Dst" with size and alignment information specified by the specific
2426 /// parameter attribute. The copy will be passed as a byval function parameter.
2427 static SDValue
2428 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2429                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2430                           SDLoc dl) {
2431   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2432
2433   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2434                        /*isVolatile*/false, /*AlwaysInline=*/true,
2435                        /*isTailCall*/false,
2436                        MachinePointerInfo(), MachinePointerInfo());
2437 }
2438
2439 /// Return true if the calling convention is one that we can guarantee TCO for.
2440 static bool canGuaranteeTCO(CallingConv::ID CC) {
2441   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2442           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2443 }
2444
2445 /// Return true if we might ever do TCO for calls with this calling convention.
2446 static bool mayTailCallThisCC(CallingConv::ID CC) {
2447   switch (CC) {
2448   // C calling conventions:
2449   case CallingConv::C:
2450   case CallingConv::X86_64_Win64:
2451   case CallingConv::X86_64_SysV:
2452   // Callee pop conventions:
2453   case CallingConv::X86_ThisCall:
2454   case CallingConv::X86_StdCall:
2455   case CallingConv::X86_VectorCall:
2456   case CallingConv::X86_FastCall:
2457     return true;
2458   default:
2459     return canGuaranteeTCO(CC);
2460   }
2461 }
2462
2463 /// Return true if the function is being made into a tailcall target by
2464 /// changing its ABI.
2465 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2466   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2467 }
2468
2469 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2470   auto Attr =
2471       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2472   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2473     return false;
2474
2475   CallSite CS(CI);
2476   CallingConv::ID CalleeCC = CS.getCallingConv();
2477   if (!mayTailCallThisCC(CalleeCC))
2478     return false;
2479
2480   return true;
2481 }
2482
2483 SDValue
2484 X86TargetLowering::LowerMemArgument(SDValue Chain,
2485                                     CallingConv::ID CallConv,
2486                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2487                                     SDLoc dl, SelectionDAG &DAG,
2488                                     const CCValAssign &VA,
2489                                     MachineFrameInfo *MFI,
2490                                     unsigned i) const {
2491   // Create the nodes corresponding to a load from this parameter slot.
2492   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2493   bool AlwaysUseMutable = shouldGuaranteeTCO(
2494       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2495   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2496   EVT ValVT;
2497
2498   // If value is passed by pointer we have address passed instead of the value
2499   // itself.
2500   bool ExtendedInMem = VA.isExtInLoc() &&
2501     VA.getValVT().getScalarType() == MVT::i1;
2502
2503   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2504     ValVT = VA.getLocVT();
2505   else
2506     ValVT = VA.getValVT();
2507
2508   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2509   // changed with more analysis.
2510   // In case of tail call optimization mark all arguments mutable. Since they
2511   // could be overwritten by lowering of arguments in case of a tail call.
2512   if (Flags.isByVal()) {
2513     unsigned Bytes = Flags.getByValSize();
2514     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2515     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2516     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2517   } else {
2518     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2519                                     VA.getLocMemOffset(), isImmutable);
2520     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2521     SDValue Val = DAG.getLoad(
2522         ValVT, dl, Chain, FIN,
2523         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2524         false, false, 0);
2525     return ExtendedInMem ?
2526       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2527   }
2528 }
2529
2530 // FIXME: Get this from tablegen.
2531 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2532                                                 const X86Subtarget *Subtarget) {
2533   assert(Subtarget->is64Bit());
2534
2535   if (Subtarget->isCallingConvWin64(CallConv)) {
2536     static const MCPhysReg GPR64ArgRegsWin64[] = {
2537       X86::RCX, X86::RDX, X86::R8,  X86::R9
2538     };
2539     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2540   }
2541
2542   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2543     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2544   };
2545   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2546 }
2547
2548 // FIXME: Get this from tablegen.
2549 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2550                                                 CallingConv::ID CallConv,
2551                                                 const X86Subtarget *Subtarget) {
2552   assert(Subtarget->is64Bit());
2553   if (Subtarget->isCallingConvWin64(CallConv)) {
2554     // The XMM registers which might contain var arg parameters are shadowed
2555     // in their paired GPR.  So we only need to save the GPR to their home
2556     // slots.
2557     // TODO: __vectorcall will change this.
2558     return None;
2559   }
2560
2561   const Function *Fn = MF.getFunction();
2562   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2563   bool isSoftFloat = Subtarget->useSoftFloat();
2564   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2565          "SSE register cannot be used when SSE is disabled!");
2566   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2567     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2568     // registers.
2569     return None;
2570
2571   static const MCPhysReg XMMArgRegs64Bit[] = {
2572     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2573     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2574   };
2575   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2576 }
2577
2578 SDValue X86TargetLowering::LowerFormalArguments(
2579     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2580     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2581     SmallVectorImpl<SDValue> &InVals) const {
2582   MachineFunction &MF = DAG.getMachineFunction();
2583   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2584   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2585
2586   const Function* Fn = MF.getFunction();
2587   if (Fn->hasExternalLinkage() &&
2588       Subtarget->isTargetCygMing() &&
2589       Fn->getName() == "main")
2590     FuncInfo->setForceFramePointer(true);
2591
2592   MachineFrameInfo *MFI = MF.getFrameInfo();
2593   bool Is64Bit = Subtarget->is64Bit();
2594   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2595
2596   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2597          "Var args not supported with calling convention fastcc, ghc or hipe");
2598
2599   // Assign locations to all of the incoming arguments.
2600   SmallVector<CCValAssign, 16> ArgLocs;
2601   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2602
2603   // Allocate shadow area for Win64
2604   if (IsWin64)
2605     CCInfo.AllocateStack(32, 8);
2606
2607   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2608
2609   unsigned LastVal = ~0U;
2610   SDValue ArgValue;
2611   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2612     CCValAssign &VA = ArgLocs[i];
2613     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2614     // places.
2615     assert(VA.getValNo() != LastVal &&
2616            "Don't support value assigned to multiple locs yet");
2617     (void)LastVal;
2618     LastVal = VA.getValNo();
2619
2620     if (VA.isRegLoc()) {
2621       EVT RegVT = VA.getLocVT();
2622       const TargetRegisterClass *RC;
2623       if (RegVT == MVT::i32)
2624         RC = &X86::GR32RegClass;
2625       else if (Is64Bit && RegVT == MVT::i64)
2626         RC = &X86::GR64RegClass;
2627       else if (RegVT == MVT::f32)
2628         RC = &X86::FR32RegClass;
2629       else if (RegVT == MVT::f64)
2630         RC = &X86::FR64RegClass;
2631       else if (RegVT.is512BitVector())
2632         RC = &X86::VR512RegClass;
2633       else if (RegVT.is256BitVector())
2634         RC = &X86::VR256RegClass;
2635       else if (RegVT.is128BitVector())
2636         RC = &X86::VR128RegClass;
2637       else if (RegVT == MVT::x86mmx)
2638         RC = &X86::VR64RegClass;
2639       else if (RegVT == MVT::i1)
2640         RC = &X86::VK1RegClass;
2641       else if (RegVT == MVT::v8i1)
2642         RC = &X86::VK8RegClass;
2643       else if (RegVT == MVT::v16i1)
2644         RC = &X86::VK16RegClass;
2645       else if (RegVT == MVT::v32i1)
2646         RC = &X86::VK32RegClass;
2647       else if (RegVT == MVT::v64i1)
2648         RC = &X86::VK64RegClass;
2649       else
2650         llvm_unreachable("Unknown argument type!");
2651
2652       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2653       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2654
2655       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2656       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2657       // right size.
2658       if (VA.getLocInfo() == CCValAssign::SExt)
2659         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2660                                DAG.getValueType(VA.getValVT()));
2661       else if (VA.getLocInfo() == CCValAssign::ZExt)
2662         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2663                                DAG.getValueType(VA.getValVT()));
2664       else if (VA.getLocInfo() == CCValAssign::BCvt)
2665         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2666
2667       if (VA.isExtInLoc()) {
2668         // Handle MMX values passed in XMM regs.
2669         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2670           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2671         else
2672           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2673       }
2674     } else {
2675       assert(VA.isMemLoc());
2676       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2677     }
2678
2679     // If value is passed via pointer - do a load.
2680     if (VA.getLocInfo() == CCValAssign::Indirect)
2681       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2682                              MachinePointerInfo(), false, false, false, 0);
2683
2684     InVals.push_back(ArgValue);
2685   }
2686
2687   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2688     // All x86 ABIs require that for returning structs by value we copy the
2689     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2690     // the argument into a virtual register so that we can access it from the
2691     // return points.
2692     if (Ins[i].Flags.isSRet()) {
2693       unsigned Reg = FuncInfo->getSRetReturnReg();
2694       if (!Reg) {
2695         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2696         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2697         FuncInfo->setSRetReturnReg(Reg);
2698       }
2699       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2700       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2701       break;
2702     }
2703   }
2704
2705   unsigned StackSize = CCInfo.getNextStackOffset();
2706   // Align stack specially for tail calls.
2707   if (shouldGuaranteeTCO(CallConv,
2708                          MF.getTarget().Options.GuaranteedTailCallOpt))
2709     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2710
2711   // If the function takes variable number of arguments, make a frame index for
2712   // the start of the first vararg value... for expansion of llvm.va_start. We
2713   // can skip this if there are no va_start calls.
2714   if (MFI->hasVAStart() &&
2715       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2716                    CallConv != CallingConv::X86_ThisCall))) {
2717     FuncInfo->setVarArgsFrameIndex(
2718         MFI->CreateFixedObject(1, StackSize, true));
2719   }
2720
2721   MachineModuleInfo &MMI = MF.getMMI();
2722
2723   // Figure out if XMM registers are in use.
2724   assert(!(Subtarget->useSoftFloat() &&
2725            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2726          "SSE register cannot be used when SSE is disabled!");
2727
2728   // 64-bit calling conventions support varargs and register parameters, so we
2729   // have to do extra work to spill them in the prologue.
2730   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2731     // Find the first unallocated argument registers.
2732     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2733     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2734     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2735     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2736     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2737            "SSE register cannot be used when SSE is disabled!");
2738
2739     // Gather all the live in physical registers.
2740     SmallVector<SDValue, 6> LiveGPRs;
2741     SmallVector<SDValue, 8> LiveXMMRegs;
2742     SDValue ALVal;
2743     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2744       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2745       LiveGPRs.push_back(
2746           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2747     }
2748     if (!ArgXMMs.empty()) {
2749       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2750       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2751       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2752         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2753         LiveXMMRegs.push_back(
2754             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2755       }
2756     }
2757
2758     if (IsWin64) {
2759       // Get to the caller-allocated home save location.  Add 8 to account
2760       // for the return address.
2761       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2762       FuncInfo->setRegSaveFrameIndex(
2763           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2764       // Fixup to set vararg frame on shadow area (4 x i64).
2765       if (NumIntRegs < 4)
2766         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2767     } else {
2768       // For X86-64, if there are vararg parameters that are passed via
2769       // registers, then we must store them to their spots on the stack so
2770       // they may be loaded by deferencing the result of va_next.
2771       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2772       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2773       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2774           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2775     }
2776
2777     // Store the integer parameter registers.
2778     SmallVector<SDValue, 8> MemOps;
2779     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2780                                       getPointerTy(DAG.getDataLayout()));
2781     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2782     for (SDValue Val : LiveGPRs) {
2783       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2784                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2785       SDValue Store =
2786           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2787                        MachinePointerInfo::getFixedStack(
2788                            DAG.getMachineFunction(),
2789                            FuncInfo->getRegSaveFrameIndex(), Offset),
2790                        false, false, 0);
2791       MemOps.push_back(Store);
2792       Offset += 8;
2793     }
2794
2795     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2796       // Now store the XMM (fp + vector) parameter registers.
2797       SmallVector<SDValue, 12> SaveXMMOps;
2798       SaveXMMOps.push_back(Chain);
2799       SaveXMMOps.push_back(ALVal);
2800       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2801                              FuncInfo->getRegSaveFrameIndex(), dl));
2802       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2803                              FuncInfo->getVarArgsFPOffset(), dl));
2804       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2805                         LiveXMMRegs.end());
2806       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2807                                    MVT::Other, SaveXMMOps));
2808     }
2809
2810     if (!MemOps.empty())
2811       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2812   }
2813
2814   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2815     // Find the largest legal vector type.
2816     MVT VecVT = MVT::Other;
2817     // FIXME: Only some x86_32 calling conventions support AVX512.
2818     if (Subtarget->hasAVX512() &&
2819         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2820                      CallConv == CallingConv::Intel_OCL_BI)))
2821       VecVT = MVT::v16f32;
2822     else if (Subtarget->hasAVX())
2823       VecVT = MVT::v8f32;
2824     else if (Subtarget->hasSSE2())
2825       VecVT = MVT::v4f32;
2826
2827     // We forward some GPRs and some vector types.
2828     SmallVector<MVT, 2> RegParmTypes;
2829     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2830     RegParmTypes.push_back(IntVT);
2831     if (VecVT != MVT::Other)
2832       RegParmTypes.push_back(VecVT);
2833
2834     // Compute the set of forwarded registers. The rest are scratch.
2835     SmallVectorImpl<ForwardedRegister> &Forwards =
2836         FuncInfo->getForwardedMustTailRegParms();
2837     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2838
2839     // Conservatively forward AL on x86_64, since it might be used for varargs.
2840     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2841       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2842       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2843     }
2844
2845     // Copy all forwards from physical to virtual registers.
2846     for (ForwardedRegister &F : Forwards) {
2847       // FIXME: Can we use a less constrained schedule?
2848       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2849       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2850       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2851     }
2852   }
2853
2854   // Some CCs need callee pop.
2855   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2856                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2857     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2858   } else {
2859     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2860     // If this is an sret function, the return should pop the hidden pointer.
2861     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2862         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2863         argsAreStructReturn(Ins) == StackStructReturn)
2864       FuncInfo->setBytesToPopOnReturn(4);
2865   }
2866
2867   if (!Is64Bit) {
2868     // RegSaveFrameIndex is X86-64 only.
2869     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2870     if (CallConv == CallingConv::X86_FastCall ||
2871         CallConv == CallingConv::X86_ThisCall)
2872       // fastcc functions can't have varargs.
2873       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2874   }
2875
2876   FuncInfo->setArgumentStackSize(StackSize);
2877
2878   if (MMI.hasWinEHFuncInfo(Fn)) {
2879     if (Is64Bit) {
2880       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2881       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2882       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2883       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2884       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2885                            MachinePointerInfo::getFixedStack(
2886                                DAG.getMachineFunction(), UnwindHelpFI),
2887                            /*isVolatile=*/true,
2888                            /*isNonTemporal=*/false, /*Alignment=*/0);
2889     } else {
2890       // Functions using Win32 EH are considered to have opaque SP adjustments
2891       // to force local variables to be addressed from the frame or base
2892       // pointers.
2893       MFI->setHasOpaqueSPAdjustment(true);
2894     }
2895   }
2896
2897   return Chain;
2898 }
2899
2900 SDValue
2901 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2902                                     SDValue StackPtr, SDValue Arg,
2903                                     SDLoc dl, SelectionDAG &DAG,
2904                                     const CCValAssign &VA,
2905                                     ISD::ArgFlagsTy Flags) const {
2906   unsigned LocMemOffset = VA.getLocMemOffset();
2907   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2908   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2909                        StackPtr, PtrOff);
2910   if (Flags.isByVal())
2911     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2912
2913   return DAG.getStore(
2914       Chain, dl, Arg, PtrOff,
2915       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2916       false, false, 0);
2917 }
2918
2919 /// Emit a load of return address if tail call
2920 /// optimization is performed and it is required.
2921 SDValue
2922 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2923                                            SDValue &OutRetAddr, SDValue Chain,
2924                                            bool IsTailCall, bool Is64Bit,
2925                                            int FPDiff, SDLoc dl) const {
2926   // Adjust the Return address stack slot.
2927   EVT VT = getPointerTy(DAG.getDataLayout());
2928   OutRetAddr = getReturnAddressFrameIndex(DAG);
2929
2930   // Load the "old" Return address.
2931   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2932                            false, false, false, 0);
2933   return SDValue(OutRetAddr.getNode(), 1);
2934 }
2935
2936 /// Emit a store of the return address if tail call
2937 /// optimization is performed and it is required (FPDiff!=0).
2938 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2939                                         SDValue Chain, SDValue RetAddrFrIdx,
2940                                         EVT PtrVT, unsigned SlotSize,
2941                                         int FPDiff, SDLoc dl) {
2942   // Store the return address to the appropriate stack slot.
2943   if (!FPDiff) return Chain;
2944   // Calculate the new stack slot for the return address.
2945   int NewReturnAddrFI =
2946     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2947                                          false);
2948   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2949   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2950                        MachinePointerInfo::getFixedStack(
2951                            DAG.getMachineFunction(), NewReturnAddrFI),
2952                        false, false, 0);
2953   return Chain;
2954 }
2955
2956 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2957 /// operation of specified width.
2958 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2959                        SDValue V2) {
2960   unsigned NumElems = VT.getVectorNumElements();
2961   SmallVector<int, 8> Mask;
2962   Mask.push_back(NumElems);
2963   for (unsigned i = 1; i != NumElems; ++i)
2964     Mask.push_back(i);
2965   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2966 }
2967
2968 SDValue
2969 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2970                              SmallVectorImpl<SDValue> &InVals) const {
2971   SelectionDAG &DAG                     = CLI.DAG;
2972   SDLoc &dl                             = CLI.DL;
2973   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2974   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2975   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2976   SDValue Chain                         = CLI.Chain;
2977   SDValue Callee                        = CLI.Callee;
2978   CallingConv::ID CallConv              = CLI.CallConv;
2979   bool &isTailCall                      = CLI.IsTailCall;
2980   bool isVarArg                         = CLI.IsVarArg;
2981
2982   MachineFunction &MF = DAG.getMachineFunction();
2983   bool Is64Bit        = Subtarget->is64Bit();
2984   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2985   StructReturnType SR = callIsStructReturn(Outs);
2986   bool IsSibcall      = false;
2987   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2988   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2989
2990   if (Attr.getValueAsString() == "true")
2991     isTailCall = false;
2992
2993   if (Subtarget->isPICStyleGOT() &&
2994       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2995     // If we are using a GOT, disable tail calls to external symbols with
2996     // default visibility. Tail calling such a symbol requires using a GOT
2997     // relocation, which forces early binding of the symbol. This breaks code
2998     // that require lazy function symbol resolution. Using musttail or
2999     // GuaranteedTailCallOpt will override this.
3000     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3001     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3002                G->getGlobal()->hasDefaultVisibility()))
3003       isTailCall = false;
3004   }
3005
3006   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3007   if (IsMustTail) {
3008     // Force this to be a tail call.  The verifier rules are enough to ensure
3009     // that we can lower this successfully without moving the return address
3010     // around.
3011     isTailCall = true;
3012   } else if (isTailCall) {
3013     // Check if it's really possible to do a tail call.
3014     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3015                     isVarArg, SR != NotStructReturn,
3016                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3017                     Outs, OutVals, Ins, DAG);
3018
3019     // Sibcalls are automatically detected tailcalls which do not require
3020     // ABI changes.
3021     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3022       IsSibcall = true;
3023
3024     if (isTailCall)
3025       ++NumTailCalls;
3026   }
3027
3028   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3029          "Var args not supported with calling convention fastcc, ghc or hipe");
3030
3031   // Analyze operands of the call, assigning locations to each operand.
3032   SmallVector<CCValAssign, 16> ArgLocs;
3033   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3034
3035   // Allocate shadow area for Win64
3036   if (IsWin64)
3037     CCInfo.AllocateStack(32, 8);
3038
3039   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3040
3041   // Get a count of how many bytes are to be pushed on the stack.
3042   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3043   if (IsSibcall)
3044     // This is a sibcall. The memory operands are available in caller's
3045     // own caller's stack.
3046     NumBytes = 0;
3047   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3048            canGuaranteeTCO(CallConv))
3049     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3050
3051   int FPDiff = 0;
3052   if (isTailCall && !IsSibcall && !IsMustTail) {
3053     // Lower arguments at fp - stackoffset + fpdiff.
3054     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3055
3056     FPDiff = NumBytesCallerPushed - NumBytes;
3057
3058     // Set the delta of movement of the returnaddr stackslot.
3059     // But only set if delta is greater than previous delta.
3060     if (FPDiff < X86Info->getTCReturnAddrDelta())
3061       X86Info->setTCReturnAddrDelta(FPDiff);
3062   }
3063
3064   unsigned NumBytesToPush = NumBytes;
3065   unsigned NumBytesToPop = NumBytes;
3066
3067   // If we have an inalloca argument, all stack space has already been allocated
3068   // for us and be right at the top of the stack.  We don't support multiple
3069   // arguments passed in memory when using inalloca.
3070   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3071     NumBytesToPush = 0;
3072     if (!ArgLocs.back().isMemLoc())
3073       report_fatal_error("cannot use inalloca attribute on a register "
3074                          "parameter");
3075     if (ArgLocs.back().getLocMemOffset() != 0)
3076       report_fatal_error("any parameter with the inalloca attribute must be "
3077                          "the only memory argument");
3078   }
3079
3080   if (!IsSibcall)
3081     Chain = DAG.getCALLSEQ_START(
3082         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3083
3084   SDValue RetAddrFrIdx;
3085   // Load return address for tail calls.
3086   if (isTailCall && FPDiff)
3087     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3088                                     Is64Bit, FPDiff, dl);
3089
3090   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3091   SmallVector<SDValue, 8> MemOpChains;
3092   SDValue StackPtr;
3093
3094   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3095   // of tail call optimization arguments are handle later.
3096   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3097   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3098     // Skip inalloca arguments, they have already been written.
3099     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3100     if (Flags.isInAlloca())
3101       continue;
3102
3103     CCValAssign &VA = ArgLocs[i];
3104     EVT RegVT = VA.getLocVT();
3105     SDValue Arg = OutVals[i];
3106     bool isByVal = Flags.isByVal();
3107
3108     // Promote the value if needed.
3109     switch (VA.getLocInfo()) {
3110     default: llvm_unreachable("Unknown loc info!");
3111     case CCValAssign::Full: break;
3112     case CCValAssign::SExt:
3113       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3114       break;
3115     case CCValAssign::ZExt:
3116       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3117       break;
3118     case CCValAssign::AExt:
3119       if (Arg.getValueType().isVector() &&
3120           Arg.getValueType().getScalarType() == MVT::i1)
3121         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3122       else if (RegVT.is128BitVector()) {
3123         // Special case: passing MMX values in XMM registers.
3124         Arg = DAG.getBitcast(MVT::i64, Arg);
3125         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3126         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3127       } else
3128         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3129       break;
3130     case CCValAssign::BCvt:
3131       Arg = DAG.getBitcast(RegVT, Arg);
3132       break;
3133     case CCValAssign::Indirect: {
3134       // Store the argument.
3135       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3136       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3137       Chain = DAG.getStore(
3138           Chain, dl, Arg, SpillSlot,
3139           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3140           false, false, 0);
3141       Arg = SpillSlot;
3142       break;
3143     }
3144     }
3145
3146     if (VA.isRegLoc()) {
3147       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3148       if (isVarArg && IsWin64) {
3149         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3150         // shadow reg if callee is a varargs function.
3151         unsigned ShadowReg = 0;
3152         switch (VA.getLocReg()) {
3153         case X86::XMM0: ShadowReg = X86::RCX; break;
3154         case X86::XMM1: ShadowReg = X86::RDX; break;
3155         case X86::XMM2: ShadowReg = X86::R8; break;
3156         case X86::XMM3: ShadowReg = X86::R9; break;
3157         }
3158         if (ShadowReg)
3159           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3160       }
3161     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3162       assert(VA.isMemLoc());
3163       if (!StackPtr.getNode())
3164         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3165                                       getPointerTy(DAG.getDataLayout()));
3166       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3167                                              dl, DAG, VA, Flags));
3168     }
3169   }
3170
3171   if (!MemOpChains.empty())
3172     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3173
3174   if (Subtarget->isPICStyleGOT()) {
3175     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3176     // GOT pointer.
3177     if (!isTailCall) {
3178       RegsToPass.push_back(std::make_pair(
3179           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3180                                           getPointerTy(DAG.getDataLayout()))));
3181     } else {
3182       // If we are tail calling and generating PIC/GOT style code load the
3183       // address of the callee into ECX. The value in ecx is used as target of
3184       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3185       // for tail calls on PIC/GOT architectures. Normally we would just put the
3186       // address of GOT into ebx and then call target@PLT. But for tail calls
3187       // ebx would be restored (since ebx is callee saved) before jumping to the
3188       // target@PLT.
3189
3190       // Note: The actual moving to ECX is done further down.
3191       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3192       if (G && !G->getGlobal()->hasLocalLinkage() &&
3193           G->getGlobal()->hasDefaultVisibility())
3194         Callee = LowerGlobalAddress(Callee, DAG);
3195       else if (isa<ExternalSymbolSDNode>(Callee))
3196         Callee = LowerExternalSymbol(Callee, DAG);
3197     }
3198   }
3199
3200   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3201     // From AMD64 ABI document:
3202     // For calls that may call functions that use varargs or stdargs
3203     // (prototype-less calls or calls to functions containing ellipsis (...) in
3204     // the declaration) %al is used as hidden argument to specify the number
3205     // of SSE registers used. The contents of %al do not need to match exactly
3206     // the number of registers, but must be an ubound on the number of SSE
3207     // registers used and is in the range 0 - 8 inclusive.
3208
3209     // Count the number of XMM registers allocated.
3210     static const MCPhysReg XMMArgRegs[] = {
3211       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3212       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3213     };
3214     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3215     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3216            && "SSE registers cannot be used when SSE is disabled");
3217
3218     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3219                                         DAG.getConstant(NumXMMRegs, dl,
3220                                                         MVT::i8)));
3221   }
3222
3223   if (isVarArg && IsMustTail) {
3224     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3225     for (const auto &F : Forwards) {
3226       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3227       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3228     }
3229   }
3230
3231   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3232   // don't need this because the eligibility check rejects calls that require
3233   // shuffling arguments passed in memory.
3234   if (!IsSibcall && isTailCall) {
3235     // Force all the incoming stack arguments to be loaded from the stack
3236     // before any new outgoing arguments are stored to the stack, because the
3237     // outgoing stack slots may alias the incoming argument stack slots, and
3238     // the alias isn't otherwise explicit. This is slightly more conservative
3239     // than necessary, because it means that each store effectively depends
3240     // on every argument instead of just those arguments it would clobber.
3241     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3242
3243     SmallVector<SDValue, 8> MemOpChains2;
3244     SDValue FIN;
3245     int FI = 0;
3246     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3247       CCValAssign &VA = ArgLocs[i];
3248       if (VA.isRegLoc())
3249         continue;
3250       assert(VA.isMemLoc());
3251       SDValue Arg = OutVals[i];
3252       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3253       // Skip inalloca arguments.  They don't require any work.
3254       if (Flags.isInAlloca())
3255         continue;
3256       // Create frame index.
3257       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3258       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3259       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3260       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3261
3262       if (Flags.isByVal()) {
3263         // Copy relative to framepointer.
3264         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3265         if (!StackPtr.getNode())
3266           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3267                                         getPointerTy(DAG.getDataLayout()));
3268         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3269                              StackPtr, Source);
3270
3271         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3272                                                          ArgChain,
3273