Bug Summary

File:include/llvm/CodeGen/SelectionDAGNodes.h
Warning:line 1148, column 10
Called C++ object pointer is null

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-config-compatibility-mode=true -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-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn348900/build-llvm/lib/Target/X86 -I /build/llvm-toolchain-snapshot-8~svn348900/lib/Target/X86 -I /build/llvm-toolchain-snapshot-8~svn348900/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn348900/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-command-line-argument -Wno-unknown-warning-option -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn348900/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-12-12-042652-12204-1 -x c++ /build/llvm-toolchain-snapshot-8~svn348900/lib/Target/X86/X86ISelLowering.cpp -faddrsig

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