Bug Summary

File:include/llvm/ADT/SmallBitVector.h
Warning:line 125, column 3
Potential memory leak

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name X86ISelLowering.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/lib/Target/X86 -I /build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86 -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn338205/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/8/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/lib/Target/X86 -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-07-29-043837-17923-1 -x c++ /build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp -faddrsig

/build/llvm-toolchain-snapshot-7~svn338205/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 "X86IntrinsicsInfo.h"
21#include "X86MachineFunctionInfo.h"
22#include "X86ShuffleDecodeConstantPool.h"
23#include "X86TargetMachine.h"
24#include "X86TargetObjectFile.h"
25#include "llvm/ADT/SmallBitVector.h"
26#include "llvm/ADT/SmallSet.h"
27#include "llvm/ADT/Statistic.h"
28#include "llvm/ADT/StringExtras.h"
29#include "llvm/ADT/StringSwitch.h"
30#include "llvm/Analysis/EHPersonalities.h"
31#include "llvm/CodeGen/IntrinsicLowering.h"
32#include "llvm/CodeGen/MachineFrameInfo.h"
33#include "llvm/CodeGen/MachineFunction.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
35#include "llvm/CodeGen/MachineJumpTableInfo.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
38#include "llvm/CodeGen/TargetLowering.h"
39#include "llvm/CodeGen/WinEHFuncInfo.h"
40#include "llvm/IR/CallSite.h"
41#include "llvm/IR/CallingConv.h"
42#include "llvm/IR/Constants.h"
43#include "llvm/IR/DerivedTypes.h"
44#include "llvm/IR/DiagnosticInfo.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/GlobalAlias.h"
47#include "llvm/IR/GlobalVariable.h"
48#include "llvm/IR/Instructions.h"
49#include "llvm/IR/Intrinsics.h"
50#include "llvm/MC/MCAsmInfo.h"
51#include "llvm/MC/MCContext.h"
52#include "llvm/MC/MCExpr.h"
53#include "llvm/MC/MCSymbol.h"
54#include "llvm/Support/CommandLine.h"
55#include "llvm/Support/Debug.h"
56#include "llvm/Support/ErrorHandling.h"
57#include "llvm/Support/KnownBits.h"
58#include "llvm/Support/MathExtras.h"
59#include "llvm/Target/TargetOptions.h"
60#include <algorithm>
61#include <bitset>
62#include <cctype>
63#include <numeric>
64using namespace llvm;
65
66#define DEBUG_TYPE"x86-isel" "x86-isel"
67
68STATISTIC(NumTailCalls, "Number of tail calls")static llvm::Statistic NumTailCalls = {"x86-isel", "NumTailCalls"
, "Number of tail calls", {0}, {false}}
;
69
70static cl::opt<bool> ExperimentalVectorWideningLegalization(
71 "x86-experimental-vector-widening-legalization", cl::init(false),
72 cl::desc("Enable an experimental vector type legalization through widening "
73 "rather than promotion."),
74 cl::Hidden);
75
76static cl::opt<int> ExperimentalPrefLoopAlignment(
77 "x86-experimental-pref-loop-alignment", cl::init(4),
78 cl::desc("Sets the preferable loop alignment for experiments "
79 "(the last x86-experimental-pref-loop-alignment bits"
80 " of the loop header PC will be 0)."),
81 cl::Hidden);
82
83static cl::opt<bool> MulConstantOptimization(
84 "mul-constant-optimization", cl::init(true),
85 cl::desc("Replace 'mul x, Const' with more effective instructions like "
86 "SHIFT, LEA, etc."),
87 cl::Hidden);
88
89/// Call this when the user attempts to do something unsupported, like
90/// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike
91/// report_fatal_error, so calling code should attempt to recover without
92/// crashing.
93static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl,
94 const char *Msg) {
95 MachineFunction &MF = DAG.getMachineFunction();
96 DAG.getContext()->diagnose(
97 DiagnosticInfoUnsupported(MF.getFunction(), Msg, dl.getDebugLoc()));
98}
99
100X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
101 const X86Subtarget &STI)
102 : TargetLowering(TM), Subtarget(STI) {
103 bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
104 X86ScalarSSEf64 = Subtarget.hasSSE2();
105 X86ScalarSSEf32 = Subtarget.hasSSE1();
106 MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
107
108 // Set up the TargetLowering object.
109
110 // X86 is weird. It always uses i8 for shift amounts and setcc results.
111 setBooleanContents(ZeroOrOneBooleanContent);
112 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
113 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
114
115 // For 64-bit, since we have so many registers, use the ILP scheduler.
116 // For 32-bit, use the register pressure specific scheduling.
117 // For Atom, always use ILP scheduling.
118 if (Subtarget.isAtom())
119 setSchedulingPreference(Sched::ILP);
120 else if (Subtarget.is64Bit())
121 setSchedulingPreference(Sched::ILP);
122 else
123 setSchedulingPreference(Sched::RegPressure);
124 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
125 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
126
127 // Bypass expensive divides and use cheaper ones.
128 if (TM.getOptLevel() >= CodeGenOpt::Default) {
129 if (Subtarget.hasSlowDivide32())
130 addBypassSlowDiv(32, 8);
131 if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
132 addBypassSlowDiv(64, 32);
133 }
134
135 if (Subtarget.isTargetKnownWindowsMSVC() ||
136 Subtarget.isTargetWindowsItanium()) {
137 // Setup Windows compiler runtime calls.
138 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
139 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
140 setLibcallName(RTLIB::SREM_I64, "_allrem");
141 setLibcallName(RTLIB::UREM_I64, "_aullrem");
142 setLibcallName(RTLIB::MUL_I64, "_allmul");
143 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
144 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
145 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
146 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
147 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
148 }
149
150 if (Subtarget.isTargetDarwin()) {
151 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
152 setUseUnderscoreSetJmp(false);
153 setUseUnderscoreLongJmp(false);
154 } else if (Subtarget.isTargetWindowsGNU()) {
155 // MS runtime is weird: it exports _setjmp, but longjmp!
156 setUseUnderscoreSetJmp(true);
157 setUseUnderscoreLongJmp(false);
158 } else {
159 setUseUnderscoreSetJmp(true);
160 setUseUnderscoreLongJmp(true);
161 }
162
163 // Set up the register classes.
164 addRegisterClass(MVT::i8, &X86::GR8RegClass);
165 addRegisterClass(MVT::i16, &X86::GR16RegClass);
166 addRegisterClass(MVT::i32, &X86::GR32RegClass);
167 if (Subtarget.is64Bit())
168 addRegisterClass(MVT::i64, &X86::GR64RegClass);
169
170 for (MVT VT : MVT::integer_valuetypes())
171 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
172
173 // We don't accept any truncstore of integer registers.
174 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
175 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
176 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
177 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
178 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
179 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
180
181 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
182
183 // SETOEQ and SETUNE require checking two conditions.
184 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
185 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
186 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
187 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
188 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
189 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
190
191 // Integer absolute.
192 if (Subtarget.hasCMov()) {
193 setOperationAction(ISD::ABS , MVT::i16 , Custom);
194 setOperationAction(ISD::ABS , MVT::i32 , Custom);
195 if (Subtarget.is64Bit())
196 setOperationAction(ISD::ABS , MVT::i64 , Custom);
197 }
198
199 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
200 // operation.
201 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
202 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
203 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
204
205 if (Subtarget.is64Bit()) {
206 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512())
207 // f32/f64 are legal, f80 is custom.
208 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
209 else
210 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
211 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
212 } else if (!Subtarget.useSoftFloat()) {
213 // We have an algorithm for SSE2->double, and we turn this into a
214 // 64-bit FILD followed by conditional FADD for other targets.
215 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
216 // We have an algorithm for SSE2, and we turn this into a 64-bit
217 // FILD or VCVTUSI2SS/SD for other targets.
218 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
219 } else {
220 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
221 }
222
223 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
224 // this operation.
225 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
226 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
227
228 if (!Subtarget.useSoftFloat()) {
229 // SSE has no i16 to fp conversion, only i32.
230 if (X86ScalarSSEf32) {
231 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
232 // f32 and f64 cases are Legal, f80 case is not
233 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
234 } else {
235 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
236 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
237 }
238 } else {
239 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
240 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Expand);
241 }
242
243 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
244 // this operation.
245 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
246 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
247
248 if (!Subtarget.useSoftFloat()) {
249 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
250 // are Legal, f80 is custom lowered.
251 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
252 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
253
254 if (X86ScalarSSEf32) {
255 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
256 // f32 and f64 cases are Legal, f80 case is not
257 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
258 } else {
259 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
260 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
261 }
262 } else {
263 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
264 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Expand);
265 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Expand);
266 }
267
268 // Handle FP_TO_UINT by promoting the destination to a larger signed
269 // conversion.
270 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
271 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
272 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
273
274 if (Subtarget.is64Bit()) {
275 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
276 // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
277 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
278 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
279 } else {
280 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
281 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
282 }
283 } else if (!Subtarget.useSoftFloat()) {
284 // Since AVX is a superset of SSE3, only check for SSE here.
285 if (Subtarget.hasSSE1() && !Subtarget.hasSSE3())
286 // Expand FP_TO_UINT into a select.
287 // FIXME: We would like to use a Custom expander here eventually to do
288 // the optimal thing for SSE vs. the default expansion in the legalizer.
289 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
290 else
291 // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
292 // With SSE3 we can use fisttpll to convert to a signed i64; without
293 // SSE, we're stuck with a fistpll.
294 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
295
296 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
297 }
298
299 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
300 if (!X86ScalarSSEf64) {
301 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
302 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
303 if (Subtarget.is64Bit()) {
304 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
305 // Without SSE, i64->f64 goes through memory.
306 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
307 }
308 } else if (!Subtarget.is64Bit())
309 setOperationAction(ISD::BITCAST , MVT::i64 , Custom);
310
311 // Scalar integer divide and remainder are lowered to use operations that
312 // produce two results, to match the available instructions. This exposes
313 // the two-result form to trivial CSE, which is able to combine x/y and x%y
314 // into a single instruction.
315 //
316 // Scalar integer multiply-high is also lowered to use two-result
317 // operations, to match the available instructions. However, plain multiply
318 // (low) operations are left as Legal, as there are single-result
319 // instructions for this in x86. Using the two-result multiply instructions
320 // when both high and low results are needed must be arranged by dagcombine.
321 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
322 setOperationAction(ISD::MULHS, VT, Expand);
323 setOperationAction(ISD::MULHU, VT, Expand);
324 setOperationAction(ISD::SDIV, VT, Expand);
325 setOperationAction(ISD::UDIV, VT, Expand);
326 setOperationAction(ISD::SREM, VT, Expand);
327 setOperationAction(ISD::UREM, VT, Expand);
328 }
329
330 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
331 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
332 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
333 MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
334 setOperationAction(ISD::BR_CC, VT, Expand);
335 setOperationAction(ISD::SELECT_CC, VT, Expand);
336 }
337 if (Subtarget.is64Bit())
338 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
339 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
340 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
341 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
342 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
343
344 setOperationAction(ISD::FREM , MVT::f32 , Expand);
345 setOperationAction(ISD::FREM , MVT::f64 , Expand);
346 setOperationAction(ISD::FREM , MVT::f80 , Expand);
347 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
348
349 // Promote the i8 variants and force them on up to i32 which has a shorter
350 // encoding.
351 setOperationPromotedToType(ISD::CTTZ , MVT::i8 , MVT::i32);
352 setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
353 if (!Subtarget.hasBMI()) {
354 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
355 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
356 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Legal);
357 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Legal);
358 if (Subtarget.is64Bit()) {
359 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
360 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Legal);
361 }
362 }
363
364 if (Subtarget.hasLZCNT()) {
365 // When promoting the i8 variants, force them to i32 for a shorter
366 // encoding.
367 setOperationPromotedToType(ISD::CTLZ , MVT::i8 , MVT::i32);
368 setOperationPromotedToType(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
369 } else {
370 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
371 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
372 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
373 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
374 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
375 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
376 if (Subtarget.is64Bit()) {
377 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
378 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
379 }
380 }
381
382 // Special handling for half-precision floating point conversions.
383 // If we don't have F16C support, then lower half float conversions
384 // into library calls.
385 if (Subtarget.useSoftFloat() || !Subtarget.hasF16C()) {
386 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
387 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
388 }
389
390 // There's never any support for operations beyond MVT::f32.
391 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
392 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
393 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
394 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
395
396 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
397 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
398 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
399 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
400 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
401 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
402
403 if (Subtarget.hasPOPCNT()) {
404 setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);
405 } else {
406 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
407 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
408 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
409 if (Subtarget.is64Bit())
410 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
411 }
412
413 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
414
415 if (!Subtarget.hasMOVBE())
416 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
417
418 // These should be promoted to a larger select which is supported.
419 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
420 // X86 wants to expand cmov itself.
421 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
422 setOperationAction(ISD::SELECT, VT, Custom);
423 setOperationAction(ISD::SETCC, VT, Custom);
424 }
425 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
426 if (VT == MVT::i64 && !Subtarget.is64Bit())
427 continue;
428 setOperationAction(ISD::SELECT, VT, Custom);
429 setOperationAction(ISD::SETCC, VT, Custom);
430 }
431
432 // Custom action for SELECT MMX and expand action for SELECT_CC MMX
433 setOperationAction(ISD::SELECT, MVT::x86mmx, Custom);
434 setOperationAction(ISD::SELECT_CC, MVT::x86mmx, Expand);
435
436 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
437 // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
438 // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
439 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
440 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
441 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
442 if (TM.Options.ExceptionModel == ExceptionHandling::SjLj)
443 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
444
445 // Darwin ABI issue.
446 for (auto VT : { MVT::i32, MVT::i64 }) {
447 if (VT == MVT::i64 && !Subtarget.is64Bit())
448 continue;
449 setOperationAction(ISD::ConstantPool , VT, Custom);
450 setOperationAction(ISD::JumpTable , VT, Custom);
451 setOperationAction(ISD::GlobalAddress , VT, Custom);
452 setOperationAction(ISD::GlobalTLSAddress, VT, Custom);
453 setOperationAction(ISD::ExternalSymbol , VT, Custom);
454 setOperationAction(ISD::BlockAddress , VT, Custom);
455 }
456
457 // 64-bit shl, sra, srl (iff 32-bit x86)
458 for (auto VT : { MVT::i32, MVT::i64 }) {
459 if (VT == MVT::i64 && !Subtarget.is64Bit())
460 continue;
461 setOperationAction(ISD::SHL_PARTS, VT, Custom);
462 setOperationAction(ISD::SRA_PARTS, VT, Custom);
463 setOperationAction(ISD::SRL_PARTS, VT, Custom);
464 }
465
466 if (Subtarget.hasSSEPrefetch() || Subtarget.has3DNow())
467 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
468
469 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
470
471 // Expand certain atomics
472 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
473 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
474 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
475 setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom);
476 setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom);
477 setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom);
478 setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom);
479 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
480 }
481
482 if (Subtarget.hasCmpxchg16b()) {
483 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
484 }
485
486 // FIXME - use subtarget debug flags
487 if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
488 !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
489 TM.Options.ExceptionModel != ExceptionHandling::SjLj) {
490 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
491 }
492
493 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
494 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
495
496 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
497 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
498
499 setOperationAction(ISD::TRAP, MVT::Other, Legal);
500 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
501
502 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
503 setOperationAction(ISD::VASTART , MVT::Other, Custom);
504 setOperationAction(ISD::VAEND , MVT::Other, Expand);
505 bool Is64Bit = Subtarget.is64Bit();
506 setOperationAction(ISD::VAARG, MVT::Other, Is64Bit ? Custom : Expand);
507 setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
508
509 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
510 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
511
512 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
513
514 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
515 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
516 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
517
518 if (!Subtarget.useSoftFloat() && X86ScalarSSEf64) {
519 // f32 and f64 use SSE.
520 // Set up the FP register classes.
521 addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
522 : &X86::FR32RegClass);
523 addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
524 : &X86::FR64RegClass);
525
526 for (auto VT : { MVT::f32, MVT::f64 }) {
527 // Use ANDPD to simulate FABS.
528 setOperationAction(ISD::FABS, VT, Custom);
529
530 // Use XORP to simulate FNEG.
531 setOperationAction(ISD::FNEG, VT, Custom);
532
533 // Use ANDPD and ORPD to simulate FCOPYSIGN.
534 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
535
536 // We don't support sin/cos/fmod
537 setOperationAction(ISD::FSIN , VT, Expand);
538 setOperationAction(ISD::FCOS , VT, Expand);
539 setOperationAction(ISD::FSINCOS, VT, Expand);
540 }
541
542 // Lower this to MOVMSK plus an AND.
543 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
544 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
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 (UseX87 && 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 // Always expand sin/cos functions even though x87 has an instruction.
581 setOperationAction(ISD::FSIN , MVT::f64, Expand);
582 setOperationAction(ISD::FCOS , MVT::f64, Expand);
583 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
584 } else if (UseX87) {
585 // f32 and f64 in x87.
586 // Set up the FP register classes.
587 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
588 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
589
590 for (auto VT : { MVT::f32, MVT::f64 }) {
591 setOperationAction(ISD::UNDEF, VT, Expand);
592 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
593
594 // Always expand sin/cos functions even though x87 has an instruction.
595 setOperationAction(ISD::FSIN , VT, Expand);
596 setOperationAction(ISD::FCOS , VT, Expand);
597 setOperationAction(ISD::FSINCOS, VT, Expand);
598 }
599 addLegalFPImmediate(APFloat(+0.0)); // FLD0
600 addLegalFPImmediate(APFloat(+1.0)); // FLD1
601 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
602 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
603 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
604 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
605 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
606 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
607 }
608
609 // We don't support FMA.
610 setOperationAction(ISD::FMA, MVT::f64, Expand);
611 setOperationAction(ISD::FMA, MVT::f32, Expand);
612
613 // Long double always uses X87, except f128 in MMX.
614 if (UseX87) {
615 if (Subtarget.is64Bit() && Subtarget.hasMMX()) {
616 addRegisterClass(MVT::f128, &X86::VR128RegClass);
617 ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
618 setOperationAction(ISD::FABS , MVT::f128, Custom);
619 setOperationAction(ISD::FNEG , MVT::f128, Custom);
620 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
621 }
622
623 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
624 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
625 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
626 {
627 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended());
628 addLegalFPImmediate(TmpFlt); // FLD0
629 TmpFlt.changeSign();
630 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
631
632 bool ignored;
633 APFloat TmpFlt2(+1.0);
634 TmpFlt2.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven,
635 &ignored);
636 addLegalFPImmediate(TmpFlt2); // FLD1
637 TmpFlt2.changeSign();
638 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
639 }
640
641 // Always expand sin/cos functions even though x87 has an instruction.
642 setOperationAction(ISD::FSIN , MVT::f80, Expand);
643 setOperationAction(ISD::FCOS , MVT::f80, Expand);
644 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
645
646 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
647 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
648 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
649 setOperationAction(ISD::FRINT, MVT::f80, Expand);
650 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
651 setOperationAction(ISD::FMA, MVT::f80, Expand);
652 }
653
654 // Always use a library call for pow.
655 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
656 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
657 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
658
659 setOperationAction(ISD::FLOG, MVT::f80, Expand);
660 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
661 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
662 setOperationAction(ISD::FEXP, MVT::f80, Expand);
663 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
664 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
665 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
666
667 // Some FP actions are always expanded for vector types.
668 for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
669 MVT::v2f64, MVT::v4f64, MVT::v8f64 }) {
670 setOperationAction(ISD::FSIN, VT, Expand);
671 setOperationAction(ISD::FSINCOS, VT, Expand);
672 setOperationAction(ISD::FCOS, VT, Expand);
673 setOperationAction(ISD::FREM, VT, Expand);
674 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
675 setOperationAction(ISD::FPOW, VT, Expand);
676 setOperationAction(ISD::FLOG, VT, Expand);
677 setOperationAction(ISD::FLOG2, VT, Expand);
678 setOperationAction(ISD::FLOG10, VT, Expand);
679 setOperationAction(ISD::FEXP, VT, Expand);
680 setOperationAction(ISD::FEXP2, VT, Expand);
681 }
682
683 // First set operation action for all vector types to either promote
684 // (for widening) or expand (for scalarization). Then we will selectively
685 // turn on ones that can be effectively codegen'd.
686 for (MVT VT : MVT::vector_valuetypes()) {
687 setOperationAction(ISD::SDIV, VT, Expand);
688 setOperationAction(ISD::UDIV, VT, Expand);
689 setOperationAction(ISD::SREM, VT, Expand);
690 setOperationAction(ISD::UREM, VT, Expand);
691 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
692 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
693 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
694 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
695 setOperationAction(ISD::FMA, VT, Expand);
696 setOperationAction(ISD::FFLOOR, VT, Expand);
697 setOperationAction(ISD::FCEIL, VT, Expand);
698 setOperationAction(ISD::FTRUNC, VT, Expand);
699 setOperationAction(ISD::FRINT, VT, Expand);
700 setOperationAction(ISD::FNEARBYINT, VT, Expand);
701 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
702 setOperationAction(ISD::MULHS, VT, Expand);
703 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
704 setOperationAction(ISD::MULHU, VT, Expand);
705 setOperationAction(ISD::SDIVREM, VT, Expand);
706 setOperationAction(ISD::UDIVREM, VT, Expand);
707 setOperationAction(ISD::CTPOP, VT, Expand);
708 setOperationAction(ISD::CTTZ, VT, Expand);
709 setOperationAction(ISD::CTLZ, VT, Expand);
710 setOperationAction(ISD::ROTL, VT, Expand);
711 setOperationAction(ISD::ROTR, VT, Expand);
712 setOperationAction(ISD::BSWAP, VT, Expand);
713 setOperationAction(ISD::SETCC, VT, Expand);
714 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
715 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
716 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
717 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
718 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
719 setOperationAction(ISD::TRUNCATE, VT, Expand);
720 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
721 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
722 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
723 setOperationAction(ISD::SELECT_CC, VT, Expand);
724 for (MVT InnerVT : MVT::vector_valuetypes()) {
725 setTruncStoreAction(InnerVT, VT, Expand);
726
727 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
728 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
729
730 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
731 // types, we have to deal with them whether we ask for Expansion or not.
732 // Setting Expand causes its own optimisation problems though, so leave
733 // them legal.
734 if (VT.getVectorElementType() == MVT::i1)
735 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
736
737 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
738 // split/scalarized right now.
739 if (VT.getVectorElementType() == MVT::f16)
740 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
741 }
742 }
743
744 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
745 // with -msoft-float, disable use of MMX as well.
746 if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
747 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
748 // No operations on x86mmx supported, everything uses intrinsics.
749 }
750
751 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
752 addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
753 : &X86::VR128RegClass);
754
755 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
756 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
757 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Custom);
758 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
759 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
760 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
761 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
762 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
763 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
764 }
765
766 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
767 addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
768 : &X86::VR128RegClass);
769
770 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
771 // registers cannot be used even for integer operations.
772 addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
773 : &X86::VR128RegClass);
774 addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
775 : &X86::VR128RegClass);
776 addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
777 : &X86::VR128RegClass);
778 addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
779 : &X86::VR128RegClass);
780
781 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
782 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
783 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
784 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
785 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
786 setOperationAction(ISD::MULHU, MVT::v16i8, Custom);
787 setOperationAction(ISD::MULHS, MVT::v16i8, Custom);
788 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
789 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
790 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
791 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
792 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
793 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Custom);
794
795 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
796 setOperationAction(ISD::SMAX, VT, VT == MVT::v8i16 ? Legal : Custom);
797 setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
798 setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
799 setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
800 }
801
802 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
803 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
804 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
805
806 // Provide custom widening for v2f32 setcc. This is really for VLX when
807 // setcc result type returns v2i1/v4i1 vector for v2f32/v4f32 leading to
808 // type legalization changing the result type to v4i1 during widening.
809 // It works fine for SSE2 and is probably faster so no need to qualify with
810 // VLX support.
811 setOperationAction(ISD::SETCC, MVT::v2i32, Custom);
812
813 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
814 setOperationAction(ISD::SETCC, VT, Custom);
815 setOperationAction(ISD::CTPOP, VT, Custom);
816 setOperationAction(ISD::CTTZ, VT, Custom);
817
818 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
819 // setcc all the way to isel and prefer SETGT in some isel patterns.
820 setCondCodeAction(ISD::SETLT, VT, Custom);
821 setCondCodeAction(ISD::SETLE, VT, Custom);
822 }
823
824 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
825 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
826 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
827 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
828 setOperationAction(ISD::VSELECT, VT, Custom);
829 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
830 }
831
832 // We support custom legalizing of sext and anyext loads for specific
833 // memory vector types which we can load as a scalar (or sequence of
834 // scalars) and extend in-register to a legal 128-bit vector type. For sext
835 // loads these must work with a single scalar load.
836 for (MVT VT : MVT::integer_vector_valuetypes()) {
837 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
838 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
839 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
840 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
841 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
842 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
843 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
844 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
845 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
846 }
847
848 for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
849 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
850 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
851 setOperationAction(ISD::VSELECT, VT, Custom);
852
853 if (VT == MVT::v2i64 && !Subtarget.is64Bit())
854 continue;
855
856 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
857 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
858 }
859
860 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
861 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
862 setOperationPromotedToType(ISD::AND, VT, MVT::v2i64);
863 setOperationPromotedToType(ISD::OR, VT, MVT::v2i64);
864 setOperationPromotedToType(ISD::XOR, VT, MVT::v2i64);
865 setOperationPromotedToType(ISD::LOAD, VT, MVT::v2i64);
866 setOperationPromotedToType(ISD::SELECT, VT, MVT::v2i64);
867 }
868
869 // Custom lower v2i64 and v2f64 selects.
870 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
871 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
872
873 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
874 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
875
876 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
877 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
878
879 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
880
881 // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
882 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
883
884 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
885 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
886
887 for (MVT VT : MVT::fp_vector_valuetypes())
888 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
889
890 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
891 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
892 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
893 if (!Subtarget.hasAVX512())
894 setOperationAction(ISD::BITCAST, MVT::v16i1, Custom);
895
896 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
897 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
898 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
899
900 // In the customized shift lowering, the legal v4i32/v2i64 cases
901 // in AVX2 will be recognized.
902 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
903 setOperationAction(ISD::SRL, VT, Custom);
904 setOperationAction(ISD::SHL, VT, Custom);
905 setOperationAction(ISD::SRA, VT, Custom);
906 }
907
908 setOperationAction(ISD::ROTL, MVT::v4i32, Custom);
909 setOperationAction(ISD::ROTL, MVT::v8i16, Custom);
910 setOperationAction(ISD::ROTL, MVT::v16i8, Custom);
911 }
912
913 if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
914 setOperationAction(ISD::ABS, MVT::v16i8, Legal);
915 setOperationAction(ISD::ABS, MVT::v8i16, Legal);
916 setOperationAction(ISD::ABS, MVT::v4i32, Legal);
917 setOperationAction(ISD::BITREVERSE, MVT::v16i8, Custom);
918 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
919 setOperationAction(ISD::CTLZ, MVT::v8i16, Custom);
920 setOperationAction(ISD::CTLZ, MVT::v4i32, Custom);
921 setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
922 }
923
924 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
925 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
926 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
927 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
928 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
929 setOperationAction(ISD::FRINT, RoundedTy, Legal);
930 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
931 }
932
933 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
934 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
935 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
936 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
937 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
938 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
939 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
940 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
941
942 // FIXME: Do we need to handle scalar-to-vector here?
943 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
944
945 // We directly match byte blends in the backend as they match the VSELECT
946 // condition form.
947 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
948
949 // SSE41 brings specific instructions for doing vector sign extend even in
950 // cases where we don't have SRA.
951 for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
952 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Legal);
953 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Legal);
954 }
955
956 for (MVT VT : MVT::integer_vector_valuetypes()) {
957 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
958 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
959 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
960 }
961
962 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
963 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
964 setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8, Legal);
965 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8, Legal);
966 setLoadExtAction(LoadExtOp, MVT::v2i32, MVT::v2i8, Legal);
967 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8, Legal);
968 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
969 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
970 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
971 }
972
973 // i8 vectors are custom because the source register and source
974 // source memory operand types are not the same width.
975 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
976 }
977
978 if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
979 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
980 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
981 setOperationAction(ISD::ROTL, VT, Custom);
982
983 // XOP can efficiently perform BITREVERSE with VPPERM.
984 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
985 setOperationAction(ISD::BITREVERSE, VT, Custom);
986
987 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
988 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
989 setOperationAction(ISD::BITREVERSE, VT, Custom);
990 }
991
992 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
993 bool HasInt256 = Subtarget.hasInt256();
994
995 addRegisterClass(MVT::v32i8, Subtarget.hasVLX() ? &X86::VR256XRegClass
996 : &X86::VR256RegClass);
997 addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
998 : &X86::VR256RegClass);
999 addRegisterClass(MVT::v8i32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1000 : &X86::VR256RegClass);
1001 addRegisterClass(MVT::v8f32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1002 : &X86::VR256RegClass);
1003 addRegisterClass(MVT::v4i64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1004 : &X86::VR256RegClass);
1005 addRegisterClass(MVT::v4f64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1006 : &X86::VR256RegClass);
1007
1008 for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1009 setOperationAction(ISD::FFLOOR, VT, Legal);
1010 setOperationAction(ISD::FCEIL, VT, Legal);
1011 setOperationAction(ISD::FTRUNC, VT, Legal);
1012 setOperationAction(ISD::FRINT, VT, Legal);
1013 setOperationAction(ISD::FNEARBYINT, VT, Legal);
1014 setOperationAction(ISD::FNEG, VT, Custom);
1015 setOperationAction(ISD::FABS, VT, Custom);
1016 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1017 }
1018
1019 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1020 // even though v8i16 is a legal type.
1021 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1022 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1023 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1024
1025 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1026 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1027
1028 if (!Subtarget.hasAVX512())
1029 setOperationAction(ISD::BITCAST, MVT::v32i1, Custom);
1030
1031 for (MVT VT : MVT::fp_vector_valuetypes())
1032 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1033
1034 // In the customized shift lowering, the legal v8i32/v4i64 cases
1035 // in AVX2 will be recognized.
1036 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1037 setOperationAction(ISD::SRL, VT, Custom);
1038 setOperationAction(ISD::SHL, VT, Custom);
1039 setOperationAction(ISD::SRA, VT, Custom);
1040 }
1041
1042 setOperationAction(ISD::ROTL, MVT::v8i32, Custom);
1043 setOperationAction(ISD::ROTL, MVT::v16i16, Custom);
1044 setOperationAction(ISD::ROTL, MVT::v32i8, Custom);
1045
1046 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1047 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1048 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1049
1050 for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1051 setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1052 setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1053 setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1054 }
1055
1056 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1057 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1058 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1059 setOperationAction(ISD::BITREVERSE, MVT::v32i8, Custom);
1060
1061 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1062 setOperationAction(ISD::SETCC, VT, Custom);
1063 setOperationAction(ISD::CTPOP, VT, Custom);
1064 setOperationAction(ISD::CTTZ, VT, Custom);
1065 setOperationAction(ISD::CTLZ, VT, Custom);
1066
1067 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1068 // setcc all the way to isel and prefer SETGT in some isel patterns.
1069 setCondCodeAction(ISD::SETLT, VT, Custom);
1070 setCondCodeAction(ISD::SETLE, VT, Custom);
1071 }
1072
1073 if (Subtarget.hasAnyFMA()) {
1074 for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1075 MVT::v2f64, MVT::v4f64 })
1076 setOperationAction(ISD::FMA, VT, Legal);
1077 }
1078
1079 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1080 setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1081 setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1082 }
1083
1084 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1085 setOperationAction(ISD::MUL, MVT::v8i32, HasInt256 ? Legal : Custom);
1086 setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1087 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1088
1089 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1090 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1091
1092 setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1093 setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1094 setOperationAction(ISD::MULHU, MVT::v32i8, Custom);
1095 setOperationAction(ISD::MULHS, MVT::v32i8, Custom);
1096
1097 setOperationAction(ISD::SMAX, MVT::v4i64, Custom);
1098 setOperationAction(ISD::UMAX, MVT::v4i64, Custom);
1099 setOperationAction(ISD::SMIN, MVT::v4i64, Custom);
1100 setOperationAction(ISD::UMIN, MVT::v4i64, Custom);
1101
1102 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1103 setOperationAction(ISD::ABS, VT, HasInt256 ? Legal : Custom);
1104 setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1105 setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1106 setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1107 setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1108 }
1109
1110 if (HasInt256) {
1111 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i64, Custom);
1112 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i32, Custom);
1113 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v16i16, Custom);
1114
1115 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1116 // when we have a 256bit-wide blend with immediate.
1117 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1118
1119 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1120 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1121 setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1122 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i8, Legal);
1123 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i8, Legal);
1124 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i16, Legal);
1125 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i16, Legal);
1126 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i32, Legal);
1127 }
1128 }
1129
1130 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1131 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1132 setOperationAction(ISD::MLOAD, VT, Legal);
1133 setOperationAction(ISD::MSTORE, VT, Legal);
1134 }
1135
1136 // Extract subvector is special because the value type
1137 // (result) is 128-bit but the source is 256-bit wide.
1138 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1139 MVT::v4f32, MVT::v2f64 }) {
1140 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1141 }
1142
1143 // Custom lower several nodes for 256-bit types.
1144 for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1145 MVT::v8f32, MVT::v4f64 }) {
1146 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1147 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1148 setOperationAction(ISD::VSELECT, VT, Custom);
1149 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1150 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1151 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1152 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Legal);
1153 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1154 }
1155
1156 if (HasInt256)
1157 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1158
1159 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1160 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1161 setOperationPromotedToType(ISD::AND, VT, MVT::v4i64);
1162 setOperationPromotedToType(ISD::OR, VT, MVT::v4i64);
1163 setOperationPromotedToType(ISD::XOR, VT, MVT::v4i64);
1164 setOperationPromotedToType(ISD::LOAD, VT, MVT::v4i64);
1165 setOperationPromotedToType(ISD::SELECT, VT, MVT::v4i64);
1166 }
1167
1168 if (HasInt256) {
1169 // Custom legalize 2x32 to get a little better code.
1170 setOperationAction(ISD::MGATHER, MVT::v2f32, Custom);
1171 setOperationAction(ISD::MGATHER, MVT::v2i32, Custom);
1172
1173 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1174 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1175 setOperationAction(ISD::MGATHER, VT, Custom);
1176 }
1177 }
1178
1179 // This block controls legalization of the mask vector sizes that are
1180 // available with AVX512. 512-bit vectors are in a separate block controlled
1181 // by useAVX512Regs.
1182 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1183 addRegisterClass(MVT::v1i1, &X86::VK1RegClass);
1184 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1185 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1186 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1187 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1188
1189 setOperationAction(ISD::SELECT, MVT::v1i1, Custom);
1190 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v1i1, Custom);
1191 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i1, Custom);
1192
1193 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i1, MVT::v8i32);
1194 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i1, MVT::v8i32);
1195 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v4i1, MVT::v4i32);
1196 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v4i1, MVT::v4i32);
1197 setOperationAction(ISD::FP_TO_SINT, MVT::v2i1, Custom);
1198 setOperationAction(ISD::FP_TO_UINT, MVT::v2i1, Custom);
1199
1200 // There is no byte sized k-register load or store without AVX512DQ.
1201 if (!Subtarget.hasDQI()) {
1202 setOperationAction(ISD::LOAD, MVT::v1i1, Custom);
1203 setOperationAction(ISD::LOAD, MVT::v2i1, Custom);
1204 setOperationAction(ISD::LOAD, MVT::v4i1, Custom);
1205 setOperationAction(ISD::LOAD, MVT::v8i1, Custom);
1206
1207 setOperationAction(ISD::STORE, MVT::v1i1, Custom);
1208 setOperationAction(ISD::STORE, MVT::v2i1, Custom);
1209 setOperationAction(ISD::STORE, MVT::v4i1, Custom);
1210 setOperationAction(ISD::STORE, MVT::v8i1, Custom);
1211 }
1212
1213 // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1214 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1215 setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1216 setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1217 setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1218 }
1219
1220 for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1221 setOperationAction(ISD::ADD, VT, Custom);
1222 setOperationAction(ISD::SUB, VT, Custom);
1223 setOperationAction(ISD::MUL, VT, Custom);
1224 setOperationAction(ISD::SETCC, VT, Custom);
1225 setOperationAction(ISD::SELECT, VT, Custom);
1226 setOperationAction(ISD::TRUNCATE, VT, Custom);
1227
1228 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1229 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1230 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1231 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1232 setOperationAction(ISD::VSELECT, VT, Expand);
1233 }
1234
1235 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Custom);
1236 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1237 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1238 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v2i1, Custom);
1239 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1240 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1241 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v16i1, Custom);
1242 for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1243 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1244 }
1245
1246 // This block controls legalization for 512-bit operations with 32/64 bit
1247 // elements. 512-bits can be disabled based on prefer-vector-width and
1248 // required-vector-width function attributes.
1249 if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1250 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1251 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1252 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1253 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1254
1255 for (MVT VT : MVT::fp_vector_valuetypes())
1256 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1257
1258 for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1259 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8, Legal);
1260 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1261 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i8, Legal);
1262 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i16, Legal);
1263 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i32, Legal);
1264 }
1265
1266 for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1267 setOperationAction(ISD::FNEG, VT, Custom);
1268 setOperationAction(ISD::FABS, VT, Custom);
1269 setOperationAction(ISD::FMA, VT, Legal);
1270 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1271 }
1272
1273 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1274 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v16i16, MVT::v16i32);
1275 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v16i8, MVT::v16i32);
1276 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v16i1, MVT::v16i32);
1277 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1278 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v16i1, MVT::v16i32);
1279 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v16i8, MVT::v16i32);
1280 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v16i16, MVT::v16i32);
1281 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1282 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1283
1284 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1285 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1286 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1287 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1288 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1289
1290 if (!Subtarget.hasVLX()) {
1291 // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1292 // to 512-bit rather than use the AVX2 instructions so that we can use
1293 // k-masks.
1294 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1295 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1296 setOperationAction(ISD::MLOAD, VT, Custom);
1297 setOperationAction(ISD::MSTORE, VT, Custom);
1298 }
1299 }
1300
1301 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1302 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1303 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1304 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1305 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1306 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1307 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1308 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1309
1310 for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1311 setOperationAction(ISD::FFLOOR, VT, Legal);
1312 setOperationAction(ISD::FCEIL, VT, Legal);
1313 setOperationAction(ISD::FTRUNC, VT, Legal);
1314 setOperationAction(ISD::FRINT, VT, Legal);
1315 setOperationAction(ISD::FNEARBYINT, VT, Legal);
1316 }
1317
1318 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i64, Custom);
1319 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v16i32, Custom);
1320
1321 // Without BWI we need to use custom lowering to handle MVT::v64i8 input.
1322 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v64i8, Custom);
1323 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, MVT::v64i8, Custom);
1324
1325 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1326 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1327 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1328 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1329
1330 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1331 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1332
1333 setOperationAction(ISD::UMUL_LOHI, MVT::v16i32, Custom);
1334 setOperationAction(ISD::SMUL_LOHI, MVT::v16i32, Custom);
1335
1336 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1337 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1338 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1339
1340 for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1341 setOperationAction(ISD::SMAX, VT, Legal);
1342 setOperationAction(ISD::UMAX, VT, Legal);
1343 setOperationAction(ISD::SMIN, VT, Legal);
1344 setOperationAction(ISD::UMIN, VT, Legal);
1345 setOperationAction(ISD::ABS, VT, Legal);
1346 setOperationAction(ISD::SRL, VT, Custom);
1347 setOperationAction(ISD::SHL, VT, Custom);
1348 setOperationAction(ISD::SRA, VT, Custom);
1349 setOperationAction(ISD::CTPOP, VT, Custom);
1350 setOperationAction(ISD::CTTZ, VT, Custom);
1351 setOperationAction(ISD::ROTL, VT, Custom);
1352 setOperationAction(ISD::ROTR, VT, Custom);
1353 setOperationAction(ISD::SETCC, VT, Custom);
1354
1355 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1356 // setcc all the way to isel and prefer SETGT in some isel patterns.
1357 setCondCodeAction(ISD::SETLT, VT, Custom);
1358 setCondCodeAction(ISD::SETLE, VT, Custom);
1359 }
1360
1361 // Need to promote to 64-bit even though we have 32-bit masked instructions
1362 // because the IR optimizers rearrange bitcasts around logic ops leaving
1363 // too many variations to handle if we don't promote them.
1364 setOperationPromotedToType(ISD::AND, MVT::v16i32, MVT::v8i64);
1365 setOperationPromotedToType(ISD::OR, MVT::v16i32, MVT::v8i64);
1366 setOperationPromotedToType(ISD::XOR, MVT::v16i32, MVT::v8i64);
1367
1368 if (Subtarget.hasDQI()) {
1369 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1370 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1371 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1372 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1373
1374 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1375 }
1376
1377 if (Subtarget.hasCDI()) {
1378 // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1379 for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1380 setOperationAction(ISD::CTLZ, VT, Legal);
1381 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
1382 }
1383 } // Subtarget.hasCDI()
1384
1385 if (Subtarget.hasVPOPCNTDQ()) {
1386 for (auto VT : { MVT::v16i32, MVT::v8i64 })
1387 setOperationAction(ISD::CTPOP, VT, Legal);
1388 }
1389
1390 // Extract subvector is special because the value type
1391 // (result) is 256-bit but the source is 512-bit wide.
1392 // 128-bit was made Legal under AVX1.
1393 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1394 MVT::v8f32, MVT::v4f64 })
1395 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1396
1397 for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1398 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1399 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1400 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1401 setOperationAction(ISD::VSELECT, VT, Custom);
1402 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1403 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1404 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Legal);
1405 setOperationAction(ISD::MLOAD, VT, Legal);
1406 setOperationAction(ISD::MSTORE, VT, Legal);
1407 setOperationAction(ISD::MGATHER, VT, Custom);
1408 setOperationAction(ISD::MSCATTER, VT, Custom);
1409 }
1410 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1411 setOperationPromotedToType(ISD::LOAD, VT, MVT::v8i64);
1412 setOperationPromotedToType(ISD::SELECT, VT, MVT::v8i64);
1413 }
1414
1415 // Need to custom split v32i16/v64i8 bitcasts.
1416 if (!Subtarget.hasBWI()) {
1417 setOperationAction(ISD::BITCAST, MVT::v32i16, Custom);
1418 setOperationAction(ISD::BITCAST, MVT::v64i8, Custom);
1419 }
1420 }// has AVX-512
1421
1422 // This block controls legalization for operations that don't have
1423 // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
1424 // narrower widths.
1425 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1426 // These operations are handled on non-VLX by artificially widening in
1427 // isel patterns.
1428 // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1429
1430 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1431 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1432 setOperationAction(ISD::FP_TO_UINT, MVT::v2i32, Custom);
1433 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1434 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1435
1436 for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1437 setOperationAction(ISD::SMAX, VT, Legal);
1438 setOperationAction(ISD::UMAX, VT, Legal);
1439 setOperationAction(ISD::SMIN, VT, Legal);
1440 setOperationAction(ISD::UMIN, VT, Legal);
1441 setOperationAction(ISD::ABS, VT, Legal);
1442 }
1443
1444 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1445 setOperationAction(ISD::ROTL, VT, Custom);
1446 setOperationAction(ISD::ROTR, VT, Custom);
1447 }
1448
1449 // Custom legalize 2x32 to get a little better code.
1450 setOperationAction(ISD::MSCATTER, MVT::v2f32, Custom);
1451 setOperationAction(ISD::MSCATTER, MVT::v2i32, Custom);
1452
1453 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1454 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1455 setOperationAction(ISD::MSCATTER, VT, Custom);
1456
1457 if (Subtarget.hasDQI()) {
1458 for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1459 setOperationAction(ISD::SINT_TO_FP, VT, Legal);
1460 setOperationAction(ISD::UINT_TO_FP, VT, Legal);
1461 setOperationAction(ISD::FP_TO_SINT, VT, Legal);
1462 setOperationAction(ISD::FP_TO_UINT, VT, Legal);
1463
1464 setOperationAction(ISD::MUL, VT, Legal);
1465 }
1466 }
1467
1468 if (Subtarget.hasCDI()) {
1469 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1470 setOperationAction(ISD::CTLZ, VT, Legal);
1471 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
1472 }
1473 } // Subtarget.hasCDI()
1474
1475 if (Subtarget.hasVPOPCNTDQ()) {
1476 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
1477 setOperationAction(ISD::CTPOP, VT, Legal);
1478 }
1479 }
1480
1481 // This block control legalization of v32i1/v64i1 which are available with
1482 // AVX512BW. 512-bit v32i16 and v64i8 vector legalization is controlled with
1483 // useBWIRegs.
1484 if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1485 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1486 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1487
1488 for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
1489 setOperationAction(ISD::ADD, VT, Custom);
1490 setOperationAction(ISD::SUB, VT, Custom);
1491 setOperationAction(ISD::MUL, VT, Custom);
1492 setOperationAction(ISD::VSELECT, VT, Expand);
1493
1494 setOperationAction(ISD::TRUNCATE, VT, Custom);
1495 setOperationAction(ISD::SETCC, VT, Custom);
1496 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1497 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1498 setOperationAction(ISD::SELECT, VT, Custom);
1499 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1500 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1501 }
1502
1503 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1504 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1505 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1506 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1507 for (auto VT : { MVT::v16i1, MVT::v32i1 })
1508 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1509
1510 // Extends from v32i1 masks to 256-bit vectors.
1511 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1512 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1513 setOperationAction(ISD::ANY_EXTEND, MVT::v32i8, Custom);
1514 }
1515
1516 // This block controls legalization for v32i16 and v64i8. 512-bits can be
1517 // disabled based on prefer-vector-width and required-vector-width function
1518 // attributes.
1519 if (!Subtarget.useSoftFloat() && Subtarget.useBWIRegs()) {
1520 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1521 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1522
1523 // Extends from v64i1 masks to 512-bit vectors.
1524 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1525 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1526 setOperationAction(ISD::ANY_EXTEND, MVT::v64i8, Custom);
1527
1528 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1529 setOperationAction(ISD::MUL, MVT::v64i8, Custom);
1530 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1531 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1532 setOperationAction(ISD::MULHS, MVT::v64i8, Custom);
1533 setOperationAction(ISD::MULHU, MVT::v64i8, Custom);
1534 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i16, Custom);
1535 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i8, Custom);
1536 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i16, Legal);
1537 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i8, Legal);
1538 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1539 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1540 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i16, Custom);
1541 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v64i8, Custom);
1542 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1543 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1544 setOperationAction(ISD::ANY_EXTEND, MVT::v32i16, Custom);
1545 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i16, Custom);
1546 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i8, Custom);
1547 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i16, Custom);
1548 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i8, Custom);
1549 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1550 setOperationAction(ISD::BITREVERSE, MVT::v64i8, Custom);
1551
1552 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v32i16, Custom);
1553
1554 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1555
1556 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1557 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1558 setOperationAction(ISD::VSELECT, VT, Custom);
1559 setOperationAction(ISD::ABS, VT, Legal);
1560 setOperationAction(ISD::SRL, VT, Custom);
1561 setOperationAction(ISD::SHL, VT, Custom);
1562 setOperationAction(ISD::SRA, VT, Custom);
1563 setOperationAction(ISD::MLOAD, VT, Legal);
1564 setOperationAction(ISD::MSTORE, VT, Legal);
1565 setOperationAction(ISD::CTPOP, VT, Custom);
1566 setOperationAction(ISD::CTTZ, VT, Custom);
1567 setOperationAction(ISD::CTLZ, VT, Custom);
1568 setOperationAction(ISD::SMAX, VT, Legal);
1569 setOperationAction(ISD::UMAX, VT, Legal);
1570 setOperationAction(ISD::SMIN, VT, Legal);
1571 setOperationAction(ISD::UMIN, VT, Legal);
1572 setOperationAction(ISD::SETCC, VT, Custom);
1573
1574 setOperationPromotedToType(ISD::AND, VT, MVT::v8i64);
1575 setOperationPromotedToType(ISD::OR, VT, MVT::v8i64);
1576 setOperationPromotedToType(ISD::XOR, VT, MVT::v8i64);
1577 }
1578
1579 for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1580 setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1581 }
1582
1583 if (Subtarget.hasBITALG()) {
1584 for (auto VT : { MVT::v64i8, MVT::v32i16 })
1585 setOperationAction(ISD::CTPOP, VT, Legal);
1586 }
1587 }
1588
1589 if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1590 for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1591 setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1592 setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
1593 }
1594
1595 // These operations are handled on non-VLX by artificially widening in
1596 // isel patterns.
1597 // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1598
1599 if (Subtarget.hasBITALG()) {
1600 for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
1601 setOperationAction(ISD::CTPOP, VT, Legal);
1602 }
1603 }
1604
1605 if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
1606 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1607 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1608 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1609 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1610 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1611
1612 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1613 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1614 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1615 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1616 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1617
1618 if (Subtarget.hasDQI()) {
1619 // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
1620 // v2f32 UINT_TO_FP is already custom under SSE2.
1621 setOperationAction(ISD::SINT_TO_FP, MVT::v2f32, Custom);
1622 assert(isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) &&(static_cast <bool> (isOperationCustom(ISD::UINT_TO_FP,
MVT::v2f32) && "Unexpected operation action!") ? void
(0) : __assert_fail ("isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) && \"Unexpected operation action!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 1623, __extension__ __PRETTY_FUNCTION__))
1623 "Unexpected operation action!")(static_cast <bool> (isOperationCustom(ISD::UINT_TO_FP,
MVT::v2f32) && "Unexpected operation action!") ? void
(0) : __assert_fail ("isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) && \"Unexpected operation action!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 1623, __extension__ __PRETTY_FUNCTION__))
;
1624 // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
1625 setOperationAction(ISD::FP_TO_SINT, MVT::v2f32, Custom);
1626 setOperationAction(ISD::FP_TO_UINT, MVT::v2f32, Custom);
1627 }
1628
1629 if (Subtarget.hasBWI()) {
1630 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1631 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1632 }
1633 }
1634
1635 // We want to custom lower some of our intrinsics.
1636 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1637 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1638 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1639 if (!Subtarget.is64Bit()) {
1640 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1641 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1642 }
1643
1644 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1645 // handle type legalization for these operations here.
1646 //
1647 // FIXME: We really should do custom legalization for addition and
1648 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1649 // than generic legalization for 64-bit multiplication-with-overflow, though.
1650 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1651 if (VT == MVT::i64 && !Subtarget.is64Bit())
1652 continue;
1653 // Add/Sub/Mul with overflow operations are custom lowered.
1654 setOperationAction(ISD::SADDO, VT, Custom);
1655 setOperationAction(ISD::UADDO, VT, Custom);
1656 setOperationAction(ISD::SSUBO, VT, Custom);
1657 setOperationAction(ISD::USUBO, VT, Custom);
1658 setOperationAction(ISD::SMULO, VT, Custom);
1659 setOperationAction(ISD::UMULO, VT, Custom);
1660
1661 // Support carry in as value rather than glue.
1662 setOperationAction(ISD::ADDCARRY, VT, Custom);
1663 setOperationAction(ISD::SUBCARRY, VT, Custom);
1664 setOperationAction(ISD::SETCCCARRY, VT, Custom);
1665 }
1666
1667 if (!Subtarget.is64Bit()) {
1668 // These libcalls are not available in 32-bit.
1669 setLibcallName(RTLIB::SHL_I128, nullptr);
1670 setLibcallName(RTLIB::SRL_I128, nullptr);
1671 setLibcallName(RTLIB::SRA_I128, nullptr);
1672 setLibcallName(RTLIB::MUL_I128, nullptr);
1673 }
1674
1675 // Combine sin / cos into _sincos_stret if it is available.
1676 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1677 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1678 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1679 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1680 }
1681
1682 if (Subtarget.isTargetWin64()) {
1683 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1684 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1685 setOperationAction(ISD::SREM, MVT::i128, Custom);
1686 setOperationAction(ISD::UREM, MVT::i128, Custom);
1687 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1688 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1689 }
1690
1691 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
1692 // is. We should promote the value to 64-bits to solve this.
1693 // This is what the CRT headers do - `fmodf` is an inline header
1694 // function casting to f64 and calling `fmod`.
1695 if (Subtarget.is32Bit() && (Subtarget.isTargetKnownWindowsMSVC() ||
1696 Subtarget.isTargetWindowsItanium()))
1697 for (ISD::NodeType Op :
1698 {ISD::FCEIL, ISD::FCOS, ISD::FEXP, ISD::FFLOOR, ISD::FREM, ISD::FLOG,
1699 ISD::FLOG10, ISD::FPOW, ISD::FSIN})
1700 if (isOperationExpand(Op, MVT::f32))
1701 setOperationAction(Op, MVT::f32, Promote);
1702
1703 // We have target-specific dag combine patterns for the following nodes:
1704 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1705 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
1706 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1707 setTargetDAGCombine(ISD::INSERT_SUBVECTOR);
1708 setTargetDAGCombine(ISD::EXTRACT_SUBVECTOR);
1709 setTargetDAGCombine(ISD::BITCAST);
1710 setTargetDAGCombine(ISD::VSELECT);
1711 setTargetDAGCombine(ISD::SELECT);
1712 setTargetDAGCombine(ISD::SHL);
1713 setTargetDAGCombine(ISD::SRA);
1714 setTargetDAGCombine(ISD::SRL);
1715 setTargetDAGCombine(ISD::OR);
1716 setTargetDAGCombine(ISD::AND);
1717 setTargetDAGCombine(ISD::ADD);
1718 setTargetDAGCombine(ISD::FADD);
1719 setTargetDAGCombine(ISD::FSUB);
1720 setTargetDAGCombine(ISD::FNEG);
1721 setTargetDAGCombine(ISD::FMA);
1722 setTargetDAGCombine(ISD::FMINNUM);
1723 setTargetDAGCombine(ISD::FMAXNUM);
1724 setTargetDAGCombine(ISD::SUB);
1725 setTargetDAGCombine(ISD::LOAD);
1726 setTargetDAGCombine(ISD::MLOAD);
1727 setTargetDAGCombine(ISD::STORE);
1728 setTargetDAGCombine(ISD::MSTORE);
1729 setTargetDAGCombine(ISD::TRUNCATE);
1730 setTargetDAGCombine(ISD::ZERO_EXTEND);
1731 setTargetDAGCombine(ISD::ANY_EXTEND);
1732 setTargetDAGCombine(ISD::SIGN_EXTEND);
1733 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1734 setTargetDAGCombine(ISD::SIGN_EXTEND_VECTOR_INREG);
1735 setTargetDAGCombine(ISD::ZERO_EXTEND_VECTOR_INREG);
1736 setTargetDAGCombine(ISD::SINT_TO_FP);
1737 setTargetDAGCombine(ISD::UINT_TO_FP);
1738 setTargetDAGCombine(ISD::SETCC);
1739 setTargetDAGCombine(ISD::MUL);
1740 setTargetDAGCombine(ISD::XOR);
1741 setTargetDAGCombine(ISD::MSCATTER);
1742 setTargetDAGCombine(ISD::MGATHER);
1743
1744 computeRegisterProperties(Subtarget.getRegisterInfo());
1745
1746 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1747 MaxStoresPerMemsetOptSize = 8;
1748 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1749 MaxStoresPerMemcpyOptSize = 4;
1750 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1751 MaxStoresPerMemmoveOptSize = 4;
1752
1753 // TODO: These control memcmp expansion in CGP and could be raised higher, but
1754 // that needs to benchmarked and balanced with the potential use of vector
1755 // load/store types (PR33329, PR33914).
1756 MaxLoadsPerMemcmp = 2;
1757 MaxLoadsPerMemcmpOptSize = 2;
1758
1759 // Set loop alignment to 2^ExperimentalPrefLoopAlignment bytes (default: 2^4).
1760 setPrefLoopAlignment(ExperimentalPrefLoopAlignment);
1761
1762 // An out-of-order CPU can speculatively execute past a predictable branch,
1763 // but a conditional move could be stalled by an expensive earlier operation.
1764 PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
1765 EnableExtLdPromotion = true;
1766 setPrefFunctionAlignment(4); // 2^4 bytes.
1767
1768 verifyIntrinsicTables();
1769}
1770
1771// This has so far only been implemented for 64-bit MachO.
1772bool X86TargetLowering::useLoadStackGuardNode() const {
1773 return Subtarget.isTargetMachO() && Subtarget.is64Bit();
1774}
1775
1776bool X86TargetLowering::useStackGuardXorFP() const {
1777 // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
1778 return Subtarget.getTargetTriple().isOSMSVCRT();
1779}
1780
1781SDValue X86TargetLowering::emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
1782 const SDLoc &DL) const {
1783 EVT PtrTy = getPointerTy(DAG.getDataLayout());
1784 unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
1785 MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
1786 return SDValue(Node, 0);
1787}
1788
1789TargetLoweringBase::LegalizeTypeAction
1790X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1791 if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1792 return TypeSplitVector;
1793
1794 if (ExperimentalVectorWideningLegalization &&
1795 VT.getVectorNumElements() != 1 &&
1796 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1797 return TypeWidenVector;
1798
1799 return TargetLoweringBase::getPreferredVectorAction(VT);
1800}
1801
1802MVT X86TargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1803 CallingConv::ID CC,
1804 EVT VT) const {
1805 if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1806 return MVT::v32i8;
1807 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1808}
1809
1810unsigned X86TargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1811 CallingConv::ID CC,
1812 EVT VT) const {
1813 if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1814 return 1;
1815 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1816}
1817
1818EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL,
1819 LLVMContext& Context,
1820 EVT VT) const {
1821 if (!VT.isVector())
1822 return MVT::i8;
1823
1824 if (Subtarget.hasAVX512()) {
1825 const unsigned NumElts = VT.getVectorNumElements();
1826
1827 // Figure out what this type will be legalized to.
1828 EVT LegalVT = VT;
1829 while (getTypeAction(Context, LegalVT) != TypeLegal)
1830 LegalVT = getTypeToTransformTo(Context, LegalVT);
1831
1832 // If we got a 512-bit vector then we'll definitely have a vXi1 compare.
1833 if (LegalVT.getSimpleVT().is512BitVector())
1834 return EVT::getVectorVT(Context, MVT::i1, NumElts);
1835
1836 if (LegalVT.getSimpleVT().isVector() && Subtarget.hasVLX()) {
1837 // If we legalized to less than a 512-bit vector, then we will use a vXi1
1838 // compare for vXi32/vXi64 for sure. If we have BWI we will also support
1839 // vXi16/vXi8.
1840 MVT EltVT = LegalVT.getSimpleVT().getVectorElementType();
1841 if (Subtarget.hasBWI() || EltVT.getSizeInBits() >= 32)
1842 return EVT::getVectorVT(Context, MVT::i1, NumElts);
1843 }
1844 }
1845
1846 return VT.changeVectorElementTypeToInteger();
1847}
1848
1849/// Helper for getByValTypeAlignment to determine
1850/// the desired ByVal argument alignment.
1851static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1852 if (MaxAlign == 16)
1853 return;
1854 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1855 if (VTy->getBitWidth() == 128)
1856 MaxAlign = 16;
1857 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1858 unsigned EltAlign = 0;
1859 getMaxByValAlign(ATy->getElementType(), EltAlign);
1860 if (EltAlign > MaxAlign)
1861 MaxAlign = EltAlign;
1862 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1863 for (auto *EltTy : STy->elements()) {
1864 unsigned EltAlign = 0;
1865 getMaxByValAlign(EltTy, EltAlign);
1866 if (EltAlign > MaxAlign)
1867 MaxAlign = EltAlign;
1868 if (MaxAlign == 16)
1869 break;
1870 }
1871 }
1872}
1873
1874/// Return the desired alignment for ByVal aggregate
1875/// function arguments in the caller parameter area. For X86, aggregates
1876/// that contain SSE vectors are placed at 16-byte boundaries while the rest
1877/// are at 4-byte boundaries.
1878unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1879 const DataLayout &DL) const {
1880 if (Subtarget.is64Bit()) {
1881 // Max of 8 and alignment of type.
1882 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1883 if (TyAlign > 8)
1884 return TyAlign;
1885 return 8;
1886 }
1887
1888 unsigned Align = 4;
1889 if (Subtarget.hasSSE1())
1890 getMaxByValAlign(Ty, Align);
1891 return Align;
1892}
1893
1894/// Returns the target specific optimal type for load
1895/// and store operations as a result of memset, memcpy, and memmove
1896/// lowering. If DstAlign is zero that means it's safe to destination
1897/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1898/// means there isn't a need to check it against alignment requirement,
1899/// probably because the source does not need to be loaded. If 'IsMemset' is
1900/// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1901/// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1902/// source is constant so it does not need to be loaded.
1903/// It returns EVT::Other if the type should be determined using generic
1904/// target-independent logic.
1905EVT
1906X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1907 unsigned DstAlign, unsigned SrcAlign,
1908 bool IsMemset, bool ZeroMemset,
1909 bool MemcpyStrSrc,
1910 MachineFunction &MF) const {
1911 const Function &F = MF.getFunction();
1912 if (!F.hasFnAttribute(Attribute::NoImplicitFloat)) {
1913 if (Size >= 16 &&
1914 (!Subtarget.isUnalignedMem16Slow() ||
1915 ((DstAlign == 0 || DstAlign >= 16) &&
1916 (SrcAlign == 0 || SrcAlign >= 16)))) {
1917 // FIXME: Check if unaligned 32-byte accesses are slow.
1918 if (Size >= 32 && Subtarget.hasAVX()) {
1919 // Although this isn't a well-supported type for AVX1, we'll let
1920 // legalization and shuffle lowering produce the optimal codegen. If we
1921 // choose an optimal type with a vector element larger than a byte,
1922 // getMemsetStores() may create an intermediate splat (using an integer
1923 // multiply) before we splat as a vector.
1924 return MVT::v32i8;
1925 }
1926 if (Subtarget.hasSSE2())
1927 return MVT::v16i8;
1928 // TODO: Can SSE1 handle a byte vector?
1929 if (Subtarget.hasSSE1())
1930 return MVT::v4f32;
1931 } else if ((!IsMemset || ZeroMemset) && !MemcpyStrSrc && Size >= 8 &&
1932 !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
1933 // Do not use f64 to lower memcpy if source is string constant. It's
1934 // better to use i32 to avoid the loads.
1935 // Also, do not use f64 to lower memset unless this is a memset of zeros.
1936 // The gymnastics of splatting a byte value into an XMM register and then
1937 // only using 8-byte stores (because this is a CPU with slow unaligned
1938 // 16-byte accesses) makes that a loser.
1939 return MVT::f64;
1940 }
1941 }
1942 // This is a compromise. If we reach here, unaligned accesses may be slow on
1943 // this target. However, creating smaller, aligned accesses could be even
1944 // slower and would certainly be a lot more code.
1945 if (Subtarget.is64Bit() && Size >= 8)
1946 return MVT::i64;
1947 return MVT::i32;
1948}
1949
1950bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1951 if (VT == MVT::f32)
1952 return X86ScalarSSEf32;
1953 else if (VT == MVT::f64)
1954 return X86ScalarSSEf64;
1955 return true;
1956}
1957
1958bool
1959X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1960 unsigned,
1961 unsigned,
1962 bool *Fast) const {
1963 if (Fast) {
1964 switch (VT.getSizeInBits()) {
1965 default:
1966 // 8-byte and under are always assumed to be fast.
1967 *Fast = true;
1968 break;
1969 case 128:
1970 *Fast = !Subtarget.isUnalignedMem16Slow();
1971 break;
1972 case 256:
1973 *Fast = !Subtarget.isUnalignedMem32Slow();
1974 break;
1975 // TODO: What about AVX-512 (512-bit) accesses?
1976 }
1977 }
1978 // Misaligned accesses of any size are always allowed.
1979 return true;
1980}
1981
1982/// Return the entry encoding for a jump table in the
1983/// current function. The returned value is a member of the
1984/// MachineJumpTableInfo::JTEntryKind enum.
1985unsigned X86TargetLowering::getJumpTableEncoding() const {
1986 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1987 // symbol.
1988 if (isPositionIndependent() && Subtarget.isPICStyleGOT())
1989 return MachineJumpTableInfo::EK_Custom32;
1990
1991 // Otherwise, use the normal jump table encoding heuristics.
1992 return TargetLowering::getJumpTableEncoding();
1993}
1994
1995bool X86TargetLowering::useSoftFloat() const {
1996 return Subtarget.useSoftFloat();
1997}
1998
1999void X86TargetLowering::markLibCallAttributes(MachineFunction *MF, unsigned CC,
2000 ArgListTy &Args) const {
2001
2002 // Only relabel X86-32 for C / Stdcall CCs.
2003 if (Subtarget.is64Bit())
2004 return;
2005 if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
2006 return;
2007 unsigned ParamRegs = 0;
2008 if (auto *M = MF->getFunction().getParent())
2009 ParamRegs = M->getNumberRegisterParameters();
2010
2011 // Mark the first N int arguments as having reg
2012 for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
2013 Type *T = Args[Idx].Ty;
2014 if (T->isIntOrPtrTy())
2015 if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
2016 unsigned numRegs = 1;
2017 if (MF->getDataLayout().getTypeAllocSize(T) > 4)
2018 numRegs = 2;
2019 if (ParamRegs < numRegs)
2020 return;
2021 ParamRegs -= numRegs;
2022 Args[Idx].IsInReg = true;
2023 }
2024 }
2025}
2026
2027const MCExpr *
2028X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2029 const MachineBasicBlock *MBB,
2030 unsigned uid,MCContext &Ctx) const{
2031 assert(isPositionIndependent() && Subtarget.isPICStyleGOT())(static_cast <bool> (isPositionIndependent() &&
Subtarget.isPICStyleGOT()) ? void (0) : __assert_fail ("isPositionIndependent() && Subtarget.isPICStyleGOT()"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2031, __extension__ __PRETTY_FUNCTION__))
;
2032 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2033 // entries.
2034 return MCSymbolRefExpr::create(MBB->getSymbol(),
2035 MCSymbolRefExpr::VK_GOTOFF, Ctx);
2036}
2037
2038/// Returns relocation base for the given PIC jumptable.
2039SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2040 SelectionDAG &DAG) const {
2041 if (!Subtarget.is64Bit())
2042 // This doesn't have SDLoc associated with it, but is not really the
2043 // same as a Register.
2044 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2045 getPointerTy(DAG.getDataLayout()));
2046 return Table;
2047}
2048
2049/// This returns the relocation base for the given PIC jumptable,
2050/// the same as getPICJumpTableRelocBase, but as an MCExpr.
2051const MCExpr *X86TargetLowering::
2052getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2053 MCContext &Ctx) const {
2054 // X86-64 uses RIP relative addressing based on the jump table label.
2055 if (Subtarget.isPICStyleRIPRel())
2056 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2057
2058 // Otherwise, the reference is relative to the PIC base.
2059 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2060}
2061
2062std::pair<const TargetRegisterClass *, uint8_t>
2063X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2064 MVT VT) const {
2065 const TargetRegisterClass *RRC = nullptr;
2066 uint8_t Cost = 1;
2067 switch (VT.SimpleTy) {
2068 default:
2069 return TargetLowering::findRepresentativeClass(TRI, VT);
2070 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2071 RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2072 break;
2073 case MVT::x86mmx:
2074 RRC = &X86::VR64RegClass;
2075 break;
2076 case MVT::f32: case MVT::f64:
2077 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2078 case MVT::v4f32: case MVT::v2f64:
2079 case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
2080 case MVT::v8f32: case MVT::v4f64:
2081 case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
2082 case MVT::v16f32: case MVT::v8f64:
2083 RRC = &X86::VR128XRegClass;
2084 break;
2085 }
2086 return std::make_pair(RRC, Cost);
2087}
2088
2089unsigned X86TargetLowering::getAddressSpace() const {
2090 if (Subtarget.is64Bit())
2091 return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
2092 return 256;
2093}
2094
2095static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2096 return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2097 (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2098}
2099
2100static Constant* SegmentOffset(IRBuilder<> &IRB,
2101 unsigned Offset, unsigned AddressSpace) {
2102 return ConstantExpr::getIntToPtr(
2103 ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2104 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2105}
2106
2107Value *X86TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
2108 // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2109 // tcbhead_t; use it instead of the usual global variable (see
2110 // sysdeps/{i386,x86_64}/nptl/tls.h)
2111 if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2112 if (Subtarget.isTargetFuchsia()) {
2113 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2114 return SegmentOffset(IRB, 0x10, getAddressSpace());
2115 } else {
2116 // %fs:0x28, unless we're using a Kernel code model, in which case
2117 // it's %gs:0x28. gs:0x14 on i386.
2118 unsigned Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2119 return SegmentOffset(IRB, Offset, getAddressSpace());
2120 }
2121 }
2122
2123 return TargetLowering::getIRStackGuard(IRB);
2124}
2125
2126void X86TargetLowering::insertSSPDeclarations(Module &M) const {
2127 // MSVC CRT provides functionalities for stack protection.
2128 if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2129 Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2130 // MSVC CRT has a global variable holding security cookie.
2131 M.getOrInsertGlobal("__security_cookie",
2132 Type::getInt8PtrTy(M.getContext()));
2133
2134 // MSVC CRT has a function to validate security cookie.
2135 auto *SecurityCheckCookie = cast<Function>(
2136 M.getOrInsertFunction("__security_check_cookie",
2137 Type::getVoidTy(M.getContext()),
2138 Type::getInt8PtrTy(M.getContext())));
2139 SecurityCheckCookie->setCallingConv(CallingConv::X86_FastCall);
2140 SecurityCheckCookie->addAttribute(1, Attribute::AttrKind::InReg);
2141 return;
2142 }
2143 // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2144 if (hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2145 return;
2146 TargetLowering::insertSSPDeclarations(M);
2147}
2148
2149Value *X86TargetLowering::getSDagStackGuard(const Module &M) const {
2150 // MSVC CRT has a global variable holding security cookie.
2151 if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2152 Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2153 return M.getGlobalVariable("__security_cookie");
2154 }
2155 return TargetLowering::getSDagStackGuard(M);
2156}
2157
2158Value *X86TargetLowering::getSSPStackGuardCheck(const Module &M) const {
2159 // MSVC CRT has a function to validate security cookie.
2160 if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2161 Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2162 return M.getFunction("__security_check_cookie");
2163 }
2164 return TargetLowering::getSSPStackGuardCheck(M);
2165}
2166
2167Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2168 if (Subtarget.getTargetTriple().isOSContiki())
2169 return getDefaultSafeStackPointerLocation(IRB, false);
2170
2171 // Android provides a fixed TLS slot for the SafeStack pointer. See the
2172 // definition of TLS_SLOT_SAFESTACK in
2173 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2174 if (Subtarget.isTargetAndroid()) {
2175 // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2176 // %gs:0x24 on i386
2177 unsigned Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2178 return SegmentOffset(IRB, Offset, getAddressSpace());
2179 }
2180
2181 // Fuchsia is similar.
2182 if (Subtarget.isTargetFuchsia()) {
2183 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
2184 return SegmentOffset(IRB, 0x18, getAddressSpace());
2185 }
2186
2187 return TargetLowering::getSafeStackPointerLocation(IRB);
2188}
2189
2190bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2191 unsigned DestAS) const {
2192 assert(SrcAS != DestAS && "Expected different address spaces!")(static_cast <bool> (SrcAS != DestAS && "Expected different address spaces!"
) ? void (0) : __assert_fail ("SrcAS != DestAS && \"Expected different address spaces!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2192, __extension__ __PRETTY_FUNCTION__))
;
2193
2194 return SrcAS < 256 && DestAS < 256;
2195}
2196
2197//===----------------------------------------------------------------------===//
2198// Return Value Calling Convention Implementation
2199//===----------------------------------------------------------------------===//
2200
2201#include "X86GenCallingConv.inc"
2202
2203bool X86TargetLowering::CanLowerReturn(
2204 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2205 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2206 SmallVector<CCValAssign, 16> RVLocs;
2207 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2208 return CCInfo.CheckReturn(Outs, RetCC_X86);
2209}
2210
2211const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2212 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2213 return ScratchRegs;
2214}
2215
2216/// Lowers masks values (v*i1) to the local register values
2217/// \returns DAG node after lowering to register type
2218static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
2219 const SDLoc &Dl, SelectionDAG &DAG) {
2220 EVT ValVT = ValArg.getValueType();
2221
2222 if (ValVT == MVT::v1i1)
2223 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Dl, ValLoc, ValArg,
2224 DAG.getIntPtrConstant(0, Dl));
2225
2226 if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
2227 (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
2228 // Two stage lowering might be required
2229 // bitcast: v8i1 -> i8 / v16i1 -> i16
2230 // anyextend: i8 -> i32 / i16 -> i32
2231 EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
2232 SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
2233 if (ValLoc == MVT::i32)
2234 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
2235 return ValToCopy;
2236 }
2237
2238 if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
2239 (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
2240 // One stage lowering is required
2241 // bitcast: v32i1 -> i32 / v64i1 -> i64
2242 return DAG.getBitcast(ValLoc, ValArg);
2243 }
2244
2245 return DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValArg);
2246}
2247
2248/// Breaks v64i1 value into two registers and adds the new node to the DAG
2249static void Passv64i1ArgInRegs(
2250 const SDLoc &Dl, SelectionDAG &DAG, SDValue Chain, SDValue &Arg,
2251 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, CCValAssign &VA,
2252 CCValAssign &NextVA, const X86Subtarget &Subtarget) {
2253 assert(Subtarget.hasBWI() && "Expected AVX512BW target!")(static_cast <bool> (Subtarget.hasBWI() && "Expected AVX512BW target!"
) ? void (0) : __assert_fail ("Subtarget.hasBWI() && \"Expected AVX512BW target!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2253, __extension__ __PRETTY_FUNCTION__))
;
2254 assert(Subtarget.is32Bit() && "Expecting 32 bit target")(static_cast <bool> (Subtarget.is32Bit() && "Expecting 32 bit target"
) ? void (0) : __assert_fail ("Subtarget.is32Bit() && \"Expecting 32 bit target\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2254, __extension__ __PRETTY_FUNCTION__))
;
2255 assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value")(static_cast <bool> (Arg.getValueType() == MVT::i64 &&
"Expecting 64 bit value") ? void (0) : __assert_fail ("Arg.getValueType() == MVT::i64 && \"Expecting 64 bit value\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2255, __extension__ __PRETTY_FUNCTION__))
;
2256 assert(VA.isRegLoc() && NextVA.isRegLoc() &&(static_cast <bool> (VA.isRegLoc() && NextVA.isRegLoc
() && "The value should reside in two registers") ? void
(0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The value should reside in two registers\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2257, __extension__ __PRETTY_FUNCTION__))
2257 "The value should reside in two registers")(static_cast <bool> (VA.isRegLoc() && NextVA.isRegLoc
() && "The value should reside in two registers") ? void
(0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The value should reside in two registers\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2257, __extension__ __PRETTY_FUNCTION__))
;
2258
2259 // Before splitting the value we cast it to i64
2260 Arg = DAG.getBitcast(MVT::i64, Arg);
2261
2262 // Splitting the value into two i32 types
2263 SDValue Lo, Hi;
2264 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2265 DAG.getConstant(0, Dl, MVT::i32));
2266 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2267 DAG.getConstant(1, Dl, MVT::i32));
2268
2269 // Attach the two i32 types into corresponding registers
2270 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
2271 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
2272}
2273
2274SDValue
2275X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2276 bool isVarArg,
2277 const SmallVectorImpl<ISD::OutputArg> &Outs,
2278 const SmallVectorImpl<SDValue> &OutVals,
2279 const SDLoc &dl, SelectionDAG &DAG) const {
2280 MachineFunction &MF = DAG.getMachineFunction();
2281 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2282
2283 // In some cases we need to disable registers from the default CSR list.
2284 // For example, when they are used for argument passing.
2285 bool ShouldDisableCalleeSavedRegister =
2286 CallConv == CallingConv::X86_RegCall ||
2287 MF.getFunction().hasFnAttribute("no_caller_saved_registers");
2288
2289 if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2290 report_fatal_error("X86 interrupts may not return any value");
2291
2292 SmallVector<CCValAssign, 16> RVLocs;
2293 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2294 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2295
2296 SDValue Flag;
2297 SmallVector<SDValue, 6> RetOps;
2298 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2299 // Operand #1 = Bytes To Pop
2300 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2301 MVT::i32));
2302
2303 // Copy the result values into the output registers.
2304 for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
2305 ++I, ++OutsIndex) {
2306 CCValAssign &VA = RVLocs[I];
2307 assert(VA.isRegLoc() && "Can only return in registers!")(static_cast <bool> (VA.isRegLoc() && "Can only return in registers!"
) ? void (0) : __assert_fail ("VA.isRegLoc() && \"Can only return in registers!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2307, __extension__ __PRETTY_FUNCTION__))
;
2308
2309 // Add the register to the CalleeSaveDisableRegs list.
2310 if (ShouldDisableCalleeSavedRegister)
2311 MF.getRegInfo().disableCalleeSavedRegister(VA.getLocReg());
2312
2313 SDValue ValToCopy = OutVals[OutsIndex];
2314 EVT ValVT = ValToCopy.getValueType();
2315
2316 // Promote values to the appropriate types.
2317 if (VA.getLocInfo() == CCValAssign::SExt)
2318 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2319 else if (VA.getLocInfo() == CCValAssign::ZExt)
2320 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2321 else if (VA.getLocInfo() == CCValAssign::AExt) {
2322 if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2323 ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
2324 else
2325 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2326 }
2327 else if (VA.getLocInfo() == CCValAssign::BCvt)
2328 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2329
2330 assert(VA.getLocInfo() != CCValAssign::FPExt &&(static_cast <bool> (VA.getLocInfo() != CCValAssign::FPExt
&& "Unexpected FP-extend for return value.") ? void (
0) : __assert_fail ("VA.getLocInfo() != CCValAssign::FPExt && \"Unexpected FP-extend for return value.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2331, __extension__ __PRETTY_FUNCTION__))
2331 "Unexpected FP-extend for return value.")(static_cast <bool> (VA.getLocInfo() != CCValAssign::FPExt
&& "Unexpected FP-extend for return value.") ? void (
0) : __assert_fail ("VA.getLocInfo() != CCValAssign::FPExt && \"Unexpected FP-extend for return value.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2331, __extension__ __PRETTY_FUNCTION__))
;
2332
2333 // If this is x86-64, and we disabled SSE, we can't return FP values,
2334 // or SSE or MMX vectors.
2335 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2336 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2337 (Subtarget.is64Bit() && !Subtarget.hasSSE1())) {
2338 errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2339 VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2340 } else if (ValVT == MVT::f64 &&
2341 (Subtarget.is64Bit() && !Subtarget.hasSSE2())) {
2342 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2343 // llvm-gcc has never done it right and no one has noticed, so this
2344 // should be OK for now.
2345 errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2346 VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2347 }
2348
2349 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2350 // the RET instruction and handled by the FP Stackifier.
2351 if (VA.getLocReg() == X86::FP0 ||
2352 VA.getLocReg() == X86::FP1) {
2353 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2354 // change the value to the FP stack register class.
2355 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2356 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2357 RetOps.push_back(ValToCopy);
2358 // Don't emit a copytoreg.
2359 continue;
2360 }
2361
2362 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2363 // which is returned in RAX / RDX.
2364 if (Subtarget.is64Bit()) {
2365 if (ValVT == MVT::x86mmx) {
2366 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2367 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2368 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2369 ValToCopy);
2370 // If we don't have SSE2 available, convert to v4f32 so the generated
2371 // register is legal.
2372 if (!Subtarget.hasSSE2())
2373 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2374 }
2375 }
2376 }
2377
2378 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2379
2380 if (VA.needsCustom()) {
2381 assert(VA.getValVT() == MVT::v64i1 &&(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2382, __extension__ __PRETTY_FUNCTION__))
2382 "Currently the only custom case is when we split v64i1 to 2 regs")(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2382, __extension__ __PRETTY_FUNCTION__))
;
2383
2384 Passv64i1ArgInRegs(dl, DAG, Chain, ValToCopy, RegsToPass, VA, RVLocs[++I],
2385 Subtarget);
2386
2387 assert(2 == RegsToPass.size() &&(static_cast <bool> (2 == RegsToPass.size() && "Expecting two registers after Pass64BitArgInRegs"
) ? void (0) : __assert_fail ("2 == RegsToPass.size() && \"Expecting two registers after Pass64BitArgInRegs\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2388, __extension__ __PRETTY_FUNCTION__))
2388 "Expecting two registers after Pass64BitArgInRegs")(static_cast <bool> (2 == RegsToPass.size() && "Expecting two registers after Pass64BitArgInRegs"
) ? void (0) : __assert_fail ("2 == RegsToPass.size() && \"Expecting two registers after Pass64BitArgInRegs\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2388, __extension__ __PRETTY_FUNCTION__))
;
2389
2390 // Add the second register to the CalleeSaveDisableRegs list.
2391 if (ShouldDisableCalleeSavedRegister)
2392 MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
2393 } else {
2394 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2395 }
2396
2397 // Add nodes to the DAG and add the values into the RetOps list
2398 for (auto &Reg : RegsToPass) {
2399 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, Flag);
2400 Flag = Chain.getValue(1);
2401 RetOps.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
2402 }
2403 }
2404
2405 // Swift calling convention does not require we copy the sret argument
2406 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
2407
2408 // All x86 ABIs require that for returning structs by value we copy
2409 // the sret argument into %rax/%eax (depending on ABI) for the return.
2410 // We saved the argument into a virtual register in the entry block,
2411 // so now we copy the value out and into %rax/%eax.
2412 //
2413 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2414 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2415 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2416 // either case FuncInfo->setSRetReturnReg() will have been called.
2417 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2418 // When we have both sret and another return value, we should use the
2419 // original Chain stored in RetOps[0], instead of the current Chain updated
2420 // in the above loop. If we only have sret, RetOps[0] equals to Chain.
2421
2422 // For the case of sret and another return value, we have
2423 // Chain_0 at the function entry
2424 // Chain_1 = getCopyToReg(Chain_0) in the above loop
2425 // If we use Chain_1 in getCopyFromReg, we will have
2426 // Val = getCopyFromReg(Chain_1)
2427 // Chain_2 = getCopyToReg(Chain_1, Val) from below
2428
2429 // getCopyToReg(Chain_0) will be glued together with
2430 // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
2431 // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
2432 // Data dependency from Unit B to Unit A due to usage of Val in
2433 // getCopyToReg(Chain_1, Val)
2434 // Chain dependency from Unit A to Unit B
2435
2436 // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
2437 SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
2438 getPointerTy(MF.getDataLayout()));
2439
2440 unsigned RetValReg
2441 = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
2442 X86::RAX : X86::EAX;
2443 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2444 Flag = Chain.getValue(1);
2445
2446 // RAX/EAX now acts like a return value.
2447 RetOps.push_back(
2448 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2449
2450 // Add the returned register to the CalleeSaveDisableRegs list.
2451 if (ShouldDisableCalleeSavedRegister)
2452 MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
2453 }
2454
2455 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
2456 const MCPhysReg *I =
2457 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2458 if (I) {
2459 for (; *I; ++I) {
2460 if (X86::GR64RegClass.contains(*I))
2461 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2462 else
2463 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2463)
;
2464 }
2465 }
2466
2467 RetOps[0] = Chain; // Update chain.
2468
2469 // Add the flag if we have it.
2470 if (Flag.getNode())
2471 RetOps.push_back(Flag);
2472
2473 X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2474 if (CallConv == CallingConv::X86_INTR)
2475 opcode = X86ISD::IRET;
2476 return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2477}
2478
2479bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2480 if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
2481 return false;
2482
2483 SDValue TCChain = Chain;
2484 SDNode *Copy = *N->use_begin();
2485 if (Copy->getOpcode() == ISD::CopyToReg) {
2486 // If the copy has a glue operand, we conservatively assume it isn't safe to
2487 // perform a tail call.
2488 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2489 return false;
2490 TCChain = Copy->getOperand(0);
2491 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2492 return false;
2493
2494 bool HasRet = false;
2495 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2496 UI != UE; ++UI) {
2497 if (UI->getOpcode() != X86ISD::RET_FLAG)
2498 return false;
2499 // If we are returning more than one value, we can definitely
2500 // not make a tail call see PR19530
2501 if (UI->getNumOperands() > 4)
2502 return false;
2503 if (UI->getNumOperands() == 4 &&
2504 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2505 return false;
2506 HasRet = true;
2507 }
2508
2509 if (!HasRet)
2510 return false;
2511
2512 Chain = TCChain;
2513 return true;
2514}
2515
2516EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
2517 ISD::NodeType ExtendKind) const {
2518 MVT ReturnMVT = MVT::i32;
2519
2520 bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
2521 if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
2522 // The ABI does not require i1, i8 or i16 to be extended.
2523 //
2524 // On Darwin, there is code in the wild relying on Clang's old behaviour of
2525 // always extending i8/i16 return values, so keep doing that for now.
2526 // (PR26665).
2527 ReturnMVT = MVT::i8;
2528 }
2529
2530 EVT MinVT = getRegisterType(Context, ReturnMVT);
2531 return VT.bitsLT(MinVT) ? MinVT : VT;
2532}
2533
2534/// Reads two 32 bit registers and creates a 64 bit mask value.
2535/// \param VA The current 32 bit value that need to be assigned.
2536/// \param NextVA The next 32 bit value that need to be assigned.
2537/// \param Root The parent DAG node.
2538/// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
2539/// glue purposes. In the case the DAG is already using
2540/// physical register instead of virtual, we should glue
2541/// our new SDValue to InFlag SDvalue.
2542/// \return a new SDvalue of size 64bit.
2543static SDValue getv64i1Argument(CCValAssign &VA, CCValAssign &NextVA,
2544 SDValue &Root, SelectionDAG &DAG,
2545 const SDLoc &Dl, const X86Subtarget &Subtarget,
2546 SDValue *InFlag = nullptr) {
2547 assert((Subtarget.hasBWI()) && "Expected AVX512BW target!")(static_cast <bool> ((Subtarget.hasBWI()) && "Expected AVX512BW target!"
) ? void (0) : __assert_fail ("(Subtarget.hasBWI()) && \"Expected AVX512BW target!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2547, __extension__ __PRETTY_FUNCTION__))
;
2548 assert(Subtarget.is32Bit() && "Expecting 32 bit target")(static_cast <bool> (Subtarget.is32Bit() && "Expecting 32 bit target"
) ? void (0) : __assert_fail ("Subtarget.is32Bit() && \"Expecting 32 bit target\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2548, __extension__ __PRETTY_FUNCTION__))
;
2549 assert(VA.getValVT() == MVT::v64i1 &&(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Expecting first location of 64 bit width type") ? void (0) :
__assert_fail ("VA.getValVT() == MVT::v64i1 && \"Expecting first location of 64 bit width type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2550, __extension__ __PRETTY_FUNCTION__))
2550 "Expecting first location of 64 bit width type")(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Expecting first location of 64 bit width type") ? void (0) :
__assert_fail ("VA.getValVT() == MVT::v64i1 && \"Expecting first location of 64 bit width type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2550, __extension__ __PRETTY_FUNCTION__))
;
2551 assert(NextVA.getValVT() == VA.getValVT() &&(static_cast <bool> (NextVA.getValVT() == VA.getValVT()
&& "The locations should have the same type") ? void
(0) : __assert_fail ("NextVA.getValVT() == VA.getValVT() && \"The locations should have the same type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2552, __extension__ __PRETTY_FUNCTION__))
2552 "The locations should have the same type")(static_cast <bool> (NextVA.getValVT() == VA.getValVT()
&& "The locations should have the same type") ? void
(0) : __assert_fail ("NextVA.getValVT() == VA.getValVT() && \"The locations should have the same type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2552, __extension__ __PRETTY_FUNCTION__))
;
2553 assert(VA.isRegLoc() && NextVA.isRegLoc() &&(static_cast <bool> (VA.isRegLoc() && NextVA.isRegLoc
() && "The values should reside in two registers") ? void
(0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The values should reside in two registers\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2554, __extension__ __PRETTY_FUNCTION__))
2554 "The values should reside in two registers")(static_cast <bool> (VA.isRegLoc() && NextVA.isRegLoc
() && "The values should reside in two registers") ? void
(0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The values should reside in two registers\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2554, __extension__ __PRETTY_FUNCTION__))
;
2555
2556 SDValue Lo, Hi;
2557 unsigned Reg;
2558 SDValue ArgValueLo, ArgValueHi;
2559
2560 MachineFunction &MF = DAG.getMachineFunction();
2561 const TargetRegisterClass *RC = &X86::GR32RegClass;
2562
2563 // Read a 32 bit value from the registers.
2564 if (nullptr == InFlag) {
2565 // When no physical register is present,
2566 // create an intermediate virtual register.
2567 Reg = MF.addLiveIn(VA.getLocReg(), RC);
2568 ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2569 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2570 ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2571 } else {
2572 // When a physical register is available read the value from it and glue
2573 // the reads together.
2574 ArgValueLo =
2575 DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
2576 *InFlag = ArgValueLo.getValue(2);
2577 ArgValueHi =
2578 DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
2579 *InFlag = ArgValueHi.getValue(2);
2580 }
2581
2582 // Convert the i32 type into v32i1 type.
2583 Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
2584
2585 // Convert the i32 type into v32i1 type.
2586 Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
2587
2588 // Concatenate the two values together.
2589 return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
2590}
2591
2592/// The function will lower a register of various sizes (8/16/32/64)
2593/// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
2594/// \returns a DAG node contains the operand after lowering to mask type.
2595static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
2596 const EVT &ValLoc, const SDLoc &Dl,
2597 SelectionDAG &DAG) {
2598 SDValue ValReturned = ValArg;
2599
2600 if (ValVT == MVT::v1i1)
2601 return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
2602
2603 if (ValVT == MVT::v64i1) {
2604 // In 32 bit machine, this case is handled by getv64i1Argument
2605 assert(ValLoc == MVT::i64 && "Expecting only i64 locations")(static_cast <bool> (ValLoc == MVT::i64 && "Expecting only i64 locations"
) ? void (0) : __assert_fail ("ValLoc == MVT::i64 && \"Expecting only i64 locations\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2605, __extension__ __PRETTY_FUNCTION__))
;
2606 // In 64 bit machine, There is no need to truncate the value only bitcast
2607 } else {
2608 MVT maskLen;
2609 switch (ValVT.getSimpleVT().SimpleTy) {
2610 case MVT::v8i1:
2611 maskLen = MVT::i8;
2612 break;
2613 case MVT::v16i1:
2614 maskLen = MVT::i16;
2615 break;
2616 case MVT::v32i1:
2617 maskLen = MVT::i32;
2618 break;
2619 default:
2620 llvm_unreachable("Expecting a vector of i1 types")::llvm::llvm_unreachable_internal("Expecting a vector of i1 types"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2620)
;
2621 }
2622
2623 ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
2624 }
2625 return DAG.getBitcast(ValVT, ValReturned);
2626}
2627
2628/// Lower the result values of a call into the
2629/// appropriate copies out of appropriate physical registers.
2630///
2631SDValue X86TargetLowering::LowerCallResult(
2632 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2633 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2634 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
2635 uint32_t *RegMask) const {
2636
2637 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2638 // Assign locations to each value returned by this call.
2639 SmallVector<CCValAssign, 16> RVLocs;
2640 bool Is64Bit = Subtarget.is64Bit();
2641 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2642 *DAG.getContext());
2643 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2644
2645 // Copy all of the result registers out of their specified physreg.
2646 for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
2647 ++I, ++InsIndex) {
2648 CCValAssign &VA = RVLocs[I];
2649 EVT CopyVT = VA.getLocVT();
2650
2651 // In some calling conventions we need to remove the used registers
2652 // from the register mask.
2653 if (RegMask) {
2654 for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
2655 SubRegs.isValid(); ++SubRegs)
2656 RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
2657 }
2658
2659 // If this is x86-64, and we disabled SSE, we can't return FP values
2660 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2661 ((Is64Bit || Ins[InsIndex].Flags.isInReg()) && !Subtarget.hasSSE1())) {
2662 errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2663 VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2664 }
2665
2666 // If we prefer to use the value in xmm registers, copy it out as f80 and
2667 // use a truncate to move it from fp stack reg to xmm reg.
2668 bool RoundAfterCopy = false;
2669 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2670 isScalarFPTypeInSSEReg(VA.getValVT())) {
2671 if (!Subtarget.hasX87())
2672 report_fatal_error("X87 register return with X87 disabled");
2673 CopyVT = MVT::f80;
2674 RoundAfterCopy = (CopyVT != VA.getLocVT());
2675 }
2676
2677 SDValue Val;
2678 if (VA.needsCustom()) {
2679 assert(VA.getValVT() == MVT::v64i1 &&(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2680, __extension__ __PRETTY_FUNCTION__))
2680 "Currently the only custom case is when we split v64i1 to 2 regs")(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2680, __extension__ __PRETTY_FUNCTION__))
;
2681 Val =
2682 getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
2683 } else {
2684 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
2685 .getValue(1);
2686 Val = Chain.getValue(0);
2687 InFlag = Chain.getValue(2);
2688 }
2689
2690 if (RoundAfterCopy)
2691 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2692 // This truncation won't change the value.
2693 DAG.getIntPtrConstant(1, dl));
2694
2695 if (VA.isExtInLoc() && (VA.getValVT().getScalarType() == MVT::i1)) {
2696 if (VA.getValVT().isVector() &&
2697 ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
2698 (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
2699 // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
2700 Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
2701 } else
2702 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2703 }
2704
2705 InVals.push_back(Val);
2706 }
2707
2708 return Chain;
2709}
2710
2711//===----------------------------------------------------------------------===//
2712// C & StdCall & Fast Calling Convention implementation
2713//===----------------------------------------------------------------------===//
2714// StdCall calling convention seems to be standard for many Windows' API
2715// routines and around. It differs from C calling convention just a little:
2716// callee should clean up the stack, not caller. Symbols should be also
2717// decorated in some fancy way :) It doesn't support any vector arguments.
2718// For info on fast calling convention see Fast Calling Convention (tail call)
2719// implementation LowerX86_32FastCCCallTo.
2720
2721/// CallIsStructReturn - Determines whether a call uses struct return
2722/// semantics.
2723enum StructReturnType {
2724 NotStructReturn,
2725 RegStructReturn,
2726 StackStructReturn
2727};
2728static StructReturnType
2729callIsStructReturn(ArrayRef<ISD::OutputArg> Outs, bool IsMCU) {
2730 if (Outs.empty())
2731 return NotStructReturn;
2732
2733 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2734 if (!Flags.isSRet())
2735 return NotStructReturn;
2736 if (Flags.isInReg() || IsMCU)
2737 return RegStructReturn;
2738 return StackStructReturn;
2739}
2740
2741/// Determines whether a function uses struct return semantics.
2742static StructReturnType
2743argsAreStructReturn(ArrayRef<ISD::InputArg> Ins, bool IsMCU) {
2744 if (Ins.empty())
2745 return NotStructReturn;
2746
2747 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2748 if (!Flags.isSRet())
2749 return NotStructReturn;
2750 if (Flags.isInReg() || IsMCU)
2751 return RegStructReturn;
2752 return StackStructReturn;
2753}
2754
2755/// Make a copy of an aggregate at address specified by "Src" to address
2756/// "Dst" with size and alignment information specified by the specific
2757/// parameter attribute. The copy will be passed as a byval function parameter.
2758static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
2759 SDValue Chain, ISD::ArgFlagsTy Flags,
2760 SelectionDAG &DAG, const SDLoc &dl) {
2761 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2762
2763 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2764 /*isVolatile*/false, /*AlwaysInline=*/true,
2765 /*isTailCall*/false,
2766 MachinePointerInfo(), MachinePointerInfo());
2767}
2768
2769/// Return true if the calling convention is one that we can guarantee TCO for.
2770static bool canGuaranteeTCO(CallingConv::ID CC) {
2771 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2772 CC == CallingConv::X86_RegCall || CC == CallingConv::HiPE ||
2773 CC == CallingConv::HHVM);
2774}
2775
2776/// Return true if we might ever do TCO for calls with this calling convention.
2777static bool mayTailCallThisCC(CallingConv::ID CC) {
2778 switch (CC) {
2779 // C calling conventions:
2780 case CallingConv::C:
2781 case CallingConv::Win64:
2782 case CallingConv::X86_64_SysV:
2783 // Callee pop conventions:
2784 case CallingConv::X86_ThisCall:
2785 case CallingConv::X86_StdCall:
2786 case CallingConv::X86_VectorCall:
2787 case CallingConv::X86_FastCall:
2788 return true;
2789 default:
2790 return canGuaranteeTCO(CC);
2791 }
2792}
2793
2794/// Return true if the function is being made into a tailcall target by
2795/// changing its ABI.
2796static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2797 return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2798}
2799
2800bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2801 auto Attr =
2802 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2803 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2804 return false;
2805
2806 ImmutableCallSite CS(CI);
2807 CallingConv::ID CalleeCC = CS.getCallingConv();
2808 if (!mayTailCallThisCC(CalleeCC))
2809 return false;
2810
2811 return true;
2812}
2813
2814SDValue
2815X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
2816 const SmallVectorImpl<ISD::InputArg> &Ins,
2817 const SDLoc &dl, SelectionDAG &DAG,
2818 const CCValAssign &VA,
2819 MachineFrameInfo &MFI, unsigned i) const {
2820 // Create the nodes corresponding to a load from this parameter slot.
2821 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2822 bool AlwaysUseMutable = shouldGuaranteeTCO(
2823 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2824 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2825 EVT ValVT;
2826 MVT PtrVT = getPointerTy(DAG.getDataLayout());
2827
2828 // If value is passed by pointer we have address passed instead of the value
2829 // itself. No need to extend if the mask value and location share the same
2830 // absolute size.
2831 bool ExtendedInMem =
2832 VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
2833 VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
2834
2835 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2836 ValVT = VA.getLocVT();
2837 else
2838 ValVT = VA.getValVT();
2839
2840 // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2841 // taken by a return address.
2842 int Offset = 0;
2843 if (CallConv == CallingConv::X86_INTR) {
2844 // X86 interrupts may take one or two arguments.
2845 // On the stack there will be no return address as in regular call.
2846 // Offset of last argument need to be set to -4/-8 bytes.
2847 // Where offset of the first argument out of two, should be set to 0 bytes.
2848 Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2849 if (Subtarget.is64Bit() && Ins.size() == 2) {
2850 // The stack pointer needs to be realigned for 64 bit handlers with error
2851 // code, so the argument offset changes by 8 bytes.
2852 Offset += 8;
2853 }
2854 }
2855
2856 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2857 // changed with more analysis.
2858 // In case of tail call optimization mark all arguments mutable. Since they
2859 // could be overwritten by lowering of arguments in case of a tail call.
2860 if (Flags.isByVal()) {
2861 unsigned Bytes = Flags.getByValSize();
2862 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2863
2864 // FIXME: For now, all byval parameter objects are marked as aliasing. This
2865 // can be improved with deeper analysis.
2866 int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable,
2867 /*isAliased=*/true);
2868 // Adjust SP offset of interrupt parameter.
2869 if (CallConv == CallingConv::X86_INTR) {
2870 MFI.setObjectOffset(FI, Offset);
2871 }
2872 return DAG.getFrameIndex(FI, PtrVT);
2873 }
2874
2875 // This is an argument in memory. We might be able to perform copy elision.
2876 if (Flags.isCopyElisionCandidate()) {
2877 EVT ArgVT = Ins[i].ArgVT;
2878 SDValue PartAddr;
2879 if (Ins[i].PartOffset == 0) {
2880 // If this is a one-part value or the first part of a multi-part value,
2881 // create a stack object for the entire argument value type and return a
2882 // load from our portion of it. This assumes that if the first part of an
2883 // argument is in memory, the rest will also be in memory.
2884 int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
2885 /*Immutable=*/false);
2886 PartAddr = DAG.getFrameIndex(FI, PtrVT);
2887 return DAG.getLoad(
2888 ValVT, dl, Chain, PartAddr,
2889 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
2890 } else {
2891 // This is not the first piece of an argument in memory. See if there is
2892 // already a fixed stack object including this offset. If so, assume it
2893 // was created by the PartOffset == 0 branch above and create a load from
2894 // the appropriate offset into it.
2895 int64_t PartBegin = VA.getLocMemOffset();
2896 int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
2897 int FI = MFI.getObjectIndexBegin();
2898 for (; MFI.isFixedObjectIndex(FI); ++FI) {
2899 int64_t ObjBegin = MFI.getObjectOffset(FI);
2900 int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
2901 if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
2902 break;
2903 }
2904 if (MFI.isFixedObjectIndex(FI)) {
2905 SDValue Addr =
2906 DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
2907 DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
2908 return DAG.getLoad(
2909 ValVT, dl, Chain, Addr,
2910 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI,
2911 Ins[i].PartOffset));
2912 }
2913 }
2914 }
2915
2916 int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
2917 VA.getLocMemOffset(), isImmutable);
2918
2919 // Set SExt or ZExt flag.
2920 if (VA.getLocInfo() == CCValAssign::ZExt) {
2921 MFI.setObjectZExt(FI, true);
2922 } else if (VA.getLocInfo() == CCValAssign::SExt) {
2923 MFI.setObjectSExt(FI, true);
2924 }
2925
2926 // Adjust SP offset of interrupt parameter.
2927 if (CallConv == CallingConv::X86_INTR) {
2928 MFI.setObjectOffset(FI, Offset);
2929 }
2930
2931 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2932 SDValue Val = DAG.getLoad(
2933 ValVT, dl, Chain, FIN,
2934 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
2935 return ExtendedInMem
2936 ? (VA.getValVT().isVector()
2937 ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
2938 : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
2939 : Val;
2940}
2941
2942// FIXME: Get this from tablegen.
2943static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2944 const X86Subtarget &Subtarget) {
2945 assert(Subtarget.is64Bit())(static_cast <bool> (Subtarget.is64Bit()) ? void (0) : __assert_fail
("Subtarget.is64Bit()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2945, __extension__ __PRETTY_FUNCTION__))
;
2946
2947 if (Subtarget.isCallingConvWin64(CallConv)) {
2948 static const MCPhysReg GPR64ArgRegsWin64[] = {
2949 X86::RCX, X86::RDX, X86::R8, X86::R9
2950 };
2951 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2952 }
2953
2954 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2955 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2956 };
2957 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2958}
2959
2960// FIXME: Get this from tablegen.
2961static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2962 CallingConv::ID CallConv,
2963 const X86Subtarget &Subtarget) {
2964 assert(Subtarget.is64Bit())(static_cast <bool> (Subtarget.is64Bit()) ? void (0) : __assert_fail
("Subtarget.is64Bit()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2964, __extension__ __PRETTY_FUNCTION__))
;
2965 if (Subtarget.isCallingConvWin64(CallConv)) {
2966 // The XMM registers which might contain var arg parameters are shadowed
2967 // in their paired GPR. So we only need to save the GPR to their home
2968 // slots.
2969 // TODO: __vectorcall will change this.
2970 return None;
2971 }
2972
2973 const Function &F = MF.getFunction();
2974 bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
2975 bool isSoftFloat = Subtarget.useSoftFloat();
2976 assert(!(isSoftFloat && NoImplicitFloatOps) &&(static_cast <bool> (!(isSoftFloat && NoImplicitFloatOps
) && "SSE register cannot be used when SSE is disabled!"
) ? void (0) : __assert_fail ("!(isSoftFloat && NoImplicitFloatOps) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2977, __extension__ __PRETTY_FUNCTION__))
2977 "SSE register cannot be used when SSE is disabled!")(static_cast <bool> (!(isSoftFloat && NoImplicitFloatOps
) && "SSE register cannot be used when SSE is disabled!"
) ? void (0) : __assert_fail ("!(isSoftFloat && NoImplicitFloatOps) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 2977, __extension__ __PRETTY_FUNCTION__))
;
2978 if (isSoftFloat || NoImplicitFloatOps || !Subtarget.hasSSE1())
2979 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2980 // registers.
2981 return None;
2982
2983 static const MCPhysReg XMMArgRegs64Bit[] = {
2984 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2985 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2986 };
2987 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2988}
2989
2990#ifndef NDEBUG
2991static bool isSortedByValueNo(ArrayRef<CCValAssign> ArgLocs) {
2992 return std::is_sorted(ArgLocs.begin(), ArgLocs.end(),
2993 [](const CCValAssign &A, const CCValAssign &B) -> bool {
2994 return A.getValNo() < B.getValNo();
2995 });
2996}
2997#endif
2998
2999SDValue X86TargetLowering::LowerFormalArguments(
3000 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3001 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3002 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3003 MachineFunction &MF = DAG.getMachineFunction();
3004 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3005 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
3006
3007 const Function &F = MF.getFunction();
3008 if (F.hasExternalLinkage() && Subtarget.isTargetCygMing() &&
3009 F.getName() == "main")
3010 FuncInfo->setForceFramePointer(true);
3011
3012 MachineFrameInfo &MFI = MF.getFrameInfo();
3013 bool Is64Bit = Subtarget.is64Bit();
3014 bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3015
3016 assert((static_cast <bool> (!(isVarArg && canGuaranteeTCO
(CallConv)) && "Var args not supported with calling conv' regcall, fastcc, ghc or hipe"
) ? void (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling conv' regcall, fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3018, __extension__ __PRETTY_FUNCTION__))
3017 !(isVarArg && canGuaranteeTCO(CallConv)) &&(static_cast <bool> (!(isVarArg && canGuaranteeTCO
(CallConv)) && "Var args not supported with calling conv' regcall, fastcc, ghc or hipe"
) ? void (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling conv' regcall, fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3018, __extension__ __PRETTY_FUNCTION__))
3018 "Var args not supported with calling conv' regcall, fastcc, ghc or hipe")(static_cast <bool> (!(isVarArg && canGuaranteeTCO
(CallConv)) && "Var args not supported with calling conv' regcall, fastcc, ghc or hipe"
) ? void (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling conv' regcall, fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3018, __extension__ __PRETTY_FUNCTION__))
;
3019
3020 if (CallConv == CallingConv::X86_INTR) {
3021 bool isLegal = Ins.size() == 1 ||
3022 (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
3023 (!Is64Bit && Ins[1].VT == MVT::i32)));
3024 if (!isLegal)
3025 report_fatal_error("X86 interrupts may take one or two arguments");
3026 }
3027
3028 // Assign locations to all of the incoming arguments.
3029 SmallVector<CCValAssign, 16> ArgLocs;
3030 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3031
3032 // Allocate shadow area for Win64.
3033 if (IsWin64)
3034 CCInfo.AllocateStack(32, 8);
3035
3036 CCInfo.AnalyzeArguments(Ins, CC_X86);
3037
3038 // In vectorcall calling convention a second pass is required for the HVA
3039 // types.
3040 if (CallingConv::X86_VectorCall == CallConv) {
3041 CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
3042 }
3043
3044 // The next loop assumes that the locations are in the same order of the
3045 // input arguments.
3046 assert(isSortedByValueNo(ArgLocs) &&(static_cast <bool> (isSortedByValueNo(ArgLocs) &&
"Argument Location list must be sorted before lowering") ? void
(0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3047, __extension__ __PRETTY_FUNCTION__))
3047 "Argument Location list must be sorted before lowering")(static_cast <bool> (isSortedByValueNo(ArgLocs) &&
"Argument Location list must be sorted before lowering") ? void
(0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3047, __extension__ __PRETTY_FUNCTION__))
;
3048
3049 SDValue ArgValue;
3050 for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
3051 ++I, ++InsIndex) {
3052 assert(InsIndex < Ins.size() && "Invalid Ins index")(static_cast <bool> (InsIndex < Ins.size() &&
"Invalid Ins index") ? void (0) : __assert_fail ("InsIndex < Ins.size() && \"Invalid Ins index\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3052, __extension__ __PRETTY_FUNCTION__))
;
3053 CCValAssign &VA = ArgLocs[I];
3054
3055 if (VA.isRegLoc()) {
3056 EVT RegVT = VA.getLocVT();
3057 if (VA.needsCustom()) {
3058 assert((static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3060, __extension__ __PRETTY_FUNCTION__))
3059 VA.getValVT() == MVT::v64i1 &&(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3060, __extension__ __PRETTY_FUNCTION__))
3060 "Currently the only custom case is when we split v64i1 to 2 regs")(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3060, __extension__ __PRETTY_FUNCTION__))
;
3061
3062 // v64i1 values, in regcall calling convention, that are
3063 // compiled to 32 bit arch, are split up into two registers.
3064 ArgValue =
3065 getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
3066 } else {
3067 const TargetRegisterClass *RC;
3068 if (RegVT == MVT::i8)
3069 RC = &X86::GR8RegClass;
3070 else if (RegVT == MVT::i16)
3071 RC = &X86::GR16RegClass;
3072 else if (RegVT == MVT::i32)
3073 RC = &X86::GR32RegClass;
3074 else if (Is64Bit && RegVT == MVT::i64)
3075 RC = &X86::GR64RegClass;
3076 else if (RegVT == MVT::f32)
3077 RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
3078 else if (RegVT == MVT::f64)
3079 RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
3080 else if (RegVT == MVT::f80)
3081 RC = &X86::RFP80RegClass;
3082 else if (RegVT == MVT::f128)
3083 RC = &X86::VR128RegClass;
3084 else if (RegVT.is512BitVector())
3085 RC = &X86::VR512RegClass;
3086 else if (RegVT.is256BitVector())
3087 RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
3088 else if (RegVT.is128BitVector())
3089 RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
3090 else if (RegVT == MVT::x86mmx)
3091 RC = &X86::VR64RegClass;
3092 else if (RegVT == MVT::v1i1)
3093 RC = &X86::VK1RegClass;
3094 else if (RegVT == MVT::v8i1)
3095 RC = &X86::VK8RegClass;
3096 else if (RegVT == MVT::v16i1)
3097 RC = &X86::VK16RegClass;
3098 else if (RegVT == MVT::v32i1)
3099 RC = &X86::VK32RegClass;
3100 else if (RegVT == MVT::v64i1)
3101 RC = &X86::VK64RegClass;
3102 else
3103 llvm_unreachable("Unknown argument type!")::llvm::llvm_unreachable_internal("Unknown argument type!", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3103)
;
3104
3105 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3106 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3107 }
3108
3109 // If this is an 8 or 16-bit value, it is really passed promoted to 32
3110 // bits. Insert an assert[sz]ext to capture this, then truncate to the
3111 // right size.
3112 if (VA.getLocInfo() == CCValAssign::SExt)
3113 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3114 DAG.getValueType(VA.getValVT()));
3115 else if (VA.getLocInfo() == CCValAssign::ZExt)
3116 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3117 DAG.getValueType(VA.getValVT()));
3118 else if (VA.getLocInfo() == CCValAssign::BCvt)
3119 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
3120
3121 if (VA.isExtInLoc()) {
3122 // Handle MMX values passed in XMM regs.
3123 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
3124 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
3125 else if (VA.getValVT().isVector() &&
3126 VA.getValVT().getScalarType() == MVT::i1 &&
3127 ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3128 (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3129 // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3130 ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
3131 } else
3132 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3133 }
3134 } else {
3135 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3135, __extension__ __PRETTY_FUNCTION__))
;
3136 ArgValue =
3137 LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
3138 }
3139
3140 // If value is passed via pointer - do a load.
3141 if (VA.getLocInfo() == CCValAssign::Indirect)
3142 ArgValue =
3143 DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
3144
3145 InVals.push_back(ArgValue);
3146 }
3147
3148 for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3149 // Swift calling convention does not require we copy the sret argument
3150 // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
3151 if (CallConv == CallingConv::Swift)
3152 continue;
3153
3154 // All x86 ABIs require that for returning structs by value we copy the
3155 // sret argument into %rax/%eax (depending on ABI) for the return. Save
3156 // the argument into a virtual register so that we can access it from the
3157 // return points.
3158 if (Ins[I].Flags.isSRet()) {
3159 unsigned Reg = FuncInfo->getSRetReturnReg();
3160 if (!Reg) {
3161 MVT PtrTy = getPointerTy(DAG.getDataLayout());
3162 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3163 FuncInfo->setSRetReturnReg(Reg);
3164 }
3165 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
3166 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3167 break;
3168 }
3169 }
3170
3171 unsigned StackSize = CCInfo.getNextStackOffset();
3172 // Align stack specially for tail calls.
3173 if (shouldGuaranteeTCO(CallConv,
3174 MF.getTarget().Options.GuaranteedTailCallOpt))
3175 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
3176
3177 // If the function takes variable number of arguments, make a frame index for
3178 // the start of the first vararg value... for expansion of llvm.va_start. We
3179 // can skip this if there are no va_start calls.
3180 if (MFI.hasVAStart() &&
3181 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
3182 CallConv != CallingConv::X86_ThisCall))) {
3183 FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
3184 }
3185
3186 // Figure out if XMM registers are in use.
3187 assert(!(Subtarget.useSoftFloat() &&(static_cast <bool> (!(Subtarget.useSoftFloat() &&
F.hasFnAttribute(Attribute::NoImplicitFloat)) && "SSE register cannot be used when SSE is disabled!"
) ? void (0) : __assert_fail ("!(Subtarget.useSoftFloat() && F.hasFnAttribute(Attribute::NoImplicitFloat)) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3189, __extension__ __PRETTY_FUNCTION__))
3188 F.hasFnAttribute(Attribute::NoImplicitFloat)) &&(static_cast <bool> (!(Subtarget.useSoftFloat() &&
F.hasFnAttribute(Attribute::NoImplicitFloat)) && "SSE register cannot be used when SSE is disabled!"
) ? void (0) : __assert_fail ("!(Subtarget.useSoftFloat() && F.hasFnAttribute(Attribute::NoImplicitFloat)) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3189, __extension__ __PRETTY_FUNCTION__))
3189 "SSE register cannot be used when SSE is disabled!")(static_cast <bool> (!(Subtarget.useSoftFloat() &&
F.hasFnAttribute(Attribute::NoImplicitFloat)) && "SSE register cannot be used when SSE is disabled!"
) ? void (0) : __assert_fail ("!(Subtarget.useSoftFloat() && F.hasFnAttribute(Attribute::NoImplicitFloat)) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3189, __extension__ __PRETTY_FUNCTION__))
;
3190
3191 // 64-bit calling conventions support varargs and register parameters, so we
3192 // have to do extra work to spill them in the prologue.
3193 if (Is64Bit && isVarArg && MFI.hasVAStart()) {
3194 // Find the first unallocated argument registers.
3195 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3196 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
3197 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3198 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3199 assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&(static_cast <bool> (!(NumXMMRegs && !Subtarget
.hasSSE1()) && "SSE register cannot be used when SSE is disabled!"
) ? void (0) : __assert_fail ("!(NumXMMRegs && !Subtarget.hasSSE1()) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3200, __extension__ __PRETTY_FUNCTION__))
3200 "SSE register cannot be used when SSE is disabled!")(static_cast <bool> (!(NumXMMRegs && !Subtarget
.hasSSE1()) && "SSE register cannot be used when SSE is disabled!"
) ? void (0) : __assert_fail ("!(NumXMMRegs && !Subtarget.hasSSE1()) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3200, __extension__ __PRETTY_FUNCTION__))
;
3201
3202 // Gather all the live in physical registers.
3203 SmallVector<SDValue, 6> LiveGPRs;
3204 SmallVector<SDValue, 8> LiveXMMRegs;
3205 SDValue ALVal;
3206 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3207 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
3208 LiveGPRs.push_back(
3209 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
3210 }
3211 if (!ArgXMMs.empty()) {
3212 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3213 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
3214 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
3215 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
3216 LiveXMMRegs.push_back(
3217 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
3218 }
3219 }
3220
3221 if (IsWin64) {
3222 // Get to the caller-allocated home save location. Add 8 to account
3223 // for the return address.
3224 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
3225 FuncInfo->setRegSaveFrameIndex(
3226 MFI.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3227 // Fixup to set vararg frame on shadow area (4 x i64).
3228 if (NumIntRegs < 4)
3229 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3230 } else {
3231 // For X86-64, if there are vararg parameters that are passed via
3232 // registers, then we must store them to their spots on the stack so
3233 // they may be loaded by dereferencing the result of va_next.
3234 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3235 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3236 FuncInfo->setRegSaveFrameIndex(MFI.CreateStackObject(
3237 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
3238 }
3239
3240 // Store the integer parameter registers.
3241 SmallVector<SDValue, 8> MemOps;
3242 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3243 getPointerTy(DAG.getDataLayout()));
3244 unsigned Offset = FuncInfo->getVarArgsGPOffset();
3245 for (SDValue Val : LiveGPRs) {
3246 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3247 RSFIN, DAG.getIntPtrConstant(Offset, dl));
3248 SDValue Store =
3249 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3250 MachinePointerInfo::getFixedStack(
3251 DAG.getMachineFunction(),
3252 FuncInfo->getRegSaveFrameIndex(), Offset));
3253 MemOps.push_back(Store);
3254 Offset += 8;
3255 }
3256
3257 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
3258 // Now store the XMM (fp + vector) parameter registers.
3259 SmallVector<SDValue, 12> SaveXMMOps;
3260 SaveXMMOps.push_back(Chain);
3261 SaveXMMOps.push_back(ALVal);
3262 SaveXMMOps.push_back(DAG.getIntPtrConstant(
3263 FuncInfo->getRegSaveFrameIndex(), dl));
3264 SaveXMMOps.push_back(DAG.getIntPtrConstant(
3265 FuncInfo->getVarArgsFPOffset(), dl));
3266 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
3267 LiveXMMRegs.end());
3268 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
3269 MVT::Other, SaveXMMOps));
3270 }
3271
3272 if (!MemOps.empty())
3273 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3274 }
3275
3276 if (isVarArg && MFI.hasMustTailInVarArgFunc()) {
3277 // Find the largest legal vector type.
3278 MVT VecVT = MVT::Other;
3279 // FIXME: Only some x86_32 calling conventions support AVX512.
3280 if (Subtarget.hasAVX512() &&
3281 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
3282 CallConv == CallingConv::Intel_OCL_BI)))
3283 VecVT = MVT::v16f32;
3284 else if (Subtarget.hasAVX())
3285 VecVT = MVT::v8f32;
3286 else if (Subtarget.hasSSE2())
3287 VecVT = MVT::v4f32;
3288
3289 // We forward some GPRs and some vector types.
3290 SmallVector<MVT, 2> RegParmTypes;
3291 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
3292 RegParmTypes.push_back(IntVT);
3293 if (VecVT != MVT::Other)
3294 RegParmTypes.push_back(VecVT);
3295
3296 // Compute the set of forwarded registers. The rest are scratch.
3297 SmallVectorImpl<ForwardedRegister> &Forwards =
3298 FuncInfo->getForwardedMustTailRegParms();
3299 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3300
3301 // Conservatively forward AL on x86_64, since it might be used for varargs.
3302 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
3303 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3304 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3305 }
3306
3307 // Copy all forwards from physical to virtual registers.
3308 for (ForwardedRegister &F : Forwards) {
3309 // FIXME: Can we use a less constrained schedule?
3310 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3311 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
3312 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
3313 }
3314 }
3315
3316 // Some CCs need callee pop.
3317 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3318 MF.getTarget().Options.GuaranteedTailCallOpt)) {
3319 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
3320 } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
3321 // X86 interrupts must pop the error code (and the alignment padding) if
3322 // present.
3323 FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
3324 } else {
3325 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
3326 // If this is an sret function, the return should pop the hidden pointer.
3327 if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3328 !Subtarget.getTargetTriple().isOSMSVCRT() &&
3329 argsAreStructReturn(Ins, Subtarget.isTargetMCU()) == StackStructReturn)
3330 FuncInfo->setBytesToPopOnReturn(4);
3331 }
3332
3333 if (!Is64Bit) {
3334 // RegSaveFrameIndex is X86-64 only.
3335 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3336 if (CallConv == CallingConv::X86_FastCall ||
3337 CallConv == CallingConv::X86_ThisCall)
3338 // fastcc functions can't have varargs.
3339 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
3340 }
3341
3342 FuncInfo->setArgumentStackSize(StackSize);
3343
3344 if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
3345 EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
3346 if (Personality == EHPersonality::CoreCLR) {
3347 assert(Is64Bit)(static_cast <bool> (Is64Bit) ? void (0) : __assert_fail
("Is64Bit", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3347, __extension__ __PRETTY_FUNCTION__))
;
3348 // TODO: Add a mechanism to frame lowering that will allow us to indicate
3349 // that we'd prefer this slot be allocated towards the bottom of the frame
3350 // (i.e. near the stack pointer after allocating the frame). Every
3351 // funclet needs a copy of this slot in its (mostly empty) frame, and the
3352 // offset from the bottom of this and each funclet's frame must be the
3353 // same, so the size of funclets' (mostly empty) frames is dictated by
3354 // how far this slot is from the bottom (since they allocate just enough
3355 // space to accommodate holding this slot at the correct offset).
3356 int PSPSymFI = MFI.CreateStackObject(8, 8, /*isSS=*/false);
3357 EHInfo->PSPSymFrameIdx = PSPSymFI;
3358 }
3359 }
3360
3361 if (CallConv == CallingConv::X86_RegCall ||
3362 F.hasFnAttribute("no_caller_saved_registers")) {
3363 MachineRegisterInfo &MRI = MF.getRegInfo();
3364 for (std::pair<unsigned, unsigned> Pair : MRI.liveins())
3365 MRI.disableCalleeSavedRegister(Pair.first);
3366 }
3367
3368 return Chain;
3369}
3370
3371SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
3372 SDValue Arg, const SDLoc &dl,
3373 SelectionDAG &DAG,
3374 const CCValAssign &VA,
3375 ISD::ArgFlagsTy Flags) const {
3376 unsigned LocMemOffset = VA.getLocMemOffset();
3377 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3378 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3379 StackPtr, PtrOff);
3380 if (Flags.isByVal())
3381 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3382
3383 return DAG.getStore(
3384 Chain, dl, Arg, PtrOff,
3385 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
3386}
3387
3388/// Emit a load of return address if tail call
3389/// optimization is performed and it is required.
3390SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
3391 SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
3392 bool Is64Bit, int FPDiff, const SDLoc &dl) const {
3393 // Adjust the Return address stack slot.
3394 EVT VT = getPointerTy(DAG.getDataLayout());
3395 OutRetAddr = getReturnAddressFrameIndex(DAG);
3396
3397 // Load the "old" Return address.
3398 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
3399 return SDValue(OutRetAddr.getNode(), 1);
3400}
3401
3402/// Emit a store of the return address if tail call
3403/// optimization is performed and it is required (FPDiff!=0).
3404static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3405 SDValue Chain, SDValue RetAddrFrIdx,
3406 EVT PtrVT, unsigned SlotSize,
3407 int FPDiff, const SDLoc &dl) {
3408 // Store the return address to the appropriate stack slot.
3409 if (!FPDiff) return Chain;
3410 // Calculate the new stack slot for the return address.
3411 int NewReturnAddrFI =
3412 MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3413 false);
3414 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3415 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3416 MachinePointerInfo::getFixedStack(
3417 DAG.getMachineFunction(), NewReturnAddrFI));
3418 return Chain;
3419}
3420
3421/// Returns a vector_shuffle mask for an movs{s|d}, movd
3422/// operation of specified width.
3423static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
3424 SDValue V2) {
3425 unsigned NumElems = VT.getVectorNumElements();
3426 SmallVector<int, 8> Mask;
3427 Mask.push_back(NumElems);
3428 for (unsigned i = 1; i != NumElems; ++i)
3429 Mask.push_back(i);
3430 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
3431}
3432
3433SDValue
3434X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3435 SmallVectorImpl<SDValue> &InVals) const {
3436 SelectionDAG &DAG = CLI.DAG;
3437 SDLoc &dl = CLI.DL;
3438 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3439 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3440 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3441 SDValue Chain = CLI.Chain;
3442 SDValue Callee = CLI.Callee;
3443 CallingConv::ID CallConv = CLI.CallConv;
3444 bool &isTailCall = CLI.IsTailCall;
3445 bool isVarArg = CLI.IsVarArg;
3446
3447 MachineFunction &MF = DAG.getMachineFunction();
3448 bool Is64Bit = Subtarget.is64Bit();
3449 bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3450 StructReturnType SR = callIsStructReturn(Outs, Subtarget.isTargetMCU());
3451 bool IsSibcall = false;
3452 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3453 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
3454 const auto *CI = dyn_cast_or_null<CallInst>(CLI.CS.getInstruction());
3455 const Function *Fn = CI ? CI->getCalledFunction() : nullptr;
3456 bool HasNCSR = (CI && CI->hasFnAttr("no_caller_saved_registers")) ||
3457 (Fn && Fn->hasFnAttribute("no_caller_saved_registers"));
3458 const auto *II = dyn_cast_or_null<InvokeInst>(CLI.CS.getInstruction());
3459 bool HasNoCfCheck =
3460 (CI && CI->doesNoCfCheck()) || (II && II->doesNoCfCheck());
3461 const Module *M = MF.getMMI().getModule();
3462 Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
3463
3464 if (CallConv == CallingConv::X86_INTR)
3465 report_fatal_error("X86 interrupts may not be called directly");
3466
3467 if (Attr.getValueAsString() == "true")
3468 isTailCall = false;
3469
3470 if (Subtarget.isPICStyleGOT() &&
3471 !MF.getTarget().Options.GuaranteedTailCallOpt) {
3472 // If we are using a GOT, disable tail calls to external symbols with
3473 // default visibility. Tail calling such a symbol requires using a GOT
3474 // relocation, which forces early binding of the symbol. This breaks code
3475 // that require lazy function symbol resolution. Using musttail or
3476 // GuaranteedTailCallOpt will override this.
3477 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3478 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3479 G->getGlobal()->hasDefaultVisibility()))
3480 isTailCall = false;
3481 }
3482
3483 bool IsMustTail = CLI.CS && CLI.CS.isMustTailCall();
3484 if (IsMustTail) {
3485 // Force this to be a tail call. The verifier rules are enough to ensure
3486 // that we can lower this successfully without moving the return address
3487 // around.
3488 isTailCall = true;
3489 } else if (isTailCall) {
3490 // Check if it's really possible to do a tail call.
3491 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3492 isVarArg, SR != NotStructReturn,
3493 MF.getFunction().hasStructRetAttr(), CLI.RetTy,
3494 Outs, OutVals, Ins, DAG);
3495
3496 // Sibcalls are automatically detected tailcalls which do not require
3497 // ABI changes.
3498 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3499 IsSibcall = true;
3500
3501 if (isTailCall)
3502 ++NumTailCalls;
3503 }
3504
3505 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&(static_cast <bool> (!(isVarArg && canGuaranteeTCO
(CallConv)) && "Var args not supported with calling convention fastcc, ghc or hipe"
) ? void (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling convention fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3506, __extension__ __PRETTY_FUNCTION__))
3506 "Var args not supported with calling convention fastcc, ghc or hipe")(static_cast <bool> (!(isVarArg && canGuaranteeTCO
(CallConv)) && "Var args not supported with calling convention fastcc, ghc or hipe"
) ? void (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling convention fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3506, __extension__ __PRETTY_FUNCTION__))
;
3507
3508 // Analyze operands of the call, assigning locations to each operand.
3509 SmallVector<CCValAssign, 16> ArgLocs;
3510 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3511
3512 // Allocate shadow area for Win64.
3513 if (IsWin64)
3514 CCInfo.AllocateStack(32, 8);
3515
3516 CCInfo.AnalyzeArguments(Outs, CC_X86);
3517
3518 // In vectorcall calling convention a second pass is required for the HVA
3519 // types.
3520 if (CallingConv::X86_VectorCall == CallConv) {
3521 CCInfo.AnalyzeArgumentsSecondPass(Outs, CC_X86);
3522 }
3523
3524 // Get a count of how many bytes are to be pushed on the stack.
3525 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3526 if (IsSibcall)
3527 // This is a sibcall. The memory operands are available in caller's
3528 // own caller's stack.
3529 NumBytes = 0;
3530 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3531 canGuaranteeTCO(CallConv))
3532 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3533
3534 int FPDiff = 0;
3535 if (isTailCall && !IsSibcall && !IsMustTail) {
3536 // Lower arguments at fp - stackoffset + fpdiff.
3537 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3538
3539 FPDiff = NumBytesCallerPushed - NumBytes;
3540
3541 // Set the delta of movement of the returnaddr stackslot.
3542 // But only set if delta is greater than previous delta.
3543 if (FPDiff < X86Info->getTCReturnAddrDelta())
3544 X86Info->setTCReturnAddrDelta(FPDiff);
3545 }
3546
3547 unsigned NumBytesToPush = NumBytes;
3548 unsigned NumBytesToPop = NumBytes;
3549
3550 // If we have an inalloca argument, all stack space has already been allocated
3551 // for us and be right at the top of the stack. We don't support multiple
3552 // arguments passed in memory when using inalloca.
3553 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3554 NumBytesToPush = 0;
3555 if (!ArgLocs.back().isMemLoc())
3556 report_fatal_error("cannot use inalloca attribute on a register "
3557 "parameter");
3558 if (ArgLocs.back().getLocMemOffset() != 0)
3559 report_fatal_error("any parameter with the inalloca attribute must be "
3560 "the only memory argument");
3561 }
3562
3563 if (!IsSibcall)
3564 Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
3565 NumBytes - NumBytesToPush, dl);
3566
3567 SDValue RetAddrFrIdx;
3568 // Load return address for tail calls.
3569 if (isTailCall && FPDiff)
3570 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3571 Is64Bit, FPDiff, dl);
3572
3573 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3574 SmallVector<SDValue, 8> MemOpChains;
3575 SDValue StackPtr;
3576
3577 // The next loop assumes that the locations are in the same order of the
3578 // input arguments.
3579 assert(isSortedByValueNo(ArgLocs) &&(static_cast <bool> (isSortedByValueNo(ArgLocs) &&
"Argument Location list must be sorted before lowering") ? void
(0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3580, __extension__ __PRETTY_FUNCTION__))
3580 "Argument Location list must be sorted before lowering")(static_cast <bool> (isSortedByValueNo(ArgLocs) &&
"Argument Location list must be sorted before lowering") ? void
(0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3580, __extension__ __PRETTY_FUNCTION__))
;
3581
3582 // Walk the register/memloc assignments, inserting copies/loads. In the case
3583 // of tail call optimization arguments are handle later.
3584 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3585 for (unsigned I = 0, OutIndex = 0, E = ArgLocs.size(); I != E;
3586 ++I, ++OutIndex) {
3587 assert(OutIndex < Outs.size() && "Invalid Out index")(static_cast <bool> (OutIndex < Outs.size() &&
"Invalid Out index") ? void (0) : __assert_fail ("OutIndex < Outs.size() && \"Invalid Out index\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3587, __extension__ __PRETTY_FUNCTION__))
;
3588 // Skip inalloca arguments, they have already been written.
3589 ISD::ArgFlagsTy Flags = Outs[OutIndex].Flags;
3590 if (Flags.isInAlloca())
3591 continue;
3592
3593 CCValAssign &VA = ArgLocs[I];
3594 EVT RegVT = VA.getLocVT();
3595 SDValue Arg = OutVals[OutIndex];
3596 bool isByVal = Flags.isByVal();
3597
3598 // Promote the value if needed.
3599 switch (VA.getLocInfo()) {
3600 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3600)
;
3601 case CCValAssign::Full: break;
3602 case CCValAssign::SExt:
3603 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3604 break;
3605 case CCValAssign::ZExt:
3606 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3607 break;
3608 case CCValAssign::AExt:
3609 if (Arg.getValueType().isVector() &&
3610 Arg.getValueType().getVectorElementType() == MVT::i1)
3611 Arg = lowerMasksToReg(Arg, RegVT, dl, DAG);
3612 else if (RegVT.is128BitVector()) {
3613 // Special case: passing MMX values in XMM registers.
3614 Arg = DAG.getBitcast(MVT::i64, Arg);
3615 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3616 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3617 } else
3618 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3619 break;
3620 case CCValAssign::BCvt:
3621 Arg = DAG.getBitcast(RegVT, Arg);
3622 break;
3623 case CCValAssign::Indirect: {
3624 // Store the argument.
3625 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3626 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3627 Chain = DAG.getStore(
3628 Chain, dl, Arg, SpillSlot,
3629 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3630 Arg = SpillSlot;
3631 break;
3632 }
3633 }
3634
3635 if (VA.needsCustom()) {
3636 assert(VA.getValVT() == MVT::v64i1 &&(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3637, __extension__ __PRETTY_FUNCTION__))
3637 "Currently the only custom case is when we split v64i1 to 2 regs")(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? void (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3637, __extension__ __PRETTY_FUNCTION__))
;
3638 // Split v64i1 value into two registers
3639 Passv64i1ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++I],
3640 Subtarget);
3641 } else if (VA.isRegLoc()) {
3642 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3643 if (isVarArg && IsWin64) {
3644 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3645 // shadow reg if callee is a varargs function.
3646 unsigned ShadowReg = 0;
3647 switch (VA.getLocReg()) {
3648 case X86::XMM0: ShadowReg = X86::RCX; break;
3649 case X86::XMM1: ShadowReg = X86::RDX; break;
3650 case X86::XMM2: ShadowReg = X86::R8; break;
3651 case X86::XMM3: ShadowReg = X86::R9; break;
3652 }
3653 if (ShadowReg)
3654 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3655 }
3656 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3657 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3657, __extension__ __PRETTY_FUNCTION__))
;
3658 if (!StackPtr.getNode())
3659 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3660 getPointerTy(DAG.getDataLayout()));
3661 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3662 dl, DAG, VA, Flags));
3663 }
3664 }
3665
3666 if (!MemOpChains.empty())
3667 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3668
3669 if (Subtarget.isPICStyleGOT()) {
3670 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3671 // GOT pointer.
3672 if (!isTailCall) {
3673 RegsToPass.push_back(std::make_pair(
3674 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3675 getPointerTy(DAG.getDataLayout()))));
3676 } else {
3677 // If we are tail calling and generating PIC/GOT style code load the
3678 // address of the callee into ECX. The value in ecx is used as target of
3679 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3680 // for tail calls on PIC/GOT architectures. Normally we would just put the
3681 // address of GOT into ebx and then call target@PLT. But for tail calls
3682 // ebx would be restored (since ebx is callee saved) before jumping to the
3683 // target@PLT.
3684
3685 // Note: The actual moving to ECX is done further down.
3686 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3687 if (G && !G->getGlobal()->hasLocalLinkage() &&
3688 G->getGlobal()->hasDefaultVisibility())
3689 Callee = LowerGlobalAddress(Callee, DAG);
3690 else if (isa<ExternalSymbolSDNode>(Callee))
3691 Callee = LowerExternalSymbol(Callee, DAG);
3692 }
3693 }
3694
3695 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3696 // From AMD64 ABI document:
3697 // For calls that may call functions that use varargs or stdargs
3698 // (prototype-less calls or calls to functions containing ellipsis (...) in
3699 // the declaration) %al is used as hidden argument to specify the number
3700 // of SSE registers used. The contents of %al do not need to match exactly
3701 // the number of registers, but must be an ubound on the number of SSE
3702 // registers used and is in the range 0 - 8 inclusive.
3703
3704 // Count the number of XMM registers allocated.
3705 static const MCPhysReg XMMArgRegs[] = {
3706 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3707 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3708 };
3709 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3710 assert((Subtarget.hasSSE1() || !NumXMMRegs)(static_cast <bool> ((Subtarget.hasSSE1() || !NumXMMRegs
) && "SSE registers cannot be used when SSE is disabled"
) ? void (0) : __assert_fail ("(Subtarget.hasSSE1() || !NumXMMRegs) && \"SSE registers cannot be used when SSE is disabled\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3711, __extension__ __PRETTY_FUNCTION__))
3711 && "SSE registers cannot be used when SSE is disabled")(static_cast <bool> ((Subtarget.hasSSE1() || !NumXMMRegs
) && "SSE registers cannot be used when SSE is disabled"
) ? void (0) : __assert_fail ("(Subtarget.hasSSE1() || !NumXMMRegs) && \"SSE registers cannot be used when SSE is disabled\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3711, __extension__ __PRETTY_FUNCTION__))
;
3712
3713 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3714 DAG.getConstant(NumXMMRegs, dl,
3715 MVT::i8)));
3716 }
3717
3718 if (isVarArg && IsMustTail) {
3719 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3720 for (const auto &F : Forwards) {
3721 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3722 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3723 }
3724 }
3725
3726 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3727 // don't need this because the eligibility check rejects calls that require
3728 // shuffling arguments passed in memory.
3729 if (!IsSibcall && isTailCall) {
3730 // Force all the incoming stack arguments to be loaded from the stack
3731 // before any new outgoing arguments are stored to the stack, because the
3732 // outgoing stack slots may alias the incoming argument stack slots, and
3733 // the alias isn't otherwise explicit. This is slightly more conservative
3734 // than necessary, because it means that each store effectively depends
3735 // on every argument instead of just those arguments it would clobber.
3736 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3737
3738 SmallVector<SDValue, 8> MemOpChains2;
3739 SDValue FIN;
3740 int FI = 0;
3741 for (unsigned I = 0, OutsIndex = 0, E = ArgLocs.size(); I != E;
3742 ++I, ++OutsIndex) {
3743 CCValAssign &VA = ArgLocs[I];
3744
3745 if (VA.isRegLoc()) {
3746 if (VA.needsCustom()) {
3747 assert((CallConv == CallingConv::X86_RegCall) &&(static_cast <bool> ((CallConv == CallingConv::X86_RegCall
) && "Expecting custom case only in regcall calling convention"
) ? void (0) : __assert_fail ("(CallConv == CallingConv::X86_RegCall) && \"Expecting custom case only in regcall calling convention\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3748, __extension__ __PRETTY_FUNCTION__))
3748 "Expecting custom case only in regcall calling convention")(static_cast <bool> ((CallConv == CallingConv::X86_RegCall
) && "Expecting custom case only in regcall calling convention"
) ? void (0) : __assert_fail ("(CallConv == CallingConv::X86_RegCall) && \"Expecting custom case only in regcall calling convention\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3748, __extension__ __PRETTY_FUNCTION__))
;
3749 // This means that we are in special case where one argument was
3750 // passed through two register locations - Skip the next location
3751 ++I;
3752 }
3753
3754 continue;
3755 }
3756
3757 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3757, __extension__ __PRETTY_FUNCTION__))
;
3758 SDValue Arg = OutVals[OutsIndex];
3759 ISD::ArgFlagsTy Flags = Outs[OutsIndex].Flags;
3760 // Skip inalloca arguments. They don't require any work.
3761 if (Flags.isInAlloca())
3762 continue;
3763 // Create frame index.
3764 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3765 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3766 FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3767 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3768
3769 if (Flags.isByVal()) {
3770 // Copy relative to framepointer.
3771 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3772 if (!StackPtr.getNode())
3773 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3774 getPointerTy(DAG.getDataLayout()));
3775 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3776 StackPtr, Source);
3777
3778 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3779 ArgChain,
3780 Flags, DAG, dl));
3781 } else {
3782 // Store relative to framepointer.
3783 MemOpChains2.push_back(DAG.getStore(
3784 ArgChain, dl, Arg, FIN,
3785 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
3786 }
3787 }
3788
3789 if (!MemOpChains2.empty())
3790 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3791
3792 // Store the return address to the appropriate stack slot.
3793 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3794 getPointerTy(DAG.getDataLayout()),
3795 RegInfo->getSlotSize(), FPDiff, dl);
3796 }
3797
3798 // Build a sequence of copy-to-reg nodes chained together with token chain
3799 // and flag operands which copy the outgoing args into registers.
3800 SDValue InFlag;
3801 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3802 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3803 RegsToPass[i].second, InFlag);
3804 InFlag = Chain.getValue(1);
3805 }
3806
3807 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3808 assert(Is64Bit && "Large code model is only legal in 64-bit mode.")(static_cast <bool> (Is64Bit && "Large code model is only legal in 64-bit mode."
) ? void (0) : __assert_fail ("Is64Bit && \"Large code model is only legal in 64-bit mode.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3808, __extension__ __PRETTY_FUNCTION__))
;
3809 // In the 64-bit large code model, we have to make all calls
3810 // through a register, since the call instruction's 32-bit
3811 // pc-relative offset may not be large enough to hold the whole
3812 // address.
3813 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3814 // If the callee is a GlobalAddress node (quite common, every direct call
3815 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3816 // it.
3817 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3818
3819 // We should use extra load for direct calls to dllimported functions in
3820 // non-JIT mode.
3821 const GlobalValue *GV = G->getGlobal();
3822 if (!GV->hasDLLImportStorageClass()) {
3823 unsigned char OpFlags = Subtarget.classifyGlobalFunctionReference(GV);
3824
3825 Callee = DAG.getTargetGlobalAddress(
3826 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3827
3828 if (OpFlags == X86II::MO_GOTPCREL) {
3829 // Add a wrapper.
3830 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3831 getPointerTy(DAG.getDataLayout()), Callee);
3832 // Add extra indirection
3833 Callee = DAG.getLoad(
3834 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3835 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3836 }
3837 }
3838 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3839 const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
3840 unsigned char OpFlags =
3841 Subtarget.classifyGlobalFunctionReference(nullptr, *Mod);
3842
3843 Callee = DAG.getTargetExternalSymbol(
3844 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3845
3846 if (OpFlags == X86II::MO_GOTPCREL) {
3847 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3848 getPointerTy(DAG.getDataLayout()), Callee);
3849 Callee = DAG.getLoad(
3850 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3851 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3852 }
3853 } else if (Subtarget.isTarget64BitILP32() &&
3854 Callee->getValueType(0) == MVT::i32) {
3855 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3856 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3857 }
3858
3859 // Returns a chain & a flag for retval copy to use.
3860 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3861 SmallVector<SDValue, 8> Ops;
3862
3863 if (!IsSibcall && isTailCall) {
3864 Chain = DAG.getCALLSEQ_END(Chain,
3865 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3866 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3867 InFlag = Chain.getValue(1);
3868 }
3869
3870 Ops.push_back(Chain);
3871 Ops.push_back(Callee);
3872
3873 if (isTailCall)
3874 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3875
3876 // Add argument registers to the end of the list so that they are known live
3877 // into the call.
3878 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3879 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3880 RegsToPass[i].second.getValueType()));
3881
3882 // Add a register mask operand representing the call-preserved registers.
3883 // If HasNCSR is asserted (attribute NoCallerSavedRegisters exists) then we
3884 // set X86_INTR calling convention because it has the same CSR mask
3885 // (same preserved registers).
3886 const uint32_t *Mask = RegInfo->getCallPreservedMask(
3887 MF, HasNCSR ? (CallingConv::ID)CallingConv::X86_INTR : CallConv);
3888 assert(Mask && "Missing call preserved mask for calling convention")(static_cast <bool> (Mask && "Missing call preserved mask for calling convention"
) ? void (0) : __assert_fail ("Mask && \"Missing call preserved mask for calling convention\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 3888, __extension__ __PRETTY_FUNCTION__))
;
3889
3890 // If this is an invoke in a 32-bit function using a funclet-based
3891 // personality, assume the function clobbers all registers. If an exception
3892 // is thrown, the runtime will not restore CSRs.
3893 // FIXME: Model this more precisely so that we can register allocate across
3894 // the normal edge and spill and fill across the exceptional edge.
3895 if (!Is64Bit && CLI.CS && CLI.CS.isInvoke()) {
3896 const Function &CallerFn = MF.getFunction();
3897 EHPersonality Pers =
3898 CallerFn.hasPersonalityFn()
3899 ? classifyEHPersonality(CallerFn.getPersonalityFn())
3900 : EHPersonality::Unknown;
3901 if (isFuncletEHPersonality(Pers))
3902 Mask = RegInfo->getNoPreservedMask();
3903 }
3904
3905 // Define a new register mask from the existing mask.
3906 uint32_t *RegMask = nullptr;
3907
3908 // In some calling conventions we need to remove the used physical registers
3909 // from the reg mask.
3910 if (CallConv == CallingConv::X86_RegCall || HasNCSR) {
3911 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3912
3913 // Allocate a new Reg Mask and copy Mask.
3914 RegMask = MF.allocateRegMask();
3915 unsigned RegMaskSize = MachineOperand::getRegMaskSize(TRI->getNumRegs());
3916 memcpy(RegMask, Mask, sizeof(RegMask[0]) * RegMaskSize);
3917
3918 // Make sure all sub registers of the argument registers are reset
3919 // in the RegMask.
3920 for (auto const &RegPair : RegsToPass)
3921 for (MCSubRegIterator SubRegs(RegPair.first, TRI, /*IncludeSelf=*/true);
3922 SubRegs.isValid(); ++SubRegs)
3923 RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
3924
3925 // Create the RegMask Operand according to our updated mask.
3926 Ops.push_back(DAG.getRegisterMask(RegMask));
3927 } else {
3928 // Create the RegMask Operand according to the static mask.
3929 Ops.push_back(DAG.getRegisterMask(Mask));
3930 }
3931
3932 if (InFlag.getNode())
3933 Ops.push_back(InFlag);
3934
3935 if (isTailCall) {
3936 // We used to do:
3937 //// If this is the first return lowered for this function, add the regs
3938 //// to the liveout set for the function.
3939 // This isn't right, although it's probably harmless on x86; liveouts
3940 // should be computed from returns not tail calls. Consider a void
3941 // function making a tail call to a function returning int.
3942 MF.getFrameInfo().setHasTailCall();
3943 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3944 }
3945
3946 if (HasNoCfCheck && IsCFProtectionSupported) {
3947 Chain = DAG.getNode(X86ISD::NT_CALL, dl, NodeTys, Ops);
3948 } else {
3949 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3950 }
3951 InFlag = Chain.getValue(1);
3952
3953 // Create the CALLSEQ_END node.
3954 unsigned NumBytesForCalleeToPop;
3955 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3956 DAG.getTarget().Options.GuaranteedTailCallOpt))
3957 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3958 else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3959 !Subtarget.getTargetTriple().isOSMSVCRT() &&
3960 SR == StackStructReturn)
3961 // If this is a call to a struct-return function, the callee
3962 // pops the hidden struct pointer, so we have to push it back.
3963 // This is common for Darwin/X86, Linux & Mingw32 targets.
3964 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3965 NumBytesForCalleeToPop = 4;
3966 else
3967 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3968
3969 if (CLI.DoesNotReturn && !getTargetMachine().Options.TrapUnreachable) {
3970 // No need to reset the stack after the call if the call doesn't return. To
3971 // make the MI verify, we'll pretend the callee does it for us.
3972 NumBytesForCalleeToPop = NumBytes;
3973 }
3974
3975 // Returns a flag for retval copy to use.
3976 if (!IsSibcall) {
3977 Chain = DAG.getCALLSEQ_END(Chain,
3978 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3979 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3980 true),
3981 InFlag, dl);
3982 InFlag = Chain.getValue(1);
3983 }
3984
3985 // Handle result values, copying them out of physregs into vregs that we
3986 // return.
3987 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
3988 InVals, RegMask);
3989}
3990
3991//===----------------------------------------------------------------------===//
3992// Fast Calling Convention (tail call) implementation
3993//===----------------------------------------------------------------------===//
3994
3995// Like std call, callee cleans arguments, convention except that ECX is
3996// reserved for storing the tail called function address. Only 2 registers are
3997// free for argument passing (inreg). Tail call optimization is performed
3998// provided:
3999// * tailcallopt is enabled
4000// * caller/callee are fastcc
4001// On X86_64 architecture with GOT-style position independent code only local
4002// (within module) calls are supported at the moment.
4003// To keep the stack aligned according to platform abi the function
4004// GetAlignedArgumentStackSize ensures that argument delta is always multiples
4005// of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
4006// If a tail called function callee has more arguments than the caller the
4007// caller needs to make sure that there is room to move the RETADDR to. This is
4008// achieved by reserving an area the size of the argument delta right after the
4009// original RETADDR, but before the saved framepointer or the spilled registers
4010// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
4011// stack layout:
4012// arg1
4013// arg2
4014// RETADDR
4015// [ new RETADDR
4016// move area ]
4017// (possible EBP)
4018// ESI
4019// EDI
4020// local1 ..
4021
4022/// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
4023/// requirement.
4024unsigned
4025X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
4026 SelectionDAG& DAG) const {
4027 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4028 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
4029 unsigned StackAlignment = TFI.getStackAlignment();
4030 uint64_t AlignMask = StackAlignment - 1;
4031 int64_t Offset = StackSize;
4032 unsigned SlotSize = RegInfo->getSlotSize();
4033 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
4034 // Number smaller than 12 so just add the difference.
4035 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
4036 } else {
4037 // Mask out lower bits, add stackalignment once plus the 12 bytes.
4038 Offset = ((~AlignMask) & Offset) + StackAlignment +
4039 (StackAlignment-SlotSize);
4040 }
4041 return Offset;
4042}
4043
4044/// Return true if the given stack call argument is already available in the
4045/// same position (relatively) of the caller's incoming argument stack.
4046static
4047bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
4048 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
4049 const X86InstrInfo *TII, const CCValAssign &VA) {
4050 unsigned Bytes = Arg.getValueSizeInBits() / 8;
4051
4052 for (;;) {
4053 // Look through nodes that don't alter the bits of the incoming value.
4054 unsigned Op = Arg.getOpcode();
4055 if (Op == ISD::ZERO_EXTEND || Op == ISD::ANY_EXTEND || Op == ISD::BITCAST) {
4056 Arg = Arg.getOperand(0);
4057 continue;
4058 }
4059 if (Op == ISD::TRUNCATE) {
4060 const SDValue &TruncInput = Arg.getOperand(0);
4061 if (TruncInput.getOpcode() == ISD::AssertZext &&
4062 cast<VTSDNode>(TruncInput.getOperand(1))->getVT() ==
4063 Arg.getValueType()) {
4064 Arg = TruncInput.getOperand(0);
4065 continue;
4066 }
4067 }
4068 break;
4069 }
4070
4071 int FI = INT_MAX2147483647;
4072 if (Arg.getOpcode() == ISD::CopyFromReg) {
4073 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
4074 if (!TargetRegisterInfo::isVirtualRegister(VR))
4075 return false;
4076 MachineInstr *Def = MRI->getVRegDef(VR);
4077 if (!Def)
4078 return false;
4079 if (!Flags.isByVal()) {
4080 if (!TII->isLoadFromStackSlot(*Def, FI))
4081 return false;
4082 } else {
4083 unsigned Opcode = Def->getOpcode();
4084 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
4085 Opcode == X86::LEA64_32r) &&
4086 Def->getOperand(1).isFI()) {
4087 FI = Def->getOperand(1).getIndex();
4088 Bytes = Flags.getByValSize();
4089 } else
4090 return false;
4091 }
4092 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
4093 if (Flags.isByVal())
4094 // ByVal argument is passed in as a pointer but it's now being
4095 // dereferenced. e.g.
4096 // define @foo(%struct.X* %A) {
4097 // tail call @bar(%struct.X* byval %A)
4098 // }
4099 return false;
4100 SDValue Ptr = Ld->getBasePtr();
4101 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
4102 if (!FINode)
4103 return false;
4104 FI = FINode->getIndex();
4105 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
4106 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
4107 FI = FINode->getIndex();
4108 Bytes = Flags.getByValSize();
4109 } else
4110 return false;
4111
4112 assert(FI != INT_MAX)(static_cast <bool> (FI != 2147483647) ? void (0) : __assert_fail
("FI != INT_MAX", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 4112, __extension__ __PRETTY_FUNCTION__))
;
4113 if (!MFI.isFixedObjectIndex(FI))
4114 return false;
4115
4116 if (Offset != MFI.getObjectOffset(FI))
4117 return false;
4118
4119 // If this is not byval, check that the argument stack object is immutable.
4120 // inalloca and argument copy elision can create mutable argument stack
4121 // objects. Byval objects can be mutated, but a byval call intends to pass the
4122 // mutated memory.
4123 if (!Flags.isByVal() && !MFI.isImmutableObjectIndex(FI))
4124 return false;
4125
4126 if (VA.getLocVT().getSizeInBits() > Arg.getValueSizeInBits()) {
4127 // If the argument location is wider than the argument type, check that any
4128 // extension flags match.
4129 if (Flags.isZExt() != MFI.isObjectZExt(FI) ||
4130 Flags.isSExt() != MFI.isObjectSExt(FI)) {
4131 return false;
4132 }
4133 }
4134
4135 return Bytes == MFI.getObjectSize(FI);
4136}
4137
4138/// Check whether the call is eligible for tail call optimization. Targets
4139/// that want to do tail call optimization should implement this function.
4140bool X86TargetLowering::IsEligibleForTailCallOptimization(
4141 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
4142 bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
4143 const SmallVectorImpl<ISD::OutputArg> &Outs,
4144 const SmallVectorImpl<SDValue> &OutVals,
4145 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4146 if (!mayTailCallThisCC(CalleeCC))
4147 return false;
4148
4149 // If -tailcallopt is specified, make fastcc functions tail-callable.
4150 MachineFunction &MF = DAG.getMachineFunction();
4151 const Function &CallerF = MF.getFunction();
4152
4153 // If the function return type is x86_fp80 and the callee return type is not,
4154 // then the FP_EXTEND of the call result is not a nop. It's not safe to
4155 // perform a tailcall optimization here.
4156 if (CallerF.getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
4157 return false;
4158
4159 CallingConv::ID CallerCC = CallerF.getCallingConv();
4160 bool CCMatch = CallerCC == CalleeCC;
4161 bool IsCalleeWin64 = Subtarget.isCallingConvWin64(CalleeCC);
4162 bool IsCallerWin64 = Subtarget.isCallingConvWin64(CallerCC);
4163
4164 // Win64 functions have extra shadow space for argument homing. Don't do the
4165 // sibcall if the caller and callee have mismatched expectations for this
4166 // space.
4167 if (IsCalleeWin64 != IsCallerWin64)
4168 return false;
4169
4170 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
4171 if (canGuaranteeTCO(CalleeCC) && CCMatch)
4172 return true;
4173 return false;
4174 }
4175
4176 // Look for obvious safe cases to perform tail call optimization that do not
4177 // require ABI changes. This is what gcc calls sibcall.
4178
4179 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
4180 // emit a special epilogue.
4181 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4182 if (RegInfo->needsStackRealignment(MF))
4183 return false;
4184
4185 // Also avoid sibcall optimization if either caller or callee uses struct
4186 // return semantics.
4187 if (isCalleeStructRet || isCallerStructRet)
4188 return false;
4189
4190 // Do not sibcall optimize vararg calls unless all arguments are passed via
4191 // registers.
4192 LLVMContext &C = *DAG.getContext();
4193 if (isVarArg && !Outs.empty()) {
4194 // Optimizing for varargs on Win64 is unlikely to be safe without
4195 // additional testing.
4196 if (IsCalleeWin64 || IsCallerWin64)
4197 return false;
4198
4199 SmallVector<CCValAssign, 16> ArgLocs;
4200 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4201
4202 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4203 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
4204 if (!ArgLocs[i].isRegLoc())
4205 return false;
4206 }
4207
4208 // If the call result is in ST0 / ST1, it needs to be popped off the x87
4209 // stack. Therefore, if it's not used by the call it is not safe to optimize
4210 // this into a sibcall.
4211 bool Unused = false;
4212 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4213 if (!Ins[i].Used) {
4214 Unused = true;
4215 break;
4216 }
4217 }
4218 if (Unused) {
4219 SmallVector<CCValAssign, 16> RVLocs;
4220 CCState CCInfo(CalleeCC, false, MF, RVLocs, C);
4221 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
4222 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4223 CCValAssign &VA = RVLocs[i];
4224 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
4225 return false;
4226 }
4227 }
4228
4229 // Check that the call results are passed in the same way.
4230 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
4231 RetCC_X86, RetCC_X86))
4232 return false;
4233 // The callee has to preserve all registers the caller needs to preserve.
4234 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
4235 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4236 if (!CCMatch) {
4237 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4238 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4239 return false;
4240 }
4241
4242 unsigned StackArgsSize = 0;
4243
4244 // If the callee takes no arguments then go on to check the results of the
4245 // call.
4246 if (!Outs.empty()) {
4247 // Check if stack adjustment is needed. For now, do not do this if any
4248 // argument is passed on the stack.
4249 SmallVector<CCValAssign, 16> ArgLocs;
4250 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4251
4252 // Allocate shadow area for Win64
4253 if (IsCalleeWin64)
4254 CCInfo.AllocateStack(32, 8);
4255
4256 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4257 StackArgsSize = CCInfo.getNextStackOffset();
4258
4259 if (CCInfo.getNextStackOffset()) {
4260 // Check if the arguments are already laid out in the right way as
4261 // the caller's fixed stack objects.
4262 MachineFrameInfo &MFI = MF.getFrameInfo();
4263 const MachineRegisterInfo *MRI = &MF.getRegInfo();
4264 const X86InstrInfo *TII = Subtarget.getInstrInfo();
4265 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4266 CCValAssign &VA = ArgLocs[i];
4267 SDValue Arg = OutVals[i];
4268 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4269 if (VA.getLocInfo() == CCValAssign::Indirect)
4270 return false;
4271 if (!VA.isRegLoc()) {
4272 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
4273 MFI, MRI, TII, VA))
4274 return false;
4275 }
4276 }
4277 }
4278
4279 bool PositionIndependent = isPositionIndependent();
4280 // If the tailcall address may be in a register, then make sure it's
4281 // possible to register allocate for it. In 32-bit, the call address can
4282 // only target EAX, EDX, or ECX since the tail call must be scheduled after
4283 // callee-saved registers are restored. These happen to be the same
4284 // registers used to pass 'inreg' arguments so watch out for those.
4285 if (!Subtarget.is64Bit() && ((!isa<GlobalAddressSDNode>(Callee) &&
4286 !isa<ExternalSymbolSDNode>(Callee)) ||
4287 PositionIndependent)) {
4288 unsigned NumInRegs = 0;
4289 // In PIC we need an extra register to formulate the address computation
4290 // for the callee.
4291 unsigned MaxInRegs = PositionIndependent ? 2 : 3;
4292
4293 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4294 CCValAssign &VA = ArgLocs[i];
4295 if (!VA.isRegLoc())
4296 continue;
4297 unsigned Reg = VA.getLocReg();
4298 switch (Reg) {
4299 default: break;
4300 case X86::EAX: case X86::EDX: case X86::ECX:
4301 if (++NumInRegs == MaxInRegs)
4302 return false;
4303 break;
4304 }
4305 }
4306 }
4307
4308 const MachineRegisterInfo &MRI = MF.getRegInfo();
4309 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4310 return false;
4311 }
4312
4313 bool CalleeWillPop =
4314 X86::isCalleePop(CalleeCC, Subtarget.is64Bit(), isVarArg,
4315 MF.getTarget().Options.GuaranteedTailCallOpt);
4316
4317 if (unsigned BytesToPop =
4318 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
4319 // If we have bytes to pop, the callee must pop them.
4320 bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
4321 if (!CalleePopMatches)
4322 return false;
4323 } else if (CalleeWillPop && StackArgsSize > 0) {
4324 // If we don't have bytes to pop, make sure the callee doesn't pop any.
4325 return false;
4326 }
4327
4328 return true;
4329}
4330
4331FastISel *
4332X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
4333 const TargetLibraryInfo *libInfo) const {
4334 return X86::createFastISel(funcInfo, libInfo);
4335}
4336
4337//===----------------------------------------------------------------------===//
4338// Other Lowering Hooks
4339//===----------------------------------------------------------------------===//
4340
4341static bool MayFoldLoad(SDValue Op) {
4342 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
4343}
4344
4345static bool MayFoldIntoStore(SDValue Op) {
4346 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
4347}
4348
4349static bool MayFoldIntoZeroExtend(SDValue Op) {
4350 if (Op.hasOneUse()) {
4351 unsigned Opcode = Op.getNode()->use_begin()->getOpcode();
4352 return (ISD::ZERO_EXTEND == Opcode);
4353 }
4354 return false;
4355}
4356
4357static bool isTargetShuffle(unsigned Opcode) {
4358 switch(Opcode) {
4359 default: return false;
4360 case X86ISD::BLENDI:
4361 case X86ISD::PSHUFB:
4362 case X86ISD::PSHUFD:
4363 case X86ISD::PSHUFHW:
4364 case X86ISD::PSHUFLW:
4365 case X86ISD::SHUFP:
4366 case X86ISD::INSERTPS:
4367 case X86ISD::EXTRQI:
4368 case X86ISD::INSERTQI:
4369 case X86ISD::PALIGNR:
4370 case X86ISD::VSHLDQ:
4371 case X86ISD::VSRLDQ:
4372 case X86ISD::MOVLHPS:
4373 case X86ISD::MOVHLPS:
4374 case X86ISD::MOVSHDUP:
4375 case X86ISD::MOVSLDUP:
4376 case X86ISD::MOVDDUP:
4377 case X86ISD::MOVSS:
4378 case X86ISD::MOVSD:
4379 case X86ISD::UNPCKL:
4380 case X86ISD::UNPCKH:
4381 case X86ISD::VBROADCAST:
4382 case X86ISD::VPERMILPI:
4383 case X86ISD::VPERMILPV:
4384 case X86ISD::VPERM2X128:
4385 case X86ISD::SHUF128:
4386 case X86ISD::VPERMIL2:
4387 case X86ISD::VPERMI:
4388 case X86ISD::VPPERM:
4389 case X86ISD::VPERMV:
4390 case X86ISD::VPERMV3:
4391 case X86ISD::VZEXT_MOVL:
4392 return true;
4393 }
4394}
4395
4396static bool isTargetShuffleVariableMask(unsigned Opcode) {
4397 switch (Opcode) {
4398 default: return false;
4399 // Target Shuffles.
4400 case X86ISD::PSHUFB:
4401 case X86ISD::VPERMILPV:
4402 case X86ISD::VPERMIL2:
4403 case X86ISD::VPPERM:
4404 case X86ISD::VPERMV:
4405 case X86ISD::VPERMV3:
4406 return true;
4407 // 'Faux' Target Shuffles.
4408 case ISD::AND:
4409 case X86ISD::ANDNP:
4410 return true;
4411 }
4412}
4413
4414SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
4415 MachineFunction &MF = DAG.getMachineFunction();
4416 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4417 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
4418 int ReturnAddrIndex = FuncInfo->getRAIndex();
4419
4420 if (ReturnAddrIndex == 0) {
4421 // Set up a frame object for the return address.
4422 unsigned SlotSize = RegInfo->getSlotSize();
4423 ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
4424 -(int64_t)SlotSize,
4425 false);
4426 FuncInfo->setRAIndex(ReturnAddrIndex);
4427 }
4428
4429 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
4430}
4431
4432bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
4433 bool hasSymbolicDisplacement) {
4434 // Offset should fit into 32 bit immediate field.
4435 if (!isInt<32>(Offset))
4436 return false;
4437
4438 // If we don't have a symbolic displacement - we don't have any extra
4439 // restrictions.
4440 if (!hasSymbolicDisplacement)
4441 return true;
4442
4443 // FIXME: Some tweaks might be needed for medium code model.
4444 if (M != CodeModel::Small && M != CodeModel::Kernel)
4445 return false;
4446
4447 // For small code model we assume that latest object is 16MB before end of 31
4448 // bits boundary. We may also accept pretty large negative constants knowing
4449 // that all objects are in the positive half of address space.
4450 if (M == CodeModel::Small && Offset < 16*1024*1024)
4451 return true;
4452
4453 // For kernel code model we know that all object resist in the negative half
4454 // of 32bits address space. We may not accept negative offsets, since they may
4455 // be just off and we may accept pretty large positive ones.
4456 if (M == CodeModel::Kernel && Offset >= 0)
4457 return true;
4458
4459 return false;
4460}
4461
4462/// Determines whether the callee is required to pop its own arguments.
4463/// Callee pop is necessary to support tail calls.
4464bool X86::isCalleePop(CallingConv::ID CallingConv,
4465 bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4466 // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4467 // can guarantee TCO.
4468 if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4469 return true;
4470
4471 switch (CallingConv) {
4472 default:
4473 return false;
4474 case CallingConv::X86_StdCall:
4475 case CallingConv::X86_FastCall:
4476 case CallingConv::X86_ThisCall:
4477 case CallingConv::X86_VectorCall:
4478 return !is64Bit;
4479 }
4480}
4481
4482/// Return true if the condition is an unsigned comparison operation.
4483static bool isX86CCUnsigned(unsigned X86CC) {
4484 switch (X86CC) {
4485 default:
4486 llvm_unreachable("Invalid integer condition!")::llvm::llvm_unreachable_internal("Invalid integer condition!"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 4486)
;
4487 case X86::COND_E:
4488 case X86::COND_NE:
4489 case X86::COND_B:
4490 case X86::COND_A:
4491 case X86::COND_BE:
4492 case X86::COND_AE:
4493 return true;
4494 case X86::COND_G:
4495 case X86::COND_GE:
4496 case X86::COND_L:
4497 case X86::COND_LE:
4498 return false;
4499 }
4500}
4501
4502static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4503 switch (SetCCOpcode) {
4504 default: llvm_unreachable("Invalid integer condition!")::llvm::llvm_unreachable_internal("Invalid integer condition!"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 4504)
;
4505 case ISD::SETEQ: return X86::COND_E;
4506 case ISD::SETGT: return X86::COND_G;
4507 case ISD::SETGE: return X86::COND_GE;
4508 case ISD::SETLT: return X86::COND_L;
4509 case ISD::SETLE: return X86::COND_LE;
4510 case ISD::SETNE: return X86::COND_NE;
4511 case ISD::SETULT: return X86::COND_B;
4512 case ISD::SETUGT: return X86::COND_A;
4513 case ISD::SETULE: return X86::COND_BE;
4514 case ISD::SETUGE: return X86::COND_AE;
4515 }
4516}
4517
4518/// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4519/// condition code, returning the condition code and the LHS/RHS of the
4520/// comparison to make.
4521static X86::CondCode TranslateX86CC(ISD::CondCode SetCCOpcode, const SDLoc &DL,
4522 bool isFP, SDValue &LHS, SDValue &RHS,
4523 SelectionDAG &DAG) {
4524 if (!isFP) {
4525 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4526 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4527 // X > -1 -> X == 0, jump !sign.
4528 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4529 return X86::COND_NS;
4530 }
4531 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4532 // X < 0 -> X == 0, jump on sign.
4533 return X86::COND_S;
4534 }
4535 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4536 // X < 1 -> X <= 0
4537 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4538 return X86::COND_LE;
4539 }
4540 }
4541
4542 return TranslateIntegerX86CC(SetCCOpcode);
4543 }
4544
4545 // First determine if it is required or is profitable to flip the operands.
4546
4547 // If LHS is a foldable load, but RHS is not, flip the condition.
4548 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4549 !ISD::isNON_EXTLoad(RHS.getNode())) {
4550 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4551 std::swap(LHS, RHS);
4552 }
4553
4554 switch (SetCCOpcode) {
4555 default: break;
4556 case ISD::SETOLT:
4557 case ISD::SETOLE:
4558 case ISD::SETUGT:
4559 case ISD::SETUGE:
4560 std::swap(LHS, RHS);
4561 break;
4562 }
4563
4564 // On a floating point condition, the flags are set as follows:
4565 // ZF PF CF op
4566 // 0 | 0 | 0 | X > Y
4567 // 0 | 0 | 1 | X < Y
4568 // 1 | 0 | 0 | X == Y
4569 // 1 | 1 | 1 | unordered
4570 switch (SetCCOpcode) {
4571 default: llvm_unreachable("Condcode should be pre-legalized away")::llvm::llvm_unreachable_internal("Condcode should be pre-legalized away"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 4571)
;
4572 case ISD::SETUEQ:
4573 case ISD::SETEQ: return X86::COND_E;
4574 case ISD::SETOLT: // flipped
4575 case ISD::SETOGT:
4576 case ISD::SETGT: return X86::COND_A;
4577 case ISD::SETOLE: // flipped
4578 case ISD::SETOGE:
4579 case ISD::SETGE: return X86::COND_AE;
4580 case ISD::SETUGT: // flipped
4581 case ISD::SETULT:
4582 case ISD::SETLT: return X86::COND_B;
4583 case ISD::SETUGE: // flipped
4584 case ISD::SETULE:
4585 case ISD::SETLE: return X86::COND_BE;
4586 case ISD::SETONE:
4587 case ISD::SETNE: return X86::COND_NE;
4588 case ISD::SETUO: return X86::COND_P;
4589 case ISD::SETO: return X86::COND_NP;
4590 case ISD::SETOEQ:
4591 case ISD::SETUNE: return X86::COND_INVALID;
4592 }
4593}
4594
4595/// Is there a floating point cmov for the specific X86 condition code?
4596/// Current x86 isa includes the following FP cmov instructions:
4597/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4598static bool hasFPCMov(unsigned X86CC) {
4599 switch (X86CC) {
4600 default:
4601 return false;
4602 case X86::COND_B:
4603 case X86::COND_BE:
4604 case X86::COND_E:
4605 case X86::COND_P:
4606 case X86::COND_A:
4607 case X86::COND_AE:
4608 case X86::COND_NE:
4609 case X86::COND_NP:
4610 return true;
4611 }
4612}
4613
4614
4615bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
4616 const CallInst &I,
4617 MachineFunction &MF,
4618 unsigned Intrinsic) const {
4619
4620 const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
4621 if (!IntrData)
4622 return false;
4623
4624 Info.opc = ISD::INTRINSIC_W_CHAIN;
4625 Info.flags = MachineMemOperand::MONone;
4626 Info.offset = 0;
4627
4628 switch (IntrData->Type) {
4629 case TRUNCATE_TO_MEM_VI8:
4630 case TRUNCATE_TO_MEM_VI16:
4631 case TRUNCATE_TO_MEM_VI32: {
4632 Info.ptrVal = I.getArgOperand(0);
4633 MVT VT = MVT::getVT(I.getArgOperand(1)->getType());
4634 MVT ScalarVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
4635 if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
4636 ScalarVT = MVT::i8;
4637 else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
4638 ScalarVT = MVT::i16;
4639 else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
4640 ScalarVT = MVT::i32;
4641
4642 Info.memVT = MVT::getVectorVT(ScalarVT, VT.getVectorNumElements());
4643 Info.align = 1;
4644 Info.flags |= MachineMemOperand::MOStore;
4645 break;
4646 }
4647 default:
4648 return false;
4649 }
4650
4651 return true;
4652}
4653
4654/// Returns true if the target can instruction select the
4655/// specified FP immediate natively. If false, the legalizer will
4656/// materialize the FP immediate as a load from a constant pool.
4657bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4658 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4659 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4660 return true;
4661 }
4662 return false;
4663}
4664
4665bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4666 ISD::LoadExtType ExtTy,
4667 EVT NewVT) const {
4668 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4669 // relocation target a movq or addq instruction: don't let the load shrink.
4670 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4671 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4672 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4673 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4674 return true;
4675}
4676
4677/// Returns true if it is beneficial to convert a load of a constant
4678/// to just the constant itself.
4679bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4680 Type *Ty) const {
4681 assert(Ty->isIntegerTy())(static_cast <bool> (Ty->isIntegerTy()) ? void (0) :
__assert_fail ("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 4681, __extension__ __PRETTY_FUNCTION__))
;
4682
4683 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4684 if (BitSize == 0 || BitSize > 64)
4685 return false;
4686 return true;
4687}
4688
4689bool X86TargetLowering::convertSelectOfConstantsToMath(EVT VT) const {
4690 // TODO: It might be a win to ease or lift this restriction, but the generic
4691 // folds in DAGCombiner conflict with vector folds for an AVX512 target.
4692 if (VT.isVector() && Subtarget.hasAVX512())
4693 return false;
4694
4695 return true;
4696}
4697
4698bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
4699 unsigned Index) const {
4700 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4701 return false;
4702
4703 // Mask vectors support all subregister combinations and operations that
4704 // extract half of vector.
4705 if (ResVT.getVectorElementType() == MVT::i1)
4706 return Index == 0 || ((ResVT.getSizeInBits() == SrcVT.getSizeInBits()*2) &&
4707 (Index == ResVT.getVectorNumElements()));
4708
4709 return (Index % ResVT.getVectorNumElements()) == 0;
4710}
4711
4712bool X86TargetLowering::isCheapToSpeculateCttz() const {
4713 // Speculate cttz only if we can directly use TZCNT.
4714 return Subtarget.hasBMI();
4715}
4716
4717bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4718 // Speculate ctlz only if we can directly use LZCNT.
4719 return Subtarget.hasLZCNT();
4720}
4721
4722bool X86TargetLowering::isLoadBitCastBeneficial(EVT LoadVT,
4723 EVT BitcastVT) const {
4724 if (!Subtarget.hasDQI() && BitcastVT == MVT::v8i1)
4725 return false;
4726
4727 return TargetLowering::isLoadBitCastBeneficial(LoadVT, BitcastVT);
4728}
4729
4730bool X86TargetLowering::canMergeStoresTo(unsigned AddressSpace, EVT MemVT,
4731 const SelectionDAG &DAG) const {
4732 // Do not merge to float value size (128 bytes) if no implicit
4733 // float attribute is set.
4734 bool NoFloat = DAG.getMachineFunction().getFunction().hasFnAttribute(
4735 Attribute::NoImplicitFloat);
4736
4737 if (NoFloat) {
4738 unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
4739 return (MemVT.getSizeInBits() <= MaxIntSize);
4740 }
4741 return true;
4742}
4743
4744bool X86TargetLowering::isCtlzFast() const {
4745 return Subtarget.hasFastLZCNT();
4746}
4747
4748bool X86TargetLowering::isMaskAndCmp0FoldingBeneficial(
4749 const Instruction &AndI) const {
4750 return true;
4751}
4752
4753bool X86TargetLowering::hasAndNotCompare(SDValue Y) const {
4754 EVT VT = Y.getValueType();
4755
4756 if (VT.isVector())
4757 return false;
4758
4759 if (!Subtarget.hasBMI())
4760 return false;
4761
4762 // There are only 32-bit and 64-bit forms for 'andn'.
4763 if (VT != MVT::i32 && VT != MVT::i64)
4764 return false;
4765
4766 // A mask and compare against constant is ok for an 'andn' too
4767 // even though the BMI instruction doesn't have an immediate form.
4768
4769 return true;
4770}
4771
4772bool X86TargetLowering::hasAndNot(SDValue Y) const {
4773 EVT VT = Y.getValueType();
4774
4775 if (!VT.isVector()) // x86 can't form 'andn' with an immediate.
4776 return !isa<ConstantSDNode>(Y) && hasAndNotCompare(Y);
4777
4778 // Vector.
4779
4780 if (!Subtarget.hasSSE1() || VT.getSizeInBits() < 128)
4781 return false;
4782
4783 if (VT == MVT::v4i32)
4784 return true;
4785
4786 return Subtarget.hasSSE2();
4787}
4788
4789bool X86TargetLowering::preferShiftsToClearExtremeBits(SDValue Y) const {
4790 EVT VT = Y.getValueType();
4791
4792 // For vectors, we don't have a preference, but we probably want a mask.
4793 if (VT.isVector())
4794 return false;
4795
4796 // 64-bit shifts on 32-bit targets produce really bad bloated code.
4797 if (VT == MVT::i64 && !Subtarget.is64Bit())
4798 return false;
4799
4800 return true;
4801}
4802
4803MVT X86TargetLowering::hasFastEqualityCompare(unsigned NumBits) const {
4804 MVT VT = MVT::getIntegerVT(NumBits);
4805 if (isTypeLegal(VT))
4806 return VT;
4807
4808 // PMOVMSKB can handle this.
4809 if (NumBits == 128 && isTypeLegal(MVT::v16i8))
4810 return MVT::v16i8;
4811
4812 // VPMOVMSKB can handle this.
4813 if (NumBits == 256 && isTypeLegal(MVT::v32i8))
4814 return MVT::v32i8;
4815
4816 // TODO: Allow 64-bit type for 32-bit target.
4817 // TODO: 512-bit types should be allowed, but make sure that those
4818 // cases are handled in combineVectorSizedSetCCEquality().
4819
4820 return MVT::INVALID_SIMPLE_VALUE_TYPE;
4821}
4822
4823/// Val is the undef sentinel value or equal to the specified value.
4824static bool isUndefOrEqual(int Val, int CmpVal) {
4825 return ((Val == SM_SentinelUndef) || (Val == CmpVal));
4826}
4827
4828/// Val is either the undef or zero sentinel value.
4829static bool isUndefOrZero(int Val) {
4830 return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
4831}
4832
4833/// Return true if every element in Mask, beginning
4834/// from position Pos and ending in Pos+Size is the undef sentinel value.
4835static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4836 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4837 if (Mask[i] != SM_SentinelUndef)
4838 return false;
4839 return true;
4840}
4841
4842/// Return true if Val falls within the specified range (L, H].
4843static bool isInRange(int Val, int Low, int Hi) {
4844 return (Val >= Low && Val < Hi);
4845}
4846
4847/// Return true if the value of any element in Mask falls within the specified
4848/// range (L, H].
4849static bool isAnyInRange(ArrayRef<int> Mask, int Low, int Hi) {
4850 for (int M : Mask)
4851 if (isInRange(M, Low, Hi))
4852 return true;
4853 return false;
4854}
4855
4856/// Return true if Val is undef or if its value falls within the
4857/// specified range (L, H].
4858static bool isUndefOrInRange(int Val, int Low, int Hi) {
4859 return (Val == SM_SentinelUndef) || isInRange(Val, Low, Hi);
4860}
4861
4862/// Return true if every element in Mask is undef or if its value
4863/// falls within the specified range (L, H].
4864static bool isUndefOrInRange(ArrayRef<int> Mask,
4865 int Low, int Hi) {
4866 for (int M : Mask)
4867 if (!isUndefOrInRange(M, Low, Hi))
4868 return false;
4869 return true;
4870}
4871
4872/// Return true if Val is undef, zero or if its value falls within the
4873/// specified range (L, H].
4874static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
4875 return isUndefOrZero(Val) || isInRange(Val, Low, Hi);
4876}
4877
4878/// Return true if every element in Mask is undef, zero or if its value
4879/// falls within the specified range (L, H].
4880static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
4881 for (int M : Mask)
4882 if (!isUndefOrZeroOrInRange(M, Low, Hi))
4883 return false;
4884 return true;
4885}
4886
4887/// Return true if every element in Mask, beginning
4888/// from position Pos and ending in Pos + Size, falls within the specified
4889/// sequence (Low, Low + Step, ..., Low + (Size - 1) * Step) or is undef.
4890static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, unsigned Pos,
4891 unsigned Size, int Low, int Step = 1) {
4892 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
4893 if (!isUndefOrEqual(Mask[i], Low))
4894 return false;
4895 return true;
4896}
4897
4898/// Return true if every element in Mask, beginning
4899/// from position Pos and ending in Pos+Size, falls within the specified
4900/// sequential range (Low, Low+Size], or is undef or is zero.
4901static bool isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
4902 unsigned Size, int Low) {
4903 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, ++Low)
4904 if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
4905 return false;
4906 return true;
4907}
4908
4909/// Return true if every element in Mask, beginning
4910/// from position Pos and ending in Pos+Size is undef or is zero.
4911static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
4912 unsigned Size) {
4913 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4914 if (!isUndefOrZero(Mask[i]))
4915 return false;
4916 return true;
4917}
4918
4919/// Helper function to test whether a shuffle mask could be
4920/// simplified by widening the elements being shuffled.
4921///
4922/// Appends the mask for wider elements in WidenedMask if valid. Otherwise
4923/// leaves it in an unspecified state.
4924///
4925/// NOTE: This must handle normal vector shuffle masks and *target* vector
4926/// shuffle masks. The latter have the special property of a '-2' representing
4927/// a zero-ed lane of a vector.
4928static bool canWidenShuffleElements(ArrayRef<int> Mask,
4929 SmallVectorImpl<int> &WidenedMask) {
4930 WidenedMask.assign(Mask.size() / 2, 0);
4931 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
4932 int M0 = Mask[i];
4933 int M1 = Mask[i + 1];
4934
4935 // If both elements are undef, its trivial.
4936 if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
4937 WidenedMask[i / 2] = SM_SentinelUndef;
4938 continue;
4939 }
4940
4941 // Check for an undef mask and a mask value properly aligned to fit with
4942 // a pair of values. If we find such a case, use the non-undef mask's value.
4943 if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
4944 WidenedMask[i / 2] = M1 / 2;
4945 continue;
4946 }
4947 if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
4948 WidenedMask[i / 2] = M0 / 2;
4949 continue;
4950 }
4951
4952 // When zeroing, we need to spread the zeroing across both lanes to widen.
4953 if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
4954 if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
4955 (M1 == SM_SentinelZero || M1 == SM_SentinelUndef)) {
4956 WidenedMask[i / 2] = SM_SentinelZero;
4957 continue;
4958 }
4959 return false;
4960 }
4961
4962 // Finally check if the two mask values are adjacent and aligned with
4963 // a pair.
4964 if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
4965 WidenedMask[i / 2] = M0 / 2;
4966 continue;
4967 }
4968
4969 // Otherwise we can't safely widen the elements used in this shuffle.
4970 return false;
4971 }
4972 assert(WidenedMask.size() == Mask.size() / 2 &&(static_cast <bool> (WidenedMask.size() == Mask.size() /
2 && "Incorrect size of mask after widening the elements!"
) ? void (0) : __assert_fail ("WidenedMask.size() == Mask.size() / 2 && \"Incorrect size of mask after widening the elements!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 4973, __extension__ __PRETTY_FUNCTION__))
4973 "Incorrect size of mask after widening the elements!")(static_cast <bool> (WidenedMask.size() == Mask.size() /
2 && "Incorrect size of mask after widening the elements!"
) ? void (0) : __assert_fail ("WidenedMask.size() == Mask.size() / 2 && \"Incorrect size of mask after widening the elements!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 4973, __extension__ __PRETTY_FUNCTION__))
;
4974
4975 return true;
4976}
4977
4978static bool canWidenShuffleElements(ArrayRef<int> Mask,
4979 const APInt &Zeroable,
4980 SmallVectorImpl<int> &WidenedMask) {
4981 SmallVector<int, 32> TargetMask(Mask.begin(), Mask.end());
4982 for (int i = 0, Size = TargetMask.size(); i < Size; ++i) {
4983 if (TargetMask[i] == SM_SentinelUndef)
4984 continue;
4985 if (Zeroable[i])
4986 TargetMask[i] = SM_SentinelZero;
4987 }
4988 return canWidenShuffleElements(TargetMask, WidenedMask);
4989}
4990
4991static bool canWidenShuffleElements(ArrayRef<int> Mask) {
4992 SmallVector<int, 32> WidenedMask;
4993 return canWidenShuffleElements(Mask, WidenedMask);
4994}
4995
4996/// Returns true if Elt is a constant zero or a floating point constant +0.0.
4997bool X86::isZeroNode(SDValue Elt) {
4998 return isNullConstant(Elt) || isNullFPConstant(Elt);
4999}
5000
5001// Build a vector of constants.
5002// Use an UNDEF node if MaskElt == -1.
5003// Split 64-bit constants in the 32-bit mode.
5004static SDValue getConstVector(ArrayRef<int> Values, MVT VT, SelectionDAG &DAG,
5005 const SDLoc &dl, bool IsMask = false) {
5006
5007 SmallVector<SDValue, 32> Ops;
5008 bool Split = false;
5009
5010 MVT ConstVecVT = VT;
5011 unsigned NumElts = VT.getVectorNumElements();
5012 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
5013 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
5014 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
5015 Split = true;
5016 }
5017
5018 MVT EltVT = ConstVecVT.getVectorElementType();
5019 for (unsigned i = 0; i < NumElts; ++i) {
5020 bool IsUndef = Values[i] < 0 && IsMask;
5021 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
5022 DAG.getConstant(Values[i], dl, EltVT);
5023 Ops.push_back(OpNode);
5024 if (Split)
5025 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
5026 DAG.getConstant(0, dl, EltVT));
5027 }
5028 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
5029 if (Split)
5030 ConstsNode = DAG.getBitcast(VT, ConstsNode);
5031 return ConstsNode;
5032}
5033
5034static SDValue getConstVector(ArrayRef<APInt> Bits, APInt &Undefs,
5035 MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5036 assert(Bits.size() == Undefs.getBitWidth() &&(static_cast <bool> (Bits.size() == Undefs.getBitWidth(
) && "Unequal constant and undef arrays") ? void (0) :
__assert_fail ("Bits.size() == Undefs.getBitWidth() && \"Unequal constant and undef arrays\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5037, __extension__ __PRETTY_FUNCTION__))
5037 "Unequal constant and undef arrays")(static_cast <bool> (Bits.size() == Undefs.getBitWidth(
) && "Unequal constant and undef arrays") ? void (0) :
__assert_fail ("Bits.size() == Undefs.getBitWidth() && \"Unequal constant and undef arrays\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5037, __extension__ __PRETTY_FUNCTION__))
;
5038 SmallVector<SDValue, 32> Ops;
5039 bool Split = false;
5040
5041 MVT ConstVecVT = VT;
5042 unsigned NumElts = VT.getVectorNumElements();
5043 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
5044 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
5045 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
5046 Split = true;
5047 }
5048
5049 MVT EltVT = ConstVecVT.getVectorElementType();
5050 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
5051 if (Undefs[i]) {
5052 Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
5053 continue;
5054 }
5055 const APInt &V = Bits[i];
5056 assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes")(static_cast <bool> (V.getBitWidth() == VT.getScalarSizeInBits
() && "Unexpected sizes") ? void (0) : __assert_fail (
"V.getBitWidth() == VT.getScalarSizeInBits() && \"Unexpected sizes\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5056, __extension__ __PRETTY_FUNCTION__))
;
5057 if (Split) {
5058 Ops.push_back(DAG.getConstant(V.trunc(32), dl, EltVT));
5059 Ops.push_back(DAG.getConstant(V.lshr(32).trunc(32), dl, EltVT));
5060 } else if (EltVT == MVT::f32) {
5061 APFloat FV(APFloat::IEEEsingle(), V);
5062 Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
5063 } else if (EltVT == MVT::f64) {
5064 APFloat FV(APFloat::IEEEdouble(), V);
5065 Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
5066 } else {
5067 Ops.push_back(DAG.getConstant(V, dl, EltVT));
5068 }
5069 }
5070
5071 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
5072 return DAG.getBitcast(VT, ConstsNode);
5073}
5074
5075/// Returns a vector of specified type with all zero elements.
5076static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
5077 SelectionDAG &DAG, const SDLoc &dl) {
5078 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector() || VT.getVectorElementType() == MVT
::i1) && "Unexpected vector type") ? void (0) : __assert_fail
("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() || VT.getVectorElementType() == MVT::i1) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5080, __extension__ __PRETTY_FUNCTION__))
5079 VT.getVectorElementType() == MVT::i1) &&(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector() || VT.getVectorElementType() == MVT
::i1) && "Unexpected vector type") ? void (0) : __assert_fail
("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() || VT.getVectorElementType() == MVT::i1) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5080, __extension__ __PRETTY_FUNCTION__))
5080 "Unexpected vector type")(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector() || VT.getVectorElementType() == MVT
::i1) && "Unexpected vector type") ? void (0) : __assert_fail
("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() || VT.getVectorElementType() == MVT::i1) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5080, __extension__ __PRETTY_FUNCTION__))
;
5081
5082 // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
5083 // type. This ensures they get CSE'd. But if the integer type is not
5084 // available, use a floating-point +0.0 instead.
5085 SDValue Vec;
5086 if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
5087 Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
5088 } else if (VT.getVectorElementType() == MVT::i1) {
5089 assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&(static_cast <bool> ((Subtarget.hasBWI() || VT.getVectorNumElements
() <= 16) && "Unexpected vector type") ? void (0) :
__assert_fail ("(Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5090, __extension__ __PRETTY_FUNCTION__))
5090 "Unexpected vector type")(static_cast <bool> ((Subtarget.hasBWI() || VT.getVectorNumElements
() <= 16) && "Unexpected vector type") ? void (0) :
__assert_fail ("(Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5090, __extension__ __PRETTY_FUNCTION__))
;
5091 Vec = DAG.getConstant(0, dl, VT);
5092 } else {
5093 unsigned Num32BitElts = VT.getSizeInBits() / 32;
5094 Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
5095 }
5096 return DAG.getBitcast(VT, Vec);
5097}
5098
5099static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
5100 const SDLoc &dl, unsigned vectorWidth) {
5101 EVT VT = Vec.getValueType();
5102 EVT ElVT = VT.getVectorElementType();
5103 unsigned Factor = VT.getSizeInBits()/vectorWidth;
5104 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
5105 VT.getVectorNumElements()/Factor);
5106
5107 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
5108 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
5109 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2")(static_cast <bool> (isPowerOf2_32(ElemsPerChunk) &&
"Elements per chunk not power of 2") ? void (0) : __assert_fail
("isPowerOf2_32(ElemsPerChunk) && \"Elements per chunk not power of 2\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5109, __extension__ __PRETTY_FUNCTION__))
;
5110
5111 // This is the index of the first element of the vectorWidth-bit chunk
5112 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
5113 IdxVal &= ~(ElemsPerChunk - 1);
5114
5115 // If the input is a buildvector just emit a smaller one.
5116 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
5117 return DAG.getBuildVector(ResultVT, dl,
5118 Vec->ops().slice(IdxVal, ElemsPerChunk));
5119
5120 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
5121 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
5122}
5123
5124/// Generate a DAG to grab 128-bits from a vector > 128 bits. This
5125/// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
5126/// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
5127/// instructions or a simple subregister reference. Idx is an index in the
5128/// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
5129/// lowering EXTRACT_VECTOR_ELT operations easier.
5130static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
5131 SelectionDAG &DAG, const SDLoc &dl) {
5132 assert((Vec.getValueType().is256BitVector() ||(static_cast <bool> ((Vec.getValueType().is256BitVector
() || Vec.getValueType().is512BitVector()) && "Unexpected vector size!"
) ? void (0) : __assert_fail ("(Vec.getValueType().is256BitVector() || Vec.getValueType().is512BitVector()) && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5133, __extension__ __PRETTY_FUNCTION__))
5133 Vec.getValueType().is512BitVector()) && "Unexpected vector size!")(static_cast <bool> ((Vec.getValueType().is256BitVector
() || Vec.getValueType().is512BitVector()) && "Unexpected vector size!"
) ? void (0) : __assert_fail ("(Vec.getValueType().is256BitVector() || Vec.getValueType().is512BitVector()) && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5133, __extension__ __PRETTY_FUNCTION__))
;
5134 return extractSubVector(Vec, IdxVal, DAG, dl, 128);
5135}
5136
5137/// Generate a DAG to grab 256-bits from a 512-bit vector.
5138static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
5139 SelectionDAG &DAG, const SDLoc &dl) {
5140 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!")(static_cast <bool> (Vec.getValueType().is512BitVector(
) && "Unexpected vector size!") ? void (0) : __assert_fail
("Vec.getValueType().is512BitVector() && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5140, __extension__ __PRETTY_FUNCTION__))
;
5141 return extractSubVector(Vec, IdxVal, DAG, dl, 256);
5142}
5143
5144static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
5145 SelectionDAG &DAG, const SDLoc &dl,
5146 unsigned vectorWidth) {
5147 assert((vectorWidth == 128 || vectorWidth == 256) &&(static_cast <bool> ((vectorWidth == 128 || vectorWidth
== 256) && "Unsupported vector width") ? void (0) : __assert_fail
("(vectorWidth == 128 || vectorWidth == 256) && \"Unsupported vector width\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5148, __extension__ __PRETTY_FUNCTION__))
5148 "Unsupported vector width")(static_cast <bool> ((vectorWidth == 128 || vectorWidth
== 256) && "Unsupported vector width") ? void (0) : __assert_fail
("(vectorWidth == 128 || vectorWidth == 256) && \"Unsupported vector width\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5148, __extension__ __PRETTY_FUNCTION__))
;
5149 // Inserting UNDEF is Result
5150 if (Vec.isUndef())
5151 return Result;
5152 EVT VT = Vec.getValueType();
5153 EVT ElVT = VT.getVectorElementType();
5154 EVT ResultVT = Result.getValueType();
5155
5156 // Insert the relevant vectorWidth bits.
5157 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
5158 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2")(static_cast <bool> (isPowerOf2_32(ElemsPerChunk) &&
"Elements per chunk not power of 2") ? void (0) : __assert_fail
("isPowerOf2_32(ElemsPerChunk) && \"Elements per chunk not power of 2\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5158, __extension__ __PRETTY_FUNCTION__))
;
5159
5160 // This is the index of the first element of the vectorWidth-bit chunk
5161 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
5162 IdxVal &= ~(ElemsPerChunk - 1);
5163
5164 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
5165 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
5166}
5167
5168/// Generate a DAG to put 128-bits into a vector > 128 bits. This
5169/// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
5170/// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
5171/// simple superregister reference. Idx is an index in the 128 bits
5172/// we want. It need not be aligned to a 128-bit boundary. That makes
5173/// lowering INSERT_VECTOR_ELT operations easier.
5174static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
5175 SelectionDAG &DAG, const SDLoc &dl) {
5176 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!")(static_cast <bool> (Vec.getValueType().is128BitVector(
) && "Unexpected vector size!") ? void (0) : __assert_fail
("Vec.getValueType().is128BitVector() && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5176, __extension__ __PRETTY_FUNCTION__))
;
5177 return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
5178}
5179
5180/// Widen a vector to a larger size with the same scalar type, with the new
5181/// elements either zero or undef.
5182static SDValue widenSubVector(MVT VT, SDValue Vec, bool ZeroNewElements,
5183 const X86Subtarget &Subtarget, SelectionDAG &DAG,
5184 const SDLoc &dl) {
5185 assert(Vec.getValueSizeInBits() < VT.getSizeInBits() &&(static_cast <bool> (Vec.getValueSizeInBits() < VT.getSizeInBits
() && Vec.getValueType().getScalarType() == VT.getScalarType
() && "Unsupported vector widening type") ? void (0) :
__assert_fail ("Vec.getValueSizeInBits() < VT.getSizeInBits() && Vec.getValueType().getScalarType() == VT.getScalarType() && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5187, __extension__ __PRETTY_FUNCTION__))
5186 Vec.getValueType().getScalarType() == VT.getScalarType() &&(static_cast <bool> (Vec.getValueSizeInBits() < VT.getSizeInBits
() && Vec.getValueType().getScalarType() == VT.getScalarType
() && "Unsupported vector widening type") ? void (0) :
__assert_fail ("Vec.getValueSizeInBits() < VT.getSizeInBits() && Vec.getValueType().getScalarType() == VT.getScalarType() && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5187, __extension__ __PRETTY_FUNCTION__))
5187 "Unsupported vector widening type")(static_cast <bool> (Vec.getValueSizeInBits() < VT.getSizeInBits
() && Vec.getValueType().getScalarType() == VT.getScalarType
() && "Unsupported vector widening type") ? void (0) :
__assert_fail ("Vec.getValueSizeInBits() < VT.getSizeInBits() && Vec.getValueType().getScalarType() == VT.getScalarType() && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5187, __extension__ __PRETTY_FUNCTION__))
;
5188 SDValue Res = ZeroNewElements ? getZeroVector(VT, Subtarget, DAG, dl)
5189 : DAG.getUNDEF(VT);
5190 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, Vec,
5191 DAG.getIntPtrConstant(0, dl));
5192}
5193
5194// Helper for splitting operands of an operation to legal target size and
5195// apply a function on each part.
5196// Useful for operations that are available on SSE2 in 128-bit, on AVX2 in
5197// 256-bit and on AVX512BW in 512-bit. The argument VT is the type used for
5198// deciding if/how to split Ops. Ops elements do *not* have to be of type VT.
5199// The argument Builder is a function that will be applied on each split part:
5200// SDValue Builder(SelectionDAG&G, SDLoc, ArrayRef<SDValue>)
5201template <typename F>
5202SDValue SplitOpsAndApply(SelectionDAG &DAG, const X86Subtarget &Subtarget,
5203 const SDLoc &DL, EVT VT, ArrayRef<SDValue> Ops,
5204 F Builder, bool CheckBWI = true) {
5205 assert(Subtarget.hasSSE2() && "Target assumed to support at least SSE2")(static_cast <bool> (Subtarget.hasSSE2() && "Target assumed to support at least SSE2"
) ? void (0) : __assert_fail ("Subtarget.hasSSE2() && \"Target assumed to support at least SSE2\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5205, __extension__ __PRETTY_FUNCTION__))
;
5206 unsigned NumSubs = 1;
5207 if ((CheckBWI && Subtarget.useBWIRegs()) ||
5208 (!CheckBWI && Subtarget.useAVX512Regs())) {
5209 if (VT.getSizeInBits() > 512) {
5210 NumSubs = VT.getSizeInBits() / 512;
5211 assert((VT.getSizeInBits() % 512) == 0 && "Illegal vector size")(static_cast <bool> ((VT.getSizeInBits() % 512) == 0 &&
"Illegal vector size") ? void (0) : __assert_fail ("(VT.getSizeInBits() % 512) == 0 && \"Illegal vector size\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5211, __extension__ __PRETTY_FUNCTION__))
;
5212 }
5213 } else if (Subtarget.hasAVX2()) {
5214 if (VT.getSizeInBits() > 256) {
5215 NumSubs = VT.getSizeInBits() / 256;
5216 assert((VT.getSizeInBits() % 256) == 0 && "Illegal vector size")(static_cast <bool> ((VT.getSizeInBits() % 256) == 0 &&
"Illegal vector size") ? void (0) : __assert_fail ("(VT.getSizeInBits() % 256) == 0 && \"Illegal vector size\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5216, __extension__ __PRETTY_FUNCTION__))
;
5217 }
5218 } else {
5219 if (VT.getSizeInBits() > 128) {
5220 NumSubs = VT.getSizeInBits() / 128;
5221 assert((VT.getSizeInBits() % 128) == 0 && "Illegal vector size")(static_cast <bool> ((VT.getSizeInBits() % 128) == 0 &&
"Illegal vector size") ? void (0) : __assert_fail ("(VT.getSizeInBits() % 128) == 0 && \"Illegal vector size\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5221, __extension__ __PRETTY_FUNCTION__))
;
5222 }
5223 }
5224
5225 if (NumSubs == 1)
5226 return Builder(DAG, DL, Ops);
5227
5228 SmallVector<SDValue, 4> Subs;
5229 for (unsigned i = 0; i != NumSubs; ++i) {
5230 SmallVector<SDValue, 2> SubOps;
5231 for (SDValue Op : Ops) {
5232 EVT OpVT = Op.getValueType();
5233 unsigned NumSubElts = OpVT.getVectorNumElements() / NumSubs;
5234 unsigned SizeSub = OpVT.getSizeInBits() / NumSubs;
5235 SubOps.push_back(extractSubVector(Op, i * NumSubElts, DAG, DL, SizeSub));
5236 }
5237 Subs.push_back(Builder(DAG, DL, SubOps));
5238 }
5239 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
5240}
5241
5242// Return true if the instruction zeroes the unused upper part of the
5243// destination and accepts mask.
5244static bool isMaskedZeroUpperBitsvXi1(unsigned int Opcode) {
5245 switch (Opcode) {
5246 default:
5247 return false;
5248 case X86ISD::CMPM:
5249 case X86ISD::CMPM_RND:
5250 case ISD::SETCC:
5251 return true;
5252 }
5253}
5254
5255/// Insert i1-subvector to i1-vector.
5256static SDValue insert1BitVector(SDValue Op, SelectionDAG &DAG,
5257 const X86Subtarget &Subtarget) {
5258
5259 SDLoc dl(Op);
5260 SDValue Vec = Op.getOperand(0);
5261 SDValue SubVec = Op.getOperand(1);
5262 SDValue Idx = Op.getOperand(2);
5263
5264 if (!isa<ConstantSDNode>(Idx))
5265 return SDValue();
5266
5267 // Inserting undef is a nop. We can just return the original vector.
5268 if (SubVec.isUndef())
5269 return Vec;
5270
5271 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5272 if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
5273 return Op;
5274
5275 MVT OpVT = Op.getSimpleValueType();
5276 unsigned NumElems = OpVT.getVectorNumElements();
5277
5278 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
5279
5280 // Extend to natively supported kshift.
5281 MVT WideOpVT = OpVT;
5282 if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
5283 WideOpVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
5284
5285 // Inserting into the lsbs of a zero vector is legal. ISel will insert shifts
5286 // if necessary.
5287 if (IdxVal == 0 && ISD::isBuildVectorAllZeros(Vec.getNode())) {
5288 // May need to promote to a legal type.
5289 Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5290 getZeroVector(WideOpVT, Subtarget, DAG, dl),
5291 SubVec, Idx);
5292 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5293 }
5294
5295 MVT SubVecVT = SubVec.getSimpleValueType();
5296 unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
5297
5298 assert(IdxVal + SubVecNumElems <= NumElems &&(static_cast <bool> (IdxVal + SubVecNumElems <= NumElems
&& IdxVal % SubVecVT.getSizeInBits() == 0 &&
"Unexpected index value in INSERT_SUBVECTOR") ? void (0) : __assert_fail
("IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT.getSizeInBits() == 0 && \"Unexpected index value in INSERT_SUBVECTOR\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5300, __extension__ __PRETTY_FUNCTION__))
5299 IdxVal % SubVecVT.getSizeInBits() == 0 &&(static_cast <bool> (IdxVal + SubVecNumElems <= NumElems
&& IdxVal % SubVecVT.getSizeInBits() == 0 &&
"Unexpected index value in INSERT_SUBVECTOR") ? void (0) : __assert_fail
("IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT.getSizeInBits() == 0 && \"Unexpected index value in INSERT_SUBVECTOR\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5300, __extension__ __PRETTY_FUNCTION__))
5300 "Unexpected index value in INSERT_SUBVECTOR")(static_cast <bool> (IdxVal + SubVecNumElems <= NumElems
&& IdxVal % SubVecVT.getSizeInBits() == 0 &&
"Unexpected index value in INSERT_SUBVECTOR") ? void (0) : __assert_fail
("IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT.getSizeInBits() == 0 && \"Unexpected index value in INSERT_SUBVECTOR\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5300, __extension__ __PRETTY_FUNCTION__))
;
5301
5302 SDValue Undef = DAG.getUNDEF(WideOpVT);
5303
5304 if (IdxVal == 0) {
5305 // Zero lower bits of the Vec
5306 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
5307 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec,
5308 ZeroIdx);
5309 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
5310 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
5311 // Merge them together, SubVec should be zero extended.
5312 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5313 getZeroVector(WideOpVT, Subtarget, DAG, dl),
5314 SubVec, ZeroIdx);
5315 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
5316 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5317 }
5318
5319 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5320 Undef, SubVec, ZeroIdx);
5321
5322 if (Vec.isUndef()) {
5323 assert(IdxVal != 0 && "Unexpected index")(static_cast <bool> (IdxVal != 0 && "Unexpected index"
) ? void (0) : __assert_fail ("IdxVal != 0 && \"Unexpected index\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5323, __extension__ __PRETTY_FUNCTION__))
;
5324 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5325 DAG.getConstant(IdxVal, dl, MVT::i8));
5326 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
5327 }
5328
5329 if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
5330 assert(IdxVal != 0 && "Unexpected index")(static_cast <bool> (IdxVal != 0 && "Unexpected index"
) ? void (0) : __assert_fail ("IdxVal != 0 && \"Unexpected index\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5330, __extension__ __PRETTY_FUNCTION__))
;
5331 NumElems = WideOpVT.getVectorNumElements();
5332 unsigned ShiftLeft = NumElems - SubVecNumElems;
5333 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
5334 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5335 DAG.getConstant(ShiftLeft, dl, MVT::i8));
5336 if (ShiftRight != 0)
5337 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
5338 DAG.getConstant(ShiftRight, dl, MVT::i8));
5339 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
5340 }
5341
5342 // Simple case when we put subvector in the upper part
5343 if (IdxVal + SubVecNumElems == NumElems) {
5344 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5345 DAG.getConstant(IdxVal, dl, MVT::i8));
5346 if (SubVecNumElems * 2 == NumElems) {
5347 // Special case, use legal zero extending insert_subvector. This allows
5348 // isel to opimitize when bits are known zero.
5349 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVecVT, Vec, ZeroIdx);
5350 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5351 getZeroVector(WideOpVT, Subtarget, DAG, dl),
5352 Vec, ZeroIdx);
5353 } else {
5354 // Otherwise use explicit shifts to zero the bits.
5355 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5356 Undef, Vec, ZeroIdx);
5357 NumElems = WideOpVT.getVectorNumElements();
5358 SDValue ShiftBits = DAG.getConstant(NumElems - IdxVal, dl, MVT::i8);
5359 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
5360 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
5361 }
5362 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
5363 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5364 }
5365
5366 // Inserting into the middle is more complicated.
5367
5368 NumElems = WideOpVT.getVectorNumElements();
5369
5370 // Widen the vector if needed.
5371 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
5372 // Move the current value of the bit to be replace to the lsbs.
5373 Op = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
5374 DAG.getConstant(IdxVal, dl, MVT::i8));
5375 // Xor with the new bit.
5376 Op = DAG.getNode(ISD::XOR, dl, WideOpVT, Op, SubVec);
5377 // Shift to MSB, filling bottom bits with 0.
5378 unsigned ShiftLeft = NumElems - SubVecNumElems;
5379 Op = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Op,
5380 DAG.getConstant(ShiftLeft, dl, MVT::i8));
5381 // Shift to the final position, filling upper bits with 0.
5382 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
5383 Op = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Op,
5384 DAG.getConstant(ShiftRight, dl, MVT::i8));
5385 // Xor with original vector leaving the new value.
5386 Op = DAG.getNode(ISD::XOR, dl, WideOpVT, Vec, Op);
5387 // Reduce to original width if needed.
5388 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5389}
5390
5391static SDValue concatSubVectors(SDValue V1, SDValue V2, EVT VT,
5392 unsigned NumElems, SelectionDAG &DAG,
5393 const SDLoc &dl, unsigned VectorWidth) {
5394 SDValue V = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, dl, VectorWidth);
5395 return insertSubVector(V, V2, NumElems / 2, DAG, dl, VectorWidth);
5396}
5397
5398/// Returns a vector of specified type with all bits set.
5399/// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
5400/// Then bitcast to their original type, ensuring they get CSE'd.
5401static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5402 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector()) && "Expected a 128/256/512-bit vector type"
) ? void (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Expected a 128/256/512-bit vector type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5403, __extension__ __PRETTY_FUNCTION__))
5403 "Expected a 128/256/512-bit vector type")(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector()) && "Expected a 128/256/512-bit vector type"
) ? void (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Expected a 128/256/512-bit vector type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5403, __extension__ __PRETTY_FUNCTION__))
;
5404
5405 APInt Ones = APInt::getAllOnesValue(32);
5406 unsigned NumElts = VT.getSizeInBits() / 32;
5407 SDValue Vec = DAG.getConstant(Ones, dl, MVT::getVectorVT(MVT::i32, NumElts));
5408 return DAG.getBitcast(VT, Vec);
5409}
5410
5411static SDValue getExtendInVec(unsigned Opc, const SDLoc &DL, EVT VT, SDValue In,
5412 SelectionDAG &DAG) {
5413 EVT InVT = In.getValueType();
5414 assert((X86ISD::VSEXT == Opc || X86ISD::VZEXT == Opc) && "Unexpected opcode")(static_cast <bool> ((X86ISD::VSEXT == Opc || X86ISD::VZEXT
== Opc) && "Unexpected opcode") ? void (0) : __assert_fail
("(X86ISD::VSEXT == Opc || X86ISD::VZEXT == Opc) && \"Unexpected opcode\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5414, __extension__ __PRETTY_FUNCTION__))
;
5415
5416 if (VT.is128BitVector() && InVT.is128BitVector())
5417 return X86ISD::VSEXT == Opc ? DAG.getSignExtendVectorInReg(In, DL, VT)
5418 : DAG.getZeroExtendVectorInReg(In, DL, VT);
5419
5420 // For 256-bit vectors, we only need the lower (128-bit) input half.
5421 // For 512-bit vectors, we only need the lower input half or quarter.
5422 if (VT.getSizeInBits() > 128 && InVT.getSizeInBits() > 128) {
5423 int Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
5424 In = extractSubVector(In, 0, DAG, DL,
5425 std::max(128, (int)VT.getSizeInBits() / Scale));
5426 }
5427
5428 return DAG.getNode(Opc, DL, VT, In);
5429}
5430
5431/// Returns a vector_shuffle node for an unpackl operation.
5432static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, MVT VT,
5433 SDValue V1, SDValue V2) {
5434 SmallVector<int, 8> Mask;
5435 createUnpackShuffleMask(VT, Mask, /* Lo = */ true, /* Unary = */ false);
5436 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
5437}
5438
5439/// Returns a vector_shuffle node for an unpackh operation.
5440static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, MVT VT,
5441 SDValue V1, SDValue V2) {
5442 SmallVector<int, 8> Mask;
5443 createUnpackShuffleMask(VT, Mask, /* Lo = */ false, /* Unary = */ false);
5444 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
5445}
5446
5447/// Return a vector_shuffle of the specified vector of zero or undef vector.
5448/// This produces a shuffle where the low element of V2 is swizzled into the
5449/// zero/undef vector, landing at element Idx.
5450/// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5451static SDValue getShuffleVectorZeroOrUndef(SDValue V2, int Idx,
5452 bool IsZero,
5453 const X86Subtarget &Subtarget,
5454 SelectionDAG &DAG) {
5455 MVT VT = V2.getSimpleValueType();
5456 SDValue V1 = IsZero
5457 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5458 int NumElems = VT.getVectorNumElements();
5459 SmallVector<int, 16> MaskVec(NumElems);
5460 for (int i = 0; i != NumElems; ++i)
5461 // If this is the insertion idx, put the low elt of V2 here.
5462 MaskVec[i] = (i == Idx) ? NumElems : i;
5463 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
5464}
5465
5466static SDValue peekThroughBitcasts(SDValue V) {
5467 while (V.getNode() && V.getOpcode() == ISD::BITCAST)
5468 V = V.getOperand(0);
5469 return V;
5470}
5471
5472static SDValue peekThroughOneUseBitcasts(SDValue V) {
5473 while (V.getNode() && V.getOpcode() == ISD::BITCAST &&
5474 V.getOperand(0).hasOneUse())
5475 V = V.getOperand(0);
5476 return V;
5477}
5478
5479// Peek through EXTRACT_SUBVECTORs - typically used for AVX1 256-bit intops.
5480static SDValue peekThroughEXTRACT_SUBVECTORs(SDValue V) {
5481 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
5482 V = V.getOperand(0);
5483 return V;
5484}
5485
5486static const Constant *getTargetConstantFromNode(SDValue Op) {
5487 Op = peekThroughBitcasts(Op);
5488
5489 auto *Load = dyn_cast<LoadSDNode>(Op);
5490 if (!Load)
5491 return nullptr;
5492
5493 SDValue Ptr = Load->getBasePtr();
5494 if (Ptr->getOpcode() == X86ISD::Wrapper ||
5495 Ptr->getOpcode() == X86ISD::WrapperRIP)
5496 Ptr = Ptr->getOperand(0);
5497
5498 auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
5499 if (!CNode || CNode->isMachineConstantPoolEntry())
5500 return nullptr;
5501
5502 return dyn_cast<Constant>(CNode->getConstVal());
5503}
5504
5505// Extract raw constant bits from constant pools.
5506static bool getTargetConstantBitsFromNode(SDValue Op, unsigned EltSizeInBits,
5507 APInt &UndefElts,
5508 SmallVectorImpl<APInt> &EltBits,
5509 bool AllowWholeUndefs = true,
5510 bool AllowPartialUndefs = true) {
5511 assert(EltBits.empty() && "Expected an empty EltBits vector")(static_cast <bool> (EltBits.empty() && "Expected an empty EltBits vector"
) ? void (0) : __assert_fail ("EltBits.empty() && \"Expected an empty EltBits vector\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5511, __extension__ __PRETTY_FUNCTION__))
;
5512
5513 Op = peekThroughBitcasts(Op);
5514
5515 EVT VT = Op.getValueType();
5516 unsigned SizeInBits = VT.getSizeInBits();
5517 assert((SizeInBits % EltSizeInBits) == 0 && "Can't split constant!")(static_cast <bool> ((SizeInBits % EltSizeInBits) == 0 &&
"Can't split constant!") ? void (0) : __assert_fail ("(SizeInBits % EltSizeInBits) == 0 && \"Can't split constant!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5517, __extension__ __PRETTY_FUNCTION__))
;
5518 unsigned NumElts = SizeInBits / EltSizeInBits;
5519
5520 // Bitcast a source array of element bits to the target size.
5521 auto CastBitData = [&](APInt &UndefSrcElts, ArrayRef<APInt> SrcEltBits) {
5522 unsigned NumSrcElts = UndefSrcElts.getBitWidth();
5523 unsigned SrcEltSizeInBits = SrcEltBits[0].getBitWidth();
5524 assert((NumSrcElts * SrcEltSizeInBits) == SizeInBits &&(static_cast <bool> ((NumSrcElts * SrcEltSizeInBits) ==
SizeInBits && "Constant bit sizes don't match") ? void
(0) : __assert_fail ("(NumSrcElts * SrcEltSizeInBits) == SizeInBits && \"Constant bit sizes don't match\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5525, __extension__ __PRETTY_FUNCTION__))
5525 "Constant bit sizes don't match")(static_cast <bool> ((NumSrcElts * SrcEltSizeInBits) ==
SizeInBits && "Constant bit sizes don't match") ? void
(0) : __assert_fail ("(NumSrcElts * SrcEltSizeInBits) == SizeInBits && \"Constant bit sizes don't match\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5525, __extension__ __PRETTY_FUNCTION__))
;
5526
5527 // Don't split if we don't allow undef bits.
5528 bool AllowUndefs = AllowWholeUndefs || AllowPartialUndefs;
5529 if (UndefSrcElts.getBoolValue() && !AllowUndefs)
5530 return false;
5531
5532 // If we're already the right size, don't bother bitcasting.
5533 if (NumSrcElts == NumElts) {
5534 UndefElts = UndefSrcElts;
5535 EltBits.assign(SrcEltBits.begin(), SrcEltBits.end());
5536 return true;
5537 }
5538
5539 // Extract all the undef/constant element data and pack into single bitsets.
5540 APInt UndefBits(SizeInBits, 0);
5541 APInt MaskBits(SizeInBits, 0);
5542
5543 for (unsigned i = 0; i != NumSrcElts; ++i) {
5544 unsigned BitOffset = i * SrcEltSizeInBits;
5545 if (UndefSrcElts[i])
5546 UndefBits.setBits(BitOffset, BitOffset + SrcEltSizeInBits);
5547 MaskBits.insertBits(SrcEltBits[i], BitOffset);
5548 }
5549
5550 // Split the undef/constant single bitset data into the target elements.
5551 UndefElts = APInt(NumElts, 0);
5552 EltBits.resize(NumElts, APInt(EltSizeInBits, 0));
5553
5554 for (unsigned i = 0; i != NumElts; ++i) {
5555 unsigned BitOffset = i * EltSizeInBits;
5556 APInt UndefEltBits = UndefBits.extractBits(EltSizeInBits, BitOffset);
5557
5558 // Only treat an element as UNDEF if all bits are UNDEF.
5559 if (UndefEltBits.isAllOnesValue()) {
5560 if (!AllowWholeUndefs)
5561 return false;
5562 UndefElts.setBit(i);
5563 continue;
5564 }
5565
5566 // If only some bits are UNDEF then treat them as zero (or bail if not
5567 // supported).
5568 if (UndefEltBits.getBoolValue() && !AllowPartialUndefs)
5569 return false;
5570
5571 APInt Bits = MaskBits.extractBits(EltSizeInBits, BitOffset);
5572 EltBits[i] = Bits.getZExtValue();
5573 }
5574 return true;
5575 };
5576
5577 // Collect constant bits and insert into mask/undef bit masks.
5578 auto CollectConstantBits = [](const Constant *Cst, APInt &Mask, APInt &Undefs,
5579 unsigned UndefBitIndex) {
5580 if (!Cst)
5581 return false;
5582 if (isa<UndefValue>(Cst)) {
5583 Undefs.setBit(UndefBitIndex);
5584 return true;
5585 }
5586 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
5587 Mask = CInt->getValue();
5588 return true;
5589 }
5590 if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
5591 Mask = CFP->getValueAPF().bitcastToAPInt();
5592 return true;
5593 }
5594 return false;
5595 };
5596
5597 // Handle UNDEFs.
5598 if (Op.isUndef()) {
5599 APInt UndefSrcElts = APInt::getAllOnesValue(NumElts);
5600 SmallVector<APInt, 64> SrcEltBits(NumElts, APInt(EltSizeInBits, 0));
5601 return CastBitData(UndefSrcElts, SrcEltBits);
5602 }
5603
5604 // Extract scalar constant bits.
5605 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
5606 APInt UndefSrcElts = APInt::getNullValue(1);
5607 SmallVector<APInt, 64> SrcEltBits(1, Cst->getAPIntValue());
5608 return CastBitData(UndefSrcElts, SrcEltBits);
5609 }
5610 if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
5611 APInt UndefSrcElts = APInt::getNullValue(1);
5612 APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
5613 SmallVector<APInt, 64> SrcEltBits(1, RawBits);
5614 return CastBitData(UndefSrcElts, SrcEltBits);
5615 }
5616
5617 // Extract constant bits from build vector.
5618 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5619 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5620 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5621
5622 APInt UndefSrcElts(NumSrcElts, 0);
5623 SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
5624 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
5625 const SDValue &Src = Op.getOperand(i);
5626 if (Src.isUndef()) {
5627 UndefSrcElts.setBit(i);
5628 continue;
5629 }
5630 auto *Cst = cast<ConstantSDNode>(Src);
5631 SrcEltBits[i] = Cst->getAPIntValue().zextOrTrunc(SrcEltSizeInBits);
5632 }
5633 return CastBitData(UndefSrcElts, SrcEltBits);
5634 }
5635
5636 // Extract constant bits from constant pool vector.
5637 if (auto *Cst = getTargetConstantFromNode(Op)) {
5638 Type *CstTy = Cst->getType();
5639 if (!CstTy->isVectorTy() || (SizeInBits != CstTy->getPrimitiveSizeInBits()))
5640 return false;
5641
5642 unsigned SrcEltSizeInBits = CstTy->getScalarSizeInBits();
5643 unsigned NumSrcElts = CstTy->getVectorNumElements();
5644
5645 APInt UndefSrcElts(NumSrcElts, 0);
5646 SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
5647 for (unsigned i = 0; i != NumSrcElts; ++i)
5648 if (!CollectConstantBits(Cst->getAggregateElement(i), SrcEltBits[i],
5649 UndefSrcElts, i))
5650 return false;
5651
5652 return CastBitData(UndefSrcElts, SrcEltBits);
5653 }
5654
5655 // Extract constant bits from a broadcasted constant pool scalar.
5656 if (Op.getOpcode() == X86ISD::VBROADCAST &&
5657 EltSizeInBits <= VT.getScalarSizeInBits()) {
5658 if (auto *Broadcast = getTargetConstantFromNode(Op.getOperand(0))) {
5659 unsigned SrcEltSizeInBits = Broadcast->getType()->getScalarSizeInBits();
5660 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5661
5662 APInt UndefSrcElts(NumSrcElts, 0);
5663 SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
5664 if (CollectConstantBits(Broadcast, SrcEltBits[0], UndefSrcElts, 0)) {
5665 if (UndefSrcElts[0])
5666 UndefSrcElts.setBits(0, NumSrcElts);
5667 SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
5668 return CastBitData(UndefSrcElts, SrcEltBits);
5669 }
5670 }
5671 }
5672
5673 // Extract a rematerialized scalar constant insertion.
5674 if (Op.getOpcode() == X86ISD::VZEXT_MOVL &&
5675 Op.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
5676 isa<ConstantSDNode>(Op.getOperand(0).getOperand(0))) {
5677 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5678 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5679
5680 APInt UndefSrcElts(NumSrcElts, 0);
5681 SmallVector<APInt, 64> SrcEltBits;
5682 auto *CN = cast<ConstantSDNode>(Op.getOperand(0).getOperand(0));
5683 SrcEltBits.push_back(CN->getAPIntValue().zextOrTrunc(SrcEltSizeInBits));
5684 SrcEltBits.append(NumSrcElts - 1, APInt(SrcEltSizeInBits, 0));
5685 return CastBitData(UndefSrcElts, SrcEltBits);
5686 }
5687
5688 return false;
5689}
5690
5691static bool getTargetShuffleMaskIndices(SDValue MaskNode,
5692 unsigned MaskEltSizeInBits,
5693 SmallVectorImpl<uint64_t> &RawMask) {
5694 APInt UndefElts;
5695 SmallVector<APInt, 64> EltBits;
5696
5697 // Extract the raw target constant bits.
5698 // FIXME: We currently don't support UNDEF bits or mask entries.
5699 if (!getTargetConstantBitsFromNode(MaskNode, MaskEltSizeInBits, UndefElts,
5700 EltBits, /* AllowWholeUndefs */ false,
5701 /* AllowPartialUndefs */ false))
5702 return false;
5703
5704 // Insert the extracted elements into the mask.
5705 for (APInt Elt : EltBits)
5706 RawMask.push_back(Elt.getZExtValue());
5707
5708 return true;
5709}
5710
5711/// Create a shuffle mask that matches the PACKSS/PACKUS truncation.
5712/// Note: This ignores saturation, so inputs must be checked first.
5713static void createPackShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
5714 bool Unary) {
5715 assert(Mask.empty() && "Expected an empty shuffle mask vector")(static_cast <bool> (Mask.empty() && "Expected an empty shuffle mask vector"
) ? void (0) : __assert_fail ("Mask.empty() && \"Expected an empty shuffle mask vector\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5715, __extension__ __PRETTY_FUNCTION__))
;
5716 unsigned NumElts = VT.getVectorNumElements();
5717 unsigned NumLanes = VT.getSizeInBits() / 128;
5718 unsigned NumEltsPerLane = 128 / VT.getScalarSizeInBits();
5719 unsigned Offset = Unary ? 0 : NumElts;
5720
5721 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
5722 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += 2)
5723 Mask.push_back(Elt + (Lane * NumEltsPerLane));
5724 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += 2)
5725 Mask.push_back(Elt + (Lane * NumEltsPerLane) + Offset);
5726 }
5727}
5728
5729/// Calculates the shuffle mask corresponding to the target-specific opcode.
5730/// If the mask could be calculated, returns it in \p Mask, returns the shuffle
5731/// operands in \p Ops, and returns true.
5732/// Sets \p IsUnary to true if only one source is used. Note that this will set
5733/// IsUnary for shuffles which use a single input multiple times, and in those
5734/// cases it will adjust the mask to only have indices within that single input.
5735/// It is an error to call this with non-empty Mask/Ops vectors.
5736static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
5737 SmallVectorImpl<SDValue> &Ops,
5738 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5739 unsigned NumElems = VT.getVectorNumElements();
5740 SDValue ImmN;
5741
5742 assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector")(static_cast <bool> (Mask.empty() && "getTargetShuffleMask expects an empty Mask vector"
) ? void (0) : __assert_fail ("Mask.empty() && \"getTargetShuffleMask expects an empty Mask vector\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5742, __extension__ __PRETTY_FUNCTION__))
;
5743 assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector")(static_cast <bool> (Ops.empty() && "getTargetShuffleMask expects an empty Ops vector"
) ? void (0) : __assert_fail ("Ops.empty() && \"getTargetShuffleMask expects an empty Ops vector\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5743, __extension__ __PRETTY_FUNCTION__))
;
5744
5745 IsUnary = false;
5746 bool IsFakeUnary = false;
5747 switch(N->getOpcode()) {
5748 case X86ISD::BLENDI:
5749 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5749, __extension__ __PRETTY_FUNCTION__))
;
5750 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5750, __extension__ __PRETTY_FUNCTION__))
;
5751 ImmN = N->getOperand(N->getNumOperands()-1);
5752 DecodeBLENDMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5753 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5754 break;
5755 case X86ISD::SHUFP:
5756 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5756, __extension__ __PRETTY_FUNCTION__))
;
5757 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5757, __extension__ __PRETTY_FUNCTION__))
;
5758 ImmN = N->getOperand(N->getNumOperands()-1);
5759 DecodeSHUFPMask(NumElems, VT.getScalarSizeInBits(),
5760 cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5761 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5762 break;
5763 case X86ISD::INSERTPS:
5764 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5764, __extension__ __PRETTY_FUNCTION__))
;
5765 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5765, __extension__ __PRETTY_FUNCTION__))
;
5766 ImmN = N->getOperand(N->getNumOperands()-1);
5767 DecodeINSERTPSMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5768 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5769 break;
5770 case X86ISD::EXTRQI:
5771 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5771, __extension__ __PRETTY_FUNCTION__))
;
5772 if (isa<ConstantSDNode>(N->getOperand(1)) &&
5773 isa<ConstantSDNode>(N->getOperand(2))) {
5774 int BitLen = N->getConstantOperandVal(1);
5775 int BitIdx = N->getConstantOperandVal(2);
5776 DecodeEXTRQIMask(NumElems, VT.getScalarSizeInBits(), BitLen, BitIdx,
5777 Mask);
5778 IsUnary = true;
5779 }
5780 break;
5781 case X86ISD::INSERTQI:
5782 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5782, __extension__ __PRETTY_FUNCTION__))
;
5783 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5783, __extension__ __PRETTY_FUNCTION__))
;
5784 if (isa<ConstantSDNode>(N->getOperand(2)) &&
5785 isa<ConstantSDNode>(N->getOperand(3))) {
5786 int BitLen = N->getConstantOperandVal(2);
5787 int BitIdx = N->getConstantOperandVal(3);
5788 DecodeINSERTQIMask(NumElems, VT.getScalarSizeInBits(), BitLen, BitIdx,
5789 Mask);
5790 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5791 }
5792 break;
5793 case X86ISD::UNPCKH:
5794 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5794, __extension__ __PRETTY_FUNCTION__))
;
5795 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5795, __extension__ __PRETTY_FUNCTION__))
;
5796 DecodeUNPCKHMask(NumElems, VT.getScalarSizeInBits(), Mask);
5797 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5798 break;
5799 case X86ISD::UNPCKL:
5800 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5800, __extension__ __PRETTY_FUNCTION__))
;
5801 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5801, __extension__ __PRETTY_FUNCTION__))
;
5802 DecodeUNPCKLMask(NumElems, VT.getScalarSizeInBits(), Mask);
5803 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5804 break;
5805 case X86ISD::MOVHLPS:
5806 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5806, __extension__ __PRETTY_FUNCTION__))
;
5807 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5807, __extension__ __PRETTY_FUNCTION__))
;
5808 DecodeMOVHLPSMask(NumElems, Mask);
5809 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5810 break;
5811 case X86ISD::MOVLHPS:
5812 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5812, __extension__ __PRETTY_FUNCTION__))
;
5813 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5813, __extension__ __PRETTY_FUNCTION__))
;
5814 DecodeMOVLHPSMask(NumElems, Mask);
5815 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5816 break;
5817 case X86ISD::PALIGNR:
5818 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected")(static_cast <bool> (VT.getScalarType() == MVT::i8 &&
"Byte vector expected") ? void (0) : __assert_fail ("VT.getScalarType() == MVT::i8 && \"Byte vector expected\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5818, __extension__ __PRETTY_FUNCTION__))
;
5819 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5819, __extension__ __PRETTY_FUNCTION__))
;
5820 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5820, __extension__ __PRETTY_FUNCTION__))
;
5821 ImmN = N->getOperand(N->getNumOperands()-1);
5822 DecodePALIGNRMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
5823 Mask);
5824 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5825 Ops.push_back(N->getOperand(1));
5826 Ops.push_back(N->getOperand(0));
5827 break;
5828 case X86ISD::VSHLDQ:
5829 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected")(static_cast <bool> (VT.getScalarType() == MVT::i8 &&
"Byte vector expected") ? void (0) : __assert_fail ("VT.getScalarType() == MVT::i8 && \"Byte vector expected\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5829, __extension__ __PRETTY_FUNCTION__))
;
5830 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5830, __extension__ __PRETTY_FUNCTION__))
;
5831 ImmN = N->getOperand(N->getNumOperands() - 1);
5832 DecodePSLLDQMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
5833 Mask);
5834 IsUnary = true;
5835 break;
5836 case X86ISD::VSRLDQ:
5837 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected")(static_cast <bool> (VT.getScalarType() == MVT::i8 &&
"Byte vector expected") ? void (0) : __assert_fail ("VT.getScalarType() == MVT::i8 && \"Byte vector expected\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5837, __extension__ __PRETTY_FUNCTION__))
;
5838 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86ISelLowering.cpp"
, 5838, __extension__ __PRETTY_FUNCTION__))
;
5839 ImmN = N->getOperand(N->getNumOperands() - 1);
5840 DecodePSRLD