70a5c0c28297d7d4cdc2bfb23ec3c9aab2067f76
[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 (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
862       MVT VT = (MVT::SimpleValueType)i;
863       // Do not attempt to custom lower non-power-of-2 vectors
864       if (!isPowerOf2_32(VT.getVectorNumElements()))
865         continue;
866       // Do not attempt to custom lower non-128-bit vectors
867       if (!VT.is128BitVector())
868         continue;
869       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
870       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
871       setOperationAction(ISD::VSELECT,            VT, Custom);
872       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
873     }
874
875     // We support custom legalizing of sext and anyext loads for specific
876     // memory vector types which we can load as a scalar (or sequence of
877     // scalars) and extend in-register to a legal 128-bit vector type. For sext
878     // loads these must work with a single scalar load.
879     for (MVT VT : MVT::integer_vector_valuetypes()) {
880       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
881       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
882       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
883       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
884       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
885       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
886       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
887       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
888       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
889     }
890
891     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
892     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
893     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
894     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
895     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
896     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
897     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
898     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
899
900     if (Subtarget->is64Bit()) {
901       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
902       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
903     }
904
905     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
906     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
907       MVT VT = (MVT::SimpleValueType)i;
908
909       // Do not attempt to promote non-128-bit vectors
910       if (!VT.is128BitVector())
911         continue;
912
913       setOperationAction(ISD::AND,    VT, Promote);
914       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
915       setOperationAction(ISD::OR,     VT, Promote);
916       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
917       setOperationAction(ISD::XOR,    VT, Promote);
918       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
919       setOperationAction(ISD::LOAD,   VT, Promote);
920       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
921       setOperationAction(ISD::SELECT, VT, Promote);
922       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
923     }
924
925     // Custom lower v2i64 and v2f64 selects.
926     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
927     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
928     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
929     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
930
931     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
932     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
933
934     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
935
936     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
937     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
938     // As there is no 64-bit GPR available, we need build a special custom
939     // sequence to convert from v2i32 to v2f32.
940     if (!Subtarget->is64Bit())
941       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
942
943     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
944     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
945
946     for (MVT VT : MVT::fp_vector_valuetypes())
947       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
948
949     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
950     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
951     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
952   }
953
954   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
955     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
956       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
957       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
958       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
959       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
960       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
961     }
962
963     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
964     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
965     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
966     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
967     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
968     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
969     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
970     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
971
972     // FIXME: Do we need to handle scalar-to-vector here?
973     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
974
975     // We directly match byte blends in the backend as they match the VSELECT
976     // condition form.
977     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
978
979     // SSE41 brings specific instructions for doing vector sign extend even in
980     // cases where we don't have SRA.
981     for (MVT VT : MVT::integer_vector_valuetypes()) {
982       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
983       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
984       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
985     }
986
987     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
988     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
989     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
990     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
991     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
992     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
993     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
994
995     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
996     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
997     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
998     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
999     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1000     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1001
1002     // i8 and i16 vectors are custom because the source register and source
1003     // source memory operand types are not the same width.  f32 vectors are
1004     // custom since the immediate controlling the insert encodes additional
1005     // information.
1006     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1007     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1008     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1009     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1010
1011     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1012     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1013     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1014     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1015
1016     // FIXME: these should be Legal, but that's only for the case where
1017     // the index is constant.  For now custom expand to deal with that.
1018     if (Subtarget->is64Bit()) {
1019       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1020       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1021     }
1022   }
1023
1024   if (Subtarget->hasSSE2()) {
1025     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1026     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1027     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1028
1029     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1030     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1031
1032     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1033     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1034
1035     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1036     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1037
1038     // In the customized shift lowering, the legal cases in AVX2 will be
1039     // recognized.
1040     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1041     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1042
1043     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1044     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1045
1046     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1047     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1048   }
1049
1050   if (Subtarget->hasXOP()) {
1051     setOperationAction(ISD::ROTL,              MVT::v16i8, Custom);
1052     setOperationAction(ISD::ROTL,              MVT::v8i16, Custom);
1053     setOperationAction(ISD::ROTL,              MVT::v4i32, Custom);
1054     setOperationAction(ISD::ROTL,              MVT::v2i64, Custom);
1055     setOperationAction(ISD::ROTL,              MVT::v32i8, Custom);
1056     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1057     setOperationAction(ISD::ROTL,              MVT::v8i32, Custom);
1058     setOperationAction(ISD::ROTL,              MVT::v4i64, Custom);
1059   }
1060
1061   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1062     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1063     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1064     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1065     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1066     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1067     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1068
1069     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1070     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1071     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1072
1073     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1074     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1075     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1076     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1077     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1078     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1079     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1080     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1081     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1082     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1083     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1084     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1085
1086     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1087     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1088     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1089     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1090     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1091     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1092     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1093     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1094     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1095     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1096     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1097     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1098
1099     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1100     // even though v8i16 is a legal type.
1101     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1102     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1103     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1104
1105     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1106     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1107     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1108
1109     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1110     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1111
1112     for (MVT VT : MVT::fp_vector_valuetypes())
1113       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1114
1115     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1116     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1117
1118     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1119     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1120
1121     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1122     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1123
1124     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1125     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1126     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1127     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1128
1129     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1130     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1131     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1132
1133     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1134     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1135     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1136     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1137     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1138     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1139     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1140     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1141     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1142     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1143     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1144     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1145
1146     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1147     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1148     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1149     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1150
1151     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1152     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1153     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1154     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1155     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1156     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1157     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1158     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1159
1160     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1161       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1162       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1163       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1164       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1165       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1166       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1167     }
1168
1169     if (Subtarget->hasInt256()) {
1170       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1171       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1172       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1173       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1174
1175       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1176       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1177       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1178       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1179
1180       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1181       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1182       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1183       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1184
1185       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1186       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1187       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1188       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1189
1190       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1191       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1192       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1193       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1194       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1195       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1196       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1197       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1198       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1199       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1200       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1201       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1202
1203       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1204       // when we have a 256bit-wide blend with immediate.
1205       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1206
1207       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1208       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1209       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1210       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1211       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1212       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1213       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1214
1215       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1216       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1217       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1218       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1219       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1220       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1221     } else {
1222       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1223       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1224       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1225       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1226
1227       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1228       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1229       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1230       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1231
1232       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1233       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1234       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1235       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1236
1237       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1238       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1239       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1240       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1241       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1242       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1243       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1244       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1245       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1246       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1247       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1248       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1249     }
1250
1251     // In the customized shift lowering, the legal cases in AVX2 will be
1252     // recognized.
1253     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1254     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1255
1256     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1257     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1258
1259     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1260     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1261
1262     // Custom lower several nodes for 256-bit types.
1263     for (MVT VT : MVT::vector_valuetypes()) {
1264       if (VT.getScalarSizeInBits() >= 32) {
1265         setOperationAction(ISD::MLOAD,  VT, Legal);
1266         setOperationAction(ISD::MSTORE, VT, Legal);
1267       }
1268       // Extract subvector is special because the value type
1269       // (result) is 128-bit but the source is 256-bit wide.
1270       if (VT.is128BitVector()) {
1271         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1272       }
1273       // Do not attempt to custom lower other non-256-bit vectors
1274       if (!VT.is256BitVector())
1275         continue;
1276
1277       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1278       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1279       setOperationAction(ISD::VSELECT,            VT, Custom);
1280       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1281       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1282       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1283       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1284       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1285     }
1286
1287     if (Subtarget->hasInt256())
1288       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1289
1290     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1291     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1292       MVT VT = (MVT::SimpleValueType)i;
1293
1294       // Do not attempt to promote non-256-bit vectors
1295       if (!VT.is256BitVector())
1296         continue;
1297
1298       setOperationAction(ISD::AND,    VT, Promote);
1299       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1300       setOperationAction(ISD::OR,     VT, Promote);
1301       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1302       setOperationAction(ISD::XOR,    VT, Promote);
1303       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1304       setOperationAction(ISD::LOAD,   VT, Promote);
1305       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1306       setOperationAction(ISD::SELECT, VT, Promote);
1307       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1308     }
1309   }
1310
1311   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1312     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1313     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1314     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1315     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1316
1317     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1318     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1319     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1320
1321     for (MVT VT : MVT::fp_vector_valuetypes())
1322       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1323
1324     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1325     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1326     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1327     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1328     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1329     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1330     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1331     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1332     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1333     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1334     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1335     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1336
1337     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1338     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1339     setOperationAction(ISD::SELECT_CC,          MVT::i1,    Expand);
1340     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1341     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1342     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1343     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1344     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1345     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1346     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1347     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1348     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1349     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1350     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1351
1352     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1353     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1354     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1355     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1356     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1357     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1358
1359     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1360     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1361     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1362     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1363     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1364     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1365     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1366     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1367
1368     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1369     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1370     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1371     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1372     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1373     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1374     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1375     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1376     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1377     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1378     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1379     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1380     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1381     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1382     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1383     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1384
1385     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1386     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1387     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1388     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1389     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1390     if (Subtarget->hasVLX()){
1391       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1392       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1393       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1394       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1395       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1396
1397       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1398       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1399       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1400       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1401       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1402     }
1403     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1404     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1405     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1406     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1407     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1408     if (Subtarget->hasDQI()) {
1409       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1410       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1411
1412       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1413       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1414       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1415       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1416       if (Subtarget->hasVLX()) {
1417         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1418         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1419         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1420         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1421         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1422         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1423         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1424         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1425       }
1426     }
1427     if (Subtarget->hasVLX()) {
1428       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1429       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1430       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1431       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1432       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1433       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1434       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1435       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1436     }
1437     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1438     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1439     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1440     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1441     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1442     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1443     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1444     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1445     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1446     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1447     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1448     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1449     if (Subtarget->hasDQI()) {
1450       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1451       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1452     }
1453     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1454     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1455     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1456     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1457     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1458     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1459     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1460     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1461     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1462     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1463
1464     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1465     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1466     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1467     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1468     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1469
1470     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1471     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1472
1473     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1474
1475     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1476     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1477     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1478     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1479     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1480     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1481     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1482     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1483     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1484     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1485     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1486
1487     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1488     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1489     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1490     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1491     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1492     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1493     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1494     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1495
1496     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1497     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1498
1499     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1500     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1501
1502     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1503
1504     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1505     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1506
1507     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1508     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1509
1510     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1511     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1512
1513     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1514     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1515     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1516     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1517     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1518     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1519
1520     if (Subtarget->hasCDI()) {
1521       setOperationAction(ISD::CTLZ,             MVT::v8i64,  Legal);
1522       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1523       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64,  Legal);
1524       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1525
1526       setOperationAction(ISD::CTLZ,             MVT::v8i16,  Custom);
1527       setOperationAction(ISD::CTLZ,             MVT::v16i8,  Custom);
1528       setOperationAction(ISD::CTLZ,             MVT::v16i16, Custom);
1529       setOperationAction(ISD::CTLZ,             MVT::v32i8,  Custom);
1530       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i16,  Custom);
1531       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i8,  Custom);
1532       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i16, Custom);
1533       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v32i8,  Custom);
1534
1535       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64,  Custom);
1536       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1537
1538       if (Subtarget->hasVLX()) {
1539         setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1540         setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1541         setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1542         setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1543         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1544         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1545         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1546         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1547
1548         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1549         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1550         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1551         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1552       } else {
1553         setOperationAction(ISD::CTLZ,             MVT::v4i64, Custom);
1554         setOperationAction(ISD::CTLZ,             MVT::v8i32, Custom);
1555         setOperationAction(ISD::CTLZ,             MVT::v2i64, Custom);
1556         setOperationAction(ISD::CTLZ,             MVT::v4i32, Custom);
1557         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1558         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1559         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1560         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1561       }
1562     } // Subtarget->hasCDI()
1563
1564     if (Subtarget->hasDQI()) {
1565       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1566       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1567       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1568     }
1569     // Custom lower several nodes.
1570     for (MVT VT : MVT::vector_valuetypes()) {
1571       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1572       if (EltSize == 1) {
1573         setOperationAction(ISD::AND, VT, Legal);
1574         setOperationAction(ISD::OR,  VT, Legal);
1575         setOperationAction(ISD::XOR,  VT, Legal);
1576       }
1577       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1578         setOperationAction(ISD::MGATHER,  VT, Custom);
1579         setOperationAction(ISD::MSCATTER, VT, Custom);
1580       }
1581       // Extract subvector is special because the value type
1582       // (result) is 256/128-bit but the source is 512-bit wide.
1583       if (VT.is128BitVector() || VT.is256BitVector()) {
1584         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1585       }
1586       if (VT.getVectorElementType() == MVT::i1)
1587         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1588
1589       // Do not attempt to custom lower other non-512-bit vectors
1590       if (!VT.is512BitVector())
1591         continue;
1592
1593       if (EltSize >= 32) {
1594         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1595         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1596         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1597         setOperationAction(ISD::VSELECT,             VT, Legal);
1598         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1599         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1600         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1601         setOperationAction(ISD::MLOAD,               VT, Legal);
1602         setOperationAction(ISD::MSTORE,              VT, Legal);
1603       }
1604     }
1605     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1606       MVT VT = (MVT::SimpleValueType)i;
1607
1608       // Do not attempt to promote non-512-bit vectors.
1609       if (!VT.is512BitVector())
1610         continue;
1611
1612       setOperationAction(ISD::SELECT, VT, Promote);
1613       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1614     }
1615   }// has  AVX-512
1616
1617   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1618     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1619     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1620
1621     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1622     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1623
1624     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1625     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1626     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1627     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1628     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1629     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1630     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1631     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1632     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1633     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1634     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1635     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Legal);
1636     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Legal);
1637     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1638     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1639     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1640     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1641     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Custom);
1642     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Custom);
1643     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1644     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1645     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1646     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1647     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1648     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1649     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1650     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1651     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1652     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1653     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1654     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1655     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1656     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1657     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1658     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1659     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1660     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1661     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1662     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1663     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1664     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1665     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1666
1667     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1668     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1669     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1670     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1671     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1672     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1673     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1674     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1675
1676     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1677     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1678     if (Subtarget->hasVLX())
1679       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1680
1681     if (Subtarget->hasCDI()) {
1682       setOperationAction(ISD::CTLZ,            MVT::v32i16, Custom);
1683       setOperationAction(ISD::CTLZ,            MVT::v64i8,  Custom);
1684       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Custom);
1685       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8,  Custom);
1686     }
1687
1688     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1689       const MVT VT = (MVT::SimpleValueType)i;
1690
1691       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1692
1693       // Do not attempt to promote non-512-bit vectors.
1694       if (!VT.is512BitVector())
1695         continue;
1696
1697       if (EltSize < 32) {
1698         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1699         setOperationAction(ISD::VSELECT,             VT, Legal);
1700       }
1701     }
1702   }
1703
1704   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1705     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1706     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1707
1708     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1709     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1710     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1711     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1712     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1713     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1714     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1715     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1716     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1717     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1718     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1719     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1720
1721     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1722     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1723     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1724     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1725     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1726     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1727     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1728     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1729
1730     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1731     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1732     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1733     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1734     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1735     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1736     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1737     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1738   }
1739
1740   // We want to custom lower some of our intrinsics.
1741   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1742   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1743   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1744   if (!Subtarget->is64Bit())
1745     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1746
1747   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1748   // handle type legalization for these operations here.
1749   //
1750   // FIXME: We really should do custom legalization for addition and
1751   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1752   // than generic legalization for 64-bit multiplication-with-overflow, though.
1753   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1754     if (VT == MVT::i64 && !Subtarget->is64Bit())
1755       continue;
1756     // Add/Sub/Mul with overflow operations are custom lowered.
1757     setOperationAction(ISD::SADDO, VT, Custom);
1758     setOperationAction(ISD::UADDO, VT, Custom);
1759     setOperationAction(ISD::SSUBO, VT, Custom);
1760     setOperationAction(ISD::USUBO, VT, Custom);
1761     setOperationAction(ISD::SMULO, VT, Custom);
1762     setOperationAction(ISD::UMULO, VT, Custom);
1763   }
1764
1765   if (!Subtarget->is64Bit()) {
1766     // These libcalls are not available in 32-bit.
1767     setLibcallName(RTLIB::SHL_I128, nullptr);
1768     setLibcallName(RTLIB::SRL_I128, nullptr);
1769     setLibcallName(RTLIB::SRA_I128, nullptr);
1770   }
1771
1772   // Combine sin / cos into one node or libcall if possible.
1773   if (Subtarget->hasSinCos()) {
1774     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1775     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1776     if (Subtarget->isTargetDarwin()) {
1777       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1778       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1779       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1780       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1781     }
1782   }
1783
1784   if (Subtarget->isTargetWin64()) {
1785     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1786     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1787     setOperationAction(ISD::SREM, MVT::i128, Custom);
1788     setOperationAction(ISD::UREM, MVT::i128, Custom);
1789     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1790     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1791   }
1792
1793   // We have target-specific dag combine patterns for the following nodes:
1794   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1795   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1796   setTargetDAGCombine(ISD::BITCAST);
1797   setTargetDAGCombine(ISD::VSELECT);
1798   setTargetDAGCombine(ISD::SELECT);
1799   setTargetDAGCombine(ISD::SHL);
1800   setTargetDAGCombine(ISD::SRA);
1801   setTargetDAGCombine(ISD::SRL);
1802   setTargetDAGCombine(ISD::OR);
1803   setTargetDAGCombine(ISD::AND);
1804   setTargetDAGCombine(ISD::ADD);
1805   setTargetDAGCombine(ISD::FADD);
1806   setTargetDAGCombine(ISD::FSUB);
1807   setTargetDAGCombine(ISD::FMA);
1808   setTargetDAGCombine(ISD::SUB);
1809   setTargetDAGCombine(ISD::LOAD);
1810   setTargetDAGCombine(ISD::MLOAD);
1811   setTargetDAGCombine(ISD::STORE);
1812   setTargetDAGCombine(ISD::MSTORE);
1813   setTargetDAGCombine(ISD::ZERO_EXTEND);
1814   setTargetDAGCombine(ISD::ANY_EXTEND);
1815   setTargetDAGCombine(ISD::SIGN_EXTEND);
1816   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1817   setTargetDAGCombine(ISD::SINT_TO_FP);
1818   setTargetDAGCombine(ISD::UINT_TO_FP);
1819   setTargetDAGCombine(ISD::SETCC);
1820   setTargetDAGCombine(ISD::BUILD_VECTOR);
1821   setTargetDAGCombine(ISD::MUL);
1822   setTargetDAGCombine(ISD::XOR);
1823
1824   computeRegisterProperties(Subtarget->getRegisterInfo());
1825
1826   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1827   MaxStoresPerMemsetOptSize = 8;
1828   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1829   MaxStoresPerMemcpyOptSize = 4;
1830   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1831   MaxStoresPerMemmoveOptSize = 4;
1832   setPrefLoopAlignment(4); // 2^4 bytes.
1833
1834   // A predictable cmov does not hurt on an in-order CPU.
1835   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1836   PredictableSelectIsExpensive = !Subtarget->isAtom();
1837   EnableExtLdPromotion = true;
1838   setPrefFunctionAlignment(4); // 2^4 bytes.
1839
1840   verifyIntrinsicTables();
1841 }
1842
1843 // This has so far only been implemented for 64-bit MachO.
1844 bool X86TargetLowering::useLoadStackGuardNode() const {
1845   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1846 }
1847
1848 TargetLoweringBase::LegalizeTypeAction
1849 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1850   if (ExperimentalVectorWideningLegalization &&
1851       VT.getVectorNumElements() != 1 &&
1852       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1853     return TypeWidenVector;
1854
1855   return TargetLoweringBase::getPreferredVectorAction(VT);
1856 }
1857
1858 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1859                                           EVT VT) const {
1860   if (!VT.isVector())
1861     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1862
1863   const unsigned NumElts = VT.getVectorNumElements();
1864   const EVT EltVT = VT.getVectorElementType();
1865   if (VT.is512BitVector()) {
1866     if (Subtarget->hasAVX512())
1867       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1868           EltVT == MVT::f32 || EltVT == MVT::f64)
1869         switch(NumElts) {
1870         case  8: return MVT::v8i1;
1871         case 16: return MVT::v16i1;
1872       }
1873     if (Subtarget->hasBWI())
1874       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1875         switch(NumElts) {
1876         case 32: return MVT::v32i1;
1877         case 64: return MVT::v64i1;
1878       }
1879   }
1880
1881   if (VT.is256BitVector() || VT.is128BitVector()) {
1882     if (Subtarget->hasVLX())
1883       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1884           EltVT == MVT::f32 || EltVT == MVT::f64)
1885         switch(NumElts) {
1886         case 2: return MVT::v2i1;
1887         case 4: return MVT::v4i1;
1888         case 8: return MVT::v8i1;
1889       }
1890     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1891       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1892         switch(NumElts) {
1893         case  8: return MVT::v8i1;
1894         case 16: return MVT::v16i1;
1895         case 32: return MVT::v32i1;
1896       }
1897   }
1898
1899   return VT.changeVectorElementTypeToInteger();
1900 }
1901
1902 /// Helper for getByValTypeAlignment to determine
1903 /// the desired ByVal argument alignment.
1904 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1905   if (MaxAlign == 16)
1906     return;
1907   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1908     if (VTy->getBitWidth() == 128)
1909       MaxAlign = 16;
1910   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1911     unsigned EltAlign = 0;
1912     getMaxByValAlign(ATy->getElementType(), EltAlign);
1913     if (EltAlign > MaxAlign)
1914       MaxAlign = EltAlign;
1915   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1916     for (auto *EltTy : STy->elements()) {
1917       unsigned EltAlign = 0;
1918       getMaxByValAlign(EltTy, EltAlign);
1919       if (EltAlign > MaxAlign)
1920         MaxAlign = EltAlign;
1921       if (MaxAlign == 16)
1922         break;
1923     }
1924   }
1925 }
1926
1927 /// Return the desired alignment for ByVal aggregate
1928 /// function arguments in the caller parameter area. For X86, aggregates
1929 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1930 /// are at 4-byte boundaries.
1931 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1932                                                   const DataLayout &DL) const {
1933   if (Subtarget->is64Bit()) {
1934     // Max of 8 and alignment of type.
1935     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1936     if (TyAlign > 8)
1937       return TyAlign;
1938     return 8;
1939   }
1940
1941   unsigned Align = 4;
1942   if (Subtarget->hasSSE1())
1943     getMaxByValAlign(Ty, Align);
1944   return Align;
1945 }
1946
1947 /// Returns the target specific optimal type for load
1948 /// and store operations as a result of memset, memcpy, and memmove
1949 /// lowering. If DstAlign is zero that means it's safe to destination
1950 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1951 /// means there isn't a need to check it against alignment requirement,
1952 /// probably because the source does not need to be loaded. If 'IsMemset' is
1953 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1954 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1955 /// source is constant so it does not need to be loaded.
1956 /// It returns EVT::Other if the type should be determined using generic
1957 /// target-independent logic.
1958 EVT
1959 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1960                                        unsigned DstAlign, unsigned SrcAlign,
1961                                        bool IsMemset, bool ZeroMemset,
1962                                        bool MemcpyStrSrc,
1963                                        MachineFunction &MF) const {
1964   const Function *F = MF.getFunction();
1965   if ((!IsMemset || ZeroMemset) &&
1966       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1967     if (Size >= 16 &&
1968         (!Subtarget->isUnalignedMem16Slow() ||
1969          ((DstAlign == 0 || DstAlign >= 16) &&
1970           (SrcAlign == 0 || SrcAlign >= 16)))) {
1971       if (Size >= 32) {
1972         // FIXME: Check if unaligned 32-byte accesses are slow.
1973         if (Subtarget->hasInt256())
1974           return MVT::v8i32;
1975         if (Subtarget->hasFp256())
1976           return MVT::v8f32;
1977       }
1978       if (Subtarget->hasSSE2())
1979         return MVT::v4i32;
1980       if (Subtarget->hasSSE1())
1981         return MVT::v4f32;
1982     } else if (!MemcpyStrSrc && Size >= 8 &&
1983                !Subtarget->is64Bit() &&
1984                Subtarget->hasSSE2()) {
1985       // Do not use f64 to lower memcpy if source is string constant. It's
1986       // better to use i32 to avoid the loads.
1987       return MVT::f64;
1988     }
1989   }
1990   // This is a compromise. If we reach here, unaligned accesses may be slow on
1991   // this target. However, creating smaller, aligned accesses could be even
1992   // slower and would certainly be a lot more code.
1993   if (Subtarget->is64Bit() && Size >= 8)
1994     return MVT::i64;
1995   return MVT::i32;
1996 }
1997
1998 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1999   if (VT == MVT::f32)
2000     return X86ScalarSSEf32;
2001   else if (VT == MVT::f64)
2002     return X86ScalarSSEf64;
2003   return true;
2004 }
2005
2006 bool
2007 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2008                                                   unsigned,
2009                                                   unsigned,
2010                                                   bool *Fast) const {
2011   if (Fast) {
2012     switch (VT.getSizeInBits()) {
2013     default:
2014       // 8-byte and under are always assumed to be fast.
2015       *Fast = true;
2016       break;
2017     case 128:
2018       *Fast = !Subtarget->isUnalignedMem16Slow();
2019       break;
2020     case 256:
2021       *Fast = !Subtarget->isUnalignedMem32Slow();
2022       break;
2023     // TODO: What about AVX-512 (512-bit) accesses?
2024     }
2025   }
2026   // Misaligned accesses of any size are always allowed.
2027   return true;
2028 }
2029
2030 /// Return the entry encoding for a jump table in the
2031 /// current function.  The returned value is a member of the
2032 /// MachineJumpTableInfo::JTEntryKind enum.
2033 unsigned X86TargetLowering::getJumpTableEncoding() const {
2034   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2035   // symbol.
2036   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2037       Subtarget->isPICStyleGOT())
2038     return MachineJumpTableInfo::EK_Custom32;
2039
2040   // Otherwise, use the normal jump table encoding heuristics.
2041   return TargetLowering::getJumpTableEncoding();
2042 }
2043
2044 bool X86TargetLowering::useSoftFloat() const {
2045   return Subtarget->useSoftFloat();
2046 }
2047
2048 const MCExpr *
2049 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2050                                              const MachineBasicBlock *MBB,
2051                                              unsigned uid,MCContext &Ctx) const{
2052   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2053          Subtarget->isPICStyleGOT());
2054   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2055   // entries.
2056   return MCSymbolRefExpr::create(MBB->getSymbol(),
2057                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2058 }
2059
2060 /// Returns relocation base for the given PIC jumptable.
2061 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2062                                                     SelectionDAG &DAG) const {
2063   if (!Subtarget->is64Bit())
2064     // This doesn't have SDLoc associated with it, but is not really the
2065     // same as a Register.
2066     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2067                        getPointerTy(DAG.getDataLayout()));
2068   return Table;
2069 }
2070
2071 /// This returns the relocation base for the given PIC jumptable,
2072 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2073 const MCExpr *X86TargetLowering::
2074 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2075                              MCContext &Ctx) const {
2076   // X86-64 uses RIP relative addressing based on the jump table label.
2077   if (Subtarget->isPICStyleRIPRel())
2078     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2079
2080   // Otherwise, the reference is relative to the PIC base.
2081   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2082 }
2083
2084 std::pair<const TargetRegisterClass *, uint8_t>
2085 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2086                                            MVT VT) const {
2087   const TargetRegisterClass *RRC = nullptr;
2088   uint8_t Cost = 1;
2089   switch (VT.SimpleTy) {
2090   default:
2091     return TargetLowering::findRepresentativeClass(TRI, VT);
2092   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2093     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2094     break;
2095   case MVT::x86mmx:
2096     RRC = &X86::VR64RegClass;
2097     break;
2098   case MVT::f32: case MVT::f64:
2099   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2100   case MVT::v4f32: case MVT::v2f64:
2101   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2102   case MVT::v4f64:
2103     RRC = &X86::VR128RegClass;
2104     break;
2105   }
2106   return std::make_pair(RRC, Cost);
2107 }
2108
2109 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2110                                                unsigned &Offset) const {
2111   if (!Subtarget->isTargetLinux())
2112     return false;
2113
2114   if (Subtarget->is64Bit()) {
2115     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2116     Offset = 0x28;
2117     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2118       AddressSpace = 256;
2119     else
2120       AddressSpace = 257;
2121   } else {
2122     // %gs:0x14 on i386
2123     Offset = 0x14;
2124     AddressSpace = 256;
2125   }
2126   return true;
2127 }
2128
2129 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2130   if (!Subtarget->isTargetAndroid())
2131     return TargetLowering::getSafeStackPointerLocation(IRB);
2132
2133   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2134   // definition of TLS_SLOT_SAFESTACK in
2135   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2136   unsigned AddressSpace, Offset;
2137   if (Subtarget->is64Bit()) {
2138     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2139     Offset = 0x48;
2140     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2141       AddressSpace = 256;
2142     else
2143       AddressSpace = 257;
2144   } else {
2145     // %gs:0x24 on i386
2146     Offset = 0x24;
2147     AddressSpace = 256;
2148   }
2149
2150   return ConstantExpr::getIntToPtr(
2151       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2152       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2153 }
2154
2155 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2156                                             unsigned DestAS) const {
2157   assert(SrcAS != DestAS && "Expected different address spaces!");
2158
2159   return SrcAS < 256 && DestAS < 256;
2160 }
2161
2162 //===----------------------------------------------------------------------===//
2163 //               Return Value Calling Convention Implementation
2164 //===----------------------------------------------------------------------===//
2165
2166 #include "X86GenCallingConv.inc"
2167
2168 bool X86TargetLowering::CanLowerReturn(
2169     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2170     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2171   SmallVector<CCValAssign, 16> RVLocs;
2172   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2173   return CCInfo.CheckReturn(Outs, RetCC_X86);
2174 }
2175
2176 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2177   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2178   return ScratchRegs;
2179 }
2180
2181 SDValue
2182 X86TargetLowering::LowerReturn(SDValue Chain,
2183                                CallingConv::ID CallConv, bool isVarArg,
2184                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2185                                const SmallVectorImpl<SDValue> &OutVals,
2186                                SDLoc dl, SelectionDAG &DAG) const {
2187   MachineFunction &MF = DAG.getMachineFunction();
2188   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2189
2190   SmallVector<CCValAssign, 16> RVLocs;
2191   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2192   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2193
2194   SDValue Flag;
2195   SmallVector<SDValue, 6> RetOps;
2196   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2197   // Operand #1 = Bytes To Pop
2198   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2199                    MVT::i16));
2200
2201   // Copy the result values into the output registers.
2202   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2203     CCValAssign &VA = RVLocs[i];
2204     assert(VA.isRegLoc() && "Can only return in registers!");
2205     SDValue ValToCopy = OutVals[i];
2206     EVT ValVT = ValToCopy.getValueType();
2207
2208     // Promote values to the appropriate types.
2209     if (VA.getLocInfo() == CCValAssign::SExt)
2210       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2211     else if (VA.getLocInfo() == CCValAssign::ZExt)
2212       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2213     else if (VA.getLocInfo() == CCValAssign::AExt) {
2214       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2215         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2216       else
2217         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2218     }
2219     else if (VA.getLocInfo() == CCValAssign::BCvt)
2220       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2221
2222     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2223            "Unexpected FP-extend for return value.");
2224
2225     // If this is x86-64, and we disabled SSE, we can't return FP values,
2226     // or SSE or MMX vectors.
2227     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2228          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2229           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2230       report_fatal_error("SSE register return with SSE disabled");
2231     }
2232     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2233     // llvm-gcc has never done it right and no one has noticed, so this
2234     // should be OK for now.
2235     if (ValVT == MVT::f64 &&
2236         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2237       report_fatal_error("SSE2 register return with SSE2 disabled");
2238
2239     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2240     // the RET instruction and handled by the FP Stackifier.
2241     if (VA.getLocReg() == X86::FP0 ||
2242         VA.getLocReg() == X86::FP1) {
2243       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2244       // change the value to the FP stack register class.
2245       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2246         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2247       RetOps.push_back(ValToCopy);
2248       // Don't emit a copytoreg.
2249       continue;
2250     }
2251
2252     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2253     // which is returned in RAX / RDX.
2254     if (Subtarget->is64Bit()) {
2255       if (ValVT == MVT::x86mmx) {
2256         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2257           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2258           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2259                                   ValToCopy);
2260           // If we don't have SSE2 available, convert to v4f32 so the generated
2261           // register is legal.
2262           if (!Subtarget->hasSSE2())
2263             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2264         }
2265       }
2266     }
2267
2268     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2269     Flag = Chain.getValue(1);
2270     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2271   }
2272
2273   // All x86 ABIs require that for returning structs by value we copy
2274   // the sret argument into %rax/%eax (depending on ABI) for the return.
2275   // We saved the argument into a virtual register in the entry block,
2276   // so now we copy the value out and into %rax/%eax.
2277   //
2278   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2279   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2280   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2281   // either case FuncInfo->setSRetReturnReg() will have been called.
2282   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2283     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2284                                      getPointerTy(MF.getDataLayout()));
2285
2286     unsigned RetValReg
2287         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2288           X86::RAX : X86::EAX;
2289     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2290     Flag = Chain.getValue(1);
2291
2292     // RAX/EAX now acts like a return value.
2293     RetOps.push_back(
2294         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2295   }
2296
2297   RetOps[0] = Chain;  // Update chain.
2298
2299   // Add the flag if we have it.
2300   if (Flag.getNode())
2301     RetOps.push_back(Flag);
2302
2303   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2304 }
2305
2306 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2307   if (N->getNumValues() != 1)
2308     return false;
2309   if (!N->hasNUsesOfValue(1, 0))
2310     return false;
2311
2312   SDValue TCChain = Chain;
2313   SDNode *Copy = *N->use_begin();
2314   if (Copy->getOpcode() == ISD::CopyToReg) {
2315     // If the copy has a glue operand, we conservatively assume it isn't safe to
2316     // perform a tail call.
2317     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2318       return false;
2319     TCChain = Copy->getOperand(0);
2320   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2321     return false;
2322
2323   bool HasRet = false;
2324   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2325        UI != UE; ++UI) {
2326     if (UI->getOpcode() != X86ISD::RET_FLAG)
2327       return false;
2328     // If we are returning more than one value, we can definitely
2329     // not make a tail call see PR19530
2330     if (UI->getNumOperands() > 4)
2331       return false;
2332     if (UI->getNumOperands() == 4 &&
2333         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2334       return false;
2335     HasRet = true;
2336   }
2337
2338   if (!HasRet)
2339     return false;
2340
2341   Chain = TCChain;
2342   return true;
2343 }
2344
2345 EVT
2346 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2347                                             ISD::NodeType ExtendKind) const {
2348   MVT ReturnMVT;
2349   // TODO: Is this also valid on 32-bit?
2350   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2351     ReturnMVT = MVT::i8;
2352   else
2353     ReturnMVT = MVT::i32;
2354
2355   EVT MinVT = getRegisterType(Context, ReturnMVT);
2356   return VT.bitsLT(MinVT) ? MinVT : VT;
2357 }
2358
2359 /// Lower the result values of a call into the
2360 /// appropriate copies out of appropriate physical registers.
2361 ///
2362 SDValue
2363 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2364                                    CallingConv::ID CallConv, bool isVarArg,
2365                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2366                                    SDLoc dl, SelectionDAG &DAG,
2367                                    SmallVectorImpl<SDValue> &InVals) const {
2368
2369   // Assign locations to each value returned by this call.
2370   SmallVector<CCValAssign, 16> RVLocs;
2371   bool Is64Bit = Subtarget->is64Bit();
2372   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2373                  *DAG.getContext());
2374   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2375
2376   // Copy all of the result registers out of their specified physreg.
2377   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2378     CCValAssign &VA = RVLocs[i];
2379     EVT CopyVT = VA.getLocVT();
2380
2381     // If this is x86-64, and we disabled SSE, we can't return FP values
2382     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2383         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2384       report_fatal_error("SSE register return with SSE disabled");
2385     }
2386
2387     // If we prefer to use the value in xmm registers, copy it out as f80 and
2388     // use a truncate to move it from fp stack reg to xmm reg.
2389     bool RoundAfterCopy = false;
2390     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2391         isScalarFPTypeInSSEReg(VA.getValVT())) {
2392       CopyVT = MVT::f80;
2393       RoundAfterCopy = (CopyVT != VA.getLocVT());
2394     }
2395
2396     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2397                                CopyVT, InFlag).getValue(1);
2398     SDValue Val = Chain.getValue(0);
2399
2400     if (RoundAfterCopy)
2401       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2402                         // This truncation won't change the value.
2403                         DAG.getIntPtrConstant(1, dl));
2404
2405     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2406       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2407
2408     InFlag = Chain.getValue(2);
2409     InVals.push_back(Val);
2410   }
2411
2412   return Chain;
2413 }
2414
2415 //===----------------------------------------------------------------------===//
2416 //                C & StdCall & Fast Calling Convention implementation
2417 //===----------------------------------------------------------------------===//
2418 //  StdCall calling convention seems to be standard for many Windows' API
2419 //  routines and around. It differs from C calling convention just a little:
2420 //  callee should clean up the stack, not caller. Symbols should be also
2421 //  decorated in some fancy way :) It doesn't support any vector arguments.
2422 //  For info on fast calling convention see Fast Calling Convention (tail call)
2423 //  implementation LowerX86_32FastCCCallTo.
2424
2425 /// CallIsStructReturn - Determines whether a call uses struct return
2426 /// semantics.
2427 enum StructReturnType {
2428   NotStructReturn,
2429   RegStructReturn,
2430   StackStructReturn
2431 };
2432 static StructReturnType
2433 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2434   if (Outs.empty())
2435     return NotStructReturn;
2436
2437   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2438   if (!Flags.isSRet())
2439     return NotStructReturn;
2440   if (Flags.isInReg())
2441     return RegStructReturn;
2442   return StackStructReturn;
2443 }
2444
2445 /// Determines whether a function uses struct return semantics.
2446 static StructReturnType
2447 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2448   if (Ins.empty())
2449     return NotStructReturn;
2450
2451   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2452   if (!Flags.isSRet())
2453     return NotStructReturn;
2454   if (Flags.isInReg())
2455     return RegStructReturn;
2456   return StackStructReturn;
2457 }
2458
2459 /// Make a copy of an aggregate at address specified by "Src" to address
2460 /// "Dst" with size and alignment information specified by the specific
2461 /// parameter attribute. The copy will be passed as a byval function parameter.
2462 static SDValue
2463 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2464                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2465                           SDLoc dl) {
2466   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2467
2468   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2469                        /*isVolatile*/false, /*AlwaysInline=*/true,
2470                        /*isTailCall*/false,
2471                        MachinePointerInfo(), MachinePointerInfo());
2472 }
2473
2474 /// Return true if the calling convention is one that we can guarantee TCO for.
2475 static bool canGuaranteeTCO(CallingConv::ID CC) {
2476   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2477           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2478 }
2479
2480 /// Return true if we might ever do TCO for calls with this calling convention.
2481 static bool mayTailCallThisCC(CallingConv::ID CC) {
2482   switch (CC) {
2483   // C calling conventions:
2484   case CallingConv::C:
2485   case CallingConv::X86_64_Win64:
2486   case CallingConv::X86_64_SysV:
2487   // Callee pop conventions:
2488   case CallingConv::X86_ThisCall:
2489   case CallingConv::X86_StdCall:
2490   case CallingConv::X86_VectorCall:
2491   case CallingConv::X86_FastCall:
2492     return true;
2493   default:
2494     return canGuaranteeTCO(CC);
2495   }
2496 }
2497
2498 /// Return true if the function is being made into a tailcall target by
2499 /// changing its ABI.
2500 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2501   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2502 }
2503
2504 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2505   auto Attr =
2506       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2507   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2508     return false;
2509
2510   CallSite CS(CI);
2511   CallingConv::ID CalleeCC = CS.getCallingConv();
2512   if (!mayTailCallThisCC(CalleeCC))
2513     return false;
2514
2515   return true;
2516 }
2517
2518 SDValue
2519 X86TargetLowering::LowerMemArgument(SDValue Chain,
2520                                     CallingConv::ID CallConv,
2521                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2522                                     SDLoc dl, SelectionDAG &DAG,
2523                                     const CCValAssign &VA,
2524                                     MachineFrameInfo *MFI,
2525                                     unsigned i) const {
2526   // Create the nodes corresponding to a load from this parameter slot.
2527   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2528   bool AlwaysUseMutable = shouldGuaranteeTCO(
2529       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2530   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2531   EVT ValVT;
2532
2533   // If value is passed by pointer we have address passed instead of the value
2534   // itself.
2535   bool ExtendedInMem = VA.isExtInLoc() &&
2536     VA.getValVT().getScalarType() == MVT::i1;
2537
2538   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2539     ValVT = VA.getLocVT();
2540   else
2541     ValVT = VA.getValVT();
2542
2543   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2544   // changed with more analysis.
2545   // In case of tail call optimization mark all arguments mutable. Since they
2546   // could be overwritten by lowering of arguments in case of a tail call.
2547   if (Flags.isByVal()) {
2548     unsigned Bytes = Flags.getByValSize();
2549     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2550     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2551     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2552   } else {
2553     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2554                                     VA.getLocMemOffset(), isImmutable);
2555     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2556     SDValue Val = DAG.getLoad(
2557         ValVT, dl, Chain, FIN,
2558         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2559         false, false, 0);
2560     return ExtendedInMem ?
2561       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2562   }
2563 }
2564
2565 // FIXME: Get this from tablegen.
2566 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2567                                                 const X86Subtarget *Subtarget) {
2568   assert(Subtarget->is64Bit());
2569
2570   if (Subtarget->isCallingConvWin64(CallConv)) {
2571     static const MCPhysReg GPR64ArgRegsWin64[] = {
2572       X86::RCX, X86::RDX, X86::R8,  X86::R9
2573     };
2574     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2575   }
2576
2577   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2578     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2579   };
2580   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2581 }
2582
2583 // FIXME: Get this from tablegen.
2584 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2585                                                 CallingConv::ID CallConv,
2586                                                 const X86Subtarget *Subtarget) {
2587   assert(Subtarget->is64Bit());
2588   if (Subtarget->isCallingConvWin64(CallConv)) {
2589     // The XMM registers which might contain var arg parameters are shadowed
2590     // in their paired GPR.  So we only need to save the GPR to their home
2591     // slots.
2592     // TODO: __vectorcall will change this.
2593     return None;
2594   }
2595
2596   const Function *Fn = MF.getFunction();
2597   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2598   bool isSoftFloat = Subtarget->useSoftFloat();
2599   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2600          "SSE register cannot be used when SSE is disabled!");
2601   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2602     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2603     // registers.
2604     return None;
2605
2606   static const MCPhysReg XMMArgRegs64Bit[] = {
2607     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2608     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2609   };
2610   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2611 }
2612
2613 SDValue X86TargetLowering::LowerFormalArguments(
2614     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2615     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2616     SmallVectorImpl<SDValue> &InVals) const {
2617   MachineFunction &MF = DAG.getMachineFunction();
2618   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2619   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2620
2621   const Function* Fn = MF.getFunction();
2622   if (Fn->hasExternalLinkage() &&
2623       Subtarget->isTargetCygMing() &&
2624       Fn->getName() == "main")
2625     FuncInfo->setForceFramePointer(true);
2626
2627   MachineFrameInfo *MFI = MF.getFrameInfo();
2628   bool Is64Bit = Subtarget->is64Bit();
2629   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2630
2631   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2632          "Var args not supported with calling convention fastcc, ghc or hipe");
2633
2634   // Assign locations to all of the incoming arguments.
2635   SmallVector<CCValAssign, 16> ArgLocs;
2636   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2637
2638   // Allocate shadow area for Win64
2639   if (IsWin64)
2640     CCInfo.AllocateStack(32, 8);
2641
2642   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2643
2644   unsigned LastVal = ~0U;
2645   SDValue ArgValue;
2646   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2647     CCValAssign &VA = ArgLocs[i];
2648     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2649     // places.
2650     assert(VA.getValNo() != LastVal &&
2651            "Don't support value assigned to multiple locs yet");
2652     (void)LastVal;
2653     LastVal = VA.getValNo();
2654
2655     if (VA.isRegLoc()) {
2656       EVT RegVT = VA.getLocVT();
2657       const TargetRegisterClass *RC;
2658       if (RegVT == MVT::i32)
2659         RC = &X86::GR32RegClass;
2660       else if (Is64Bit && RegVT == MVT::i64)
2661         RC = &X86::GR64RegClass;
2662       else if (RegVT == MVT::f32)
2663         RC = &X86::FR32RegClass;
2664       else if (RegVT == MVT::f64)
2665         RC = &X86::FR64RegClass;
2666       else if (RegVT.is512BitVector())
2667         RC = &X86::VR512RegClass;
2668       else if (RegVT.is256BitVector())
2669         RC = &X86::VR256RegClass;
2670       else if (RegVT.is128BitVector())
2671         RC = &X86::VR128RegClass;
2672       else if (RegVT == MVT::x86mmx)
2673         RC = &X86::VR64RegClass;
2674       else if (RegVT == MVT::i1)
2675         RC = &X86::VK1RegClass;
2676       else if (RegVT == MVT::v8i1)
2677         RC = &X86::VK8RegClass;
2678       else if (RegVT == MVT::v16i1)
2679         RC = &X86::VK16RegClass;
2680       else if (RegVT == MVT::v32i1)
2681         RC = &X86::VK32RegClass;
2682       else if (RegVT == MVT::v64i1)
2683         RC = &X86::VK64RegClass;
2684       else
2685         llvm_unreachable("Unknown argument type!");
2686
2687       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2688       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2689
2690       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2691       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2692       // right size.
2693       if (VA.getLocInfo() == CCValAssign::SExt)
2694         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2695                                DAG.getValueType(VA.getValVT()));
2696       else if (VA.getLocInfo() == CCValAssign::ZExt)
2697         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2698                                DAG.getValueType(VA.getValVT()));
2699       else if (VA.getLocInfo() == CCValAssign::BCvt)
2700         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2701
2702       if (VA.isExtInLoc()) {
2703         // Handle MMX values passed in XMM regs.
2704         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2705           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2706         else
2707           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2708       }
2709     } else {
2710       assert(VA.isMemLoc());
2711       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2712     }
2713
2714     // If value is passed via pointer - do a load.
2715     if (VA.getLocInfo() == CCValAssign::Indirect)
2716       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2717                              MachinePointerInfo(), false, false, false, 0);
2718
2719     InVals.push_back(ArgValue);
2720   }
2721
2722   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2723     // All x86 ABIs require that for returning structs by value we copy the
2724     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2725     // the argument into a virtual register so that we can access it from the
2726     // return points.
2727     if (Ins[i].Flags.isSRet()) {
2728       unsigned Reg = FuncInfo->getSRetReturnReg();
2729       if (!Reg) {
2730         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2731         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2732         FuncInfo->setSRetReturnReg(Reg);
2733       }
2734       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2735       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2736       break;
2737     }
2738   }
2739
2740   unsigned StackSize = CCInfo.getNextStackOffset();
2741   // Align stack specially for tail calls.
2742   if (shouldGuaranteeTCO(CallConv,
2743                          MF.getTarget().Options.GuaranteedTailCallOpt))
2744     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2745
2746   // If the function takes variable number of arguments, make a frame index for
2747   // the start of the first vararg value... for expansion of llvm.va_start. We
2748   // can skip this if there are no va_start calls.
2749   if (MFI->hasVAStart() &&
2750       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2751                    CallConv != CallingConv::X86_ThisCall))) {
2752     FuncInfo->setVarArgsFrameIndex(
2753         MFI->CreateFixedObject(1, StackSize, true));
2754   }
2755
2756   MachineModuleInfo &MMI = MF.getMMI();
2757
2758   // Figure out if XMM registers are in use.
2759   assert(!(Subtarget->useSoftFloat() &&
2760            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2761          "SSE register cannot be used when SSE is disabled!");
2762
2763   // 64-bit calling conventions support varargs and register parameters, so we
2764   // have to do extra work to spill them in the prologue.
2765   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2766     // Find the first unallocated argument registers.
2767     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2768     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2769     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2770     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2771     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2772            "SSE register cannot be used when SSE is disabled!");
2773
2774     // Gather all the live in physical registers.
2775     SmallVector<SDValue, 6> LiveGPRs;
2776     SmallVector<SDValue, 8> LiveXMMRegs;
2777     SDValue ALVal;
2778     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2779       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2780       LiveGPRs.push_back(
2781           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2782     }
2783     if (!ArgXMMs.empty()) {
2784       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2785       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2786       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2787         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2788         LiveXMMRegs.push_back(
2789             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2790       }
2791     }
2792
2793     if (IsWin64) {
2794       // Get to the caller-allocated home save location.  Add 8 to account
2795       // for the return address.
2796       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2797       FuncInfo->setRegSaveFrameIndex(
2798           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2799       // Fixup to set vararg frame on shadow area (4 x i64).
2800       if (NumIntRegs < 4)
2801         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2802     } else {
2803       // For X86-64, if there are vararg parameters that are passed via
2804       // registers, then we must store them to their spots on the stack so
2805       // they may be loaded by deferencing the result of va_next.
2806       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2807       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2808       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2809           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2810     }
2811
2812     // Store the integer parameter registers.
2813     SmallVector<SDValue, 8> MemOps;
2814     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2815                                       getPointerTy(DAG.getDataLayout()));
2816     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2817     for (SDValue Val : LiveGPRs) {
2818       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2819                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2820       SDValue Store =
2821           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2822                        MachinePointerInfo::getFixedStack(
2823                            DAG.getMachineFunction(),
2824                            FuncInfo->getRegSaveFrameIndex(), Offset),
2825                        false, false, 0);
2826       MemOps.push_back(Store);
2827       Offset += 8;
2828     }
2829
2830     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2831       // Now store the XMM (fp + vector) parameter registers.
2832       SmallVector<SDValue, 12> SaveXMMOps;
2833       SaveXMMOps.push_back(Chain);
2834       SaveXMMOps.push_back(ALVal);
2835       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2836                              FuncInfo->getRegSaveFrameIndex(), dl));
2837       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2838                              FuncInfo->getVarArgsFPOffset(), dl));
2839       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2840                         LiveXMMRegs.end());
2841       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2842                                    MVT::Other, SaveXMMOps));
2843     }
2844
2845     if (!MemOps.empty())
2846       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2847   }
2848
2849   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2850     // Find the largest legal vector type.
2851     MVT VecVT = MVT::Other;
2852     // FIXME: Only some x86_32 calling conventions support AVX512.
2853     if (Subtarget->hasAVX512() &&
2854         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2855                      CallConv == CallingConv::Intel_OCL_BI)))
2856       VecVT = MVT::v16f32;
2857     else if (Subtarget->hasAVX())
2858       VecVT = MVT::v8f32;
2859     else if (Subtarget->hasSSE2())
2860       VecVT = MVT::v4f32;
2861
2862     // We forward some GPRs and some vector types.
2863     SmallVector<MVT, 2> RegParmTypes;
2864     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2865     RegParmTypes.push_back(IntVT);
2866     if (VecVT != MVT::Other)
2867       RegParmTypes.push_back(VecVT);
2868
2869     // Compute the set of forwarded registers. The rest are scratch.
2870     SmallVectorImpl<ForwardedRegister> &Forwards =
2871         FuncInfo->getForwardedMustTailRegParms();
2872     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2873
2874     // Conservatively forward AL on x86_64, since it might be used for varargs.
2875     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2876       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2877       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2878     }
2879
2880     // Copy all forwards from physical to virtual registers.
2881     for (ForwardedRegister &F : Forwards) {
2882       // FIXME: Can we use a less constrained schedule?
2883       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2884       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2885       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2886     }
2887   }
2888
2889   // Some CCs need callee pop.
2890   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2891                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2892     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2893   } else {
2894     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2895     // If this is an sret function, the return should pop the hidden pointer.
2896     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2897         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2898         argsAreStructReturn(Ins) == StackStructReturn)
2899       FuncInfo->setBytesToPopOnReturn(4);
2900   }
2901
2902   if (!Is64Bit) {
2903     // RegSaveFrameIndex is X86-64 only.
2904     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2905     if (CallConv == CallingConv::X86_FastCall ||
2906         CallConv == CallingConv::X86_ThisCall)
2907       // fastcc functions can't have varargs.
2908       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2909   }
2910
2911   FuncInfo->setArgumentStackSize(StackSize);
2912
2913   if (MMI.hasWinEHFuncInfo(Fn)) {
2914     if (Is64Bit) {
2915       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2916       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2917       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2918       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2919       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2920                            MachinePointerInfo::getFixedStack(
2921                                DAG.getMachineFunction(), UnwindHelpFI),
2922                            /*isVolatile=*/true,
2923                            /*isNonTemporal=*/false, /*Alignment=*/0);
2924     } else {
2925       // Functions using Win32 EH are considered to have opaque SP adjustments
2926       // to force local variables to be addressed from the frame or base
2927       // pointers.
2928       MFI->setHasOpaqueSPAdjustment(true);
2929     }
2930   }
2931
2932   return Chain;
2933 }
2934
2935 SDValue
2936 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2937                                     SDValue StackPtr, SDValue Arg,
2938                                     SDLoc dl, SelectionDAG &DAG,
2939                                     const CCValAssign &VA,
2940                                     ISD::ArgFlagsTy Flags) const {
2941   unsigned LocMemOffset = VA.getLocMemOffset();
2942   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2943   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2944                        StackPtr, PtrOff);
2945   if (Flags.isByVal())
2946     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2947
2948   return DAG.getStore(
2949       Chain, dl, Arg, PtrOff,
2950       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2951       false, false, 0);
2952 }
2953
2954 /// Emit a load of return address if tail call
2955 /// optimization is performed and it is required.
2956 SDValue
2957 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2958                                            SDValue &OutRetAddr, SDValue Chain,
2959                                            bool IsTailCall, bool Is64Bit,
2960                                            int FPDiff, SDLoc dl) const {
2961   // Adjust the Return address stack slot.
2962   EVT VT = getPointerTy(DAG.getDataLayout());
2963   OutRetAddr = getReturnAddressFrameIndex(DAG);
2964
2965   // Load the "old" Return address.
2966   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2967                            false, false, false, 0);
2968   return SDValue(OutRetAddr.getNode(), 1);
2969 }
2970
2971 /// Emit a store of the return address if tail call
2972 /// optimization is performed and it is required (FPDiff!=0).
2973 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2974                                         SDValue Chain, SDValue RetAddrFrIdx,
2975                                         EVT PtrVT, unsigned SlotSize,
2976                                         int FPDiff, SDLoc dl) {
2977   // Store the return address to the appropriate stack slot.
2978   if (!FPDiff) return Chain;
2979   // Calculate the new stack slot for the return address.
2980   int NewReturnAddrFI =
2981     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2982                                          false);
2983   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2984   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2985                        MachinePointerInfo::getFixedStack(
2986                            DAG.getMachineFunction(), NewReturnAddrFI),
2987                        false, false, 0);
2988   return Chain;
2989 }
2990
2991 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2992 /// operation of specified width.
2993 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2994                        SDValue V2) {
2995   unsigned NumElems = VT.getVectorNumElements();
2996   SmallVector<int, 8> Mask;
2997   Mask.push_back(NumElems);
2998   for (unsigned i = 1; i != NumElems; ++i)
2999     Mask.push_back(i);
3000   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3001 }
3002
3003 SDValue
3004 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3005                              SmallVectorImpl<SDValue> &InVals) const {
3006   SelectionDAG &DAG                     = CLI.DAG;
3007   SDLoc &dl                             = CLI.DL;
3008   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3009   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3010   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3011   SDValue Chain                         = CLI.Chain;
3012   SDValue Callee                        = CLI.Callee;
3013   CallingConv::ID CallConv              = CLI.CallConv;
3014   bool &isTailCall                      = CLI.IsTailCall;
3015   bool isVarArg                         = CLI.IsVarArg;
3016
3017   MachineFunction &MF = DAG.getMachineFunction();
3018   bool Is64Bit        = Subtarget->is64Bit();
3019   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
3020   StructReturnType SR = callIsStructReturn(Outs);
3021   bool IsSibcall      = false;
3022   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3023   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3024
3025   if (Attr.getValueAsString() == "true")
3026     isTailCall = false;
3027
3028   if (Subtarget->isPICStyleGOT() &&
3029       !MF.getTarget().Options.GuaranteedTailCallOpt) {
3030     // If we are using a GOT, disable tail calls to external symbols with
3031     // default visibility. Tail calling such a symbol requires using a GOT
3032     // relocation, which forces early binding of the symbol. This breaks code
3033     // that require lazy function symbol resolution. Using musttail or
3034     // GuaranteedTailCallOpt will override this.
3035     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3036     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3037                G->getGlobal()->hasDefaultVisibility()))
3038       isTailCall = false;
3039   }
3040
3041   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3042   if (IsMustTail) {
3043     // Force this to be a tail call.  The verifier rules are enough to ensure
3044     // that we can lower this successfully without moving the return address
3045     // around.
3046     isTailCall = true;
3047   } else if (isTailCall) {
3048     // Check if it's really possible to do a tail call.
3049     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3050                     isVarArg, SR != NotStructReturn,
3051                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3052                     Outs, OutVals, Ins, DAG);
3053
3054     // Sibcalls are automatically detected tailcalls which do not require
3055     // ABI changes.
3056     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3057       IsSibcall = true;
3058
3059     if (isTailCall)
3060       ++NumTailCalls;
3061   }
3062
3063   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3064          "Var args not supported with calling convention fastcc, ghc or hipe");
3065
3066   // Analyze operands of the call, assigning locations to each operand.
3067   SmallVector<CCValAssign, 16> ArgLocs;
3068   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3069
3070   // Allocate shadow area for Win64
3071   if (IsWin64)
3072     CCInfo.AllocateStack(32, 8);
3073
3074   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3075
3076   // Get a count of how many bytes are to be pushed on the stack.
3077   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3078   if (IsSibcall)
3079     // This is a sibcall. The memory operands are available in caller's
3080     // own caller's stack.
3081     NumBytes = 0;
3082   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3083            canGuaranteeTCO(CallConv))
3084     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3085
3086   int FPDiff = 0;
3087   if (isTailCall && !IsSibcall && !IsMustTail) {
3088     // Lower arguments at fp - stackoffset + fpdiff.
3089     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3090
3091     FPDiff = NumBytesCallerPushed - NumBytes;
3092
3093     // Set the delta of movement of the returnaddr stackslot.
3094     // But only set if delta is greater than previous delta.
3095     if (FPDiff < X86Info->getTCReturnAddrDelta())
3096       X86Info->setTCReturnAddrDelta(FPDiff);
3097   }
3098
3099   unsigned NumBytesToPush = NumBytes;
3100   unsigned NumBytesToPop = NumBytes;
3101
3102   // If we have an inalloca argument, all stack space has already been allocated
3103   // for us and be right at the top of the stack.  We don't support multiple
3104   // arguments passed in memory when using inalloca.
3105   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3106     NumBytesToPush = 0;
3107     if (!ArgLocs.back().isMemLoc())
3108       report_fatal_error("cannot use inalloca attribute on a register "
3109                          "parameter");
3110     if (ArgLocs.back().getLocMemOffset() != 0)
3111       report_fatal_error("any parameter with the inalloca attribute must be "
3112                          "the only memory argument");
3113   }
3114
3115   if (!IsSibcall)
3116     Chain = DAG.getCALLSEQ_START(
3117         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3118
3119   SDValue RetAddrFrIdx;
3120   // Load return address for tail calls.
3121   if (isTailCall && FPDiff)
3122     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3123                                     Is64Bit, FPDiff, dl);
3124
3125   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3126   SmallVector<SDValue, 8> MemOpChains;
3127   SDValue StackPtr;
3128
3129   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3130   // of tail call optimization arguments are handle later.
3131   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3132   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3133     // Skip inalloca arguments, they have already been written.
3134     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3135     if (Flags.isInAlloca())
3136       continue;
3137
3138     CCValAssign &VA = ArgLocs[i];
3139     EVT RegVT = VA.getLocVT();
3140     SDValue Arg = OutVals[i];
3141     bool isByVal = Flags.isByVal();
3142
3143     // Promote the value if needed.
3144     switch (VA.getLocInfo()) {
3145     default: llvm_unreachable("Unknown loc info!");
3146     case CCValAssign::Full: break;
3147     case CCValAssign::SExt:
3148       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3149       break;
3150     case CCValAssign::ZExt:
3151       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3152       break;
3153     case CCValAssign::AExt:
3154       if (Arg.getValueType().isVector() &&
3155           Arg.getValueType().getScalarType() == MVT::i1)
3156         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3157       else if (RegVT.is128BitVector()) {
3158         // Special case: passing MMX values in XMM registers.
3159         Arg = DAG.getBitcast(MVT::i64, Arg);
3160         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3161         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3162       } else
3163         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3164       break;
3165     case CCValAssign::BCvt:
3166       Arg = DAG.getBitcast(RegVT, Arg);
3167       break;
3168     case CCValAssign::Indirect: {
3169       // Store the argument.
3170       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3171       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3172       Chain = DAG.getStore(
3173           Chain, dl, Arg, SpillSlot,
3174           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3175           false, false, 0);
3176       Arg = SpillSlot;
3177       break;
3178     }
3179     }
3180
3181     if (VA.isRegLoc()) {
3182       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3183       if (isVarArg && IsWin64) {
3184         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3185         // shadow reg if callee is a varargs function.
3186         unsigned ShadowReg = 0;
3187         switch (VA.getLocReg()) {
3188         case X86::XMM0: ShadowReg = X86::RCX; break;
3189         case X86::XMM1: ShadowReg = X86::RDX; break;
3190         case X86::XMM2: ShadowReg = X86::R8; break;
3191         case X86::XMM3: ShadowReg = X86::R9; break;
3192         }
3193         if (ShadowReg)
3194           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3195       }
3196     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3197       assert(VA.isMemLoc());
3198       if (!StackPtr.getNode())
3199         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3200                                       getPointerTy(DAG.getDataLayout()));
3201       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3202                                              dl, DAG, VA, Flags));
3203     }
3204   }
3205
3206   if (!MemOpChains.empty())
3207     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3208
3209   if (Subtarget->isPICStyleGOT()) {
3210     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3211     // GOT pointer.
3212     if (!isTailCall) {
3213       RegsToPass.push_back(std::make_pair(
3214           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3215                                           getPointerTy(DAG.getDataLayout()))));
3216     } else {
3217       // If we are tail calling and generating PIC/GOT style code load the
3218       // address of the callee into ECX. The value in ecx is used as target of
3219       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3220       // for tail calls on PIC/GOT architectures. Normally we would just put the
3221       // address of GOT into ebx and then call target@PLT. But for tail calls
3222       // ebx would be restored (since ebx is callee saved) before jumping to the
3223       // target@PLT.
3224
3225       // Note: The actual moving to ECX is done further down.
3226       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3227       if (G && !G->getGlobal()->hasLocalLinkage() &&
3228           G->getGlobal()->hasDefaultVisibility())
3229         Callee = LowerGlobalAddress(Callee, DAG);
3230       else if (isa<ExternalSymbolSDNode>(Callee))
3231         Callee = LowerExternalSymbol(Callee, DAG);
3232     }
3233   }
3234
3235   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3236     // From AMD64 ABI document:
3237     // For calls that may call functions that use varargs or stdargs
3238     // (prototype-less calls or calls to functions containing ellipsis (...) in
3239     // the declaration) %al is used as hidden argument to specify the number
3240     // of SSE registers used. The contents of %al do not need to match exactly
3241     // the number of registers, but must be an ubound on the number of SSE
3242     // registers used and is in the range 0 - 8 inclusive.
3243
3244     // Count the number of XMM registers allocated.
3245     static const MCPhysReg XMMArgRegs[] = {
3246       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3247       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3248     };
3249     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3250     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3251            && "SSE registers cannot be used when SSE is disabled");
3252
3253     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3254                                         DAG.getConstant(NumXMMRegs, dl,
3255                                                         MVT::i8)));
3256   }
3257
3258   if (isVarArg && IsMustTail) {
3259     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3260     for (const auto &F : Forwards) {
3261       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3262       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3263     }
3264   }
3265
3266   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3267   // don't need this because the eligibility check rejects calls that require
3268   // shuffling arguments passed in memory.
3269   if (!IsSibcall && isTailCall) {
3270     // Force all the incoming stack arguments to be loaded from the stack
3271     // before any new outgoing arguments are stored to the stack, because the
3272     // outgoing stack slots may alias the incoming argument stack slots, and
3273     // the alias isn't otherwise explicit. This is slightly more conservative
3274     // than necessary, because it means that each store effectively depends
3275     // on every argument instead of just those arguments it would clobber.
3276     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3277
3278     SmallVector<SDValue, 8> MemOpChains2;
3279     SDValue FIN;
3280     int FI = 0;
3281     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3282       CCValAssign &VA = ArgLocs[i];
3283       if (VA.isRegLoc())
3284         continue;
3285       assert(VA.isMemLoc());
3286       SDValue Arg = OutVals[i];
3287       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3288       // Skip inalloca arguments.  They don't require any work.
3289       if (Flags.isInAlloca())
3290         continue;
3291       // Create frame index.
3292       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3293       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3294       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3295       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3296
3297       if (Flags.isByVal()) {
3298         // Copy relative to framepointer.
3299         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3300         if (!StackPtr.getNode())
3301           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3302                                         getPointerTy(DAG.getDataLayout()));
3303         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3304                              StackPtr, Source);
3305
3306         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3307                                                          ArgChain,
3308                                                          Flags, DAG, dl));
3309       } else {
3310         // Store relative to framepointer.
3311         MemOpChains2.push_back(DAG.getStore(
3312             ArgChain, dl, Arg, FIN,
3313             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3314             false, false, 0));
3315       }
3316     }
3317
3318     if (!MemOpChains2.empty())
3319       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3320
3321     // Store the return address to the appropriate stack slot.
3322     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3323                                      getPointerTy(DAG.getDataLayout()),
3324                                      RegInfo->getSlotSize(), FPDiff, dl);
3325   }
3326
3327   // Build a sequence of copy-to-reg nodes chained together with token chain
3328   // and flag operands which copy the outgoing args into registers.
3329   SDValue InFlag;
3330   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3331     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3332                              RegsToPass[i].second, InFlag);
3333     InFlag = Chain.getValue(1);
3334   }
3335
3336   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3337     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3338     // In the 64-bit large code model, we have to make all calls
3339     // through a register, since the call instruction's 32-bit
3340     // pc-relative offset may not be large enough to hold the whole
3341     // address.
3342   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3343     // If the callee is a GlobalAddress node (quite common, every direct call
3344     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3345     // it.
3346     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3347
3348     // We should use extra load for direct calls to dllimported functions in
3349     // non-JIT mode.
3350     const GlobalValue *GV = G->getGlobal();
3351     if (!GV->hasDLLImportStorageClass()) {
3352       unsigned char OpFlags = 0;
3353       bool ExtraLoad = false;
3354       unsigned WrapperKind = ISD::DELETED_NODE;
3355
3356       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3357       // external symbols most go through the PLT in PIC mode.  If the symbol
3358       // has hidden or protected visibility, or if it is static or local, then
3359       // we don't need to use the PLT - we can directly call it.
3360       if (Subtarget->isTargetELF() &&
3361           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3362           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3363         OpFlags = X86II::MO_PLT;
3364       } else if (Subtarget->isPICStyleStubAny() &&
3365                  !GV->isStrongDefinitionForLinker() &&
3366                  (!Subtarget->getTargetTriple().isMacOSX() ||
3367                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3368         // PC-relative references to external symbols should go through $stub,
3369         // unless we're building with the leopard linker or later, which
3370         // automatically synthesizes these stubs.
3371         OpFlags = X86II::MO_DARWIN_STUB;
3372       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3373                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3374         // If the function is marked as non-lazy, generate an indirect call
3375         // which loads from the GOT directly. This avoids runtime overhead
3376         // at the cost of eager binding (and one extra byte of encoding).
3377         OpFlags = X86II::MO_GOTPCREL;
3378         WrapperKind = X86ISD::WrapperRIP;
3379         ExtraLoad = true;
3380       }
3381
3382       Callee = DAG.getTargetGlobalAddress(
3383           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3384
3385       // Add a wrapper if needed.
3386       if (WrapperKind != ISD::DELETED_NODE)
3387         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3388                              getPointerTy(DAG.getDataLayout()), Callee);
3389       // Add extra indirection if needed.
3390       if (ExtraLoad)
3391         Callee = DAG.getLoad(
3392             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3393             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3394             false, 0);
3395     }
3396   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3397     unsigned char OpFlags = 0;
3398
3399     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3400     // external symbols should go through the PLT.
3401     if (Subtarget->isTargetELF() &&
3402         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3403       OpFlags = X86II::MO_PLT;
3404     } else if (Subtarget->isPICStyleStubAny() &&
3405                (!Subtarget->getTargetTriple().isMacOSX() ||
3406                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3407       // PC-relative references to external symbols should go through $stub,
3408       // unless we're building with the leopard linker or later, which
3409       // automatically synthesizes these stubs.
3410       OpFlags = X86II::MO_DARWIN_STUB;
3411     }
3412
3413     Callee = DAG.getTargetExternalSymbol(
3414         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3415   } else if (Subtarget->isTarget64BitILP32() &&
3416              Callee->getValueType(0) == MVT::i32) {
3417     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3418     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3419   }
3420
3421   // Returns a chain & a flag for retval copy to use.
3422   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3423   SmallVector<SDValue, 8> Ops;
3424
3425   if (!IsSibcall && isTailCall) {
3426     Chain = DAG.getCALLSEQ_END(Chain,
3427                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3428                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3429     InFlag = Chain.getValue(1);
3430   }
3431
3432   Ops.push_back(Chain);
3433   Ops.push_back(Callee);
3434
3435   if (isTailCall)
3436     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3437
3438   // Add argument registers to the end of the list so that they are known live
3439   // into the call.
3440   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3441     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3442                                   RegsToPass[i].second.getValueType()));
3443
3444   // Add a register mask operand representing the call-preserved registers.
3445   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3446   assert(Mask && "Missing call preserved mask for calling convention");
3447
3448   // If this is an invoke in a 32-bit function using a funclet-based
3449   // personality, assume the function clobbers all registers. If an exception
3450   // is thrown, the runtime will not restore CSRs.
3451   // FIXME: Model this more precisely so that we can register allocate across
3452   // the normal edge and spill and fill across the exceptional edge.
3453   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3454     const Function *CallerFn = MF.getFunction();
3455     EHPersonality Pers =
3456         CallerFn->hasPersonalityFn()
3457             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3458             : EHPersonality::Unknown;
3459     if (isFuncletEHPersonality(Pers))
3460       Mask = RegInfo->getNoPreservedMask();
3461   }
3462
3463   Ops.push_back(DAG.getRegisterMask(Mask));
3464
3465   if (InFlag.getNode())
3466     Ops.push_back(InFlag);
3467
3468   if (isTailCall) {
3469     // We used to do:
3470     //// If this is the first return lowered for this function, add the regs
3471     //// to the liveout set for the function.
3472     // This isn't right, although it's probably harmless on x86; liveouts
3473     // should be computed from returns not tail calls.  Consider a void
3474     // function making a tail call to a function returning int.
3475     MF.getFrameInfo()->setHasTailCall();
3476     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3477   }
3478
3479   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3480   InFlag = Chain.getValue(1);
3481
3482   // Create the CALLSEQ_END node.
3483   unsigned NumBytesForCalleeToPop;
3484   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3485                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3486     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3487   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3488            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3489            SR == StackStructReturn)
3490     // If this is a call to a struct-return function, the callee
3491     // pops the hidden struct pointer, so we have to push it back.
3492     // This is common for Darwin/X86, Linux & Mingw32 targets.
3493     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3494     NumBytesForCalleeToPop = 4;
3495   else
3496     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3497
3498   // Returns a flag for retval copy to use.
3499   if (!IsSibcall) {
3500     Chain = DAG.getCALLSEQ_END(Chain,
3501                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3502                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3503                                                      true),
3504                                InFlag, dl);
3505     InFlag = Chain.getValue(1);
3506   }
3507
3508   // Handle result values, copying them out of physregs into vregs that we
3509   // return.
3510   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3511                          Ins, dl, DAG, InVals);
3512 }
3513
3514 //===----------------------------------------------------------------------===//
3515 //                Fast Calling Convention (tail call) implementation
3516 //===----------------------------------------------------------------------===//
3517
3518 //  Like std call, callee cleans arguments, convention except that ECX is
3519 //  reserved for storing the tail called function address. Only 2 registers are
3520 //  free for argument passing (inreg). Tail call optimization is performed
3521 //  provided:
3522 //                * tailcallopt is enabled
3523 //                * caller/callee are fastcc
3524 //  On X86_64 architecture with GOT-style position independent code only local
3525 //  (within module) calls are supported at the moment.
3526 //  To keep the stack aligned according to platform abi the function
3527 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3528 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3529 //  If a tail called function callee has more arguments than the caller the
3530 //  caller needs to make sure that there is room to move the RETADDR to. This is
3531 //  achieved by reserving an area the size of the argument delta right after the
3532 //  original RETADDR, but before the saved framepointer or the spilled registers
3533 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3534 //  stack layout:
3535 //    arg1
3536 //    arg2
3537 //    RETADDR
3538 //    [ new RETADDR
3539 //      move area ]
3540 //    (possible EBP)
3541 //    ESI
3542 //    EDI
3543 //    local1 ..
3544
3545 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3546 /// requirement.
3547 unsigned
3548 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3549                                                SelectionDAG& DAG) const {
3550   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3551   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3552   unsigned StackAlignment = TFI.getStackAlignment();
3553   uint64_t AlignMask = StackAlignment - 1;
3554   int64_t Offset = StackSize;
3555   unsigned SlotSize = RegInfo->getSlotSize();
3556   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3557     // Number smaller than 12 so just add the difference.
3558     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3559   } else {
3560     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3561     Offset = ((~AlignMask) & Offset) + StackAlignment +
3562       (StackAlignment-SlotSize);
3563   }
3564   return Offset;
3565 }
3566
3567 /// Return true if the given stack call argument is already available in the
3568 /// same position (relatively) of the caller's incoming argument stack.
3569 static
3570 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3571                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3572                          const X86InstrInfo *TII) {
3573   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3574   int FI = INT_MAX;
3575   if (Arg.getOpcode() == ISD::CopyFromReg) {
3576     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3577     if (!TargetRegisterInfo::isVirtualRegister(VR))
3578       return false;
3579     MachineInstr *Def = MRI->getVRegDef(VR);
3580     if (!Def)
3581       return false;
3582     if (!Flags.isByVal()) {
3583       if (!TII->isLoadFromStackSlot(Def, FI))
3584         return false;
3585     } else {
3586       unsigned Opcode = Def->getOpcode();
3587       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3588            Opcode == X86::LEA64_32r) &&
3589           Def->getOperand(1).isFI()) {
3590         FI = Def->getOperand(1).getIndex();
3591         Bytes = Flags.getByValSize();
3592       } else
3593         return false;
3594     }
3595   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3596     if (Flags.isByVal())
3597       // ByVal argument is passed in as a pointer but it's now being
3598       // dereferenced. e.g.
3599       // define @foo(%struct.X* %A) {
3600       //   tail call @bar(%struct.X* byval %A)
3601       // }
3602       return false;
3603     SDValue Ptr = Ld->getBasePtr();
3604     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3605     if (!FINode)
3606       return false;
3607     FI = FINode->getIndex();
3608   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3609     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3610     FI = FINode->getIndex();
3611     Bytes = Flags.getByValSize();
3612   } else
3613     return false;
3614
3615   assert(FI != INT_MAX);
3616   if (!MFI->isFixedObjectIndex(FI))
3617     return false;
3618   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3619 }
3620
3621 /// Check whether the call is eligible for tail call optimization. Targets
3622 /// that want to do tail call optimization should implement this function.
3623 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3624     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3625     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3626     const SmallVectorImpl<ISD::OutputArg> &Outs,
3627     const SmallVectorImpl<SDValue> &OutVals,
3628     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3629   if (!mayTailCallThisCC(CalleeCC))
3630     return false;
3631
3632   // If -tailcallopt is specified, make fastcc functions tail-callable.
3633   MachineFunction &MF = DAG.getMachineFunction();
3634   const Function *CallerF = MF.getFunction();
3635
3636   // If the function return type is x86_fp80 and the callee return type is not,
3637   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3638   // perform a tailcall optimization here.
3639   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3640     return false;
3641
3642   CallingConv::ID CallerCC = CallerF->getCallingConv();
3643   bool CCMatch = CallerCC == CalleeCC;
3644   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3645   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3646
3647   // Win64 functions have extra shadow space for argument homing. Don't do the
3648   // sibcall if the caller and callee have mismatched expectations for this
3649   // space.
3650   if (IsCalleeWin64 != IsCallerWin64)
3651     return false;
3652
3653   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3654     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3655       return true;
3656     return false;
3657   }
3658
3659   // Look for obvious safe cases to perform tail call optimization that do not
3660   // require ABI changes. This is what gcc calls sibcall.
3661
3662   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3663   // emit a special epilogue.
3664   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3665   if (RegInfo->needsStackRealignment(MF))
3666     return false;
3667
3668   // Also avoid sibcall optimization if either caller or callee uses struct
3669   // return semantics.
3670   if (isCalleeStructRet || isCallerStructRet)
3671     return false;
3672
3673   // Do not sibcall optimize vararg calls unless all arguments are passed via
3674   // registers.
3675   if (isVarArg && !Outs.empty()) {
3676     // Optimizing for varargs on Win64 is unlikely to be safe without
3677     // additional testing.
3678     if (IsCalleeWin64 || IsCallerWin64)
3679       return false;
3680
3681     SmallVector<CCValAssign, 16> ArgLocs;
3682     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3683                    *DAG.getContext());
3684
3685     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3686     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3687       if (!ArgLocs[i].isRegLoc())
3688         return false;
3689   }
3690
3691   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3692   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3693   // this into a sibcall.
3694   bool Unused = false;
3695   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3696     if (!Ins[i].Used) {
3697       Unused = true;
3698       break;
3699     }
3700   }
3701   if (Unused) {
3702     SmallVector<CCValAssign, 16> RVLocs;
3703     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3704                    *DAG.getContext());
3705     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3706     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3707       CCValAssign &VA = RVLocs[i];
3708       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3709         return false;
3710     }
3711   }
3712
3713   // If the calling conventions do not match, then we'd better make sure the
3714   // results are returned in the same way as what the caller expects.
3715   if (!CCMatch) {
3716     SmallVector<CCValAssign, 16> RVLocs1;
3717     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3718                     *DAG.getContext());
3719     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3720
3721     SmallVector<CCValAssign, 16> RVLocs2;
3722     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3723                     *DAG.getContext());
3724     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3725
3726     if (RVLocs1.size() != RVLocs2.size())
3727       return false;
3728     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3729       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3730         return false;
3731       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3732         return false;
3733       if (RVLocs1[i].isRegLoc()) {
3734         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3735           return false;
3736       } else {
3737         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3738           return false;
3739       }
3740     }
3741   }
3742
3743   unsigned StackArgsSize = 0;
3744
3745   // If the callee takes no arguments then go on to check the results of the
3746   // call.
3747   if (!Outs.empty()) {
3748     // Check if stack adjustment is needed. For now, do not do this if any
3749     // argument is passed on the stack.
3750     SmallVector<CCValAssign, 16> ArgLocs;
3751     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3752                    *DAG.getContext());
3753
3754     // Allocate shadow area for Win64
3755     if (IsCalleeWin64)
3756       CCInfo.AllocateStack(32, 8);
3757
3758     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3759     StackArgsSize = CCInfo.getNextStackOffset();
3760
3761     if (CCInfo.getNextStackOffset()) {
3762       // Check if the arguments are already laid out in the right way as
3763       // the caller's fixed stack objects.
3764       MachineFrameInfo *MFI = MF.getFrameInfo();
3765       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3766       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3767       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3768         CCValAssign &VA = ArgLocs[i];
3769         SDValue Arg = OutVals[i];
3770         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3771         if (VA.getLocInfo() == CCValAssign::Indirect)
3772           return false;
3773         if (!VA.isRegLoc()) {
3774           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3775                                    MFI, MRI, TII))
3776             return false;
3777         }
3778       }
3779     }
3780
3781     // If the tailcall address may be in a register, then make sure it's
3782     // possible to register allocate for it. In 32-bit, the call address can
3783     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3784     // callee-saved registers are restored. These happen to be the same
3785     // registers used to pass 'inreg' arguments so watch out for those.
3786     if (!Subtarget->is64Bit() &&
3787         ((!isa<GlobalAddressSDNode>(Callee) &&
3788           !isa<ExternalSymbolSDNode>(Callee)) ||
3789          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3790       unsigned NumInRegs = 0;
3791       // In PIC we need an extra register to formulate the address computation
3792       // for the callee.
3793       unsigned MaxInRegs =
3794         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3795
3796       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3797         CCValAssign &VA = ArgLocs[i];
3798         if (!VA.isRegLoc())
3799           continue;
3800         unsigned Reg = VA.getLocReg();
3801         switch (Reg) {
3802         default: break;
3803         case X86::EAX: case X86::EDX: case X86::ECX:
3804           if (++NumInRegs == MaxInRegs)
3805             return false;
3806           break;
3807         }
3808       }
3809     }
3810   }
3811
3812   bool CalleeWillPop =
3813       X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3814        &nb