[Alignment][NFC] Use Align with TargetLowering::setPrefLoopAlignment
[llvm-complete.git] / lib / Target / ARM / ARMISelLowering.cpp
blobeacaa75bc1033ad4831014b038f1bbaba7c5cd6f
1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that ARM uses to lower LLVM code into a
10 // selection DAG.
12 //===----------------------------------------------------------------------===//
14 #include "ARMISelLowering.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMPerfectShuffle.h"
21 #include "ARMRegisterInfo.h"
22 #include "ARMSelectionDAGInfo.h"
23 #include "ARMSubtarget.h"
24 #include "MCTargetDesc/ARMAddressingModes.h"
25 #include "MCTargetDesc/ARMBaseInfo.h"
26 #include "Utils/ARMBaseInfo.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Analysis/VectorUtils.h"
42 #include "llvm/CodeGen/CallingConvLower.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/IntrinsicLowering.h"
45 #include "llvm/CodeGen/MachineBasicBlock.h"
46 #include "llvm/CodeGen/MachineConstantPool.h"
47 #include "llvm/CodeGen/MachineFrameInfo.h"
48 #include "llvm/CodeGen/MachineFunction.h"
49 #include "llvm/CodeGen/MachineInstr.h"
50 #include "llvm/CodeGen/MachineInstrBuilder.h"
51 #include "llvm/CodeGen/MachineJumpTableInfo.h"
52 #include "llvm/CodeGen/MachineMemOperand.h"
53 #include "llvm/CodeGen/MachineOperand.h"
54 #include "llvm/CodeGen/MachineRegisterInfo.h"
55 #include "llvm/CodeGen/RuntimeLibcalls.h"
56 #include "llvm/CodeGen/SelectionDAG.h"
57 #include "llvm/CodeGen/SelectionDAGNodes.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGen/ValueTypes.h"
64 #include "llvm/IR/Attributes.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DebugLoc.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/GlobalAlias.h"
73 #include "llvm/IR/GlobalValue.h"
74 #include "llvm/IR/GlobalVariable.h"
75 #include "llvm/IR/IRBuilder.h"
76 #include "llvm/IR/InlineAsm.h"
77 #include "llvm/IR/Instruction.h"
78 #include "llvm/IR/Instructions.h"
79 #include "llvm/IR/IntrinsicInst.h"
80 #include "llvm/IR/Intrinsics.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/PatternMatch.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/User.h"
85 #include "llvm/IR/Value.h"
86 #include "llvm/MC/MCInstrDesc.h"
87 #include "llvm/MC/MCInstrItineraries.h"
88 #include "llvm/MC/MCRegisterInfo.h"
89 #include "llvm/MC/MCSchedule.h"
90 #include "llvm/Support/AtomicOrdering.h"
91 #include "llvm/Support/BranchProbability.h"
92 #include "llvm/Support/Casting.h"
93 #include "llvm/Support/CodeGen.h"
94 #include "llvm/Support/CommandLine.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/ErrorHandling.h"
98 #include "llvm/Support/KnownBits.h"
99 #include "llvm/Support/MachineValueType.h"
100 #include "llvm/Support/MathExtras.h"
101 #include "llvm/Support/raw_ostream.h"
102 #include "llvm/Target/TargetMachine.h"
103 #include "llvm/Target/TargetOptions.h"
104 #include <algorithm>
105 #include <cassert>
106 #include <cstdint>
107 #include <cstdlib>
108 #include <iterator>
109 #include <limits>
110 #include <string>
111 #include <tuple>
112 #include <utility>
113 #include <vector>
115 using namespace llvm;
116 using namespace llvm::PatternMatch;
118 #define DEBUG_TYPE "arm-isel"
120 STATISTIC(NumTailCalls, "Number of tail calls");
121 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
122 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
123 STATISTIC(NumConstpoolPromoted,
124 "Number of constants with their storage promoted into constant pools");
126 static cl::opt<bool>
127 ARMInterworking("arm-interworking", cl::Hidden,
128 cl::desc("Enable / disable ARM interworking (for debugging only)"),
129 cl::init(true));
131 static cl::opt<bool> EnableConstpoolPromotion(
132 "arm-promote-constant", cl::Hidden,
133 cl::desc("Enable / disable promotion of unnamed_addr constants into "
134 "constant pools"),
135 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
136 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
137 "arm-promote-constant-max-size", cl::Hidden,
138 cl::desc("Maximum size of constant to promote into a constant pool"),
139 cl::init(64));
140 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
141 "arm-promote-constant-max-total", cl::Hidden,
142 cl::desc("Maximum size of ALL constants to promote into a constant pool"),
143 cl::init(128));
145 // The APCS parameter registers.
146 static const MCPhysReg GPRArgRegs[] = {
147 ARM::R0, ARM::R1, ARM::R2, ARM::R3
150 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
151 MVT PromotedBitwiseVT) {
152 if (VT != PromotedLdStVT) {
153 setOperationAction(ISD::LOAD, VT, Promote);
154 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
156 setOperationAction(ISD::STORE, VT, Promote);
157 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
160 MVT ElemTy = VT.getVectorElementType();
161 if (ElemTy != MVT::f64)
162 setOperationAction(ISD::SETCC, VT, Custom);
163 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
164 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
165 if (ElemTy == MVT::i32) {
166 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
167 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
168 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
169 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
170 } else {
171 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
172 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
173 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
174 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
176 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
177 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
178 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
179 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
180 setOperationAction(ISD::SELECT, VT, Expand);
181 setOperationAction(ISD::SELECT_CC, VT, Expand);
182 setOperationAction(ISD::VSELECT, VT, Expand);
183 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
184 if (VT.isInteger()) {
185 setOperationAction(ISD::SHL, VT, Custom);
186 setOperationAction(ISD::SRA, VT, Custom);
187 setOperationAction(ISD::SRL, VT, Custom);
190 // Promote all bit-wise operations.
191 if (VT.isInteger() && VT != PromotedBitwiseVT) {
192 setOperationAction(ISD::AND, VT, Promote);
193 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
194 setOperationAction(ISD::OR, VT, Promote);
195 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
196 setOperationAction(ISD::XOR, VT, Promote);
197 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
200 // Neon does not support vector divide/remainder operations.
201 setOperationAction(ISD::SDIV, VT, Expand);
202 setOperationAction(ISD::UDIV, VT, Expand);
203 setOperationAction(ISD::FDIV, VT, Expand);
204 setOperationAction(ISD::SREM, VT, Expand);
205 setOperationAction(ISD::UREM, VT, Expand);
206 setOperationAction(ISD::FREM, VT, Expand);
208 if (!VT.isFloatingPoint() &&
209 VT != MVT::v2i64 && VT != MVT::v1i64)
210 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
211 setOperationAction(Opcode, VT, Legal);
214 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
215 addRegisterClass(VT, &ARM::DPRRegClass);
216 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
219 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
220 addRegisterClass(VT, &ARM::DPairRegClass);
221 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
224 void ARMTargetLowering::setAllExpand(MVT VT) {
225 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
226 setOperationAction(Opc, VT, Expand);
228 // We support these really simple operations even on types where all
229 // the actual arithmetic has to be broken down into simpler
230 // operations or turned into library calls.
231 setOperationAction(ISD::BITCAST, VT, Legal);
232 setOperationAction(ISD::LOAD, VT, Legal);
233 setOperationAction(ISD::STORE, VT, Legal);
234 setOperationAction(ISD::UNDEF, VT, Legal);
237 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
238 LegalizeAction Action) {
239 setLoadExtAction(ISD::EXTLOAD, From, To, Action);
240 setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
241 setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
244 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
245 const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
247 for (auto VT : IntTypes) {
248 addRegisterClass(VT, &ARM::MQPRRegClass);
249 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
250 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
251 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
252 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
253 setOperationAction(ISD::SHL, VT, Custom);
254 setOperationAction(ISD::SRA, VT, Custom);
255 setOperationAction(ISD::SRL, VT, Custom);
256 setOperationAction(ISD::SMIN, VT, Legal);
257 setOperationAction(ISD::SMAX, VT, Legal);
258 setOperationAction(ISD::UMIN, VT, Legal);
259 setOperationAction(ISD::UMAX, VT, Legal);
260 setOperationAction(ISD::ABS, VT, Legal);
261 setOperationAction(ISD::SETCC, VT, Custom);
263 // No native support for these.
264 setOperationAction(ISD::UDIV, VT, Expand);
265 setOperationAction(ISD::SDIV, VT, Expand);
266 setOperationAction(ISD::UREM, VT, Expand);
267 setOperationAction(ISD::SREM, VT, Expand);
268 setOperationAction(ISD::CTPOP, VT, Expand);
270 // Vector reductions
271 setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
273 if (!HasMVEFP) {
274 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
275 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
276 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
277 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
280 // Pre and Post inc are supported on loads and stores
281 for (unsigned im = (unsigned)ISD::PRE_INC;
282 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
283 setIndexedLoadAction(im, VT, Legal);
284 setIndexedStoreAction(im, VT, Legal);
288 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
289 for (auto VT : FloatTypes) {
290 addRegisterClass(VT, &ARM::MQPRRegClass);
291 if (!HasMVEFP)
292 setAllExpand(VT);
294 // These are legal or custom whether we have MVE.fp or not
295 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
296 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
297 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
298 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
299 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
300 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
301 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
302 setOperationAction(ISD::SETCC, VT, Custom);
304 // Pre and Post inc are supported on loads and stores
305 for (unsigned im = (unsigned)ISD::PRE_INC;
306 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
307 setIndexedLoadAction(im, VT, Legal);
308 setIndexedStoreAction(im, VT, Legal);
311 if (HasMVEFP) {
312 setOperationAction(ISD::FMINNUM, VT, Legal);
313 setOperationAction(ISD::FMAXNUM, VT, Legal);
314 setOperationAction(ISD::FROUND, VT, Legal);
316 // No native support for these.
317 setOperationAction(ISD::FDIV, VT, Expand);
318 setOperationAction(ISD::FREM, VT, Expand);
319 setOperationAction(ISD::FSQRT, VT, Expand);
320 setOperationAction(ISD::FSIN, VT, Expand);
321 setOperationAction(ISD::FCOS, VT, Expand);
322 setOperationAction(ISD::FPOW, VT, Expand);
323 setOperationAction(ISD::FLOG, VT, Expand);
324 setOperationAction(ISD::FLOG2, VT, Expand);
325 setOperationAction(ISD::FLOG10, VT, Expand);
326 setOperationAction(ISD::FEXP, VT, Expand);
327 setOperationAction(ISD::FEXP2, VT, Expand);
328 setOperationAction(ISD::FNEARBYINT, VT, Expand);
332 // We 'support' these types up to bitcast/load/store level, regardless of
333 // MVE integer-only / float support. Only doing FP data processing on the FP
334 // vector types is inhibited at integer-only level.
335 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
336 for (auto VT : LongTypes) {
337 addRegisterClass(VT, &ARM::MQPRRegClass);
338 setAllExpand(VT);
339 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
340 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
341 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
343 // We can do bitwise operations on v2i64 vectors
344 setOperationAction(ISD::AND, MVT::v2i64, Legal);
345 setOperationAction(ISD::OR, MVT::v2i64, Legal);
346 setOperationAction(ISD::XOR, MVT::v2i64, Legal);
348 // It is legal to extload from v4i8 to v4i16 or v4i32.
349 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
350 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
351 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
353 // Some truncating stores are legal too.
354 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
355 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
356 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
358 // Pre and Post inc on these are legal, given the correct extends
359 for (unsigned im = (unsigned)ISD::PRE_INC;
360 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
361 setIndexedLoadAction(im, MVT::v8i8, Legal);
362 setIndexedStoreAction(im, MVT::v8i8, Legal);
363 setIndexedLoadAction(im, MVT::v4i8, Legal);
364 setIndexedStoreAction(im, MVT::v4i8, Legal);
365 setIndexedLoadAction(im, MVT::v4i16, Legal);
366 setIndexedStoreAction(im, MVT::v4i16, Legal);
369 // Predicate types
370 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1};
371 for (auto VT : pTypes) {
372 addRegisterClass(VT, &ARM::VCCRRegClass);
373 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
374 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
375 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
376 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
377 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
378 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
379 setOperationAction(ISD::SETCC, VT, Custom);
380 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
384 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
385 const ARMSubtarget &STI)
386 : TargetLowering(TM), Subtarget(&STI) {
387 RegInfo = Subtarget->getRegisterInfo();
388 Itins = Subtarget->getInstrItineraryData();
390 setBooleanContents(ZeroOrOneBooleanContent);
391 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
393 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
394 !Subtarget->isTargetWatchOS()) {
395 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
396 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
397 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
398 IsHFTarget ? CallingConv::ARM_AAPCS_VFP
399 : CallingConv::ARM_AAPCS);
402 if (Subtarget->isTargetMachO()) {
403 // Uses VFP for Thumb libfuncs if available.
404 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
405 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
406 static const struct {
407 const RTLIB::Libcall Op;
408 const char * const Name;
409 const ISD::CondCode Cond;
410 } LibraryCalls[] = {
411 // Single-precision floating-point arithmetic.
412 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
413 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
414 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
415 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
417 // Double-precision floating-point arithmetic.
418 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
419 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
420 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
421 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
423 // Single-precision comparisons.
424 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
425 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
426 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
427 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
428 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
429 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
430 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
431 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
433 // Double-precision comparisons.
434 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
435 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
436 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
437 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
438 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
439 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
440 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
441 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
443 // Floating-point to integer conversions.
444 // i64 conversions are done via library routines even when generating VFP
445 // instructions, so use the same ones.
446 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
447 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
448 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
449 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
451 // Conversions between floating types.
452 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
453 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
455 // Integer to floating-point conversions.
456 // i64 conversions are done via library routines even when generating VFP
457 // instructions, so use the same ones.
458 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
459 // e.g., __floatunsidf vs. __floatunssidfvfp.
460 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
461 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
462 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
463 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
466 for (const auto &LC : LibraryCalls) {
467 setLibcallName(LC.Op, LC.Name);
468 if (LC.Cond != ISD::SETCC_INVALID)
469 setCmpLibcallCC(LC.Op, LC.Cond);
474 // These libcalls are not available in 32-bit.
475 setLibcallName(RTLIB::SHL_I128, nullptr);
476 setLibcallName(RTLIB::SRL_I128, nullptr);
477 setLibcallName(RTLIB::SRA_I128, nullptr);
479 // RTLIB
480 if (Subtarget->isAAPCS_ABI() &&
481 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
482 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
483 static const struct {
484 const RTLIB::Libcall Op;
485 const char * const Name;
486 const CallingConv::ID CC;
487 const ISD::CondCode Cond;
488 } LibraryCalls[] = {
489 // Double-precision floating-point arithmetic helper functions
490 // RTABI chapter 4.1.2, Table 2
491 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
492 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
493 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
494 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
496 // Double-precision floating-point comparison helper functions
497 // RTABI chapter 4.1.2, Table 3
498 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
499 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
500 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
501 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
502 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
503 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
504 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
505 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
507 // Single-precision floating-point arithmetic helper functions
508 // RTABI chapter 4.1.2, Table 4
509 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
510 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
511 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
512 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
514 // Single-precision floating-point comparison helper functions
515 // RTABI chapter 4.1.2, Table 5
516 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
517 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
518 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
519 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
520 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
521 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
522 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
523 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
525 // Floating-point to integer conversions.
526 // RTABI chapter 4.1.2, Table 6
527 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
528 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
529 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
530 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
531 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
532 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
533 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
534 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
536 // Conversions between floating types.
537 // RTABI chapter 4.1.2, Table 7
538 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
539 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
540 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
542 // Integer to floating-point conversions.
543 // RTABI chapter 4.1.2, Table 8
544 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
545 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
546 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
547 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
548 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
549 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
550 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
551 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
553 // Long long helper functions
554 // RTABI chapter 4.2, Table 9
555 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
556 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
557 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
558 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
560 // Integer division functions
561 // RTABI chapter 4.3.1
562 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
563 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
564 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
565 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
566 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
567 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
568 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
569 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
572 for (const auto &LC : LibraryCalls) {
573 setLibcallName(LC.Op, LC.Name);
574 setLibcallCallingConv(LC.Op, LC.CC);
575 if (LC.Cond != ISD::SETCC_INVALID)
576 setCmpLibcallCC(LC.Op, LC.Cond);
579 // EABI dependent RTLIB
580 if (TM.Options.EABIVersion == EABI::EABI4 ||
581 TM.Options.EABIVersion == EABI::EABI5) {
582 static const struct {
583 const RTLIB::Libcall Op;
584 const char *const Name;
585 const CallingConv::ID CC;
586 const ISD::CondCode Cond;
587 } MemOpsLibraryCalls[] = {
588 // Memory operations
589 // RTABI chapter 4.3.4
590 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
591 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
592 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
595 for (const auto &LC : MemOpsLibraryCalls) {
596 setLibcallName(LC.Op, LC.Name);
597 setLibcallCallingConv(LC.Op, LC.CC);
598 if (LC.Cond != ISD::SETCC_INVALID)
599 setCmpLibcallCC(LC.Op, LC.Cond);
604 if (Subtarget->isTargetWindows()) {
605 static const struct {
606 const RTLIB::Libcall Op;
607 const char * const Name;
608 const CallingConv::ID CC;
609 } LibraryCalls[] = {
610 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
611 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
612 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
613 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
614 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
615 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
616 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
617 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
620 for (const auto &LC : LibraryCalls) {
621 setLibcallName(LC.Op, LC.Name);
622 setLibcallCallingConv(LC.Op, LC.CC);
626 // Use divmod compiler-rt calls for iOS 5.0 and later.
627 if (Subtarget->isTargetMachO() &&
628 !(Subtarget->isTargetIOS() &&
629 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
630 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
631 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
634 // The half <-> float conversion functions are always soft-float on
635 // non-watchos platforms, but are needed for some targets which use a
636 // hard-float calling convention by default.
637 if (!Subtarget->isTargetWatchABI()) {
638 if (Subtarget->isAAPCS_ABI()) {
639 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
640 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
641 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
642 } else {
643 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
644 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
645 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
649 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
650 // a __gnu_ prefix (which is the default).
651 if (Subtarget->isTargetAEABI()) {
652 static const struct {
653 const RTLIB::Libcall Op;
654 const char * const Name;
655 const CallingConv::ID CC;
656 } LibraryCalls[] = {
657 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
658 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
659 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
662 for (const auto &LC : LibraryCalls) {
663 setLibcallName(LC.Op, LC.Name);
664 setLibcallCallingConv(LC.Op, LC.CC);
668 if (Subtarget->isThumb1Only())
669 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
670 else
671 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
673 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
674 Subtarget->hasFPRegs()) {
675 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
676 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
677 if (!Subtarget->hasVFP2Base())
678 setAllExpand(MVT::f32);
679 if (!Subtarget->hasFP64())
680 setAllExpand(MVT::f64);
683 if (Subtarget->hasFullFP16()) {
684 addRegisterClass(MVT::f16, &ARM::HPRRegClass);
685 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
686 setOperationAction(ISD::BITCAST, MVT::i32, Custom);
687 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
689 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
690 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
693 for (MVT VT : MVT::vector_valuetypes()) {
694 for (MVT InnerVT : MVT::vector_valuetypes()) {
695 setTruncStoreAction(VT, InnerVT, Expand);
696 addAllExtLoads(VT, InnerVT, Expand);
699 setOperationAction(ISD::MULHS, VT, Expand);
700 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701 setOperationAction(ISD::MULHU, VT, Expand);
702 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
704 setOperationAction(ISD::BSWAP, VT, Expand);
707 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
708 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
710 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
711 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
713 if (Subtarget->hasMVEIntegerOps())
714 addMVEVectorTypes(Subtarget->hasMVEFloatOps());
716 // Combine low-overhead loop intrinsics so that we can lower i1 types.
717 if (Subtarget->hasLOB()) {
718 setTargetDAGCombine(ISD::BRCOND);
719 setTargetDAGCombine(ISD::BR_CC);
722 if (Subtarget->hasNEON()) {
723 addDRTypeForNEON(MVT::v2f32);
724 addDRTypeForNEON(MVT::v8i8);
725 addDRTypeForNEON(MVT::v4i16);
726 addDRTypeForNEON(MVT::v2i32);
727 addDRTypeForNEON(MVT::v1i64);
729 addQRTypeForNEON(MVT::v4f32);
730 addQRTypeForNEON(MVT::v2f64);
731 addQRTypeForNEON(MVT::v16i8);
732 addQRTypeForNEON(MVT::v8i16);
733 addQRTypeForNEON(MVT::v4i32);
734 addQRTypeForNEON(MVT::v2i64);
736 if (Subtarget->hasFullFP16()) {
737 addQRTypeForNEON(MVT::v8f16);
738 addDRTypeForNEON(MVT::v4f16);
742 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
743 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
744 // none of Neon, MVE or VFP supports any arithmetic operations on it.
745 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
746 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
747 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
748 // FIXME: Code duplication: FDIV and FREM are expanded always, see
749 // ARMTargetLowering::addTypeForNEON method for details.
750 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
751 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
752 // FIXME: Create unittest.
753 // In another words, find a way when "copysign" appears in DAG with vector
754 // operands.
755 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
756 // FIXME: Code duplication: SETCC has custom operation action, see
757 // ARMTargetLowering::addTypeForNEON method for details.
758 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
759 // FIXME: Create unittest for FNEG and for FABS.
760 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
761 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
762 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
763 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
764 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
765 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
766 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
767 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
768 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
769 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
770 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
771 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
772 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
773 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
774 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
775 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
776 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
777 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
780 if (Subtarget->hasNEON()) {
781 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
782 // supported for v4f32.
783 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
784 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
785 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
786 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
787 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
788 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
789 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
790 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
791 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
792 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
793 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
794 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
795 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
796 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
798 // Mark v2f32 intrinsics.
799 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
800 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
801 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
802 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
803 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
804 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
805 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
806 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
807 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
808 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
809 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
810 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
811 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
812 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
814 // Neon does not support some operations on v1i64 and v2i64 types.
815 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
816 // Custom handling for some quad-vector types to detect VMULL.
817 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
818 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
819 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
820 // Custom handling for some vector types to avoid expensive expansions
821 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
822 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
823 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
824 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
825 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
826 // a destination type that is wider than the source, and nor does
827 // it have a FP_TO_[SU]INT instruction with a narrower destination than
828 // source.
829 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
830 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
831 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
832 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
833 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
834 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
835 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
836 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
838 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
839 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
841 // NEON does not have single instruction CTPOP for vectors with element
842 // types wider than 8-bits. However, custom lowering can leverage the
843 // v8i8/v16i8 vcnt instruction.
844 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
845 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
846 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
847 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
848 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom);
849 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
851 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
852 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
854 // NEON does not have single instruction CTTZ for vectors.
855 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
856 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
857 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
858 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
860 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
861 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
862 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
863 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
865 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
866 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
867 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
868 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
870 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
871 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
872 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
873 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
875 // NEON only has FMA instructions as of VFP4.
876 if (!Subtarget->hasVFP4Base()) {
877 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
878 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
881 setTargetDAGCombine(ISD::INTRINSIC_VOID);
882 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
883 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
884 setTargetDAGCombine(ISD::SHL);
885 setTargetDAGCombine(ISD::SRL);
886 setTargetDAGCombine(ISD::SRA);
887 setTargetDAGCombine(ISD::SIGN_EXTEND);
888 setTargetDAGCombine(ISD::ZERO_EXTEND);
889 setTargetDAGCombine(ISD::ANY_EXTEND);
890 setTargetDAGCombine(ISD::STORE);
891 setTargetDAGCombine(ISD::FP_TO_SINT);
892 setTargetDAGCombine(ISD::FP_TO_UINT);
893 setTargetDAGCombine(ISD::FDIV);
894 setTargetDAGCombine(ISD::LOAD);
896 // It is legal to extload from v4i8 to v4i16 or v4i32.
897 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
898 MVT::v2i32}) {
899 for (MVT VT : MVT::integer_vector_valuetypes()) {
900 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
901 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
902 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
907 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
908 setTargetDAGCombine(ISD::BUILD_VECTOR);
909 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
910 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
913 if (!Subtarget->hasFP64()) {
914 // When targeting a floating-point unit with only single-precision
915 // operations, f64 is legal for the few double-precision instructions which
916 // are present However, no double-precision operations other than moves,
917 // loads and stores are provided by the hardware.
918 setOperationAction(ISD::FADD, MVT::f64, Expand);
919 setOperationAction(ISD::FSUB, MVT::f64, Expand);
920 setOperationAction(ISD::FMUL, MVT::f64, Expand);
921 setOperationAction(ISD::FMA, MVT::f64, Expand);
922 setOperationAction(ISD::FDIV, MVT::f64, Expand);
923 setOperationAction(ISD::FREM, MVT::f64, Expand);
924 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
925 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
926 setOperationAction(ISD::FNEG, MVT::f64, Expand);
927 setOperationAction(ISD::FABS, MVT::f64, Expand);
928 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
929 setOperationAction(ISD::FSIN, MVT::f64, Expand);
930 setOperationAction(ISD::FCOS, MVT::f64, Expand);
931 setOperationAction(ISD::FPOW, MVT::f64, Expand);
932 setOperationAction(ISD::FLOG, MVT::f64, Expand);
933 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
934 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
935 setOperationAction(ISD::FEXP, MVT::f64, Expand);
936 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
937 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
938 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
939 setOperationAction(ISD::FRINT, MVT::f64, Expand);
940 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
941 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
942 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
943 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
944 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
945 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
946 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
947 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
948 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
951 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
952 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
953 if (Subtarget->hasFullFP16())
954 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
957 if (!Subtarget->hasFP16())
958 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom);
960 if (!Subtarget->hasFP64())
961 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
963 computeRegisterProperties(Subtarget->getRegisterInfo());
965 // ARM does not have floating-point extending loads.
966 for (MVT VT : MVT::fp_valuetypes()) {
967 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
968 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
971 // ... or truncating stores
972 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
973 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
974 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
976 // ARM does not have i1 sign extending load.
977 for (MVT VT : MVT::integer_valuetypes())
978 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
980 // ARM supports all 4 flavors of integer indexed load / store.
981 if (!Subtarget->isThumb1Only()) {
982 for (unsigned im = (unsigned)ISD::PRE_INC;
983 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
984 setIndexedLoadAction(im, MVT::i1, Legal);
985 setIndexedLoadAction(im, MVT::i8, Legal);
986 setIndexedLoadAction(im, MVT::i16, Legal);
987 setIndexedLoadAction(im, MVT::i32, Legal);
988 setIndexedStoreAction(im, MVT::i1, Legal);
989 setIndexedStoreAction(im, MVT::i8, Legal);
990 setIndexedStoreAction(im, MVT::i16, Legal);
991 setIndexedStoreAction(im, MVT::i32, Legal);
993 } else {
994 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
995 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
996 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
999 setOperationAction(ISD::SADDO, MVT::i32, Custom);
1000 setOperationAction(ISD::UADDO, MVT::i32, Custom);
1001 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1002 setOperationAction(ISD::USUBO, MVT::i32, Custom);
1004 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1005 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1007 // i64 operation support.
1008 setOperationAction(ISD::MUL, MVT::i64, Expand);
1009 setOperationAction(ISD::MULHU, MVT::i32, Expand);
1010 if (Subtarget->isThumb1Only()) {
1011 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1012 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1014 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1015 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1016 setOperationAction(ISD::MULHS, MVT::i32, Expand);
1018 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1019 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1020 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1021 setOperationAction(ISD::SRL, MVT::i64, Custom);
1022 setOperationAction(ISD::SRA, MVT::i64, Custom);
1023 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1024 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1026 // MVE lowers 64 bit shifts to lsll and lsrl
1027 // assuming that ISD::SRL and SRA of i64 are already marked custom
1028 if (Subtarget->hasMVEIntegerOps())
1029 setOperationAction(ISD::SHL, MVT::i64, Custom);
1031 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1032 if (Subtarget->isThumb1Only()) {
1033 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1034 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1035 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1038 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1039 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1041 // ARM does not have ROTL.
1042 setOperationAction(ISD::ROTL, MVT::i32, Expand);
1043 for (MVT VT : MVT::vector_valuetypes()) {
1044 setOperationAction(ISD::ROTL, VT, Expand);
1045 setOperationAction(ISD::ROTR, VT, Expand);
1047 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
1048 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1049 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1050 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1051 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1054 // @llvm.readcyclecounter requires the Performance Monitors extension.
1055 // Default to the 0 expansion on unsupported platforms.
1056 // FIXME: Technically there are older ARM CPUs that have
1057 // implementation-specific ways of obtaining this information.
1058 if (Subtarget->hasPerfMon())
1059 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1061 // Only ARMv6 has BSWAP.
1062 if (!Subtarget->hasV6Ops())
1063 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1065 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1066 : Subtarget->hasDivideInARMMode();
1067 if (!hasDivide) {
1068 // These are expanded into libcalls if the cpu doesn't have HW divider.
1069 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
1070 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
1073 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1074 setOperationAction(ISD::SDIV, MVT::i32, Custom);
1075 setOperationAction(ISD::UDIV, MVT::i32, Custom);
1077 setOperationAction(ISD::SDIV, MVT::i64, Custom);
1078 setOperationAction(ISD::UDIV, MVT::i64, Custom);
1081 setOperationAction(ISD::SREM, MVT::i32, Expand);
1082 setOperationAction(ISD::UREM, MVT::i32, Expand);
1084 // Register based DivRem for AEABI (RTABI 4.2)
1085 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1086 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1087 Subtarget->isTargetWindows()) {
1088 setOperationAction(ISD::SREM, MVT::i64, Custom);
1089 setOperationAction(ISD::UREM, MVT::i64, Custom);
1090 HasStandaloneRem = false;
1092 if (Subtarget->isTargetWindows()) {
1093 const struct {
1094 const RTLIB::Libcall Op;
1095 const char * const Name;
1096 const CallingConv::ID CC;
1097 } LibraryCalls[] = {
1098 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1099 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1100 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1101 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1103 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1104 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1105 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1106 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1109 for (const auto &LC : LibraryCalls) {
1110 setLibcallName(LC.Op, LC.Name);
1111 setLibcallCallingConv(LC.Op, LC.CC);
1113 } else {
1114 const struct {
1115 const RTLIB::Libcall Op;
1116 const char * const Name;
1117 const CallingConv::ID CC;
1118 } LibraryCalls[] = {
1119 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1120 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1121 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1122 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1124 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1125 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1126 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1127 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1130 for (const auto &LC : LibraryCalls) {
1131 setLibcallName(LC.Op, LC.Name);
1132 setLibcallCallingConv(LC.Op, LC.CC);
1136 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1137 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1138 setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1139 setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1140 } else {
1141 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1142 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1145 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
1146 for (auto &VT : {MVT::f32, MVT::f64})
1147 setOperationAction(ISD::FPOWI, VT, Custom);
1149 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1150 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
1151 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1152 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1154 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1155 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1157 // Use the default implementation.
1158 setOperationAction(ISD::VASTART, MVT::Other, Custom);
1159 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1160 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
1161 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1162 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1163 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1165 if (Subtarget->isTargetWindows())
1166 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1167 else
1168 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1170 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1171 // the default expansion.
1172 InsertFencesForAtomic = false;
1173 if (Subtarget->hasAnyDataBarrier() &&
1174 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1175 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1176 // to ldrex/strex loops already.
1177 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1178 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1179 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
1181 // On v8, we have particularly efficient implementations of atomic fences
1182 // if they can be combined with nearby atomic loads and stores.
1183 if (!Subtarget->hasAcquireRelease() ||
1184 getTargetMachine().getOptLevel() == 0) {
1185 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1186 InsertFencesForAtomic = true;
1188 } else {
1189 // If there's anything we can use as a barrier, go through custom lowering
1190 // for ATOMIC_FENCE.
1191 // If target has DMB in thumb, Fences can be inserted.
1192 if (Subtarget->hasDataBarrier())
1193 InsertFencesForAtomic = true;
1195 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
1196 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1198 // Set them all for expansion, which will force libcalls.
1199 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
1200 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
1201 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
1202 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
1203 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
1204 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
1205 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
1206 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1207 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1208 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1209 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1210 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1211 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1212 // Unordered/Monotonic case.
1213 if (!InsertFencesForAtomic) {
1214 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1215 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1219 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
1221 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1222 if (!Subtarget->hasV6Ops()) {
1223 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1224 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
1226 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1228 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1229 !Subtarget->isThumb1Only()) {
1230 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1231 // iff target supports vfp2.
1232 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1233 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1236 // We want to custom lower some of our intrinsics.
1237 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1238 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1239 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1240 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1241 if (Subtarget->useSjLjEH())
1242 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1244 setOperationAction(ISD::SETCC, MVT::i32, Expand);
1245 setOperationAction(ISD::SETCC, MVT::f32, Expand);
1246 setOperationAction(ISD::SETCC, MVT::f64, Expand);
1247 setOperationAction(ISD::SELECT, MVT::i32, Custom);
1248 setOperationAction(ISD::SELECT, MVT::f32, Custom);
1249 setOperationAction(ISD::SELECT, MVT::f64, Custom);
1250 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1251 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1252 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1253 if (Subtarget->hasFullFP16()) {
1254 setOperationAction(ISD::SETCC, MVT::f16, Expand);
1255 setOperationAction(ISD::SELECT, MVT::f16, Custom);
1256 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1259 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1261 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
1262 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1263 if (Subtarget->hasFullFP16())
1264 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
1265 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1266 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1267 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1269 // We don't support sin/cos/fmod/copysign/pow
1270 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1271 setOperationAction(ISD::FSIN, MVT::f32, Expand);
1272 setOperationAction(ISD::FCOS, MVT::f32, Expand);
1273 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1274 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1275 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1276 setOperationAction(ISD::FREM, MVT::f64, Expand);
1277 setOperationAction(ISD::FREM, MVT::f32, Expand);
1278 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1279 !Subtarget->isThumb1Only()) {
1280 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1281 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1283 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1284 setOperationAction(ISD::FPOW, MVT::f32, Expand);
1286 if (!Subtarget->hasVFP4Base()) {
1287 setOperationAction(ISD::FMA, MVT::f64, Expand);
1288 setOperationAction(ISD::FMA, MVT::f32, Expand);
1291 // Various VFP goodness
1292 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1293 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1294 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1295 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1296 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1299 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1300 if (!Subtarget->hasFP16()) {
1301 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1302 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1306 // Use __sincos_stret if available.
1307 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1308 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1309 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1310 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1313 // FP-ARMv8 implements a lot of rounding-like FP operations.
1314 if (Subtarget->hasFPARMv8Base()) {
1315 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1316 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1317 setOperationAction(ISD::FROUND, MVT::f32, Legal);
1318 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1319 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1320 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1321 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1322 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1323 if (Subtarget->hasNEON()) {
1324 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1325 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1326 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1327 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1330 if (Subtarget->hasFP64()) {
1331 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1332 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1333 setOperationAction(ISD::FROUND, MVT::f64, Legal);
1334 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1335 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1336 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1337 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1338 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1342 // FP16 often need to be promoted to call lib functions
1343 if (Subtarget->hasFullFP16()) {
1344 setOperationAction(ISD::FREM, MVT::f16, Promote);
1345 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1346 setOperationAction(ISD::FSIN, MVT::f16, Promote);
1347 setOperationAction(ISD::FCOS, MVT::f16, Promote);
1348 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1349 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1350 setOperationAction(ISD::FPOW, MVT::f16, Promote);
1351 setOperationAction(ISD::FEXP, MVT::f16, Promote);
1352 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1353 setOperationAction(ISD::FLOG, MVT::f16, Promote);
1354 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1355 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1357 setOperationAction(ISD::FROUND, MVT::f16, Legal);
1360 if (Subtarget->hasNEON()) {
1361 // vmin and vmax aren't available in a scalar form, so we use
1362 // a NEON instruction with an undef lane instead.
1363 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1364 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1365 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1366 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1367 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1368 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1369 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1370 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1372 if (Subtarget->hasFullFP16()) {
1373 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1374 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1375 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1376 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1378 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1379 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1380 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1381 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1385 // We have target-specific dag combine patterns for the following nodes:
1386 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1387 setTargetDAGCombine(ISD::ADD);
1388 setTargetDAGCombine(ISD::SUB);
1389 setTargetDAGCombine(ISD::MUL);
1390 setTargetDAGCombine(ISD::AND);
1391 setTargetDAGCombine(ISD::OR);
1392 setTargetDAGCombine(ISD::XOR);
1394 if (Subtarget->hasV6Ops())
1395 setTargetDAGCombine(ISD::SRL);
1396 if (Subtarget->isThumb1Only())
1397 setTargetDAGCombine(ISD::SHL);
1399 setStackPointerRegisterToSaveRestore(ARM::SP);
1401 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1402 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1403 setSchedulingPreference(Sched::RegPressure);
1404 else
1405 setSchedulingPreference(Sched::Hybrid);
1407 //// temporary - rewrite interface to use type
1408 MaxStoresPerMemset = 8;
1409 MaxStoresPerMemsetOptSize = 4;
1410 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1411 MaxStoresPerMemcpyOptSize = 2;
1412 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1413 MaxStoresPerMemmoveOptSize = 2;
1415 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1416 // are at least 4 bytes aligned.
1417 setMinStackArgumentAlignment(4);
1419 // Prefer likely predicted branches to selects on out-of-order cores.
1420 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1422 setPrefLoopAlignment(
1423 llvm::Align(1UL << Subtarget->getPrefLoopLogAlignment()));
1425 setMinFunctionAlignment(Subtarget->isThumb() ? llvm::Align(2)
1426 : llvm::Align(4));
1428 if (Subtarget->isThumb() || Subtarget->isThumb2())
1429 setTargetDAGCombine(ISD::ABS);
1432 bool ARMTargetLowering::useSoftFloat() const {
1433 return Subtarget->useSoftFloat();
1436 // FIXME: It might make sense to define the representative register class as the
1437 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1438 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1439 // SPR's representative would be DPR_VFP2. This should work well if register
1440 // pressure tracking were modified such that a register use would increment the
1441 // pressure of the register class's representative and all of it's super
1442 // classes' representatives transitively. We have not implemented this because
1443 // of the difficulty prior to coalescing of modeling operand register classes
1444 // due to the common occurrence of cross class copies and subregister insertions
1445 // and extractions.
1446 std::pair<const TargetRegisterClass *, uint8_t>
1447 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1448 MVT VT) const {
1449 const TargetRegisterClass *RRC = nullptr;
1450 uint8_t Cost = 1;
1451 switch (VT.SimpleTy) {
1452 default:
1453 return TargetLowering::findRepresentativeClass(TRI, VT);
1454 // Use DPR as representative register class for all floating point
1455 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1456 // the cost is 1 for both f32 and f64.
1457 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1458 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1459 RRC = &ARM::DPRRegClass;
1460 // When NEON is used for SP, only half of the register file is available
1461 // because operations that define both SP and DP results will be constrained
1462 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1463 // coalescing by double-counting the SP regs. See the FIXME above.
1464 if (Subtarget->useNEONForSinglePrecisionFP())
1465 Cost = 2;
1466 break;
1467 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1468 case MVT::v4f32: case MVT::v2f64:
1469 RRC = &ARM::DPRRegClass;
1470 Cost = 2;
1471 break;
1472 case MVT::v4i64:
1473 RRC = &ARM::DPRRegClass;
1474 Cost = 4;
1475 break;
1476 case MVT::v8i64:
1477 RRC = &ARM::DPRRegClass;
1478 Cost = 8;
1479 break;
1481 return std::make_pair(RRC, Cost);
1484 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1485 switch ((ARMISD::NodeType)Opcode) {
1486 case ARMISD::FIRST_NUMBER: break;
1487 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1488 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1489 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1490 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1491 case ARMISD::CALL: return "ARMISD::CALL";
1492 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1493 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1494 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1495 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1496 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1497 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1498 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1499 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1500 case ARMISD::CMP: return "ARMISD::CMP";
1501 case ARMISD::CMN: return "ARMISD::CMN";
1502 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1503 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1504 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1505 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1506 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1508 case ARMISD::CMOV: return "ARMISD::CMOV";
1509 case ARMISD::SUBS: return "ARMISD::SUBS";
1511 case ARMISD::SSAT: return "ARMISD::SSAT";
1512 case ARMISD::USAT: return "ARMISD::USAT";
1514 case ARMISD::ASRL: return "ARMISD::ASRL";
1515 case ARMISD::LSRL: return "ARMISD::LSRL";
1516 case ARMISD::LSLL: return "ARMISD::LSLL";
1518 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1519 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1520 case ARMISD::RRX: return "ARMISD::RRX";
1522 case ARMISD::ADDC: return "ARMISD::ADDC";
1523 case ARMISD::ADDE: return "ARMISD::ADDE";
1524 case ARMISD::SUBC: return "ARMISD::SUBC";
1525 case ARMISD::SUBE: return "ARMISD::SUBE";
1526 case ARMISD::LSLS: return "ARMISD::LSLS";
1528 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1529 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1530 case ARMISD::VMOVhr: return "ARMISD::VMOVhr";
1531 case ARMISD::VMOVrh: return "ARMISD::VMOVrh";
1532 case ARMISD::VMOVSR: return "ARMISD::VMOVSR";
1534 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1535 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1536 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1538 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1540 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1542 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1544 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1546 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1548 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK";
1549 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1551 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST";
1552 case ARMISD::VCMP: return "ARMISD::VCMP";
1553 case ARMISD::VCMPZ: return "ARMISD::VCMPZ";
1554 case ARMISD::VTST: return "ARMISD::VTST";
1556 case ARMISD::VSHLs: return "ARMISD::VSHLs";
1557 case ARMISD::VSHLu: return "ARMISD::VSHLu";
1558 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM";
1559 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM";
1560 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM";
1561 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM";
1562 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM";
1563 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM";
1564 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM";
1565 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM";
1566 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM";
1567 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM";
1568 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM";
1569 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM";
1570 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM";
1571 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM";
1572 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM";
1573 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM";
1574 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM";
1575 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1576 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1577 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1578 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1579 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1580 case ARMISD::VDUP: return "ARMISD::VDUP";
1581 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1582 case ARMISD::VEXT: return "ARMISD::VEXT";
1583 case ARMISD::VREV64: return "ARMISD::VREV64";
1584 case ARMISD::VREV32: return "ARMISD::VREV32";
1585 case ARMISD::VREV16: return "ARMISD::VREV16";
1586 case ARMISD::VZIP: return "ARMISD::VZIP";
1587 case ARMISD::VUZP: return "ARMISD::VUZP";
1588 case ARMISD::VTRN: return "ARMISD::VTRN";
1589 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1590 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1591 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1592 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1593 case ARMISD::UMAAL: return "ARMISD::UMAAL";
1594 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1595 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1596 case ARMISD::SMLALBB: return "ARMISD::SMLALBB";
1597 case ARMISD::SMLALBT: return "ARMISD::SMLALBT";
1598 case ARMISD::SMLALTB: return "ARMISD::SMLALTB";
1599 case ARMISD::SMLALTT: return "ARMISD::SMLALTT";
1600 case ARMISD::SMULWB: return "ARMISD::SMULWB";
1601 case ARMISD::SMULWT: return "ARMISD::SMULWT";
1602 case ARMISD::SMLALD: return "ARMISD::SMLALD";
1603 case ARMISD::SMLALDX: return "ARMISD::SMLALDX";
1604 case ARMISD::SMLSLD: return "ARMISD::SMLSLD";
1605 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX";
1606 case ARMISD::SMMLAR: return "ARMISD::SMMLAR";
1607 case ARMISD::SMMLSR: return "ARMISD::SMMLSR";
1608 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1609 case ARMISD::BFI: return "ARMISD::BFI";
1610 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1611 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1612 case ARMISD::VBSL: return "ARMISD::VBSL";
1613 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1614 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP";
1615 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1616 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1617 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1618 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1619 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1620 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1621 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1622 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1623 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1624 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1625 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD";
1626 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1627 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1628 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1629 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1630 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1631 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1632 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1633 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1634 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1635 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1636 case ARMISD::WLS: return "ARMISD::WLS";
1637 case ARMISD::LE: return "ARMISD::LE";
1638 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC";
1639 case ARMISD::CSINV: return "ARMISD::CSINV";
1640 case ARMISD::CSNEG: return "ARMISD::CSNEG";
1641 case ARMISD::CSINC: return "ARMISD::CSINC";
1643 return nullptr;
1646 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1647 EVT VT) const {
1648 if (!VT.isVector())
1649 return getPointerTy(DL);
1651 // MVE has a predicate register.
1652 if (Subtarget->hasMVEIntegerOps() &&
1653 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1654 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1655 return VT.changeVectorElementTypeToInteger();
1658 /// getRegClassFor - Return the register class that should be used for the
1659 /// specified value type.
1660 const TargetRegisterClass *
1661 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1662 (void)isDivergent;
1663 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1664 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1665 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1666 // MVE Q registers.
1667 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1668 if (VT == MVT::v4i64)
1669 return &ARM::QQPRRegClass;
1670 if (VT == MVT::v8i64)
1671 return &ARM::QQQQPRRegClass;
1673 return TargetLowering::getRegClassFor(VT);
1676 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1677 // source/dest is aligned and the copy size is large enough. We therefore want
1678 // to align such objects passed to memory intrinsics.
1679 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1680 unsigned &PrefAlign) const {
1681 if (!isa<MemIntrinsic>(CI))
1682 return false;
1683 MinSize = 8;
1684 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1685 // cycle faster than 4-byte aligned LDM.
1686 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1687 return true;
1690 // Create a fast isel object.
1691 FastISel *
1692 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1693 const TargetLibraryInfo *libInfo) const {
1694 return ARM::createFastISel(funcInfo, libInfo);
1697 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1698 unsigned NumVals = N->getNumValues();
1699 if (!NumVals)
1700 return Sched::RegPressure;
1702 for (unsigned i = 0; i != NumVals; ++i) {
1703 EVT VT = N->getValueType(i);
1704 if (VT == MVT::Glue || VT == MVT::Other)
1705 continue;
1706 if (VT.isFloatingPoint() || VT.isVector())
1707 return Sched::ILP;
1710 if (!N->isMachineOpcode())
1711 return Sched::RegPressure;
1713 // Load are scheduled for latency even if there instruction itinerary
1714 // is not available.
1715 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1716 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1718 if (MCID.getNumDefs() == 0)
1719 return Sched::RegPressure;
1720 if (!Itins->isEmpty() &&
1721 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1722 return Sched::ILP;
1724 return Sched::RegPressure;
1727 //===----------------------------------------------------------------------===//
1728 // Lowering Code
1729 //===----------------------------------------------------------------------===//
1731 static bool isSRL16(const SDValue &Op) {
1732 if (Op.getOpcode() != ISD::SRL)
1733 return false;
1734 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1735 return Const->getZExtValue() == 16;
1736 return false;
1739 static bool isSRA16(const SDValue &Op) {
1740 if (Op.getOpcode() != ISD::SRA)
1741 return false;
1742 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1743 return Const->getZExtValue() == 16;
1744 return false;
1747 static bool isSHL16(const SDValue &Op) {
1748 if (Op.getOpcode() != ISD::SHL)
1749 return false;
1750 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1751 return Const->getZExtValue() == 16;
1752 return false;
1755 // Check for a signed 16-bit value. We special case SRA because it makes it
1756 // more simple when also looking for SRAs that aren't sign extending a
1757 // smaller value. Without the check, we'd need to take extra care with
1758 // checking order for some operations.
1759 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1760 if (isSRA16(Op))
1761 return isSHL16(Op.getOperand(0));
1762 return DAG.ComputeNumSignBits(Op) == 17;
1765 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1766 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1767 switch (CC) {
1768 default: llvm_unreachable("Unknown condition code!");
1769 case ISD::SETNE: return ARMCC::NE;
1770 case ISD::SETEQ: return ARMCC::EQ;
1771 case ISD::SETGT: return ARMCC::GT;
1772 case ISD::SETGE: return ARMCC::GE;
1773 case ISD::SETLT: return ARMCC::LT;
1774 case ISD::SETLE: return ARMCC::LE;
1775 case ISD::SETUGT: return ARMCC::HI;
1776 case ISD::SETUGE: return ARMCC::HS;
1777 case ISD::SETULT: return ARMCC::LO;
1778 case ISD::SETULE: return ARMCC::LS;
1782 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1783 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1784 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1785 CondCode2 = ARMCC::AL;
1786 InvalidOnQNaN = true;
1787 switch (CC) {
1788 default: llvm_unreachable("Unknown FP condition!");
1789 case ISD::SETEQ:
1790 case ISD::SETOEQ:
1791 CondCode = ARMCC::EQ;
1792 InvalidOnQNaN = false;
1793 break;
1794 case ISD::SETGT:
1795 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1796 case ISD::SETGE:
1797 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1798 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1799 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1800 case ISD::SETONE:
1801 CondCode = ARMCC::MI;
1802 CondCode2 = ARMCC::GT;
1803 InvalidOnQNaN = false;
1804 break;
1805 case ISD::SETO: CondCode = ARMCC::VC; break;
1806 case ISD::SETUO: CondCode = ARMCC::VS; break;
1807 case ISD::SETUEQ:
1808 CondCode = ARMCC::EQ;
1809 CondCode2 = ARMCC::VS;
1810 InvalidOnQNaN = false;
1811 break;
1812 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1813 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1814 case ISD::SETLT:
1815 case ISD::SETULT: CondCode = ARMCC::LT; break;
1816 case ISD::SETLE:
1817 case ISD::SETULE: CondCode = ARMCC::LE; break;
1818 case ISD::SETNE:
1819 case ISD::SETUNE:
1820 CondCode = ARMCC::NE;
1821 InvalidOnQNaN = false;
1822 break;
1826 //===----------------------------------------------------------------------===//
1827 // Calling Convention Implementation
1828 //===----------------------------------------------------------------------===//
1830 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1831 /// account presence of floating point hardware and calling convention
1832 /// limitations, such as support for variadic functions.
1833 CallingConv::ID
1834 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1835 bool isVarArg) const {
1836 switch (CC) {
1837 default:
1838 report_fatal_error("Unsupported calling convention");
1839 case CallingConv::ARM_AAPCS:
1840 case CallingConv::ARM_APCS:
1841 case CallingConv::GHC:
1842 return CC;
1843 case CallingConv::PreserveMost:
1844 return CallingConv::PreserveMost;
1845 case CallingConv::ARM_AAPCS_VFP:
1846 case CallingConv::Swift:
1847 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1848 case CallingConv::C:
1849 if (!Subtarget->isAAPCS_ABI())
1850 return CallingConv::ARM_APCS;
1851 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1852 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1853 !isVarArg)
1854 return CallingConv::ARM_AAPCS_VFP;
1855 else
1856 return CallingConv::ARM_AAPCS;
1857 case CallingConv::Fast:
1858 case CallingConv::CXX_FAST_TLS:
1859 if (!Subtarget->isAAPCS_ABI()) {
1860 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
1861 return CallingConv::Fast;
1862 return CallingConv::ARM_APCS;
1863 } else if (Subtarget->hasVFP2Base() &&
1864 !Subtarget->isThumb1Only() && !isVarArg)
1865 return CallingConv::ARM_AAPCS_VFP;
1866 else
1867 return CallingConv::ARM_AAPCS;
1871 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1872 bool isVarArg) const {
1873 return CCAssignFnForNode(CC, false, isVarArg);
1876 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1877 bool isVarArg) const {
1878 return CCAssignFnForNode(CC, true, isVarArg);
1881 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1882 /// CallingConvention.
1883 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1884 bool Return,
1885 bool isVarArg) const {
1886 switch (getEffectiveCallingConv(CC, isVarArg)) {
1887 default:
1888 report_fatal_error("Unsupported calling convention");
1889 case CallingConv::ARM_APCS:
1890 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1891 case CallingConv::ARM_AAPCS:
1892 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1893 case CallingConv::ARM_AAPCS_VFP:
1894 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1895 case CallingConv::Fast:
1896 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1897 case CallingConv::GHC:
1898 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1899 case CallingConv::PreserveMost:
1900 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1904 /// LowerCallResult - Lower the result values of a call into the
1905 /// appropriate copies out of appropriate physical registers.
1906 SDValue ARMTargetLowering::LowerCallResult(
1907 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1908 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1909 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1910 SDValue ThisVal) const {
1911 // Assign locations to each value returned by this call.
1912 SmallVector<CCValAssign, 16> RVLocs;
1913 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1914 *DAG.getContext());
1915 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1917 // Copy all of the result registers out of their specified physreg.
1918 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1919 CCValAssign VA = RVLocs[i];
1921 // Pass 'this' value directly from the argument to return value, to avoid
1922 // reg unit interference
1923 if (i == 0 && isThisReturn) {
1924 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1925 "unexpected return calling convention register assignment");
1926 InVals.push_back(ThisVal);
1927 continue;
1930 SDValue Val;
1931 if (VA.needsCustom()) {
1932 // Handle f64 or half of a v2f64.
1933 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1934 InFlag);
1935 Chain = Lo.getValue(1);
1936 InFlag = Lo.getValue(2);
1937 VA = RVLocs[++i]; // skip ahead to next loc
1938 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1939 InFlag);
1940 Chain = Hi.getValue(1);
1941 InFlag = Hi.getValue(2);
1942 if (!Subtarget->isLittle())
1943 std::swap (Lo, Hi);
1944 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1946 if (VA.getLocVT() == MVT::v2f64) {
1947 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1948 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1949 DAG.getConstant(0, dl, MVT::i32));
1951 VA = RVLocs[++i]; // skip ahead to next loc
1952 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1953 Chain = Lo.getValue(1);
1954 InFlag = Lo.getValue(2);
1955 VA = RVLocs[++i]; // skip ahead to next loc
1956 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1957 Chain = Hi.getValue(1);
1958 InFlag = Hi.getValue(2);
1959 if (!Subtarget->isLittle())
1960 std::swap (Lo, Hi);
1961 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1962 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1963 DAG.getConstant(1, dl, MVT::i32));
1965 } else {
1966 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1967 InFlag);
1968 Chain = Val.getValue(1);
1969 InFlag = Val.getValue(2);
1972 switch (VA.getLocInfo()) {
1973 default: llvm_unreachable("Unknown loc info!");
1974 case CCValAssign::Full: break;
1975 case CCValAssign::BCvt:
1976 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1977 break;
1980 InVals.push_back(Val);
1983 return Chain;
1986 /// LowerMemOpCallTo - Store the argument to the stack.
1987 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1988 SDValue Arg, const SDLoc &dl,
1989 SelectionDAG &DAG,
1990 const CCValAssign &VA,
1991 ISD::ArgFlagsTy Flags) const {
1992 unsigned LocMemOffset = VA.getLocMemOffset();
1993 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1994 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1995 StackPtr, PtrOff);
1996 return DAG.getStore(
1997 Chain, dl, Arg, PtrOff,
1998 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
2001 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2002 SDValue Chain, SDValue &Arg,
2003 RegsToPassVector &RegsToPass,
2004 CCValAssign &VA, CCValAssign &NextVA,
2005 SDValue &StackPtr,
2006 SmallVectorImpl<SDValue> &MemOpChains,
2007 ISD::ArgFlagsTy Flags) const {
2008 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2009 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2010 unsigned id = Subtarget->isLittle() ? 0 : 1;
2011 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2013 if (NextVA.isRegLoc())
2014 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2015 else {
2016 assert(NextVA.isMemLoc());
2017 if (!StackPtr.getNode())
2018 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2019 getPointerTy(DAG.getDataLayout()));
2021 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
2022 dl, DAG, NextVA,
2023 Flags));
2027 /// LowerCall - Lowering a call into a callseq_start <-
2028 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2029 /// nodes.
2030 SDValue
2031 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2032 SmallVectorImpl<SDValue> &InVals) const {
2033 SelectionDAG &DAG = CLI.DAG;
2034 SDLoc &dl = CLI.DL;
2035 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2036 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2037 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2038 SDValue Chain = CLI.Chain;
2039 SDValue Callee = CLI.Callee;
2040 bool &isTailCall = CLI.IsTailCall;
2041 CallingConv::ID CallConv = CLI.CallConv;
2042 bool doesNotRet = CLI.DoesNotReturn;
2043 bool isVarArg = CLI.IsVarArg;
2045 MachineFunction &MF = DAG.getMachineFunction();
2046 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2047 bool isThisReturn = false;
2048 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
2049 bool PreferIndirect = false;
2051 // Disable tail calls if they're not supported.
2052 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
2053 isTailCall = false;
2055 if (isa<GlobalAddressSDNode>(Callee)) {
2056 // If we're optimizing for minimum size and the function is called three or
2057 // more times in this block, we can improve codesize by calling indirectly
2058 // as BLXr has a 16-bit encoding.
2059 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2060 if (CLI.CS) {
2061 auto *BB = CLI.CS.getParent();
2062 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2063 count_if(GV->users(), [&BB](const User *U) {
2064 return isa<Instruction>(U) &&
2065 cast<Instruction>(U)->getParent() == BB;
2066 }) > 2;
2069 if (isTailCall) {
2070 // Check if it's really possible to do a tail call.
2071 isTailCall = IsEligibleForTailCallOptimization(
2072 Callee, CallConv, isVarArg, isStructRet,
2073 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2074 PreferIndirect);
2075 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
2076 report_fatal_error("failed to perform tail call elimination on a call "
2077 "site marked musttail");
2078 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2079 // detected sibcalls.
2080 if (isTailCall)
2081 ++NumTailCalls;
2084 // Analyze operands of the call, assigning locations to each operand.
2085 SmallVector<CCValAssign, 16> ArgLocs;
2086 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2087 *DAG.getContext());
2088 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2090 // Get a count of how many bytes are to be pushed on the stack.
2091 unsigned NumBytes = CCInfo.getNextStackOffset();
2093 if (isTailCall) {
2094 // For tail calls, memory operands are available in our caller's stack.
2095 NumBytes = 0;
2096 } else {
2097 // Adjust the stack pointer for the new arguments...
2098 // These operations are automatically eliminated by the prolog/epilog pass
2099 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2102 SDValue StackPtr =
2103 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2105 RegsToPassVector RegsToPass;
2106 SmallVector<SDValue, 8> MemOpChains;
2108 // Walk the register/memloc assignments, inserting copies/loads. In the case
2109 // of tail call optimization, arguments are handled later.
2110 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2111 i != e;
2112 ++i, ++realArgIdx) {
2113 CCValAssign &VA = ArgLocs[i];
2114 SDValue Arg = OutVals[realArgIdx];
2115 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2116 bool isByVal = Flags.isByVal();
2118 // Promote the value if needed.
2119 switch (VA.getLocInfo()) {
2120 default: llvm_unreachable("Unknown loc info!");
2121 case CCValAssign::Full: break;
2122 case CCValAssign::SExt:
2123 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2124 break;
2125 case CCValAssign::ZExt:
2126 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2127 break;
2128 case CCValAssign::AExt:
2129 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2130 break;
2131 case CCValAssign::BCvt:
2132 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2133 break;
2136 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2137 if (VA.needsCustom()) {
2138 if (VA.getLocVT() == MVT::v2f64) {
2139 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2140 DAG.getConstant(0, dl, MVT::i32));
2141 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2142 DAG.getConstant(1, dl, MVT::i32));
2144 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
2145 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2147 VA = ArgLocs[++i]; // skip ahead to next loc
2148 if (VA.isRegLoc()) {
2149 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
2150 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2151 } else {
2152 assert(VA.isMemLoc());
2154 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
2155 dl, DAG, VA, Flags));
2157 } else {
2158 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2159 StackPtr, MemOpChains, Flags);
2161 } else if (VA.isRegLoc()) {
2162 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2163 Outs[0].VT == MVT::i32) {
2164 assert(VA.getLocVT() == MVT::i32 &&
2165 "unexpected calling convention register assignment");
2166 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2167 "unexpected use of 'returned'");
2168 isThisReturn = true;
2170 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2171 } else if (isByVal) {
2172 assert(VA.isMemLoc());
2173 unsigned offset = 0;
2175 // True if this byval aggregate will be split between registers
2176 // and memory.
2177 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2178 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2180 if (CurByValIdx < ByValArgsCount) {
2182 unsigned RegBegin, RegEnd;
2183 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2185 EVT PtrVT =
2186 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2187 unsigned int i, j;
2188 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2189 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2190 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2191 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
2192 MachinePointerInfo(),
2193 DAG.InferPtrAlignment(AddArg));
2194 MemOpChains.push_back(Load.getValue(1));
2195 RegsToPass.push_back(std::make_pair(j, Load));
2198 // If parameter size outsides register area, "offset" value
2199 // helps us to calculate stack slot for remained part properly.
2200 offset = RegEnd - RegBegin;
2202 CCInfo.nextInRegsParam();
2205 if (Flags.getByValSize() > 4*offset) {
2206 auto PtrVT = getPointerTy(DAG.getDataLayout());
2207 unsigned LocMemOffset = VA.getLocMemOffset();
2208 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2209 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2210 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2211 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2212 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2213 MVT::i32);
2214 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
2215 MVT::i32);
2217 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2218 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2219 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2220 Ops));
2222 } else if (!isTailCall) {
2223 assert(VA.isMemLoc());
2225 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2226 dl, DAG, VA, Flags));
2230 if (!MemOpChains.empty())
2231 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2233 // Build a sequence of copy-to-reg nodes chained together with token chain
2234 // and flag operands which copy the outgoing args into the appropriate regs.
2235 SDValue InFlag;
2236 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2237 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2238 RegsToPass[i].second, InFlag);
2239 InFlag = Chain.getValue(1);
2242 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2243 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2244 // node so that legalize doesn't hack it.
2245 bool isDirect = false;
2247 const TargetMachine &TM = getTargetMachine();
2248 const Module *Mod = MF.getFunction().getParent();
2249 const GlobalValue *GV = nullptr;
2250 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2251 GV = G->getGlobal();
2252 bool isStub =
2253 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2255 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2256 bool isLocalARMFunc = false;
2257 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2258 auto PtrVt = getPointerTy(DAG.getDataLayout());
2260 if (Subtarget->genLongCalls()) {
2261 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2262 "long-calls codegen is not position independent!");
2263 // Handle a global address or an external symbol. If it's not one of
2264 // those, the target's already in a register, so we don't need to do
2265 // anything extra.
2266 if (isa<GlobalAddressSDNode>(Callee)) {
2267 // Create a constant pool entry for the callee address
2268 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2269 ARMConstantPoolValue *CPV =
2270 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2272 // Get the address of the callee into a register
2273 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2274 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2275 Callee = DAG.getLoad(
2276 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2277 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2278 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2279 const char *Sym = S->getSymbol();
2281 // Create a constant pool entry for the callee address
2282 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2283 ARMConstantPoolValue *CPV =
2284 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2285 ARMPCLabelIndex, 0);
2286 // Get the address of the callee into a register
2287 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2288 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2289 Callee = DAG.getLoad(
2290 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2291 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2293 } else if (isa<GlobalAddressSDNode>(Callee)) {
2294 if (!PreferIndirect) {
2295 isDirect = true;
2296 bool isDef = GV->isStrongDefinitionForLinker();
2298 // ARM call to a local ARM function is predicable.
2299 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2300 // tBX takes a register source operand.
2301 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2302 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2303 Callee = DAG.getNode(
2304 ARMISD::WrapperPIC, dl, PtrVt,
2305 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2306 Callee = DAG.getLoad(
2307 PtrVt, dl, DAG.getEntryNode(), Callee,
2308 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2309 /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2310 MachineMemOperand::MOInvariant);
2311 } else if (Subtarget->isTargetCOFF()) {
2312 assert(Subtarget->isTargetWindows() &&
2313 "Windows is the only supported COFF target");
2314 unsigned TargetFlags = GV->hasDLLImportStorageClass()
2315 ? ARMII::MO_DLLIMPORT
2316 : ARMII::MO_NO_FLAG;
2317 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2318 TargetFlags);
2319 if (GV->hasDLLImportStorageClass())
2320 Callee =
2321 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2322 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2323 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2324 } else {
2325 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2328 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2329 isDirect = true;
2330 // tBX takes a register source operand.
2331 const char *Sym = S->getSymbol();
2332 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2333 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2334 ARMConstantPoolValue *CPV =
2335 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2336 ARMPCLabelIndex, 4);
2337 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2338 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2339 Callee = DAG.getLoad(
2340 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2341 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2342 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2343 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2344 } else {
2345 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2349 // FIXME: handle tail calls differently.
2350 unsigned CallOpc;
2351 if (Subtarget->isThumb()) {
2352 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2353 CallOpc = ARMISD::CALL_NOLINK;
2354 else
2355 CallOpc = ARMISD::CALL;
2356 } else {
2357 if (!isDirect && !Subtarget->hasV5TOps())
2358 CallOpc = ARMISD::CALL_NOLINK;
2359 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2360 // Emit regular call when code size is the priority
2361 !Subtarget->hasMinSize())
2362 // "mov lr, pc; b _foo" to avoid confusing the RSP
2363 CallOpc = ARMISD::CALL_NOLINK;
2364 else
2365 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2368 std::vector<SDValue> Ops;
2369 Ops.push_back(Chain);
2370 Ops.push_back(Callee);
2372 // Add argument registers to the end of the list so that they are known live
2373 // into the call.
2374 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2375 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2376 RegsToPass[i].second.getValueType()));
2378 // Add a register mask operand representing the call-preserved registers.
2379 if (!isTailCall) {
2380 const uint32_t *Mask;
2381 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2382 if (isThisReturn) {
2383 // For 'this' returns, use the R0-preserving mask if applicable
2384 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2385 if (!Mask) {
2386 // Set isThisReturn to false if the calling convention is not one that
2387 // allows 'returned' to be modeled in this way, so LowerCallResult does
2388 // not try to pass 'this' straight through
2389 isThisReturn = false;
2390 Mask = ARI->getCallPreservedMask(MF, CallConv);
2392 } else
2393 Mask = ARI->getCallPreservedMask(MF, CallConv);
2395 assert(Mask && "Missing call preserved mask for calling convention");
2396 Ops.push_back(DAG.getRegisterMask(Mask));
2399 if (InFlag.getNode())
2400 Ops.push_back(InFlag);
2402 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2403 if (isTailCall) {
2404 MF.getFrameInfo().setHasTailCall();
2405 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2408 // Returns a chain and a flag for retval copy to use.
2409 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2410 InFlag = Chain.getValue(1);
2412 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2413 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2414 if (!Ins.empty())
2415 InFlag = Chain.getValue(1);
2417 // Handle result values, copying them out of physregs into vregs that we
2418 // return.
2419 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2420 InVals, isThisReturn,
2421 isThisReturn ? OutVals[0] : SDValue());
2424 /// HandleByVal - Every parameter *after* a byval parameter is passed
2425 /// on the stack. Remember the next parameter register to allocate,
2426 /// and then confiscate the rest of the parameter registers to insure
2427 /// this.
2428 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2429 unsigned Align) const {
2430 // Byval (as with any stack) slots are always at least 4 byte aligned.
2431 Align = std::max(Align, 4U);
2433 unsigned Reg = State->AllocateReg(GPRArgRegs);
2434 if (!Reg)
2435 return;
2437 unsigned AlignInRegs = Align / 4;
2438 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2439 for (unsigned i = 0; i < Waste; ++i)
2440 Reg = State->AllocateReg(GPRArgRegs);
2442 if (!Reg)
2443 return;
2445 unsigned Excess = 4 * (ARM::R4 - Reg);
2447 // Special case when NSAA != SP and parameter size greater than size of
2448 // all remained GPR regs. In that case we can't split parameter, we must
2449 // send it to stack. We also must set NCRN to R4, so waste all
2450 // remained registers.
2451 const unsigned NSAAOffset = State->getNextStackOffset();
2452 if (NSAAOffset != 0 && Size > Excess) {
2453 while (State->AllocateReg(GPRArgRegs))
2455 return;
2458 // First register for byval parameter is the first register that wasn't
2459 // allocated before this method call, so it would be "reg".
2460 // If parameter is small enough to be saved in range [reg, r4), then
2461 // the end (first after last) register would be reg + param-size-in-regs,
2462 // else parameter would be splitted between registers and stack,
2463 // end register would be r4 in this case.
2464 unsigned ByValRegBegin = Reg;
2465 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2466 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2467 // Note, first register is allocated in the beginning of function already,
2468 // allocate remained amount of registers we need.
2469 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2470 State->AllocateReg(GPRArgRegs);
2471 // A byval parameter that is split between registers and memory needs its
2472 // size truncated here.
2473 // In the case where the entire structure fits in registers, we set the
2474 // size in memory to zero.
2475 Size = std::max<int>(Size - Excess, 0);
2478 /// MatchingStackOffset - Return true if the given stack call argument is
2479 /// already available in the same position (relatively) of the caller's
2480 /// incoming argument stack.
2481 static
2482 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2483 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2484 const TargetInstrInfo *TII) {
2485 unsigned Bytes = Arg.getValueSizeInBits() / 8;
2486 int FI = std::numeric_limits<int>::max();
2487 if (Arg.getOpcode() == ISD::CopyFromReg) {
2488 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2489 if (!Register::isVirtualRegister(VR))
2490 return false;
2491 MachineInstr *Def = MRI->getVRegDef(VR);
2492 if (!Def)
2493 return false;
2494 if (!Flags.isByVal()) {
2495 if (!TII->isLoadFromStackSlot(*Def, FI))
2496 return false;
2497 } else {
2498 return false;
2500 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2501 if (Flags.isByVal())
2502 // ByVal argument is passed in as a pointer but it's now being
2503 // dereferenced. e.g.
2504 // define @foo(%struct.X* %A) {
2505 // tail call @bar(%struct.X* byval %A)
2506 // }
2507 return false;
2508 SDValue Ptr = Ld->getBasePtr();
2509 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2510 if (!FINode)
2511 return false;
2512 FI = FINode->getIndex();
2513 } else
2514 return false;
2516 assert(FI != std::numeric_limits<int>::max());
2517 if (!MFI.isFixedObjectIndex(FI))
2518 return false;
2519 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2522 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2523 /// for tail call optimization. Targets which want to do tail call
2524 /// optimization should implement this function.
2525 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2526 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2527 bool isCalleeStructRet, bool isCallerStructRet,
2528 const SmallVectorImpl<ISD::OutputArg> &Outs,
2529 const SmallVectorImpl<SDValue> &OutVals,
2530 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2531 const bool isIndirect) const {
2532 MachineFunction &MF = DAG.getMachineFunction();
2533 const Function &CallerF = MF.getFunction();
2534 CallingConv::ID CallerCC = CallerF.getCallingConv();
2536 assert(Subtarget->supportsTailCall());
2538 // Indirect tail calls cannot be optimized for Thumb1 if the args
2539 // to the call take up r0-r3. The reason is that there are no legal registers
2540 // left to hold the pointer to the function to be called.
2541 if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2542 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2543 return false;
2545 // Look for obvious safe cases to perform tail call optimization that do not
2546 // require ABI changes. This is what gcc calls sibcall.
2548 // Exception-handling functions need a special set of instructions to indicate
2549 // a return to the hardware. Tail-calling another function would probably
2550 // break this.
2551 if (CallerF.hasFnAttribute("interrupt"))
2552 return false;
2554 // Also avoid sibcall optimization if either caller or callee uses struct
2555 // return semantics.
2556 if (isCalleeStructRet || isCallerStructRet)
2557 return false;
2559 // Externally-defined functions with weak linkage should not be
2560 // tail-called on ARM when the OS does not support dynamic
2561 // pre-emption of symbols, as the AAELF spec requires normal calls
2562 // to undefined weak functions to be replaced with a NOP or jump to the
2563 // next instruction. The behaviour of branch instructions in this
2564 // situation (as used for tail calls) is implementation-defined, so we
2565 // cannot rely on the linker replacing the tail call with a return.
2566 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2567 const GlobalValue *GV = G->getGlobal();
2568 const Triple &TT = getTargetMachine().getTargetTriple();
2569 if (GV->hasExternalWeakLinkage() &&
2570 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2571 return false;
2574 // Check that the call results are passed in the same way.
2575 LLVMContext &C = *DAG.getContext();
2576 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2577 CCAssignFnForReturn(CalleeCC, isVarArg),
2578 CCAssignFnForReturn(CallerCC, isVarArg)))
2579 return false;
2580 // The callee has to preserve all registers the caller needs to preserve.
2581 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2582 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2583 if (CalleeCC != CallerCC) {
2584 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2585 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2586 return false;
2589 // If Caller's vararg or byval argument has been split between registers and
2590 // stack, do not perform tail call, since part of the argument is in caller's
2591 // local frame.
2592 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2593 if (AFI_Caller->getArgRegsSaveSize())
2594 return false;
2596 // If the callee takes no arguments then go on to check the results of the
2597 // call.
2598 if (!Outs.empty()) {
2599 // Check if stack adjustment is needed. For now, do not do this if any
2600 // argument is passed on the stack.
2601 SmallVector<CCValAssign, 16> ArgLocs;
2602 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2603 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2604 if (CCInfo.getNextStackOffset()) {
2605 // Check if the arguments are already laid out in the right way as
2606 // the caller's fixed stack objects.
2607 MachineFrameInfo &MFI = MF.getFrameInfo();
2608 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2609 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2610 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2611 i != e;
2612 ++i, ++realArgIdx) {
2613 CCValAssign &VA = ArgLocs[i];
2614 EVT RegVT = VA.getLocVT();
2615 SDValue Arg = OutVals[realArgIdx];
2616 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2617 if (VA.getLocInfo() == CCValAssign::Indirect)
2618 return false;
2619 if (VA.needsCustom()) {
2620 // f64 and vector types are split into multiple registers or
2621 // register/stack-slot combinations. The types will not match
2622 // the registers; give up on memory f64 refs until we figure
2623 // out what to do about this.
2624 if (!VA.isRegLoc())
2625 return false;
2626 if (!ArgLocs[++i].isRegLoc())
2627 return false;
2628 if (RegVT == MVT::v2f64) {
2629 if (!ArgLocs[++i].isRegLoc())
2630 return false;
2631 if (!ArgLocs[++i].isRegLoc())
2632 return false;
2634 } else if (!VA.isRegLoc()) {
2635 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2636 MFI, MRI, TII))
2637 return false;
2642 const MachineRegisterInfo &MRI = MF.getRegInfo();
2643 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2644 return false;
2647 return true;
2650 bool
2651 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2652 MachineFunction &MF, bool isVarArg,
2653 const SmallVectorImpl<ISD::OutputArg> &Outs,
2654 LLVMContext &Context) const {
2655 SmallVector<CCValAssign, 16> RVLocs;
2656 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2657 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2660 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2661 const SDLoc &DL, SelectionDAG &DAG) {
2662 const MachineFunction &MF = DAG.getMachineFunction();
2663 const Function &F = MF.getFunction();
2665 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2667 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2668 // version of the "preferred return address". These offsets affect the return
2669 // instruction if this is a return from PL1 without hypervisor extensions.
2670 // IRQ/FIQ: +4 "subs pc, lr, #4"
2671 // SWI: 0 "subs pc, lr, #0"
2672 // ABORT: +4 "subs pc, lr, #4"
2673 // UNDEF: +4/+2 "subs pc, lr, #0"
2674 // UNDEF varies depending on where the exception came from ARM or Thumb
2675 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2677 int64_t LROffset;
2678 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2679 IntKind == "ABORT")
2680 LROffset = 4;
2681 else if (IntKind == "SWI" || IntKind == "UNDEF")
2682 LROffset = 0;
2683 else
2684 report_fatal_error("Unsupported interrupt attribute. If present, value "
2685 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2687 RetOps.insert(RetOps.begin() + 1,
2688 DAG.getConstant(LROffset, DL, MVT::i32, false));
2690 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2693 SDValue
2694 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2695 bool isVarArg,
2696 const SmallVectorImpl<ISD::OutputArg> &Outs,
2697 const SmallVectorImpl<SDValue> &OutVals,
2698 const SDLoc &dl, SelectionDAG &DAG) const {
2699 // CCValAssign - represent the assignment of the return value to a location.
2700 SmallVector<CCValAssign, 16> RVLocs;
2702 // CCState - Info about the registers and stack slots.
2703 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2704 *DAG.getContext());
2706 // Analyze outgoing return values.
2707 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2709 SDValue Flag;
2710 SmallVector<SDValue, 4> RetOps;
2711 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2712 bool isLittleEndian = Subtarget->isLittle();
2714 MachineFunction &MF = DAG.getMachineFunction();
2715 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2716 AFI->setReturnRegsCount(RVLocs.size());
2718 // Copy the result values into the output registers.
2719 for (unsigned i = 0, realRVLocIdx = 0;
2720 i != RVLocs.size();
2721 ++i, ++realRVLocIdx) {
2722 CCValAssign &VA = RVLocs[i];
2723 assert(VA.isRegLoc() && "Can only return in registers!");
2725 SDValue Arg = OutVals[realRVLocIdx];
2726 bool ReturnF16 = false;
2728 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2729 // Half-precision return values can be returned like this:
2731 // t11 f16 = fadd ...
2732 // t12: i16 = bitcast t11
2733 // t13: i32 = zero_extend t12
2734 // t14: f32 = bitcast t13 <~~~~~~~ Arg
2736 // to avoid code generation for bitcasts, we simply set Arg to the node
2737 // that produces the f16 value, t11 in this case.
2739 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2740 SDValue ZE = Arg.getOperand(0);
2741 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2742 SDValue BC = ZE.getOperand(0);
2743 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2744 Arg = BC.getOperand(0);
2745 ReturnF16 = true;
2751 switch (VA.getLocInfo()) {
2752 default: llvm_unreachable("Unknown loc info!");
2753 case CCValAssign::Full: break;
2754 case CCValAssign::BCvt:
2755 if (!ReturnF16)
2756 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2757 break;
2760 if (VA.needsCustom()) {
2761 if (VA.getLocVT() == MVT::v2f64) {
2762 // Extract the first half and return it in two registers.
2763 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2764 DAG.getConstant(0, dl, MVT::i32));
2765 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2766 DAG.getVTList(MVT::i32, MVT::i32), Half);
2768 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2769 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2770 Flag);
2771 Flag = Chain.getValue(1);
2772 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2773 VA = RVLocs[++i]; // skip ahead to next loc
2774 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2775 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2776 Flag);
2777 Flag = Chain.getValue(1);
2778 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2779 VA = RVLocs[++i]; // skip ahead to next loc
2781 // Extract the 2nd half and fall through to handle it as an f64 value.
2782 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2783 DAG.getConstant(1, dl, MVT::i32));
2785 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2786 // available.
2787 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2788 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2789 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2790 fmrrd.getValue(isLittleEndian ? 0 : 1),
2791 Flag);
2792 Flag = Chain.getValue(1);
2793 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2794 VA = RVLocs[++i]; // skip ahead to next loc
2795 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2796 fmrrd.getValue(isLittleEndian ? 1 : 0),
2797 Flag);
2798 } else
2799 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2801 // Guarantee that all emitted copies are
2802 // stuck together, avoiding something bad.
2803 Flag = Chain.getValue(1);
2804 RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2805 ReturnF16 ? MVT::f16 : VA.getLocVT()));
2807 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2808 const MCPhysReg *I =
2809 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2810 if (I) {
2811 for (; *I; ++I) {
2812 if (ARM::GPRRegClass.contains(*I))
2813 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2814 else if (ARM::DPRRegClass.contains(*I))
2815 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2816 else
2817 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2821 // Update chain and glue.
2822 RetOps[0] = Chain;
2823 if (Flag.getNode())
2824 RetOps.push_back(Flag);
2826 // CPUs which aren't M-class use a special sequence to return from
2827 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2828 // though we use "subs pc, lr, #N").
2830 // M-class CPUs actually use a normal return sequence with a special
2831 // (hardware-provided) value in LR, so the normal code path works.
2832 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2833 !Subtarget->isMClass()) {
2834 if (Subtarget->isThumb1Only())
2835 report_fatal_error("interrupt attribute is not supported in Thumb1");
2836 return LowerInterruptReturn(RetOps, dl, DAG);
2839 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2842 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2843 if (N->getNumValues() != 1)
2844 return false;
2845 if (!N->hasNUsesOfValue(1, 0))
2846 return false;
2848 SDValue TCChain = Chain;
2849 SDNode *Copy = *N->use_begin();
2850 if (Copy->getOpcode() == ISD::CopyToReg) {
2851 // If the copy has a glue operand, we conservatively assume it isn't safe to
2852 // perform a tail call.
2853 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2854 return false;
2855 TCChain = Copy->getOperand(0);
2856 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2857 SDNode *VMov = Copy;
2858 // f64 returned in a pair of GPRs.
2859 SmallPtrSet<SDNode*, 2> Copies;
2860 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2861 UI != UE; ++UI) {
2862 if (UI->getOpcode() != ISD::CopyToReg)
2863 return false;
2864 Copies.insert(*UI);
2866 if (Copies.size() > 2)
2867 return false;
2869 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2870 UI != UE; ++UI) {
2871 SDValue UseChain = UI->getOperand(0);
2872 if (Copies.count(UseChain.getNode()))
2873 // Second CopyToReg
2874 Copy = *UI;
2875 else {
2876 // We are at the top of this chain.
2877 // If the copy has a glue operand, we conservatively assume it
2878 // isn't safe to perform a tail call.
2879 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2880 return false;
2881 // First CopyToReg
2882 TCChain = UseChain;
2885 } else if (Copy->getOpcode() == ISD::BITCAST) {
2886 // f32 returned in a single GPR.
2887 if (!Copy->hasOneUse())
2888 return false;
2889 Copy = *Copy->use_begin();
2890 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2891 return false;
2892 // If the copy has a glue operand, we conservatively assume it isn't safe to
2893 // perform a tail call.
2894 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2895 return false;
2896 TCChain = Copy->getOperand(0);
2897 } else {
2898 return false;
2901 bool HasRet = false;
2902 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2903 UI != UE; ++UI) {
2904 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2905 UI->getOpcode() != ARMISD::INTRET_FLAG)
2906 return false;
2907 HasRet = true;
2910 if (!HasRet)
2911 return false;
2913 Chain = TCChain;
2914 return true;
2917 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2918 if (!Subtarget->supportsTailCall())
2919 return false;
2921 auto Attr =
2922 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2923 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2924 return false;
2926 return true;
2929 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2930 // and pass the lower and high parts through.
2931 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2932 SDLoc DL(Op);
2933 SDValue WriteValue = Op->getOperand(2);
2935 // This function is only supposed to be called for i64 type argument.
2936 assert(WriteValue.getValueType() == MVT::i64
2937 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2939 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2940 DAG.getConstant(0, DL, MVT::i32));
2941 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2942 DAG.getConstant(1, DL, MVT::i32));
2943 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2944 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2947 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2948 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2949 // one of the above mentioned nodes. It has to be wrapped because otherwise
2950 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2951 // be used to form addressing mode. These wrapped nodes will be selected
2952 // into MOVi.
2953 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2954 SelectionDAG &DAG) const {
2955 EVT PtrVT = Op.getValueType();
2956 // FIXME there is no actual debug info here
2957 SDLoc dl(Op);
2958 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2959 SDValue Res;
2961 // When generating execute-only code Constant Pools must be promoted to the
2962 // global data section. It's a bit ugly that we can't share them across basic
2963 // blocks, but this way we guarantee that execute-only behaves correct with
2964 // position-independent addressing modes.
2965 if (Subtarget->genExecuteOnly()) {
2966 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2967 auto T = const_cast<Type*>(CP->getType());
2968 auto C = const_cast<Constant*>(CP->getConstVal());
2969 auto M = const_cast<Module*>(DAG.getMachineFunction().
2970 getFunction().getParent());
2971 auto GV = new GlobalVariable(
2972 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
2973 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2974 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2975 Twine(AFI->createPICLabelUId())
2977 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2978 dl, PtrVT);
2979 return LowerGlobalAddress(GA, DAG);
2982 if (CP->isMachineConstantPoolEntry())
2983 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2984 CP->getAlignment());
2985 else
2986 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2987 CP->getAlignment());
2988 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2991 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2992 return MachineJumpTableInfo::EK_Inline;
2995 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2996 SelectionDAG &DAG) const {
2997 MachineFunction &MF = DAG.getMachineFunction();
2998 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2999 unsigned ARMPCLabelIndex = 0;
3000 SDLoc DL(Op);
3001 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3002 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3003 SDValue CPAddr;
3004 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3005 if (!IsPositionIndependent) {
3006 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
3007 } else {
3008 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3009 ARMPCLabelIndex = AFI->createPICLabelUId();
3010 ARMConstantPoolValue *CPV =
3011 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3012 ARMCP::CPBlockAddress, PCAdj);
3013 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3015 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3016 SDValue Result = DAG.getLoad(
3017 PtrVT, DL, DAG.getEntryNode(), CPAddr,
3018 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3019 if (!IsPositionIndependent)
3020 return Result;
3021 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3022 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3025 /// Convert a TLS address reference into the correct sequence of loads
3026 /// and calls to compute the variable's address for Darwin, and return an
3027 /// SDValue containing the final node.
3029 /// Darwin only has one TLS scheme which must be capable of dealing with the
3030 /// fully general situation, in the worst case. This means:
3031 /// + "extern __thread" declaration.
3032 /// + Defined in a possibly unknown dynamic library.
3034 /// The general system is that each __thread variable has a [3 x i32] descriptor
3035 /// which contains information used by the runtime to calculate the address. The
3036 /// only part of this the compiler needs to know about is the first word, which
3037 /// contains a function pointer that must be called with the address of the
3038 /// entire descriptor in "r0".
3040 /// Since this descriptor may be in a different unit, in general access must
3041 /// proceed along the usual ARM rules. A common sequence to produce is:
3043 /// movw rT1, :lower16:_var$non_lazy_ptr
3044 /// movt rT1, :upper16:_var$non_lazy_ptr
3045 /// ldr r0, [rT1]
3046 /// ldr rT2, [r0]
3047 /// blx rT2
3048 /// [...address now in r0...]
3049 SDValue
3050 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3051 SelectionDAG &DAG) const {
3052 assert(Subtarget->isTargetDarwin() &&
3053 "This function expects a Darwin target");
3054 SDLoc DL(Op);
3056 // First step is to get the address of the actua global symbol. This is where
3057 // the TLS descriptor lives.
3058 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3060 // The first entry in the descriptor is a function pointer that we must call
3061 // to obtain the address of the variable.
3062 SDValue Chain = DAG.getEntryNode();
3063 SDValue FuncTLVGet = DAG.getLoad(
3064 MVT::i32, DL, Chain, DescAddr,
3065 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3066 /* Alignment = */ 4,
3067 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3068 MachineMemOperand::MOInvariant);
3069 Chain = FuncTLVGet.getValue(1);
3071 MachineFunction &F = DAG.getMachineFunction();
3072 MachineFrameInfo &MFI = F.getFrameInfo();
3073 MFI.setAdjustsStack(true);
3075 // TLS calls preserve all registers except those that absolutely must be
3076 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3077 // silly).
3078 auto TRI =
3079 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3080 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3081 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3083 // Finally, we can make the call. This is just a degenerate version of a
3084 // normal AArch64 call node: r0 takes the address of the descriptor, and
3085 // returns the address of the variable in this thread.
3086 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3087 Chain =
3088 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3089 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3090 DAG.getRegisterMask(Mask), Chain.getValue(1));
3091 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3094 SDValue
3095 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3096 SelectionDAG &DAG) const {
3097 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3099 SDValue Chain = DAG.getEntryNode();
3100 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3101 SDLoc DL(Op);
3103 // Load the current TEB (thread environment block)
3104 SDValue Ops[] = {Chain,
3105 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3106 DAG.getConstant(15, DL, MVT::i32),
3107 DAG.getConstant(0, DL, MVT::i32),
3108 DAG.getConstant(13, DL, MVT::i32),
3109 DAG.getConstant(0, DL, MVT::i32),
3110 DAG.getConstant(2, DL, MVT::i32)};
3111 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3112 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3114 SDValue TEB = CurrentTEB.getValue(0);
3115 Chain = CurrentTEB.getValue(1);
3117 // Load the ThreadLocalStoragePointer from the TEB
3118 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3119 SDValue TLSArray =
3120 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3121 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3123 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3124 // offset into the TLSArray.
3126 // Load the TLS index from the C runtime
3127 SDValue TLSIndex =
3128 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3129 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3130 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3132 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3133 DAG.getConstant(2, DL, MVT::i32));
3134 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3135 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3136 MachinePointerInfo());
3138 // Get the offset of the start of the .tls section (section base)
3139 const auto *GA = cast<GlobalAddressSDNode>(Op);
3140 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3141 SDValue Offset = DAG.getLoad(
3142 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3143 DAG.getTargetConstantPool(CPV, PtrVT, 4)),
3144 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3146 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3149 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3150 SDValue
3151 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3152 SelectionDAG &DAG) const {
3153 SDLoc dl(GA);
3154 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3155 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3156 MachineFunction &MF = DAG.getMachineFunction();
3157 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3158 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3159 ARMConstantPoolValue *CPV =
3160 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3161 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3162 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3163 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3164 Argument = DAG.getLoad(
3165 PtrVT, dl, DAG.getEntryNode(), Argument,
3166 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3167 SDValue Chain = Argument.getValue(1);
3169 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3170 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3172 // call __tls_get_addr.
3173 ArgListTy Args;
3174 ArgListEntry Entry;
3175 Entry.Node = Argument;
3176 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3177 Args.push_back(Entry);
3179 // FIXME: is there useful debug info available here?
3180 TargetLowering::CallLoweringInfo CLI(DAG);
3181 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3182 CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3183 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3185 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3186 return CallResult.first;
3189 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3190 // "local exec" model.
3191 SDValue
3192 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3193 SelectionDAG &DAG,
3194 TLSModel::Model model) const {
3195 const GlobalValue *GV = GA->getGlobal();
3196 SDLoc dl(GA);
3197 SDValue Offset;
3198 SDValue Chain = DAG.getEntryNode();
3199 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3200 // Get the Thread Pointer
3201 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3203 if (model == TLSModel::InitialExec) {
3204 MachineFunction &MF = DAG.getMachineFunction();
3205 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3206 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3207 // Initial exec model.
3208 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3209 ARMConstantPoolValue *CPV =
3210 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3211 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3212 true);
3213 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3214 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3215 Offset = DAG.getLoad(
3216 PtrVT, dl, Chain, Offset,
3217 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3218 Chain = Offset.getValue(1);
3220 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3221 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3223 Offset = DAG.getLoad(
3224 PtrVT, dl, Chain, Offset,
3225 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3226 } else {
3227 // local exec model
3228 assert(model == TLSModel::LocalExec);
3229 ARMConstantPoolValue *CPV =
3230 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3231 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3232 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3233 Offset = DAG.getLoad(
3234 PtrVT, dl, Chain, Offset,
3235 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3238 // The address of the thread local variable is the add of the thread
3239 // pointer with the offset of the variable.
3240 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3243 SDValue
3244 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3245 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3246 if (DAG.getTarget().useEmulatedTLS())
3247 return LowerToTLSEmulatedModel(GA, DAG);
3249 if (Subtarget->isTargetDarwin())
3250 return LowerGlobalTLSAddressDarwin(Op, DAG);
3252 if (Subtarget->isTargetWindows())
3253 return LowerGlobalTLSAddressWindows(Op, DAG);
3255 // TODO: implement the "local dynamic" model
3256 assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3257 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3259 switch (model) {
3260 case TLSModel::GeneralDynamic:
3261 case TLSModel::LocalDynamic:
3262 return LowerToTLSGeneralDynamicModel(GA, DAG);
3263 case TLSModel::InitialExec:
3264 case TLSModel::LocalExec:
3265 return LowerToTLSExecModels(GA, DAG, model);
3267 llvm_unreachable("bogus TLS model");
3270 /// Return true if all users of V are within function F, looking through
3271 /// ConstantExprs.
3272 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3273 SmallVector<const User*,4> Worklist;
3274 for (auto *U : V->users())
3275 Worklist.push_back(U);
3276 while (!Worklist.empty()) {
3277 auto *U = Worklist.pop_back_val();
3278 if (isa<ConstantExpr>(U)) {
3279 for (auto *UU : U->users())
3280 Worklist.push_back(UU);
3281 continue;
3284 auto *I = dyn_cast<Instruction>(U);
3285 if (!I || I->getParent()->getParent() != F)
3286 return false;
3288 return true;
3291 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3292 const GlobalValue *GV, SelectionDAG &DAG,
3293 EVT PtrVT, const SDLoc &dl) {
3294 // If we're creating a pool entry for a constant global with unnamed address,
3295 // and the global is small enough, we can emit it inline into the constant pool
3296 // to save ourselves an indirection.
3298 // This is a win if the constant is only used in one function (so it doesn't
3299 // need to be duplicated) or duplicating the constant wouldn't increase code
3300 // size (implying the constant is no larger than 4 bytes).
3301 const Function &F = DAG.getMachineFunction().getFunction();
3303 // We rely on this decision to inline being idemopotent and unrelated to the
3304 // use-site. We know that if we inline a variable at one use site, we'll
3305 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3306 // doesn't know about this optimization, so bail out if it's enabled else
3307 // we could decide to inline here (and thus never emit the GV) but require
3308 // the GV from fast-isel generated code.
3309 if (!EnableConstpoolPromotion ||
3310 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3311 return SDValue();
3313 auto *GVar = dyn_cast<GlobalVariable>(GV);
3314 if (!GVar || !GVar->hasInitializer() ||
3315 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3316 !GVar->hasLocalLinkage())
3317 return SDValue();
3319 // If we inline a value that contains relocations, we move the relocations
3320 // from .data to .text. This is not allowed in position-independent code.
3321 auto *Init = GVar->getInitializer();
3322 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3323 Init->needsRelocation())
3324 return SDValue();
3326 // The constant islands pass can only really deal with alignment requests
3327 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3328 // any type wanting greater alignment requirements than 4 bytes. We also
3329 // can only promote constants that are multiples of 4 bytes in size or
3330 // are paddable to a multiple of 4. Currently we only try and pad constants
3331 // that are strings for simplicity.
3332 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3333 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3334 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3335 unsigned RequiredPadding = 4 - (Size % 4);
3336 bool PaddingPossible =
3337 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3338 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3339 Size == 0)
3340 return SDValue();
3342 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3343 MachineFunction &MF = DAG.getMachineFunction();
3344 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3346 // We can't bloat the constant pool too much, else the ConstantIslands pass
3347 // may fail to converge. If we haven't promoted this global yet (it may have
3348 // multiple uses), and promoting it would increase the constant pool size (Sz
3349 // > 4), ensure we have space to do so up to MaxTotal.
3350 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3351 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3352 ConstpoolPromotionMaxTotal)
3353 return SDValue();
3355 // This is only valid if all users are in a single function; we can't clone
3356 // the constant in general. The LLVM IR unnamed_addr allows merging
3357 // constants, but not cloning them.
3359 // We could potentially allow cloning if we could prove all uses of the
3360 // constant in the current function don't care about the address, like
3361 // printf format strings. But that isn't implemented for now.
3362 if (!allUsersAreInFunction(GVar, &F))
3363 return SDValue();
3365 // We're going to inline this global. Pad it out if needed.
3366 if (RequiredPadding != 4) {
3367 StringRef S = CDAInit->getAsString();
3369 SmallVector<uint8_t,16> V(S.size());
3370 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3371 while (RequiredPadding--)
3372 V.push_back(0);
3373 Init = ConstantDataArray::get(*DAG.getContext(), V);
3376 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3377 SDValue CPAddr =
3378 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3379 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3380 AFI->markGlobalAsPromotedToConstantPool(GVar);
3381 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3382 PaddedSize - 4);
3384 ++NumConstpoolPromoted;
3385 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3388 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3389 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3390 if (!(GV = GA->getBaseObject()))
3391 return false;
3392 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3393 return V->isConstant();
3394 return isa<Function>(GV);
3397 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3398 SelectionDAG &DAG) const {
3399 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3400 default: llvm_unreachable("unknown object format");
3401 case Triple::COFF:
3402 return LowerGlobalAddressWindows(Op, DAG);
3403 case Triple::ELF:
3404 return LowerGlobalAddressELF(Op, DAG);
3405 case Triple::MachO:
3406 return LowerGlobalAddressDarwin(Op, DAG);
3410 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3411 SelectionDAG &DAG) const {
3412 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3413 SDLoc dl(Op);
3414 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3415 const TargetMachine &TM = getTargetMachine();
3416 bool IsRO = isReadOnly(GV);
3418 // promoteToConstantPool only if not generating XO text section
3419 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3420 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3421 return V;
3423 if (isPositionIndependent()) {
3424 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3425 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3426 UseGOT_PREL ? ARMII::MO_GOT : 0);
3427 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3428 if (UseGOT_PREL)
3429 Result =
3430 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3431 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3432 return Result;
3433 } else if (Subtarget->isROPI() && IsRO) {
3434 // PC-relative.
3435 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3436 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3437 return Result;
3438 } else if (Subtarget->isRWPI() && !IsRO) {
3439 // SB-relative.
3440 SDValue RelAddr;
3441 if (Subtarget->useMovt()) {
3442 ++NumMovwMovt;
3443 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3444 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3445 } else { // use literal pool for address constant
3446 ARMConstantPoolValue *CPV =
3447 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3448 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3449 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3450 RelAddr = DAG.getLoad(
3451 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3452 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3454 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3455 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3456 return Result;
3459 // If we have T2 ops, we can materialize the address directly via movt/movw
3460 // pair. This is always cheaper.
3461 if (Subtarget->useMovt()) {
3462 ++NumMovwMovt;
3463 // FIXME: Once remat is capable of dealing with instructions with register
3464 // operands, expand this into two nodes.
3465 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3466 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3467 } else {
3468 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3469 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3470 return DAG.getLoad(
3471 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3472 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3476 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3477 SelectionDAG &DAG) const {
3478 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3479 "ROPI/RWPI not currently supported for Darwin");
3480 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3481 SDLoc dl(Op);
3482 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3484 if (Subtarget->useMovt())
3485 ++NumMovwMovt;
3487 // FIXME: Once remat is capable of dealing with instructions with register
3488 // operands, expand this into multiple nodes
3489 unsigned Wrapper =
3490 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3492 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3493 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3495 if (Subtarget->isGVIndirectSymbol(GV))
3496 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3497 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3498 return Result;
3501 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3502 SelectionDAG &DAG) const {
3503 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3504 assert(Subtarget->useMovt() &&
3505 "Windows on ARM expects to use movw/movt");
3506 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3507 "ROPI/RWPI not currently supported for Windows");
3509 const TargetMachine &TM = getTargetMachine();
3510 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3511 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3512 if (GV->hasDLLImportStorageClass())
3513 TargetFlags = ARMII::MO_DLLIMPORT;
3514 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3515 TargetFlags = ARMII::MO_COFFSTUB;
3516 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3517 SDValue Result;
3518 SDLoc DL(Op);
3520 ++NumMovwMovt;
3522 // FIXME: Once remat is capable of dealing with instructions with register
3523 // operands, expand this into two nodes.
3524 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3525 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3526 TargetFlags));
3527 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3528 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3529 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3530 return Result;
3533 SDValue
3534 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3535 SDLoc dl(Op);
3536 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3537 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3538 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3539 Op.getOperand(1), Val);
3542 SDValue
3543 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3544 SDLoc dl(Op);
3545 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3546 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3549 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3550 SelectionDAG &DAG) const {
3551 SDLoc dl(Op);
3552 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3553 Op.getOperand(0));
3556 SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3557 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3558 unsigned IntNo =
3559 cast<ConstantSDNode>(
3560 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3561 ->getZExtValue();
3562 switch (IntNo) {
3563 default:
3564 return SDValue(); // Don't custom lower most intrinsics.
3565 case Intrinsic::arm_gnu_eabi_mcount: {
3566 MachineFunction &MF = DAG.getMachineFunction();
3567 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3568 SDLoc dl(Op);
3569 SDValue Chain = Op.getOperand(0);
3570 // call "\01__gnu_mcount_nc"
3571 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3572 const uint32_t *Mask =
3573 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3574 assert(Mask && "Missing call preserved mask for calling convention");
3575 // Mark LR an implicit live-in.
3576 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3577 SDValue ReturnAddress =
3578 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3579 std::vector<EVT> ResultTys = {MVT::Other, MVT::Glue};
3580 SDValue Callee =
3581 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3582 SDValue RegisterMask = DAG.getRegisterMask(Mask);
3583 if (Subtarget->isThumb())
3584 return SDValue(
3585 DAG.getMachineNode(
3586 ARM::tBL_PUSHLR, dl, ResultTys,
3587 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3588 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3590 return SDValue(
3591 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3592 {ReturnAddress, Callee, RegisterMask, Chain}),
3598 SDValue
3599 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3600 const ARMSubtarget *Subtarget) const {
3601 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3602 SDLoc dl(Op);
3603 switch (IntNo) {
3604 default: return SDValue(); // Don't custom lower most intrinsics.
3605 case Intrinsic::thread_pointer: {
3606 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3607 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3609 case Intrinsic::eh_sjlj_lsda: {
3610 MachineFunction &MF = DAG.getMachineFunction();
3611 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3612 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3613 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3614 SDValue CPAddr;
3615 bool IsPositionIndependent = isPositionIndependent();
3616 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3617 ARMConstantPoolValue *CPV =
3618 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3619 ARMCP::CPLSDA, PCAdj);
3620 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3621 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3622 SDValue Result = DAG.getLoad(
3623 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3624 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3626 if (IsPositionIndependent) {
3627 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3628 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3630 return Result;
3632 case Intrinsic::arm_neon_vabs:
3633 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3634 Op.getOperand(1));
3635 case Intrinsic::arm_neon_vmulls:
3636 case Intrinsic::arm_neon_vmullu: {
3637 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3638 ? ARMISD::VMULLs : ARMISD::VMULLu;
3639 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3640 Op.getOperand(1), Op.getOperand(2));
3642 case Intrinsic::arm_neon_vminnm:
3643 case Intrinsic::arm_neon_vmaxnm: {
3644 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3645 ? ISD::FMINNUM : ISD::FMAXNUM;
3646 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3647 Op.getOperand(1), Op.getOperand(2));
3649 case Intrinsic::arm_neon_vminu:
3650 case Intrinsic::arm_neon_vmaxu: {
3651 if (Op.getValueType().isFloatingPoint())
3652 return SDValue();
3653 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3654 ? ISD::UMIN : ISD::UMAX;
3655 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3656 Op.getOperand(1), Op.getOperand(2));
3658 case Intrinsic::arm_neon_vmins:
3659 case Intrinsic::arm_neon_vmaxs: {
3660 // v{min,max}s is overloaded between signed integers and floats.
3661 if (!Op.getValueType().isFloatingPoint()) {
3662 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3663 ? ISD::SMIN : ISD::SMAX;
3664 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3665 Op.getOperand(1), Op.getOperand(2));
3667 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3668 ? ISD::FMINIMUM : ISD::FMAXIMUM;
3669 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3670 Op.getOperand(1), Op.getOperand(2));
3672 case Intrinsic::arm_neon_vtbl1:
3673 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3674 Op.getOperand(1), Op.getOperand(2));
3675 case Intrinsic::arm_neon_vtbl2:
3676 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3677 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3681 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3682 const ARMSubtarget *Subtarget) {
3683 SDLoc dl(Op);
3684 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3685 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3686 if (SSID == SyncScope::SingleThread)
3687 return Op;
3689 if (!Subtarget->hasDataBarrier()) {
3690 // Some ARMv6 cpus can support data barriers with an mcr instruction.
3691 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3692 // here.
3693 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3694 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3695 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3696 DAG.getConstant(0, dl, MVT::i32));
3699 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3700 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3701 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3702 if (Subtarget->isMClass()) {
3703 // Only a full system barrier exists in the M-class architectures.
3704 Domain = ARM_MB::SY;
3705 } else if (Subtarget->preferISHSTBarriers() &&
3706 Ord == AtomicOrdering::Release) {
3707 // Swift happens to implement ISHST barriers in a way that's compatible with
3708 // Release semantics but weaker than ISH so we'd be fools not to use
3709 // it. Beware: other processors probably don't!
3710 Domain = ARM_MB::ISHST;
3713 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3714 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3715 DAG.getConstant(Domain, dl, MVT::i32));
3718 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3719 const ARMSubtarget *Subtarget) {
3720 // ARM pre v5TE and Thumb1 does not have preload instructions.
3721 if (!(Subtarget->isThumb2() ||
3722 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3723 // Just preserve the chain.
3724 return Op.getOperand(0);
3726 SDLoc dl(Op);
3727 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3728 if (!isRead &&
3729 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3730 // ARMv7 with MP extension has PLDW.
3731 return Op.getOperand(0);
3733 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3734 if (Subtarget->isThumb()) {
3735 // Invert the bits.
3736 isRead = ~isRead & 1;
3737 isData = ~isData & 1;
3740 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3741 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3742 DAG.getConstant(isData, dl, MVT::i32));
3745 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3746 MachineFunction &MF = DAG.getMachineFunction();
3747 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3749 // vastart just stores the address of the VarArgsFrameIndex slot into the
3750 // memory location argument.
3751 SDLoc dl(Op);
3752 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3753 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3754 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3755 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3756 MachinePointerInfo(SV));
3759 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3760 CCValAssign &NextVA,
3761 SDValue &Root,
3762 SelectionDAG &DAG,
3763 const SDLoc &dl) const {
3764 MachineFunction &MF = DAG.getMachineFunction();
3765 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3767 const TargetRegisterClass *RC;
3768 if (AFI->isThumb1OnlyFunction())
3769 RC = &ARM::tGPRRegClass;
3770 else
3771 RC = &ARM::GPRRegClass;
3773 // Transform the arguments stored in physical registers into virtual ones.
3774 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3775 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3777 SDValue ArgValue2;
3778 if (NextVA.isMemLoc()) {
3779 MachineFrameInfo &MFI = MF.getFrameInfo();
3780 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3782 // Create load node to retrieve arguments from the stack.
3783 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3784 ArgValue2 = DAG.getLoad(
3785 MVT::i32, dl, Root, FIN,
3786 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3787 } else {
3788 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3789 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3791 if (!Subtarget->isLittle())
3792 std::swap (ArgValue, ArgValue2);
3793 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3796 // The remaining GPRs hold either the beginning of variable-argument
3797 // data, or the beginning of an aggregate passed by value (usually
3798 // byval). Either way, we allocate stack slots adjacent to the data
3799 // provided by our caller, and store the unallocated registers there.
3800 // If this is a variadic function, the va_list pointer will begin with
3801 // these values; otherwise, this reassembles a (byval) structure that
3802 // was split between registers and memory.
3803 // Return: The frame index registers were stored into.
3804 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3805 const SDLoc &dl, SDValue &Chain,
3806 const Value *OrigArg,
3807 unsigned InRegsParamRecordIdx,
3808 int ArgOffset, unsigned ArgSize) const {
3809 // Currently, two use-cases possible:
3810 // Case #1. Non-var-args function, and we meet first byval parameter.
3811 // Setup first unallocated register as first byval register;
3812 // eat all remained registers
3813 // (these two actions are performed by HandleByVal method).
3814 // Then, here, we initialize stack frame with
3815 // "store-reg" instructions.
3816 // Case #2. Var-args function, that doesn't contain byval parameters.
3817 // The same: eat all remained unallocated registers,
3818 // initialize stack frame.
3820 MachineFunction &MF = DAG.getMachineFunction();
3821 MachineFrameInfo &MFI = MF.getFrameInfo();
3822 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3823 unsigned RBegin, REnd;
3824 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3825 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3826 } else {
3827 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3828 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3829 REnd = ARM::R4;
3832 if (REnd != RBegin)
3833 ArgOffset = -4 * (ARM::R4 - RBegin);
3835 auto PtrVT = getPointerTy(DAG.getDataLayout());
3836 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3837 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3839 SmallVector<SDValue, 4> MemOps;
3840 const TargetRegisterClass *RC =
3841 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3843 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3844 unsigned VReg = MF.addLiveIn(Reg, RC);
3845 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3846 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3847 MachinePointerInfo(OrigArg, 4 * i));
3848 MemOps.push_back(Store);
3849 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3852 if (!MemOps.empty())
3853 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3854 return FrameIndex;
3857 // Setup stack frame, the va_list pointer will start from.
3858 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3859 const SDLoc &dl, SDValue &Chain,
3860 unsigned ArgOffset,
3861 unsigned TotalArgRegsSaveSize,
3862 bool ForceMutable) const {
3863 MachineFunction &MF = DAG.getMachineFunction();
3864 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3866 // Try to store any remaining integer argument regs
3867 // to their spots on the stack so that they may be loaded by dereferencing
3868 // the result of va_next.
3869 // If there is no regs to be stored, just point address after last
3870 // argument passed via stack.
3871 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3872 CCInfo.getInRegsParamsCount(),
3873 CCInfo.getNextStackOffset(),
3874 std::max(4U, TotalArgRegsSaveSize));
3875 AFI->setVarArgsFrameIndex(FrameIndex);
3878 SDValue ARMTargetLowering::LowerFormalArguments(
3879 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3880 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3881 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3882 MachineFunction &MF = DAG.getMachineFunction();
3883 MachineFrameInfo &MFI = MF.getFrameInfo();
3885 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3887 // Assign locations to all of the incoming arguments.
3888 SmallVector<CCValAssign, 16> ArgLocs;
3889 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3890 *DAG.getContext());
3891 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3893 SmallVector<SDValue, 16> ArgValues;
3894 SDValue ArgValue;
3895 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3896 unsigned CurArgIdx = 0;
3898 // Initially ArgRegsSaveSize is zero.
3899 // Then we increase this value each time we meet byval parameter.
3900 // We also increase this value in case of varargs function.
3901 AFI->setArgRegsSaveSize(0);
3903 // Calculate the amount of stack space that we need to allocate to store
3904 // byval and variadic arguments that are passed in registers.
3905 // We need to know this before we allocate the first byval or variadic
3906 // argument, as they will be allocated a stack slot below the CFA (Canonical
3907 // Frame Address, the stack pointer at entry to the function).
3908 unsigned ArgRegBegin = ARM::R4;
3909 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3910 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3911 break;
3913 CCValAssign &VA = ArgLocs[i];
3914 unsigned Index = VA.getValNo();
3915 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3916 if (!Flags.isByVal())
3917 continue;
3919 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3920 unsigned RBegin, REnd;
3921 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3922 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3924 CCInfo.nextInRegsParam();
3926 CCInfo.rewindByValRegsInfo();
3928 int lastInsIndex = -1;
3929 if (isVarArg && MFI.hasVAStart()) {
3930 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3931 if (RegIdx != array_lengthof(GPRArgRegs))
3932 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3935 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3936 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3937 auto PtrVT = getPointerTy(DAG.getDataLayout());
3939 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3940 CCValAssign &VA = ArgLocs[i];
3941 if (Ins[VA.getValNo()].isOrigArg()) {
3942 std::advance(CurOrigArg,
3943 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3944 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3946 // Arguments stored in registers.
3947 if (VA.isRegLoc()) {
3948 EVT RegVT = VA.getLocVT();
3950 if (VA.needsCustom()) {
3951 // f64 and vector types are split up into multiple registers or
3952 // combinations of registers and stack slots.
3953 if (VA.getLocVT() == MVT::v2f64) {
3954 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3955 Chain, DAG, dl);
3956 VA = ArgLocs[++i]; // skip ahead to next loc
3957 SDValue ArgValue2;
3958 if (VA.isMemLoc()) {
3959 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3960 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3961 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3962 MachinePointerInfo::getFixedStack(
3963 DAG.getMachineFunction(), FI));
3964 } else {
3965 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3966 Chain, DAG, dl);
3968 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3969 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3970 ArgValue, ArgValue1,
3971 DAG.getIntPtrConstant(0, dl));
3972 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3973 ArgValue, ArgValue2,
3974 DAG.getIntPtrConstant(1, dl));
3975 } else
3976 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3977 } else {
3978 const TargetRegisterClass *RC;
3981 if (RegVT == MVT::f16)
3982 RC = &ARM::HPRRegClass;
3983 else if (RegVT == MVT::f32)
3984 RC = &ARM::SPRRegClass;
3985 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
3986 RC = &ARM::DPRRegClass;
3987 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
3988 RC = &ARM::QPRRegClass;
3989 else if (RegVT == MVT::i32)
3990 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3991 : &ARM::GPRRegClass;
3992 else
3993 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3995 // Transform the arguments in physical registers into virtual ones.
3996 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3997 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3999 // If this value is passed in r0 and has the returned attribute (e.g.
4000 // C++ 'structors), record this fact for later use.
4001 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4002 AFI->setPreservesR0();
4006 // If this is an 8 or 16-bit value, it is really passed promoted
4007 // to 32 bits. Insert an assert[sz]ext to capture this, then
4008 // truncate to the right size.
4009 switch (VA.getLocInfo()) {
4010 default: llvm_unreachable("Unknown loc info!");
4011 case CCValAssign::Full: break;
4012 case CCValAssign::BCvt:
4013 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4014 break;
4015 case CCValAssign::SExt:
4016 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4017 DAG.getValueType(VA.getValVT()));
4018 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4019 break;
4020 case CCValAssign::ZExt:
4021 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4022 DAG.getValueType(VA.getValVT()));
4023 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4024 break;
4027 InVals.push_back(ArgValue);
4028 } else { // VA.isRegLoc()
4029 // sanity check
4030 assert(VA.isMemLoc());
4031 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4033 int index = VA.getValNo();
4035 // Some Ins[] entries become multiple ArgLoc[] entries.
4036 // Process them only once.
4037 if (index != lastInsIndex)
4039 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4040 // FIXME: For now, all byval parameter objects are marked mutable.
4041 // This can be changed with more analysis.
4042 // In case of tail call optimization mark all arguments mutable.
4043 // Since they could be overwritten by lowering of arguments in case of
4044 // a tail call.
4045 if (Flags.isByVal()) {
4046 assert(Ins[index].isOrigArg() &&
4047 "Byval arguments cannot be implicit");
4048 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4050 int FrameIndex = StoreByValRegs(
4051 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4052 VA.getLocMemOffset(), Flags.getByValSize());
4053 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4054 CCInfo.nextInRegsParam();
4055 } else {
4056 unsigned FIOffset = VA.getLocMemOffset();
4057 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4058 FIOffset, true);
4060 // Create load nodes to retrieve arguments from the stack.
4061 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4062 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4063 MachinePointerInfo::getFixedStack(
4064 DAG.getMachineFunction(), FI)));
4066 lastInsIndex = index;
4071 // varargs
4072 if (isVarArg && MFI.hasVAStart())
4073 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
4074 CCInfo.getNextStackOffset(),
4075 TotalArgRegsSaveSize);
4077 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4079 return Chain;
4082 /// isFloatingPointZero - Return true if this is +0.0.
4083 static bool isFloatingPointZero(SDValue Op) {
4084 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4085 return CFP->getValueAPF().isPosZero();
4086 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4087 // Maybe this has already been legalized into the constant pool?
4088 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4089 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4090 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4091 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4092 return CFP->getValueAPF().isPosZero();
4094 } else if (Op->getOpcode() == ISD::BITCAST &&
4095 Op->getValueType(0) == MVT::f64) {
4096 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4097 // created by LowerConstantFP().
4098 SDValue BitcastOp = Op->getOperand(0);
4099 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4100 isNullConstant(BitcastOp->getOperand(0)))
4101 return true;
4103 return false;
4106 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4107 /// the given operands.
4108 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4109 SDValue &ARMcc, SelectionDAG &DAG,
4110 const SDLoc &dl) const {
4111 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4112 unsigned C = RHSC->getZExtValue();
4113 if (!isLegalICmpImmediate((int32_t)C)) {
4114 // Constant does not fit, try adjusting it by one.
4115 switch (CC) {
4116 default: break;
4117 case ISD::SETLT:
4118 case ISD::SETGE:
4119 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4120 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4121 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4123 break;
4124 case ISD::SETULT:
4125 case ISD::SETUGE:
4126 if (C != 0 && isLegalICmpImmediate(C-1)) {
4127 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4128 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4130 break;
4131 case ISD::SETLE:
4132 case ISD::SETGT:
4133 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4134 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4135 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4137 break;
4138 case ISD::SETULE:
4139 case ISD::SETUGT:
4140 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4141 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4142 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4144 break;
4147 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4148 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4149 // In ARM and Thumb-2, the compare instructions can shift their second
4150 // operand.
4151 CC = ISD::getSetCCSwappedOperands(CC);
4152 std::swap(LHS, RHS);
4155 // Thumb1 has very limited immediate modes, so turning an "and" into a
4156 // shift can save multiple instructions.
4158 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4159 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4160 // own. If it's the operand to an unsigned comparison with an immediate,
4161 // we can eliminate one of the shifts: we transform
4162 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4164 // We avoid transforming cases which aren't profitable due to encoding
4165 // details:
4167 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4168 // would not; in that case, we're essentially trading one immediate load for
4169 // another.
4170 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4171 // 3. C2 is zero; we have other code for this special case.
4173 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4174 // instruction, since the AND is always one instruction anyway, but we could
4175 // use narrow instructions in some cases.
4176 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4177 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4178 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4179 !isSignedIntSetCC(CC)) {
4180 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4181 auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4182 uint64_t RHSV = RHSC->getZExtValue();
4183 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4184 unsigned ShiftBits = countLeadingZeros(Mask);
4185 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4186 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4187 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4188 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4193 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4194 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4195 // way a cmp would.
4196 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4197 // some tweaks to the heuristics for the previous and->shift transform.
4198 // FIXME: Optimize cases where the LHS isn't a shift.
4199 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4200 isa<ConstantSDNode>(RHS) &&
4201 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4202 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4203 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4204 unsigned ShiftAmt =
4205 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4206 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4207 DAG.getVTList(MVT::i32, MVT::i32),
4208 LHS.getOperand(0),
4209 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4210 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4211 Shift.getValue(1), SDValue());
4212 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4213 return Chain.getValue(1);
4216 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4218 // If the RHS is a constant zero then the V (overflow) flag will never be
4219 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4220 // simpler for other passes (like the peephole optimiser) to deal with.
4221 if (isNullConstant(RHS)) {
4222 switch (CondCode) {
4223 default: break;
4224 case ARMCC::GE:
4225 CondCode = ARMCC::PL;
4226 break;
4227 case ARMCC::LT:
4228 CondCode = ARMCC::MI;
4229 break;
4233 ARMISD::NodeType CompareType;
4234 switch (CondCode) {
4235 default:
4236 CompareType = ARMISD::CMP;
4237 break;
4238 case ARMCC::EQ:
4239 case ARMCC::NE:
4240 // Uses only Z Flag
4241 CompareType = ARMISD::CMPZ;
4242 break;
4244 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4245 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4248 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4249 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4250 SelectionDAG &DAG, const SDLoc &dl,
4251 bool InvalidOnQNaN) const {
4252 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4253 SDValue Cmp;
4254 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
4255 if (!isFloatingPointZero(RHS))
4256 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
4257 else
4258 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
4259 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4262 /// duplicateCmp - Glue values can have only one use, so this function
4263 /// duplicates a comparison node.
4264 SDValue
4265 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4266 unsigned Opc = Cmp.getOpcode();
4267 SDLoc DL(Cmp);
4268 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4269 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4271 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4272 Cmp = Cmp.getOperand(0);
4273 Opc = Cmp.getOpcode();
4274 if (Opc == ARMISD::CMPFP)
4275 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4276 Cmp.getOperand(1), Cmp.getOperand(2));
4277 else {
4278 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4279 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
4280 Cmp.getOperand(1));
4282 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4285 // This function returns three things: the arithmetic computation itself
4286 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4287 // comparison and the condition code define the case in which the arithmetic
4288 // computation *does not* overflow.
4289 std::pair<SDValue, SDValue>
4290 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4291 SDValue &ARMcc) const {
4292 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4294 SDValue Value, OverflowCmp;
4295 SDValue LHS = Op.getOperand(0);
4296 SDValue RHS = Op.getOperand(1);
4297 SDLoc dl(Op);
4299 // FIXME: We are currently always generating CMPs because we don't support
4300 // generating CMN through the backend. This is not as good as the natural
4301 // CMP case because it causes a register dependency and cannot be folded
4302 // later.
4304 switch (Op.getOpcode()) {
4305 default:
4306 llvm_unreachable("Unknown overflow instruction!");
4307 case ISD::SADDO:
4308 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4309 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4310 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4311 break;
4312 case ISD::UADDO:
4313 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4314 // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4315 // We do not use it in the USUBO case as Value may not be used.
4316 Value = DAG.getNode(ARMISD::ADDC, dl,
4317 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4318 .getValue(0);
4319 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4320 break;
4321 case ISD::SSUBO:
4322 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4323 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4324 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4325 break;
4326 case ISD::USUBO:
4327 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4328 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4329 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4330 break;
4331 case ISD::UMULO:
4332 // We generate a UMUL_LOHI and then check if the high word is 0.
4333 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4334 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4335 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4336 LHS, RHS);
4337 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4338 DAG.getConstant(0, dl, MVT::i32));
4339 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4340 break;
4341 case ISD::SMULO:
4342 // We generate a SMUL_LOHI and then check if all the bits of the high word
4343 // are the same as the sign bit of the low word.
4344 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4345 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4346 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4347 LHS, RHS);
4348 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4349 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4350 Value.getValue(0),
4351 DAG.getConstant(31, dl, MVT::i32)));
4352 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4353 break;
4354 } // switch (...)
4356 return std::make_pair(Value, OverflowCmp);
4359 SDValue
4360 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4361 // Let legalize expand this if it isn't a legal type yet.
4362 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4363 return SDValue();
4365 SDValue Value, OverflowCmp;
4366 SDValue ARMcc;
4367 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4368 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4369 SDLoc dl(Op);
4370 // We use 0 and 1 as false and true values.
4371 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4372 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4373 EVT VT = Op.getValueType();
4375 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4376 ARMcc, CCR, OverflowCmp);
4378 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4379 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4382 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4383 SelectionDAG &DAG) {
4384 SDLoc DL(BoolCarry);
4385 EVT CarryVT = BoolCarry.getValueType();
4387 // This converts the boolean value carry into the carry flag by doing
4388 // ARMISD::SUBC Carry, 1
4389 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4390 DAG.getVTList(CarryVT, MVT::i32),
4391 BoolCarry, DAG.getConstant(1, DL, CarryVT));
4392 return Carry.getValue(1);
4395 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4396 SelectionDAG &DAG) {
4397 SDLoc DL(Flags);
4399 // Now convert the carry flag into a boolean carry. We do this
4400 // using ARMISD:ADDE 0, 0, Carry
4401 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4402 DAG.getConstant(0, DL, MVT::i32),
4403 DAG.getConstant(0, DL, MVT::i32), Flags);
4406 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4407 SelectionDAG &DAG) const {
4408 // Let legalize expand this if it isn't a legal type yet.
4409 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4410 return SDValue();
4412 SDValue LHS = Op.getOperand(0);
4413 SDValue RHS = Op.getOperand(1);
4414 SDLoc dl(Op);
4416 EVT VT = Op.getValueType();
4417 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4418 SDValue Value;
4419 SDValue Overflow;
4420 switch (Op.getOpcode()) {
4421 default:
4422 llvm_unreachable("Unknown overflow instruction!");
4423 case ISD::UADDO:
4424 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4425 // Convert the carry flag into a boolean value.
4426 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4427 break;
4428 case ISD::USUBO: {
4429 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4430 // Convert the carry flag into a boolean value.
4431 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4432 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4433 // value. So compute 1 - C.
4434 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4435 DAG.getConstant(1, dl, MVT::i32), Overflow);
4436 break;
4440 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4443 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4444 SDValue Cond = Op.getOperand(0);
4445 SDValue SelectTrue = Op.getOperand(1);
4446 SDValue SelectFalse = Op.getOperand(2);
4447 SDLoc dl(Op);
4448 unsigned Opc = Cond.getOpcode();
4450 if (Cond.getResNo() == 1 &&
4451 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4452 Opc == ISD::USUBO)) {
4453 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4454 return SDValue();
4456 SDValue Value, OverflowCmp;
4457 SDValue ARMcc;
4458 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4459 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4460 EVT VT = Op.getValueType();
4462 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4463 OverflowCmp, DAG);
4466 // Convert:
4468 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4469 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4471 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4472 const ConstantSDNode *CMOVTrue =
4473 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4474 const ConstantSDNode *CMOVFalse =
4475 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4477 if (CMOVTrue && CMOVFalse) {
4478 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4479 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4481 SDValue True;
4482 SDValue False;
4483 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4484 True = SelectTrue;
4485 False = SelectFalse;
4486 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4487 True = SelectFalse;
4488 False = SelectTrue;
4491 if (True.getNode() && False.getNode()) {
4492 EVT VT = Op.getValueType();
4493 SDValue ARMcc = Cond.getOperand(2);
4494 SDValue CCR = Cond.getOperand(3);
4495 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4496 assert(True.getValueType() == VT);
4497 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4502 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4503 // undefined bits before doing a full-word comparison with zero.
4504 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4505 DAG.getConstant(1, dl, Cond.getValueType()));
4507 return DAG.getSelectCC(dl, Cond,
4508 DAG.getConstant(0, dl, Cond.getValueType()),
4509 SelectTrue, SelectFalse, ISD::SETNE);
4512 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4513 bool &swpCmpOps, bool &swpVselOps) {
4514 // Start by selecting the GE condition code for opcodes that return true for
4515 // 'equality'
4516 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4517 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
4518 CondCode = ARMCC::GE;
4520 // and GT for opcodes that return false for 'equality'.
4521 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4522 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
4523 CondCode = ARMCC::GT;
4525 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4526 // to swap the compare operands.
4527 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4528 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
4529 swpCmpOps = true;
4531 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4532 // If we have an unordered opcode, we need to swap the operands to the VSEL
4533 // instruction (effectively negating the condition).
4535 // This also has the effect of swapping which one of 'less' or 'greater'
4536 // returns true, so we also swap the compare operands. It also switches
4537 // whether we return true for 'equality', so we compensate by picking the
4538 // opposite condition code to our original choice.
4539 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4540 CC == ISD::SETUGT) {
4541 swpCmpOps = !swpCmpOps;
4542 swpVselOps = !swpVselOps;
4543 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4546 // 'ordered' is 'anything but unordered', so use the VS condition code and
4547 // swap the VSEL operands.
4548 if (CC == ISD::SETO) {
4549 CondCode = ARMCC::VS;
4550 swpVselOps = true;
4553 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4554 // code and swap the VSEL operands. Also do this if we don't care about the
4555 // unordered case.
4556 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4557 CondCode = ARMCC::EQ;
4558 swpVselOps = true;
4562 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4563 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4564 SDValue Cmp, SelectionDAG &DAG) const {
4565 if (!Subtarget->hasFP64() && VT == MVT::f64) {
4566 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4567 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4568 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4569 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4571 SDValue TrueLow = TrueVal.getValue(0);
4572 SDValue TrueHigh = TrueVal.getValue(1);
4573 SDValue FalseLow = FalseVal.getValue(0);
4574 SDValue FalseHigh = FalseVal.getValue(1);
4576 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4577 ARMcc, CCR, Cmp);
4578 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4579 ARMcc, CCR, duplicateCmp(Cmp, DAG));
4581 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4582 } else {
4583 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4584 Cmp);
4588 static bool isGTorGE(ISD::CondCode CC) {
4589 return CC == ISD::SETGT || CC == ISD::SETGE;
4592 static bool isLTorLE(ISD::CondCode CC) {
4593 return CC == ISD::SETLT || CC == ISD::SETLE;
4596 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4597 // All of these conditions (and their <= and >= counterparts) will do:
4598 // x < k ? k : x
4599 // x > k ? x : k
4600 // k < x ? x : k
4601 // k > x ? k : x
4602 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4603 const SDValue TrueVal, const SDValue FalseVal,
4604 const ISD::CondCode CC, const SDValue K) {
4605 return (isGTorGE(CC) &&
4606 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4607 (isLTorLE(CC) &&
4608 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4611 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4612 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4613 const SDValue TrueVal, const SDValue FalseVal,
4614 const ISD::CondCode CC, const SDValue K) {
4615 return (isGTorGE(CC) &&
4616 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4617 (isLTorLE(CC) &&
4618 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4621 // Check if two chained conditionals could be converted into SSAT or USAT.
4623 // SSAT can replace a set of two conditional selectors that bound a number to an
4624 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4626 // x < -k ? -k : (x > k ? k : x)
4627 // x < -k ? -k : (x < k ? x : k)
4628 // x > -k ? (x > k ? k : x) : -k
4629 // x < k ? (x < -k ? -k : x) : k
4630 // etc.
4632 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4633 // a power of 2.
4635 // It returns true if the conversion can be done, false otherwise.
4636 // Additionally, the variable is returned in parameter V, the constant in K and
4637 // usat is set to true if the conditional represents an unsigned saturation
4638 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4639 uint64_t &K, bool &usat) {
4640 SDValue LHS1 = Op.getOperand(0);
4641 SDValue RHS1 = Op.getOperand(1);
4642 SDValue TrueVal1 = Op.getOperand(2);
4643 SDValue FalseVal1 = Op.getOperand(3);
4644 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4646 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4647 if (Op2.getOpcode() != ISD::SELECT_CC)
4648 return false;
4650 SDValue LHS2 = Op2.getOperand(0);
4651 SDValue RHS2 = Op2.getOperand(1);
4652 SDValue TrueVal2 = Op2.getOperand(2);
4653 SDValue FalseVal2 = Op2.getOperand(3);
4654 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4656 // Find out which are the constants and which are the variables
4657 // in each conditional
4658 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4659 ? &RHS1
4660 : nullptr;
4661 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4662 ? &RHS2
4663 : nullptr;
4664 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4665 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4666 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4667 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4669 // We must detect cases where the original operations worked with 16- or
4670 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4671 // must work with sign-extended values but the select operations return
4672 // the original non-extended value.
4673 SDValue V2TmpReg = V2Tmp;
4674 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4675 V2TmpReg = V2Tmp->getOperand(0);
4677 // Check that the registers and the constants have the correct values
4678 // in both conditionals
4679 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4680 V2TmpReg != V2)
4681 return false;
4683 // Figure out which conditional is saturating the lower/upper bound.
4684 const SDValue *LowerCheckOp =
4685 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4686 ? &Op
4687 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4688 ? &Op2
4689 : nullptr;
4690 const SDValue *UpperCheckOp =
4691 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4692 ? &Op
4693 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4694 ? &Op2
4695 : nullptr;
4697 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4698 return false;
4700 // Check that the constant in the lower-bound check is
4701 // the opposite of the constant in the upper-bound check
4702 // in 1's complement.
4703 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4704 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4705 int64_t PosVal = std::max(Val1, Val2);
4706 int64_t NegVal = std::min(Val1, Val2);
4708 if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4709 (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4710 isPowerOf2_64(PosVal + 1)) {
4712 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4713 if (Val1 == ~Val2)
4714 usat = false;
4715 else if (NegVal == 0)
4716 usat = true;
4717 else
4718 return false;
4720 V = V2;
4721 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4723 return true;
4726 return false;
4729 // Check if a condition of the type x < k ? k : x can be converted into a
4730 // bit operation instead of conditional moves.
4731 // Currently this is allowed given:
4732 // - The conditions and values match up
4733 // - k is 0 or -1 (all ones)
4734 // This function will not check the last condition, thats up to the caller
4735 // It returns true if the transformation can be made, and in such case
4736 // returns x in V, and k in SatK.
4737 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4738 SDValue &SatK)
4740 SDValue LHS = Op.getOperand(0);
4741 SDValue RHS = Op.getOperand(1);
4742 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4743 SDValue TrueVal = Op.getOperand(2);
4744 SDValue FalseVal = Op.getOperand(3);
4746 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4747 ? &RHS
4748 : nullptr;
4750 // No constant operation in comparison, early out
4751 if (!K)
4752 return false;
4754 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4755 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4756 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4758 // If the constant on left and right side, or variable on left and right,
4759 // does not match, early out
4760 if (*K != KTmp || V != VTmp)
4761 return false;
4763 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4764 SatK = *K;
4765 return true;
4768 return false;
4771 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
4772 if (VT == MVT::f32)
4773 return !Subtarget->hasVFP2Base();
4774 if (VT == MVT::f64)
4775 return !Subtarget->hasFP64();
4776 if (VT == MVT::f16)
4777 return !Subtarget->hasFullFP16();
4778 return false;
4781 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4782 EVT VT = Op.getValueType();
4783 SDLoc dl(Op);
4785 // Try to convert two saturating conditional selects into a single SSAT
4786 SDValue SatValue;
4787 uint64_t SatConstant;
4788 bool SatUSat;
4789 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4790 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4791 if (SatUSat)
4792 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4793 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4794 else
4795 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4796 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4799 // Try to convert expressions of the form x < k ? k : x (and similar forms)
4800 // into more efficient bit operations, which is possible when k is 0 or -1
4801 // On ARM and Thumb-2 which have flexible operand 2 this will result in
4802 // single instructions. On Thumb the shift and the bit operation will be two
4803 // instructions.
4804 // Only allow this transformation on full-width (32-bit) operations
4805 SDValue LowerSatConstant;
4806 if (VT == MVT::i32 &&
4807 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4808 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4809 DAG.getConstant(31, dl, VT));
4810 if (isNullConstant(LowerSatConstant)) {
4811 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4812 DAG.getAllOnesConstant(dl, VT));
4813 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4814 } else if (isAllOnesConstant(LowerSatConstant))
4815 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4818 SDValue LHS = Op.getOperand(0);
4819 SDValue RHS = Op.getOperand(1);
4820 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4821 SDValue TrueVal = Op.getOperand(2);
4822 SDValue FalseVal = Op.getOperand(3);
4823 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
4824 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
4826 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
4827 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
4828 unsigned TVal = CTVal->getZExtValue();
4829 unsigned FVal = CFVal->getZExtValue();
4830 unsigned Opcode = 0;
4832 if (TVal == ~FVal) {
4833 Opcode = ARMISD::CSINV;
4834 } else if (TVal == ~FVal + 1) {
4835 Opcode = ARMISD::CSNEG;
4836 } else if (TVal + 1 == FVal) {
4837 Opcode = ARMISD::CSINC;
4838 } else if (TVal == FVal + 1) {
4839 Opcode = ARMISD::CSINC;
4840 std::swap(TrueVal, FalseVal);
4841 std::swap(TVal, FVal);
4842 CC = ISD::getSetCCInverse(CC, true);
4845 if (Opcode) {
4846 // If one of the constants is cheaper than another, materialise the
4847 // cheaper one and let the csel generate the other.
4848 if (Opcode != ARMISD::CSINC &&
4849 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
4850 std::swap(TrueVal, FalseVal);
4851 std::swap(TVal, FVal);
4852 CC = ISD::getSetCCInverse(CC, true);
4855 // Attempt to use ZR checking TVal is 0, possibly inverting the condition
4856 // to get there. CSINC not is invertable like the other two (~(~a) == a,
4857 // -(-a) == a, but (a+1)+1 != a).
4858 if (FVal == 0 && Opcode != ARMISD::CSINC) {
4859 std::swap(TrueVal, FalseVal);
4860 std::swap(TVal, FVal);
4861 CC = ISD::getSetCCInverse(CC, true);
4863 if (TVal == 0)
4864 TrueVal = DAG.getRegister(ARM::ZR, MVT::i32);
4866 // Drops F's value because we can get it by inverting/negating TVal.
4867 FalseVal = TrueVal;
4869 SDValue ARMcc;
4870 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4871 EVT VT = TrueVal.getValueType();
4872 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
4876 if (isUnsupportedFloatingType(LHS.getValueType())) {
4877 DAG.getTargetLoweringInfo().softenSetCCOperands(
4878 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
4880 // If softenSetCCOperands only returned one value, we should compare it to
4881 // zero.
4882 if (!RHS.getNode()) {
4883 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4884 CC = ISD::SETNE;
4888 if (LHS.getValueType() == MVT::i32) {
4889 // Try to generate VSEL on ARMv8.
4890 // The VSEL instruction can't use all the usual ARM condition
4891 // codes: it only has two bits to select the condition code, so it's
4892 // constrained to use only GE, GT, VS and EQ.
4894 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4895 // swap the operands of the previous compare instruction (effectively
4896 // inverting the compare condition, swapping 'less' and 'greater') and
4897 // sometimes need to swap the operands to the VSEL (which inverts the
4898 // condition in the sense of firing whenever the previous condition didn't)
4899 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
4900 TrueVal.getValueType() == MVT::f32 ||
4901 TrueVal.getValueType() == MVT::f64)) {
4902 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4903 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4904 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4905 CC = ISD::getSetCCInverse(CC, true);
4906 std::swap(TrueVal, FalseVal);
4910 SDValue ARMcc;
4911 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4912 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4913 // Choose GE over PL, which vsel does now support
4914 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
4915 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
4916 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4919 ARMCC::CondCodes CondCode, CondCode2;
4920 bool InvalidOnQNaN;
4921 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4923 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
4924 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
4925 // must use VSEL (limited condition codes), due to not having conditional f16
4926 // moves.
4927 if (Subtarget->hasFPARMv8Base() &&
4928 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
4929 (TrueVal.getValueType() == MVT::f16 ||
4930 TrueVal.getValueType() == MVT::f32 ||
4931 TrueVal.getValueType() == MVT::f64)) {
4932 bool swpCmpOps = false;
4933 bool swpVselOps = false;
4934 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4936 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4937 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4938 if (swpCmpOps)
4939 std::swap(LHS, RHS);
4940 if (swpVselOps)
4941 std::swap(TrueVal, FalseVal);
4945 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4946 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4947 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4948 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4949 if (CondCode2 != ARMCC::AL) {
4950 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4951 // FIXME: Needs another CMP because flag can have but one use.
4952 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4953 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4955 return Result;
4958 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4959 /// to morph to an integer compare sequence.
4960 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4961 const ARMSubtarget *Subtarget) {
4962 SDNode *N = Op.getNode();
4963 if (!N->hasOneUse())
4964 // Otherwise it requires moving the value from fp to integer registers.
4965 return false;
4966 if (!N->getNumValues())
4967 return false;
4968 EVT VT = Op.getValueType();
4969 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4970 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4971 // vmrs are very slow, e.g. cortex-a8.
4972 return false;
4974 if (isFloatingPointZero(Op)) {
4975 SeenZero = true;
4976 return true;
4978 return ISD::isNormalLoad(N);
4981 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4982 if (isFloatingPointZero(Op))
4983 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4985 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4986 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4987 Ld->getPointerInfo(), Ld->getAlignment(),
4988 Ld->getMemOperand()->getFlags());
4990 llvm_unreachable("Unknown VFP cmp argument!");
4993 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4994 SDValue &RetVal1, SDValue &RetVal2) {
4995 SDLoc dl(Op);
4997 if (isFloatingPointZero(Op)) {
4998 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4999 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5000 return;
5003 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5004 SDValue Ptr = Ld->getBasePtr();
5005 RetVal1 =
5006 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5007 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
5009 EVT PtrType = Ptr.getValueType();
5010 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
5011 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5012 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5013 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5014 Ld->getPointerInfo().getWithOffset(4), NewAlign,
5015 Ld->getMemOperand()->getFlags());
5016 return;
5019 llvm_unreachable("Unknown VFP cmp argument!");
5022 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5023 /// f32 and even f64 comparisons to integer ones.
5024 SDValue
5025 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5026 SDValue Chain = Op.getOperand(0);
5027 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5028 SDValue LHS = Op.getOperand(2);
5029 SDValue RHS = Op.getOperand(3);
5030 SDValue Dest = Op.getOperand(4);
5031 SDLoc dl(Op);
5033 bool LHSSeenZero = false;
5034 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5035 bool RHSSeenZero = false;
5036 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5037 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5038 // If unsafe fp math optimization is enabled and there are no other uses of
5039 // the CMP operands, and the condition code is EQ or NE, we can optimize it
5040 // to an integer comparison.
5041 if (CC == ISD::SETOEQ)
5042 CC = ISD::SETEQ;
5043 else if (CC == ISD::SETUNE)
5044 CC = ISD::SETNE;
5046 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5047 SDValue ARMcc;
5048 if (LHS.getValueType() == MVT::f32) {
5049 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5050 bitcastf32Toi32(LHS, DAG), Mask);
5051 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5052 bitcastf32Toi32(RHS, DAG), Mask);
5053 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5054 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5055 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5056 Chain, Dest, ARMcc, CCR, Cmp);
5059 SDValue LHS1, LHS2;
5060 SDValue RHS1, RHS2;
5061 expandf64Toi32(LHS, DAG, LHS1, LHS2);
5062 expandf64Toi32(RHS, DAG, RHS1, RHS2);
5063 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5064 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5065 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5066 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5067 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5068 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5069 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5072 return SDValue();
5075 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5076 SDValue Chain = Op.getOperand(0);
5077 SDValue Cond = Op.getOperand(1);
5078 SDValue Dest = Op.getOperand(2);
5079 SDLoc dl(Op);
5081 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5082 // instruction.
5083 unsigned Opc = Cond.getOpcode();
5084 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5085 !Subtarget->isThumb1Only();
5086 if (Cond.getResNo() == 1 &&
5087 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5088 Opc == ISD::USUBO || OptimizeMul)) {
5089 // Only lower legal XALUO ops.
5090 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5091 return SDValue();
5093 // The actual operation with overflow check.
5094 SDValue Value, OverflowCmp;
5095 SDValue ARMcc;
5096 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5098 // Reverse the condition code.
5099 ARMCC::CondCodes CondCode =
5100 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5101 CondCode = ARMCC::getOppositeCondition(CondCode);
5102 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5103 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5105 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5106 OverflowCmp);
5109 return SDValue();
5112 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5113 SDValue Chain = Op.getOperand(0);
5114 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5115 SDValue LHS = Op.getOperand(2);
5116 SDValue RHS = Op.getOperand(3);
5117 SDValue Dest = Op.getOperand(4);
5118 SDLoc dl(Op);
5120 if (isUnsupportedFloatingType(LHS.getValueType())) {
5121 DAG.getTargetLoweringInfo().softenSetCCOperands(
5122 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5124 // If softenSetCCOperands only returned one value, we should compare it to
5125 // zero.
5126 if (!RHS.getNode()) {
5127 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5128 CC = ISD::SETNE;
5132 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5133 // instruction.
5134 unsigned Opc = LHS.getOpcode();
5135 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5136 !Subtarget->isThumb1Only();
5137 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5138 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5139 Opc == ISD::USUBO || OptimizeMul) &&
5140 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5141 // Only lower legal XALUO ops.
5142 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5143 return SDValue();
5145 // The actual operation with overflow check.
5146 SDValue Value, OverflowCmp;
5147 SDValue ARMcc;
5148 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5150 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5151 // Reverse the condition code.
5152 ARMCC::CondCodes CondCode =
5153 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5154 CondCode = ARMCC::getOppositeCondition(CondCode);
5155 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5157 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5159 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5160 OverflowCmp);
5163 if (LHS.getValueType() == MVT::i32) {
5164 SDValue ARMcc;
5165 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5166 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5167 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5168 Chain, Dest, ARMcc, CCR, Cmp);
5171 if (getTargetMachine().Options.UnsafeFPMath &&
5172 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5173 CC == ISD::SETNE || CC == ISD::SETUNE)) {
5174 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5175 return Result;
5178 ARMCC::CondCodes CondCode, CondCode2;
5179 bool InvalidOnQNaN;
5180 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
5182 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5183 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
5184 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5185 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5186 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5187 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5188 if (CondCode2 != ARMCC::AL) {
5189 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5190 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5191 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5193 return Res;
5196 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5197 SDValue Chain = Op.getOperand(0);
5198 SDValue Table = Op.getOperand(1);
5199 SDValue Index = Op.getOperand(2);
5200 SDLoc dl(Op);
5202 EVT PTy = getPointerTy(DAG.getDataLayout());
5203 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5204 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5205 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5206 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5207 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5208 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5209 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5210 // which does another jump to the destination. This also makes it easier
5211 // to translate it to TBB / TBH later (Thumb2 only).
5212 // FIXME: This might not work if the function is extremely large.
5213 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5214 Addr, Op.getOperand(2), JTI);
5216 if (isPositionIndependent() || Subtarget->isROPI()) {
5217 Addr =
5218 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5219 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5220 Chain = Addr.getValue(1);
5221 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5222 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5223 } else {
5224 Addr =
5225 DAG.getLoad(PTy, dl, Chain, Addr,
5226 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5227 Chain = Addr.getValue(1);
5228 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5232 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5233 EVT VT = Op.getValueType();
5234 SDLoc dl(Op);
5236 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5237 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5238 return Op;
5239 return DAG.UnrollVectorOp(Op.getNode());
5242 const bool HasFullFP16 =
5243 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5245 EVT NewTy;
5246 const EVT OpTy = Op.getOperand(0).getValueType();
5247 if (OpTy == MVT::v4f32)
5248 NewTy = MVT::v4i32;
5249 else if (OpTy == MVT::v4f16 && HasFullFP16)
5250 NewTy = MVT::v4i16;
5251 else if (OpTy == MVT::v8f16 && HasFullFP16)
5252 NewTy = MVT::v8i16;
5253 else
5254 llvm_unreachable("Invalid type for custom lowering!");
5256 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5257 return DAG.UnrollVectorOp(Op.getNode());
5259 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5260 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5263 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5264 EVT VT = Op.getValueType();
5265 if (VT.isVector())
5266 return LowerVectorFP_TO_INT(Op, DAG);
5267 if (isUnsupportedFloatingType(Op.getOperand(0).getValueType())) {
5268 RTLIB::Libcall LC;
5269 if (Op.getOpcode() == ISD::FP_TO_SINT)
5270 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
5271 Op.getValueType());
5272 else
5273 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
5274 Op.getValueType());
5275 MakeLibCallOptions CallOptions;
5276 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5277 CallOptions, SDLoc(Op)).first;
5280 return Op;
5283 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5284 EVT VT = Op.getValueType();
5285 SDLoc dl(Op);
5287 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5288 if (VT.getVectorElementType() == MVT::f32)
5289 return Op;
5290 return DAG.UnrollVectorOp(Op.getNode());
5293 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5294 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5295 "Invalid type for custom lowering!");
5297 const bool HasFullFP16 =
5298 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5300 EVT DestVecType;
5301 if (VT == MVT::v4f32)
5302 DestVecType = MVT::v4i32;
5303 else if (VT == MVT::v4f16 && HasFullFP16)
5304 DestVecType = MVT::v4i16;
5305 else if (VT == MVT::v8f16 && HasFullFP16)
5306 DestVecType = MVT::v8i16;
5307 else
5308 return DAG.UnrollVectorOp(Op.getNode());
5310 unsigned CastOpc;
5311 unsigned Opc;
5312 switch (Op.getOpcode()) {
5313 default: llvm_unreachable("Invalid opcode!");
5314 case ISD::SINT_TO_FP:
5315 CastOpc = ISD::SIGN_EXTEND;
5316 Opc = ISD::SINT_TO_FP;
5317 break;
5318 case ISD::UINT_TO_FP:
5319 CastOpc = ISD::ZERO_EXTEND;
5320 Opc = ISD::UINT_TO_FP;
5321 break;
5324 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5325 return DAG.getNode(Opc, dl, VT, Op);
5328 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5329 EVT VT = Op.getValueType();
5330 if (VT.isVector())
5331 return LowerVectorINT_TO_FP(Op, DAG);
5332 if (isUnsupportedFloatingType(VT)) {
5333 RTLIB::Libcall LC;
5334 if (Op.getOpcode() == ISD::SINT_TO_FP)
5335 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5336 Op.getValueType());
5337 else
5338 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5339 Op.getValueType());
5340 MakeLibCallOptions CallOptions;
5341 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5342 CallOptions, SDLoc(Op)).first;
5345 return Op;
5348 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5349 // Implement fcopysign with a fabs and a conditional fneg.
5350 SDValue Tmp0 = Op.getOperand(0);
5351 SDValue Tmp1 = Op.getOperand(1);
5352 SDLoc dl(Op);
5353 EVT VT = Op.getValueType();
5354 EVT SrcVT = Tmp1.getValueType();
5355 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5356 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5357 bool UseNEON = !InGPR && Subtarget->hasNEON();
5359 if (UseNEON) {
5360 // Use VBSL to copy the sign bit.
5361 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5362 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5363 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5364 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5365 if (VT == MVT::f64)
5366 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5367 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5368 DAG.getConstant(32, dl, MVT::i32));
5369 else /*if (VT == MVT::f32)*/
5370 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5371 if (SrcVT == MVT::f32) {
5372 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5373 if (VT == MVT::f64)
5374 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5375 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5376 DAG.getConstant(32, dl, MVT::i32));
5377 } else if (VT == MVT::f32)
5378 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5379 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5380 DAG.getConstant(32, dl, MVT::i32));
5381 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5382 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5384 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5385 dl, MVT::i32);
5386 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5387 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5388 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5390 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5391 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5392 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5393 if (VT == MVT::f32) {
5394 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5395 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5396 DAG.getConstant(0, dl, MVT::i32));
5397 } else {
5398 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5401 return Res;
5404 // Bitcast operand 1 to i32.
5405 if (SrcVT == MVT::f64)
5406 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5407 Tmp1).getValue(1);
5408 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5410 // Or in the signbit with integer operations.
5411 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5412 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5413 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5414 if (VT == MVT::f32) {
5415 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5416 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5417 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5418 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5421 // f64: Or the high part with signbit and then combine two parts.
5422 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5423 Tmp0);
5424 SDValue Lo = Tmp0.getValue(0);
5425 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5426 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5427 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5430 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5431 MachineFunction &MF = DAG.getMachineFunction();
5432 MachineFrameInfo &MFI = MF.getFrameInfo();
5433 MFI.setReturnAddressIsTaken(true);
5435 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5436 return SDValue();
5438 EVT VT = Op.getValueType();
5439 SDLoc dl(Op);
5440 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5441 if (Depth) {
5442 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5443 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5444 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5445 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5446 MachinePointerInfo());
5449 // Return LR, which contains the return address. Mark it an implicit live-in.
5450 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5451 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5454 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5455 const ARMBaseRegisterInfo &ARI =
5456 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5457 MachineFunction &MF = DAG.getMachineFunction();
5458 MachineFrameInfo &MFI = MF.getFrameInfo();
5459 MFI.setFrameAddressIsTaken(true);
5461 EVT VT = Op.getValueType();
5462 SDLoc dl(Op); // FIXME probably not meaningful
5463 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5464 Register FrameReg = ARI.getFrameRegister(MF);
5465 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5466 while (Depth--)
5467 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5468 MachinePointerInfo());
5469 return FrameAddr;
5472 // FIXME? Maybe this could be a TableGen attribute on some registers and
5473 // this table could be generated automatically from RegInfo.
5474 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
5475 SelectionDAG &DAG) const {
5476 unsigned Reg = StringSwitch<unsigned>(RegName)
5477 .Case("sp", ARM::SP)
5478 .Default(0);
5479 if (Reg)
5480 return Reg;
5481 report_fatal_error(Twine("Invalid register name \""
5482 + StringRef(RegName) + "\"."));
5485 // Result is 64 bit value so split into two 32 bit values and return as a
5486 // pair of values.
5487 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5488 SelectionDAG &DAG) {
5489 SDLoc DL(N);
5491 // This function is only supposed to be called for i64 type destination.
5492 assert(N->getValueType(0) == MVT::i64
5493 && "ExpandREAD_REGISTER called for non-i64 type result.");
5495 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5496 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5497 N->getOperand(0),
5498 N->getOperand(1));
5500 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5501 Read.getValue(1)));
5502 Results.push_back(Read.getOperand(0));
5505 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5506 /// When \p DstVT, the destination type of \p BC, is on the vector
5507 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5508 /// it might be possible to combine them, such that everything stays on the
5509 /// vector register bank.
5510 /// \p return The node that would replace \p BT, if the combine
5511 /// is possible.
5512 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5513 SelectionDAG &DAG) {
5514 SDValue Op = BC->getOperand(0);
5515 EVT DstVT = BC->getValueType(0);
5517 // The only vector instruction that can produce a scalar (remember,
5518 // since the bitcast was about to be turned into VMOVDRR, the source
5519 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5520 // Moreover, we can do this combine only if there is one use.
5521 // Finally, if the destination type is not a vector, there is not
5522 // much point on forcing everything on the vector bank.
5523 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5524 !Op.hasOneUse())
5525 return SDValue();
5527 // If the index is not constant, we will introduce an additional
5528 // multiply that will stick.
5529 // Give up in that case.
5530 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5531 if (!Index)
5532 return SDValue();
5533 unsigned DstNumElt = DstVT.getVectorNumElements();
5535 // Compute the new index.
5536 const APInt &APIntIndex = Index->getAPIntValue();
5537 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5538 NewIndex *= APIntIndex;
5539 // Check if the new constant index fits into i32.
5540 if (NewIndex.getBitWidth() > 32)
5541 return SDValue();
5543 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5544 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5545 SDLoc dl(Op);
5546 SDValue ExtractSrc = Op.getOperand(0);
5547 EVT VecVT = EVT::getVectorVT(
5548 *DAG.getContext(), DstVT.getScalarType(),
5549 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5550 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5551 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5552 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5555 /// ExpandBITCAST - If the target supports VFP, this function is called to
5556 /// expand a bit convert where either the source or destination type is i64 to
5557 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
5558 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5559 /// vectors), since the legalizer won't know what to do with that.
5560 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5561 const ARMSubtarget *Subtarget) {
5562 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5563 SDLoc dl(N);
5564 SDValue Op = N->getOperand(0);
5566 // This function is only supposed to be called for i64 types, either as the
5567 // source or destination of the bit convert.
5568 EVT SrcVT = Op.getValueType();
5569 EVT DstVT = N->getValueType(0);
5570 const bool HasFullFP16 = Subtarget->hasFullFP16();
5572 if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5573 // FullFP16: half values are passed in S-registers, and we don't
5574 // need any of the bitcast and moves:
5576 // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5577 // t5: i32 = bitcast t2
5578 // t18: f16 = ARMISD::VMOVhr t5
5579 if (Op.getOpcode() != ISD::CopyFromReg ||
5580 Op.getValueType() != MVT::f32)
5581 return SDValue();
5583 auto Move = N->use_begin();
5584 if (Move->getOpcode() != ARMISD::VMOVhr)
5585 return SDValue();
5587 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5588 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5589 DAG.ReplaceAllUsesWith(*Move, &Copy);
5590 return Copy;
5593 if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5594 if (!HasFullFP16)
5595 return SDValue();
5596 // SoftFP: read half-precision arguments:
5598 // t2: i32,ch = ...
5599 // t7: i16 = truncate t2 <~~~~ Op
5600 // t8: f16 = bitcast t7 <~~~~ N
5602 if (Op.getOperand(0).getValueType() == MVT::i32)
5603 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5604 MVT::f16, Op.getOperand(0));
5606 return SDValue();
5609 // Half-precision return values
5610 if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5611 if (!HasFullFP16)
5612 return SDValue();
5614 // t11: f16 = fadd t8, t10
5615 // t12: i16 = bitcast t11 <~~~ SDNode N
5616 // t13: i32 = zero_extend t12
5617 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5618 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5620 // transform this into:
5622 // t20: i32 = ARMISD::VMOVrh t11
5623 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5625 auto ZeroExtend = N->use_begin();
5626 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5627 ZeroExtend->getValueType(0) != MVT::i32)
5628 return SDValue();
5630 auto Copy = ZeroExtend->use_begin();
5631 if (Copy->getOpcode() == ISD::CopyToReg &&
5632 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5633 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5634 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5635 return Cvt;
5637 return SDValue();
5640 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5641 return SDValue();
5643 // Turn i64->f64 into VMOVDRR.
5644 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5645 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5646 // if we can combine the bitcast with its source.
5647 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5648 return Val;
5650 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5651 DAG.getConstant(0, dl, MVT::i32));
5652 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5653 DAG.getConstant(1, dl, MVT::i32));
5654 return DAG.getNode(ISD::BITCAST, dl, DstVT,
5655 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5658 // Turn f64->i64 into VMOVRRD.
5659 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5660 SDValue Cvt;
5661 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5662 SrcVT.getVectorNumElements() > 1)
5663 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5664 DAG.getVTList(MVT::i32, MVT::i32),
5665 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5666 else
5667 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5668 DAG.getVTList(MVT::i32, MVT::i32), Op);
5669 // Merge the pieces into a single i64 value.
5670 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5673 return SDValue();
5676 /// getZeroVector - Returns a vector of specified type with all zero elements.
5677 /// Zero vectors are used to represent vector negation and in those cases
5678 /// will be implemented with the NEON VNEG instruction. However, VNEG does
5679 /// not support i64 elements, so sometimes the zero vectors will need to be
5680 /// explicitly constructed. Regardless, use a canonical VMOV to create the
5681 /// zero vector.
5682 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5683 assert(VT.isVector() && "Expected a vector type");
5684 // The canonical modified immediate encoding of a zero vector is....0!
5685 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5686 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5687 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5688 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5691 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5692 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5693 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5694 SelectionDAG &DAG) const {
5695 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5696 EVT VT = Op.getValueType();
5697 unsigned VTBits = VT.getSizeInBits();
5698 SDLoc dl(Op);
5699 SDValue ShOpLo = Op.getOperand(0);
5700 SDValue ShOpHi = Op.getOperand(1);
5701 SDValue ShAmt = Op.getOperand(2);
5702 SDValue ARMcc;
5703 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5704 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5706 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5708 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5709 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5710 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5711 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5712 DAG.getConstant(VTBits, dl, MVT::i32));
5713 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5714 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5715 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5716 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5717 ISD::SETGE, ARMcc, DAG, dl);
5718 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5719 ARMcc, CCR, CmpLo);
5721 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5722 SDValue HiBigShift = Opc == ISD::SRA
5723 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5724 DAG.getConstant(VTBits - 1, dl, VT))
5725 : DAG.getConstant(0, dl, VT);
5726 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5727 ISD::SETGE, ARMcc, DAG, dl);
5728 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5729 ARMcc, CCR, CmpHi);
5731 SDValue Ops[2] = { Lo, Hi };
5732 return DAG.getMergeValues(Ops, dl);
5735 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5736 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5737 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5738 SelectionDAG &DAG) const {
5739 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5740 EVT VT = Op.getValueType();
5741 unsigned VTBits = VT.getSizeInBits();
5742 SDLoc dl(Op);
5743 SDValue ShOpLo = Op.getOperand(0);
5744 SDValue ShOpHi = Op.getOperand(1);
5745 SDValue ShAmt = Op.getOperand(2);
5746 SDValue ARMcc;
5747 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5749 assert(Op.getOpcode() == ISD::SHL_PARTS);
5750 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5751 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5752 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5753 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5754 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5756 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5757 DAG.getConstant(VTBits, dl, MVT::i32));
5758 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5759 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5760 ISD::SETGE, ARMcc, DAG, dl);
5761 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5762 ARMcc, CCR, CmpHi);
5764 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5765 ISD::SETGE, ARMcc, DAG, dl);
5766 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5767 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5768 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5770 SDValue Ops[2] = { Lo, Hi };
5771 return DAG.getMergeValues(Ops, dl);
5774 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5775 SelectionDAG &DAG) const {
5776 // The rounding mode is in bits 23:22 of the FPSCR.
5777 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5778 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5779 // so that the shift + and get folded into a bitfield extract.
5780 SDLoc dl(Op);
5781 SDValue Ops[] = { DAG.getEntryNode(),
5782 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5784 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5785 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5786 DAG.getConstant(1U << 22, dl, MVT::i32));
5787 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5788 DAG.getConstant(22, dl, MVT::i32));
5789 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5790 DAG.getConstant(3, dl, MVT::i32));
5793 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5794 const ARMSubtarget *ST) {
5795 SDLoc dl(N);
5796 EVT VT = N->getValueType(0);
5797 if (VT.isVector()) {
5798 assert(ST->hasNEON());
5800 // Compute the least significant set bit: LSB = X & -X
5801 SDValue X = N->getOperand(0);
5802 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5803 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5805 EVT ElemTy = VT.getVectorElementType();
5807 if (ElemTy == MVT::i8) {
5808 // Compute with: cttz(x) = ctpop(lsb - 1)
5809 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5810 DAG.getTargetConstant(1, dl, ElemTy));
5811 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5812 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5815 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5816 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5817 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5818 unsigned NumBits = ElemTy.getSizeInBits();
5819 SDValue WidthMinus1 =
5820 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5821 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5822 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5823 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5826 // Compute with: cttz(x) = ctpop(lsb - 1)
5828 // Compute LSB - 1.
5829 SDValue Bits;
5830 if (ElemTy == MVT::i64) {
5831 // Load constant 0xffff'ffff'ffff'ffff to register.
5832 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5833 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5834 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5835 } else {
5836 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5837 DAG.getTargetConstant(1, dl, ElemTy));
5838 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5840 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5843 if (!ST->hasV6T2Ops())
5844 return SDValue();
5846 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5847 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5850 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5851 const ARMSubtarget *ST) {
5852 EVT VT = N->getValueType(0);
5853 SDLoc DL(N);
5855 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5856 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5857 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5858 "Unexpected type for custom ctpop lowering");
5860 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5861 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5862 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
5863 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
5865 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5866 unsigned EltSize = 8;
5867 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5868 while (EltSize != VT.getScalarSizeInBits()) {
5869 SmallVector<SDValue, 8> Ops;
5870 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
5871 TLI.getPointerTy(DAG.getDataLayout())));
5872 Ops.push_back(Res);
5874 EltSize *= 2;
5875 NumElts /= 2;
5876 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5877 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
5880 return Res;
5883 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
5884 /// operand of a vector shift operation, where all the elements of the
5885 /// build_vector must have the same constant integer value.
5886 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5887 // Ignore bit_converts.
5888 while (Op.getOpcode() == ISD::BITCAST)
5889 Op = Op.getOperand(0);
5890 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5891 APInt SplatBits, SplatUndef;
5892 unsigned SplatBitSize;
5893 bool HasAnyUndefs;
5894 if (!BVN ||
5895 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
5896 ElementBits) ||
5897 SplatBitSize > ElementBits)
5898 return false;
5899 Cnt = SplatBits.getSExtValue();
5900 return true;
5903 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5904 /// operand of a vector shift left operation. That value must be in the range:
5905 /// 0 <= Value < ElementBits for a left shift; or
5906 /// 0 <= Value <= ElementBits for a long left shift.
5907 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5908 assert(VT.isVector() && "vector shift count is not a vector type");
5909 int64_t ElementBits = VT.getScalarSizeInBits();
5910 if (!getVShiftImm(Op, ElementBits, Cnt))
5911 return false;
5912 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5915 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5916 /// operand of a vector shift right operation. For a shift opcode, the value
5917 /// is positive, but for an intrinsic the value count must be negative. The
5918 /// absolute value must be in the range:
5919 /// 1 <= |Value| <= ElementBits for a right shift; or
5920 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5921 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5922 int64_t &Cnt) {
5923 assert(VT.isVector() && "vector shift count is not a vector type");
5924 int64_t ElementBits = VT.getScalarSizeInBits();
5925 if (!getVShiftImm(Op, ElementBits, Cnt))
5926 return false;
5927 if (!isIntrinsic)
5928 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5929 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
5930 Cnt = -Cnt;
5931 return true;
5933 return false;
5936 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5937 const ARMSubtarget *ST) {
5938 EVT VT = N->getValueType(0);
5939 SDLoc dl(N);
5940 int64_t Cnt;
5942 if (!VT.isVector())
5943 return SDValue();
5945 // We essentially have two forms here. Shift by an immediate and shift by a
5946 // vector register (there are also shift by a gpr, but that is just handled
5947 // with a tablegen pattern). We cannot easily match shift by an immediate in
5948 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
5949 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
5950 // signed or unsigned, and a negative shift indicates a shift right).
5951 if (N->getOpcode() == ISD::SHL) {
5952 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
5953 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
5954 DAG.getConstant(Cnt, dl, MVT::i32));
5955 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
5956 N->getOperand(1));
5959 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
5960 "unexpected vector shift opcode");
5962 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
5963 unsigned VShiftOpc =
5964 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
5965 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
5966 DAG.getConstant(Cnt, dl, MVT::i32));
5969 // Other right shifts we don't have operations for (we use a shift left by a
5970 // negative number).
5971 EVT ShiftVT = N->getOperand(1).getValueType();
5972 SDValue NegatedCount = DAG.getNode(
5973 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
5974 unsigned VShiftOpc =
5975 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
5976 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
5979 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5980 const ARMSubtarget *ST) {
5981 EVT VT = N->getValueType(0);
5982 SDLoc dl(N);
5984 // We can get here for a node like i32 = ISD::SHL i32, i64
5985 if (VT != MVT::i64)
5986 return SDValue();
5988 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
5989 N->getOpcode() == ISD::SHL) &&
5990 "Unknown shift to lower!");
5992 unsigned ShOpc = N->getOpcode();
5993 if (ST->hasMVEIntegerOps()) {
5994 SDValue ShAmt = N->getOperand(1);
5995 unsigned ShPartsOpc = ARMISD::LSLL;
5996 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
5998 // If the shift amount is greater than 32 or has a greater bitwidth than 64
5999 // then do the default optimisation
6000 if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6001 (Con && Con->getZExtValue() >= 32))
6002 return SDValue();
6004 // Extract the lower 32 bits of the shift amount if it's not an i32
6005 if (ShAmt->getValueType(0) != MVT::i32)
6006 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6008 if (ShOpc == ISD::SRL) {
6009 if (!Con)
6010 // There is no t2LSRLr instruction so negate and perform an lsll if the
6011 // shift amount is in a register, emulating a right shift.
6012 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6013 DAG.getConstant(0, dl, MVT::i32), ShAmt);
6014 else
6015 // Else generate an lsrl on the immediate shift amount
6016 ShPartsOpc = ARMISD::LSRL;
6017 } else if (ShOpc == ISD::SRA)
6018 ShPartsOpc = ARMISD::ASRL;
6020 // Lower 32 bits of the destination/source
6021 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6022 DAG.getConstant(0, dl, MVT::i32));
6023 // Upper 32 bits of the destination/source
6024 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6025 DAG.getConstant(1, dl, MVT::i32));
6027 // Generate the shift operation as computed above
6028 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6029 ShAmt);
6030 // The upper 32 bits come from the second return value of lsll
6031 Hi = SDValue(Lo.getNode(), 1);
6032 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6035 // We only lower SRA, SRL of 1 here, all others use generic lowering.
6036 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6037 return SDValue();
6039 // If we are in thumb mode, we don't have RRX.
6040 if (ST->isThumb1Only())
6041 return SDValue();
6043 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
6044 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6045 DAG.getConstant(0, dl, MVT::i32));
6046 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6047 DAG.getConstant(1, dl, MVT::i32));
6049 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6050 // captures the result into a carry flag.
6051 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6052 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6054 // The low part is an ARMISD::RRX operand, which shifts the carry in.
6055 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6057 // Merge the pieces into a single i64 value.
6058 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6061 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6062 const ARMSubtarget *ST) {
6063 bool Invert = false;
6064 bool Swap = false;
6065 unsigned Opc = ARMCC::AL;
6067 SDValue Op0 = Op.getOperand(0);
6068 SDValue Op1 = Op.getOperand(1);
6069 SDValue CC = Op.getOperand(2);
6070 EVT VT = Op.getValueType();
6071 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6072 SDLoc dl(Op);
6074 EVT CmpVT;
6075 if (ST->hasNEON())
6076 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6077 else {
6078 assert(ST->hasMVEIntegerOps() &&
6079 "No hardware support for integer vector comparison!");
6081 if (Op.getValueType().getVectorElementType() != MVT::i1)
6082 return SDValue();
6084 // Make sure we expand floating point setcc to scalar if we do not have
6085 // mve.fp, so that we can handle them from there.
6086 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6087 return SDValue();
6089 CmpVT = VT;
6092 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6093 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6094 // Special-case integer 64-bit equality comparisons. They aren't legal,
6095 // but they can be lowered with a few vector instructions.
6096 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6097 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6098 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6099 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6100 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6101 DAG.getCondCode(ISD::SETEQ));
6102 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6103 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6104 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6105 if (SetCCOpcode == ISD::SETNE)
6106 Merged = DAG.getNOT(dl, Merged, CmpVT);
6107 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6108 return Merged;
6111 if (CmpVT.getVectorElementType() == MVT::i64)
6112 // 64-bit comparisons are not legal in general.
6113 return SDValue();
6115 if (Op1.getValueType().isFloatingPoint()) {
6116 switch (SetCCOpcode) {
6117 default: llvm_unreachable("Illegal FP comparison");
6118 case ISD::SETUNE:
6119 case ISD::SETNE:
6120 if (ST->hasMVEFloatOps()) {
6121 Opc = ARMCC::NE; break;
6122 } else {
6123 Invert = true; LLVM_FALLTHROUGH;
6125 case ISD::SETOEQ:
6126 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6127 case ISD::SETOLT:
6128 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6129 case ISD::SETOGT:
6130 case ISD::SETGT: Opc = ARMCC::GT; break;
6131 case ISD::SETOLE:
6132 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6133 case ISD::SETOGE:
6134 case ISD::SETGE: Opc = ARMCC::GE; break;
6135 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
6136 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6137 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
6138 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6139 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
6140 case ISD::SETONE: {
6141 // Expand this to (OLT | OGT).
6142 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6143 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6144 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6145 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6146 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6147 if (Invert)
6148 Result = DAG.getNOT(dl, Result, VT);
6149 return Result;
6151 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH;
6152 case ISD::SETO: {
6153 // Expand this to (OLT | OGE).
6154 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6155 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6156 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6157 DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6158 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6159 if (Invert)
6160 Result = DAG.getNOT(dl, Result, VT);
6161 return Result;
6164 } else {
6165 // Integer comparisons.
6166 switch (SetCCOpcode) {
6167 default: llvm_unreachable("Illegal integer comparison");
6168 case ISD::SETNE:
6169 if (ST->hasMVEIntegerOps()) {
6170 Opc = ARMCC::NE; break;
6171 } else {
6172 Invert = true; LLVM_FALLTHROUGH;
6174 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6175 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6176 case ISD::SETGT: Opc = ARMCC::GT; break;
6177 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6178 case ISD::SETGE: Opc = ARMCC::GE; break;
6179 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
6180 case ISD::SETUGT: Opc = ARMCC::HI; break;
6181 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
6182 case ISD::SETUGE: Opc = ARMCC::HS; break;
6185 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6186 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6187 SDValue AndOp;
6188 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6189 AndOp = Op0;
6190 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6191 AndOp = Op1;
6193 // Ignore bitconvert.
6194 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6195 AndOp = AndOp.getOperand(0);
6197 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6198 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6199 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6200 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6201 if (!Invert)
6202 Result = DAG.getNOT(dl, Result, VT);
6203 return Result;
6208 if (Swap)
6209 std::swap(Op0, Op1);
6211 // If one of the operands is a constant vector zero, attempt to fold the
6212 // comparison to a specialized compare-against-zero form.
6213 SDValue SingleOp;
6214 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6215 SingleOp = Op0;
6216 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6217 if (Opc == ARMCC::GE)
6218 Opc = ARMCC::LE;
6219 else if (Opc == ARMCC::GT)
6220 Opc = ARMCC::LT;
6221 SingleOp = Op1;
6224 SDValue Result;
6225 if (SingleOp.getNode()) {
6226 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6227 DAG.getConstant(Opc, dl, MVT::i32));
6228 } else {
6229 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6230 DAG.getConstant(Opc, dl, MVT::i32));
6233 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6235 if (Invert)
6236 Result = DAG.getNOT(dl, Result, VT);
6238 return Result;
6241 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6242 SDValue LHS = Op.getOperand(0);
6243 SDValue RHS = Op.getOperand(1);
6244 SDValue Carry = Op.getOperand(2);
6245 SDValue Cond = Op.getOperand(3);
6246 SDLoc DL(Op);
6248 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6250 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6251 // have to invert the carry first.
6252 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6253 DAG.getConstant(1, DL, MVT::i32), Carry);
6254 // This converts the boolean value carry into the carry flag.
6255 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6257 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6258 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6260 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6261 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6262 SDValue ARMcc = DAG.getConstant(
6263 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6264 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6265 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6266 Cmp.getValue(1), SDValue());
6267 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6268 CCR, Chain.getValue(1));
6271 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6272 /// valid vector constant for a NEON or MVE instruction with a "modified
6273 /// immediate" operand (e.g., VMOV). If so, return the encoded value.
6274 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6275 unsigned SplatBitSize, SelectionDAG &DAG,
6276 const SDLoc &dl, EVT &VT, bool is128Bits,
6277 VMOVModImmType type) {
6278 unsigned OpCmode, Imm;
6280 // SplatBitSize is set to the smallest size that splats the vector, so a
6281 // zero vector will always have SplatBitSize == 8. However, NEON modified
6282 // immediate instructions others than VMOV do not support the 8-bit encoding
6283 // of a zero vector, and the default encoding of zero is supposed to be the
6284 // 32-bit version.
6285 if (SplatBits == 0)
6286 SplatBitSize = 32;
6288 switch (SplatBitSize) {
6289 case 8:
6290 if (type != VMOVModImm)
6291 return SDValue();
6292 // Any 1-byte value is OK. Op=0, Cmode=1110.
6293 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6294 OpCmode = 0xe;
6295 Imm = SplatBits;
6296 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6297 break;
6299 case 16:
6300 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6301 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6302 if ((SplatBits & ~0xff) == 0) {
6303 // Value = 0x00nn: Op=x, Cmode=100x.
6304 OpCmode = 0x8;
6305 Imm = SplatBits;
6306 break;
6308 if ((SplatBits & ~0xff00) == 0) {
6309 // Value = 0xnn00: Op=x, Cmode=101x.
6310 OpCmode = 0xa;
6311 Imm = SplatBits >> 8;
6312 break;
6314 return SDValue();
6316 case 32:
6317 // NEON's 32-bit VMOV supports splat values where:
6318 // * only one byte is nonzero, or
6319 // * the least significant byte is 0xff and the second byte is nonzero, or
6320 // * the least significant 2 bytes are 0xff and the third is nonzero.
6321 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6322 if ((SplatBits & ~0xff) == 0) {
6323 // Value = 0x000000nn: Op=x, Cmode=000x.
6324 OpCmode = 0;
6325 Imm = SplatBits;
6326 break;
6328 if ((SplatBits & ~0xff00) == 0) {
6329 // Value = 0x0000nn00: Op=x, Cmode=001x.
6330 OpCmode = 0x2;
6331 Imm = SplatBits >> 8;
6332 break;
6334 if ((SplatBits & ~0xff0000) == 0) {
6335 // Value = 0x00nn0000: Op=x, Cmode=010x.
6336 OpCmode = 0x4;
6337 Imm = SplatBits >> 16;
6338 break;
6340 if ((SplatBits & ~0xff000000) == 0) {
6341 // Value = 0xnn000000: Op=x, Cmode=011x.
6342 OpCmode = 0x6;
6343 Imm = SplatBits >> 24;
6344 break;
6347 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6348 if (type == OtherModImm) return SDValue();
6350 if ((SplatBits & ~0xffff) == 0 &&
6351 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6352 // Value = 0x0000nnff: Op=x, Cmode=1100.
6353 OpCmode = 0xc;
6354 Imm = SplatBits >> 8;
6355 break;
6358 // cmode == 0b1101 is not supported for MVE VMVN
6359 if (type == MVEVMVNModImm)
6360 return SDValue();
6362 if ((SplatBits & ~0xffffff) == 0 &&
6363 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6364 // Value = 0x00nnffff: Op=x, Cmode=1101.
6365 OpCmode = 0xd;
6366 Imm = SplatBits >> 16;
6367 break;
6370 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6371 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6372 // VMOV.I32. A (very) minor optimization would be to replicate the value
6373 // and fall through here to test for a valid 64-bit splat. But, then the
6374 // caller would also need to check and handle the change in size.
6375 return SDValue();
6377 case 64: {
6378 if (type != VMOVModImm)
6379 return SDValue();
6380 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6381 uint64_t BitMask = 0xff;
6382 uint64_t Val = 0;
6383 unsigned ImmMask = 1;
6384 Imm = 0;
6385 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6386 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6387 Val |= BitMask;
6388 Imm |= ImmMask;
6389 } else if ((SplatBits & BitMask) != 0) {
6390 return SDValue();
6392 BitMask <<= 8;
6393 ImmMask <<= 1;
6396 if (DAG.getDataLayout().isBigEndian())
6397 // swap higher and lower 32 bit word
6398 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
6400 // Op=1, Cmode=1110.
6401 OpCmode = 0x1e;
6402 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6403 break;
6406 default:
6407 llvm_unreachable("unexpected size for isVMOVModifiedImm");
6410 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6411 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6414 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6415 const ARMSubtarget *ST) const {
6416 EVT VT = Op.getValueType();
6417 bool IsDouble = (VT == MVT::f64);
6418 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6419 const APFloat &FPVal = CFP->getValueAPF();
6421 // Prevent floating-point constants from using literal loads
6422 // when execute-only is enabled.
6423 if (ST->genExecuteOnly()) {
6424 // If we can represent the constant as an immediate, don't lower it
6425 if (isFPImmLegal(FPVal, VT))
6426 return Op;
6427 // Otherwise, construct as integer, and move to float register
6428 APInt INTVal = FPVal.bitcastToAPInt();
6429 SDLoc DL(CFP);
6430 switch (VT.getSimpleVT().SimpleTy) {
6431 default:
6432 llvm_unreachable("Unknown floating point type!");
6433 break;
6434 case MVT::f64: {
6435 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6436 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6437 if (!ST->isLittle())
6438 std::swap(Lo, Hi);
6439 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6441 case MVT::f32:
6442 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6443 DAG.getConstant(INTVal, DL, MVT::i32));
6447 if (!ST->hasVFP3Base())
6448 return SDValue();
6450 // Use the default (constant pool) lowering for double constants when we have
6451 // an SP-only FPU
6452 if (IsDouble && !Subtarget->hasFP64())
6453 return SDValue();
6455 // Try splatting with a VMOV.f32...
6456 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6458 if (ImmVal != -1) {
6459 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6460 // We have code in place to select a valid ConstantFP already, no need to
6461 // do any mangling.
6462 return Op;
6465 // It's a float and we are trying to use NEON operations where
6466 // possible. Lower it to a splat followed by an extract.
6467 SDLoc DL(Op);
6468 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6469 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6470 NewVal);
6471 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6472 DAG.getConstant(0, DL, MVT::i32));
6475 // The rest of our options are NEON only, make sure that's allowed before
6476 // proceeding..
6477 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6478 return SDValue();
6480 EVT VMovVT;
6481 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6483 // It wouldn't really be worth bothering for doubles except for one very
6484 // important value, which does happen to match: 0.0. So make sure we don't do
6485 // anything stupid.
6486 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6487 return SDValue();
6489 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6490 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6491 VMovVT, false, VMOVModImm);
6492 if (NewVal != SDValue()) {
6493 SDLoc DL(Op);
6494 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6495 NewVal);
6496 if (IsDouble)
6497 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6499 // It's a float: cast and extract a vector element.
6500 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6501 VecConstant);
6502 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6503 DAG.getConstant(0, DL, MVT::i32));
6506 // Finally, try a VMVN.i32
6507 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6508 false, VMVNModImm);
6509 if (NewVal != SDValue()) {
6510 SDLoc DL(Op);
6511 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6513 if (IsDouble)
6514 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6516 // It's a float: cast and extract a vector element.
6517 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6518 VecConstant);
6519 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6520 DAG.getConstant(0, DL, MVT::i32));
6523 return SDValue();
6526 // check if an VEXT instruction can handle the shuffle mask when the
6527 // vector sources of the shuffle are the same.
6528 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6529 unsigned NumElts = VT.getVectorNumElements();
6531 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6532 if (M[0] < 0)
6533 return false;
6535 Imm = M[0];
6537 // If this is a VEXT shuffle, the immediate value is the index of the first
6538 // element. The other shuffle indices must be the successive elements after
6539 // the first one.
6540 unsigned ExpectedElt = Imm;
6541 for (unsigned i = 1; i < NumElts; ++i) {
6542 // Increment the expected index. If it wraps around, just follow it
6543 // back to index zero and keep going.
6544 ++ExpectedElt;
6545 if (ExpectedElt == NumElts)
6546 ExpectedElt = 0;
6548 if (M[i] < 0) continue; // ignore UNDEF indices
6549 if (ExpectedElt != static_cast<unsigned>(M[i]))
6550 return false;
6553 return true;
6556 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6557 bool &ReverseVEXT, unsigned &Imm) {
6558 unsigned NumElts = VT.getVectorNumElements();
6559 ReverseVEXT = false;
6561 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6562 if (M[0] < 0)
6563 return false;
6565 Imm = M[0];
6567 // If this is a VEXT shuffle, the immediate value is the index of the first
6568 // element. The other shuffle indices must be the successive elements after
6569 // the first one.
6570 unsigned ExpectedElt = Imm;
6571 for (unsigned i = 1; i < NumElts; ++i) {
6572 // Increment the expected index. If it wraps around, it may still be
6573 // a VEXT but the source vectors must be swapped.
6574 ExpectedElt += 1;
6575 if (ExpectedElt == NumElts * 2) {
6576 ExpectedElt = 0;
6577 ReverseVEXT = true;
6580 if (M[i] < 0) continue; // ignore UNDEF indices
6581 if (ExpectedElt != static_cast<unsigned>(M[i]))
6582 return false;
6585 // Adjust the index value if the source operands will be swapped.
6586 if (ReverseVEXT)
6587 Imm -= NumElts;
6589 return true;
6592 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6593 /// instruction with the specified blocksize. (The order of the elements
6594 /// within each block of the vector is reversed.)
6595 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6596 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6597 "Only possible block sizes for VREV are: 16, 32, 64");
6599 unsigned EltSz = VT.getScalarSizeInBits();
6600 if (EltSz == 64)
6601 return false;
6603 unsigned NumElts = VT.getVectorNumElements();
6604 unsigned BlockElts = M[0] + 1;
6605 // If the first shuffle index is UNDEF, be optimistic.
6606 if (M[0] < 0)
6607 BlockElts = BlockSize / EltSz;
6609 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6610 return false;
6612 for (unsigned i = 0; i < NumElts; ++i) {
6613 if (M[i] < 0) continue; // ignore UNDEF indices
6614 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6615 return false;
6618 return true;
6621 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6622 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6623 // range, then 0 is placed into the resulting vector. So pretty much any mask
6624 // of 8 elements can work here.
6625 return VT == MVT::v8i8 && M.size() == 8;
6628 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6629 unsigned Index) {
6630 if (Mask.size() == Elements * 2)
6631 return Index / Elements;
6632 return Mask[Index] == 0 ? 0 : 1;
6635 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6636 // checking that pairs of elements in the shuffle mask represent the same index
6637 // in each vector, incrementing the expected index by 2 at each step.
6638 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6639 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6640 // v2={e,f,g,h}
6641 // WhichResult gives the offset for each element in the mask based on which
6642 // of the two results it belongs to.
6644 // The transpose can be represented either as:
6645 // result1 = shufflevector v1, v2, result1_shuffle_mask
6646 // result2 = shufflevector v1, v2, result2_shuffle_mask
6647 // where v1/v2 and the shuffle masks have the same number of elements
6648 // (here WhichResult (see below) indicates which result is being checked)
6650 // or as:
6651 // results = shufflevector v1, v2, shuffle_mask
6652 // where both results are returned in one vector and the shuffle mask has twice
6653 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6654 // want to check the low half and high half of the shuffle mask as if it were
6655 // the other case
6656 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6657 unsigned EltSz = VT.getScalarSizeInBits();
6658 if (EltSz == 64)
6659 return false;
6661 unsigned NumElts = VT.getVectorNumElements();
6662 if (M.size() != NumElts && M.size() != NumElts*2)
6663 return false;
6665 // If the mask is twice as long as the input vector then we need to check the
6666 // upper and lower parts of the mask with a matching value for WhichResult
6667 // FIXME: A mask with only even values will be rejected in case the first
6668 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6669 // M[0] is used to determine WhichResult
6670 for (unsigned i = 0; i < M.size(); i += NumElts) {
6671 WhichResult = SelectPairHalf(NumElts, M, i);
6672 for (unsigned j = 0; j < NumElts; j += 2) {
6673 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6674 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6675 return false;
6679 if (M.size() == NumElts*2)
6680 WhichResult = 0;
6682 return true;
6685 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6686 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6687 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6688 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6689 unsigned EltSz = VT.getScalarSizeInBits();
6690 if (EltSz == 64)
6691 return false;
6693 unsigned NumElts = VT.getVectorNumElements();
6694 if (M.size() != NumElts && M.size() != NumElts*2)
6695 return false;
6697 for (unsigned i = 0; i < M.size(); i += NumElts) {
6698 WhichResult = SelectPairHalf(NumElts, M, i);
6699 for (unsigned j = 0; j < NumElts; j += 2) {
6700 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6701 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6702 return false;
6706 if (M.size() == NumElts*2)
6707 WhichResult = 0;
6709 return true;
6712 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6713 // that the mask elements are either all even and in steps of size 2 or all odd
6714 // and in steps of size 2.
6715 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6716 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6717 // v2={e,f,g,h}
6718 // Requires similar checks to that of isVTRNMask with
6719 // respect the how results are returned.
6720 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6721 unsigned EltSz = VT.getScalarSizeInBits();
6722 if (EltSz == 64)
6723 return false;
6725 unsigned NumElts = VT.getVectorNumElements();
6726 if (M.size() != NumElts && M.size() != NumElts*2)
6727 return false;
6729 for (unsigned i = 0; i < M.size(); i += NumElts) {
6730 WhichResult = SelectPairHalf(NumElts, M, i);
6731 for (unsigned j = 0; j < NumElts; ++j) {
6732 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6733 return false;
6737 if (M.size() == NumElts*2)
6738 WhichResult = 0;
6740 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6741 if (VT.is64BitVector() && EltSz == 32)
6742 return false;
6744 return true;
6747 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6748 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6749 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6750 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6751 unsigned EltSz = VT.getScalarSizeInBits();
6752 if (EltSz == 64)
6753 return false;
6755 unsigned NumElts = VT.getVectorNumElements();
6756 if (M.size() != NumElts && M.size() != NumElts*2)
6757 return false;
6759 unsigned Half = NumElts / 2;
6760 for (unsigned i = 0; i < M.size(); i += NumElts) {
6761 WhichResult = SelectPairHalf(NumElts, M, i);
6762 for (unsigned j = 0; j < NumElts; j += Half) {
6763 unsigned Idx = WhichResult;
6764 for (unsigned k = 0; k < Half; ++k) {
6765 int MIdx = M[i + j + k];
6766 if (MIdx >= 0 && (unsigned) MIdx != Idx)
6767 return false;
6768 Idx += 2;
6773 if (M.size() == NumElts*2)
6774 WhichResult = 0;
6776 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6777 if (VT.is64BitVector() && EltSz == 32)
6778 return false;
6780 return true;
6783 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6784 // that pairs of elements of the shufflemask represent the same index in each
6785 // vector incrementing sequentially through the vectors.
6786 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6787 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6788 // v2={e,f,g,h}
6789 // Requires similar checks to that of isVTRNMask with respect the how results
6790 // are returned.
6791 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6792 unsigned EltSz = VT.getScalarSizeInBits();
6793 if (EltSz == 64)
6794 return false;
6796 unsigned NumElts = VT.getVectorNumElements();
6797 if (M.size() != NumElts && M.size() != NumElts*2)
6798 return false;
6800 for (unsigned i = 0; i < M.size(); i += NumElts) {
6801 WhichResult = SelectPairHalf(NumElts, M, i);
6802 unsigned Idx = WhichResult * NumElts / 2;
6803 for (unsigned j = 0; j < NumElts; j += 2) {
6804 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6805 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6806 return false;
6807 Idx += 1;
6811 if (M.size() == NumElts*2)
6812 WhichResult = 0;
6814 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6815 if (VT.is64BitVector() && EltSz == 32)
6816 return false;
6818 return true;
6821 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6822 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6823 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6824 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6825 unsigned EltSz = VT.getScalarSizeInBits();
6826 if (EltSz == 64)
6827 return false;
6829 unsigned NumElts = VT.getVectorNumElements();
6830 if (M.size() != NumElts && M.size() != NumElts*2)
6831 return false;
6833 for (unsigned i = 0; i < M.size(); i += NumElts) {
6834 WhichResult = SelectPairHalf(NumElts, M, i);
6835 unsigned Idx = WhichResult * NumElts / 2;
6836 for (unsigned j = 0; j < NumElts; j += 2) {
6837 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6838 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6839 return false;
6840 Idx += 1;
6844 if (M.size() == NumElts*2)
6845 WhichResult = 0;
6847 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6848 if (VT.is64BitVector() && EltSz == 32)
6849 return false;
6851 return true;
6854 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6855 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6856 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6857 unsigned &WhichResult,
6858 bool &isV_UNDEF) {
6859 isV_UNDEF = false;
6860 if (isVTRNMask(ShuffleMask, VT, WhichResult))
6861 return ARMISD::VTRN;
6862 if (isVUZPMask(ShuffleMask, VT, WhichResult))
6863 return ARMISD::VUZP;
6864 if (isVZIPMask(ShuffleMask, VT, WhichResult))
6865 return ARMISD::VZIP;
6867 isV_UNDEF = true;
6868 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6869 return ARMISD::VTRN;
6870 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6871 return ARMISD::VUZP;
6872 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6873 return ARMISD::VZIP;
6875 return 0;
6878 /// \return true if this is a reverse operation on an vector.
6879 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6880 unsigned NumElts = VT.getVectorNumElements();
6881 // Make sure the mask has the right size.
6882 if (NumElts != M.size())
6883 return false;
6885 // Look for <15, ..., 3, -1, 1, 0>.
6886 for (unsigned i = 0; i != NumElts; ++i)
6887 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6888 return false;
6890 return true;
6893 // If N is an integer constant that can be moved into a register in one
6894 // instruction, return an SDValue of such a constant (will become a MOV
6895 // instruction). Otherwise return null.
6896 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6897 const ARMSubtarget *ST, const SDLoc &dl) {
6898 uint64_t Val;
6899 if (!isa<ConstantSDNode>(N))
6900 return SDValue();
6901 Val = cast<ConstantSDNode>(N)->getZExtValue();
6903 if (ST->isThumb1Only()) {
6904 if (Val <= 255 || ~Val <= 255)
6905 return DAG.getConstant(Val, dl, MVT::i32);
6906 } else {
6907 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6908 return DAG.getConstant(Val, dl, MVT::i32);
6910 return SDValue();
6913 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
6914 const ARMSubtarget *ST) {
6915 SDLoc dl(Op);
6916 EVT VT = Op.getValueType();
6918 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
6920 unsigned NumElts = VT.getVectorNumElements();
6921 unsigned BoolMask;
6922 unsigned BitsPerBool;
6923 if (NumElts == 4) {
6924 BitsPerBool = 4;
6925 BoolMask = 0xf;
6926 } else if (NumElts == 8) {
6927 BitsPerBool = 2;
6928 BoolMask = 0x3;
6929 } else if (NumElts == 16) {
6930 BitsPerBool = 1;
6931 BoolMask = 0x1;
6932 } else
6933 return SDValue();
6935 // First create base with bits set where known
6936 unsigned Bits32 = 0;
6937 for (unsigned i = 0; i < NumElts; ++i) {
6938 SDValue V = Op.getOperand(i);
6939 if (!isa<ConstantSDNode>(V) && !V.isUndef())
6940 continue;
6941 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
6942 if (BitSet)
6943 Bits32 |= BoolMask << (i * BitsPerBool);
6946 // Add in unknown nodes
6947 // FIXME: Handle splats of the same value better.
6948 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
6949 DAG.getConstant(Bits32, dl, MVT::i32));
6950 for (unsigned i = 0; i < NumElts; ++i) {
6951 SDValue V = Op.getOperand(i);
6952 if (isa<ConstantSDNode>(V) || V.isUndef())
6953 continue;
6954 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
6955 DAG.getConstant(i, dl, MVT::i32));
6958 return Base;
6961 // If this is a case we can't handle, return null and let the default
6962 // expansion code take care of it.
6963 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6964 const ARMSubtarget *ST) const {
6965 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6966 SDLoc dl(Op);
6967 EVT VT = Op.getValueType();
6969 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
6970 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
6972 APInt SplatBits, SplatUndef;
6973 unsigned SplatBitSize;
6974 bool HasAnyUndefs;
6975 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6976 if (SplatUndef.isAllOnesValue())
6977 return DAG.getUNDEF(VT);
6979 if ((ST->hasNEON() && SplatBitSize <= 64) ||
6980 (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) {
6981 // Check if an immediate VMOV works.
6982 EVT VmovVT;
6983 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
6984 SplatUndef.getZExtValue(), SplatBitSize,
6985 DAG, dl, VmovVT, VT.is128BitVector(),
6986 VMOVModImm);
6988 if (Val.getNode()) {
6989 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6990 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6993 // Try an immediate VMVN.
6994 uint64_t NegatedImm = (~SplatBits).getZExtValue();
6995 Val = isVMOVModifiedImm(
6996 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
6997 DAG, dl, VmovVT, VT.is128BitVector(),
6998 ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
6999 if (Val.getNode()) {
7000 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7001 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7004 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7005 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7006 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7007 if (ImmVal != -1) {
7008 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7009 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7015 // Scan through the operands to see if only one value is used.
7017 // As an optimisation, even if more than one value is used it may be more
7018 // profitable to splat with one value then change some lanes.
7020 // Heuristically we decide to do this if the vector has a "dominant" value,
7021 // defined as splatted to more than half of the lanes.
7022 unsigned NumElts = VT.getVectorNumElements();
7023 bool isOnlyLowElement = true;
7024 bool usesOnlyOneValue = true;
7025 bool hasDominantValue = false;
7026 bool isConstant = true;
7028 // Map of the number of times a particular SDValue appears in the
7029 // element list.
7030 DenseMap<SDValue, unsigned> ValueCounts;
7031 SDValue Value;
7032 for (unsigned i = 0; i < NumElts; ++i) {
7033 SDValue V = Op.getOperand(i);
7034 if (V.isUndef())
7035 continue;
7036 if (i > 0)
7037 isOnlyLowElement = false;
7038 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7039 isConstant = false;
7041 ValueCounts.insert(std::make_pair(V, 0));
7042 unsigned &Count = ValueCounts[V];
7044 // Is this value dominant? (takes up more than half of the lanes)
7045 if (++Count > (NumElts / 2)) {
7046 hasDominantValue = true;
7047 Value = V;
7050 if (ValueCounts.size() != 1)
7051 usesOnlyOneValue = false;
7052 if (!Value.getNode() && !ValueCounts.empty())
7053 Value = ValueCounts.begin()->first;
7055 if (ValueCounts.empty())
7056 return DAG.getUNDEF(VT);
7058 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7059 // Keep going if we are hitting this case.
7060 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7061 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7063 unsigned EltSize = VT.getScalarSizeInBits();
7065 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7066 // i32 and try again.
7067 if (hasDominantValue && EltSize <= 32) {
7068 if (!isConstant) {
7069 SDValue N;
7071 // If we are VDUPing a value that comes directly from a vector, that will
7072 // cause an unnecessary move to and from a GPR, where instead we could
7073 // just use VDUPLANE. We can only do this if the lane being extracted
7074 // is at a constant index, as the VDUP from lane instructions only have
7075 // constant-index forms.
7076 ConstantSDNode *constIndex;
7077 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7078 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7079 // We need to create a new undef vector to use for the VDUPLANE if the
7080 // size of the vector from which we get the value is different than the
7081 // size of the vector that we need to create. We will insert the element
7082 // such that the register coalescer will remove unnecessary copies.
7083 if (VT != Value->getOperand(0).getValueType()) {
7084 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7085 VT.getVectorNumElements();
7086 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7087 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7088 Value, DAG.getConstant(index, dl, MVT::i32)),
7089 DAG.getConstant(index, dl, MVT::i32));
7090 } else
7091 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7092 Value->getOperand(0), Value->getOperand(1));
7093 } else
7094 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7096 if (!usesOnlyOneValue) {
7097 // The dominant value was splatted as 'N', but we now have to insert
7098 // all differing elements.
7099 for (unsigned I = 0; I < NumElts; ++I) {
7100 if (Op.getOperand(I) == Value)
7101 continue;
7102 SmallVector<SDValue, 3> Ops;
7103 Ops.push_back(N);
7104 Ops.push_back(Op.getOperand(I));
7105 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7106 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7109 return N;
7111 if (VT.getVectorElementType().isFloatingPoint()) {
7112 SmallVector<SDValue, 8> Ops;
7113 MVT FVT = VT.getVectorElementType().getSimpleVT();
7114 assert(FVT == MVT::f32 || FVT == MVT::f16);
7115 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7116 for (unsigned i = 0; i < NumElts; ++i)
7117 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7118 Op.getOperand(i)));
7119 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7120 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7121 Val = LowerBUILD_VECTOR(Val, DAG, ST);
7122 if (Val.getNode())
7123 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7125 if (usesOnlyOneValue) {
7126 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7127 if (isConstant && Val.getNode())
7128 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7132 // If all elements are constants and the case above didn't get hit, fall back
7133 // to the default expansion, which will generate a load from the constant
7134 // pool.
7135 if (isConstant)
7136 return SDValue();
7138 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7139 if (NumElts >= 4) {
7140 SDValue shuffle = ReconstructShuffle(Op, DAG);
7141 if (shuffle != SDValue())
7142 return shuffle;
7145 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7146 // If we haven't found an efficient lowering, try splitting a 128-bit vector
7147 // into two 64-bit vectors; we might discover a better way to lower it.
7148 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7149 EVT ExtVT = VT.getVectorElementType();
7150 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7151 SDValue Lower =
7152 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7153 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7154 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7155 SDValue Upper = DAG.getBuildVector(
7156 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7157 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7158 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7159 if (Lower && Upper)
7160 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7163 // Vectors with 32- or 64-bit elements can be built by directly assigning
7164 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
7165 // will be legalized.
7166 if (EltSize >= 32) {
7167 // Do the expansion with floating-point types, since that is what the VFP
7168 // registers are defined to use, and since i64 is not legal.
7169 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7170 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7171 SmallVector<SDValue, 8> Ops;
7172 for (unsigned i = 0; i < NumElts; ++i)
7173 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7174 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7175 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7178 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7179 // know the default expansion would otherwise fall back on something even
7180 // worse. For a vector with one or two non-undef values, that's
7181 // scalar_to_vector for the elements followed by a shuffle (provided the
7182 // shuffle is valid for the target) and materialization element by element
7183 // on the stack followed by a load for everything else.
7184 if (!isConstant && !usesOnlyOneValue) {
7185 SDValue Vec = DAG.getUNDEF(VT);
7186 for (unsigned i = 0 ; i < NumElts; ++i) {
7187 SDValue V = Op.getOperand(i);
7188 if (V.isUndef())
7189 continue;
7190 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7191 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7193 return Vec;
7196 return SDValue();
7199 // Gather data to see if the operation can be modelled as a
7200 // shuffle in combination with VEXTs.
7201 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7202 SelectionDAG &DAG) const {
7203 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7204 SDLoc dl(Op);
7205 EVT VT = Op.getValueType();
7206 unsigned NumElts = VT.getVectorNumElements();
7208 struct ShuffleSourceInfo {
7209 SDValue Vec;
7210 unsigned MinElt = std::numeric_limits<unsigned>::max();
7211 unsigned MaxElt = 0;
7213 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7214 // be compatible with the shuffle we intend to construct. As a result
7215 // ShuffleVec will be some sliding window into the original Vec.
7216 SDValue ShuffleVec;
7218 // Code should guarantee that element i in Vec starts at element "WindowBase
7219 // + i * WindowScale in ShuffleVec".
7220 int WindowBase = 0;
7221 int WindowScale = 1;
7223 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7225 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7228 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7229 // node.
7230 SmallVector<ShuffleSourceInfo, 2> Sources;
7231 for (unsigned i = 0; i < NumElts; ++i) {
7232 SDValue V = Op.getOperand(i);
7233 if (V.isUndef())
7234 continue;
7235 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7236 // A shuffle can only come from building a vector from various
7237 // elements of other vectors.
7238 return SDValue();
7239 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7240 // Furthermore, shuffles require a constant mask, whereas extractelts
7241 // accept variable indices.
7242 return SDValue();
7245 // Add this element source to the list if it's not already there.
7246 SDValue SourceVec = V.getOperand(0);
7247 auto Source = llvm::find(Sources, SourceVec);
7248 if (Source == Sources.end())
7249 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7251 // Update the minimum and maximum lane number seen.
7252 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7253 Source->MinElt = std::min(Source->MinElt, EltNo);
7254 Source->MaxElt = std::max(Source->MaxElt, EltNo);
7257 // Currently only do something sane when at most two source vectors
7258 // are involved.
7259 if (Sources.size() > 2)
7260 return SDValue();
7262 // Find out the smallest element size among result and two sources, and use
7263 // it as element size to build the shuffle_vector.
7264 EVT SmallestEltTy = VT.getVectorElementType();
7265 for (auto &Source : Sources) {
7266 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7267 if (SrcEltTy.bitsLT(SmallestEltTy))
7268 SmallestEltTy = SrcEltTy;
7270 unsigned ResMultiplier =
7271 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7272 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7273 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7275 // If the source vector is too wide or too narrow, we may nevertheless be able
7276 // to construct a compatible shuffle either by concatenating it with UNDEF or
7277 // extracting a suitable range of elements.
7278 for (auto &Src : Sources) {
7279 EVT SrcVT = Src.ShuffleVec.getValueType();
7281 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7282 continue;
7284 // This stage of the search produces a source with the same element type as
7285 // the original, but with a total width matching the BUILD_VECTOR output.
7286 EVT EltVT = SrcVT.getVectorElementType();
7287 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7288 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7290 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7291 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
7292 return SDValue();
7293 // We can pad out the smaller vector for free, so if it's part of a
7294 // shuffle...
7295 Src.ShuffleVec =
7296 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7297 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7298 continue;
7301 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
7302 return SDValue();
7304 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7305 // Span too large for a VEXT to cope
7306 return SDValue();
7309 if (Src.MinElt >= NumSrcElts) {
7310 // The extraction can just take the second half
7311 Src.ShuffleVec =
7312 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7313 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7314 Src.WindowBase = -NumSrcElts;
7315 } else if (Src.MaxElt < NumSrcElts) {
7316 // The extraction can just take the first half
7317 Src.ShuffleVec =
7318 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7319 DAG.getConstant(0, dl, MVT::i32));
7320 } else {
7321 // An actual VEXT is needed
7322 SDValue VEXTSrc1 =
7323 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7324 DAG.getConstant(0, dl, MVT::i32));
7325 SDValue VEXTSrc2 =
7326 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7327 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7329 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7330 VEXTSrc2,
7331 DAG.getConstant(Src.MinElt, dl, MVT::i32));
7332 Src.WindowBase = -Src.MinElt;
7336 // Another possible incompatibility occurs from the vector element types. We
7337 // can fix this by bitcasting the source vectors to the same type we intend
7338 // for the shuffle.
7339 for (auto &Src : Sources) {
7340 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7341 if (SrcEltTy == SmallestEltTy)
7342 continue;
7343 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7344 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7345 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7346 Src.WindowBase *= Src.WindowScale;
7349 // Final sanity check before we try to actually produce a shuffle.
7350 LLVM_DEBUG(for (auto Src
7351 : Sources)
7352 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7354 // The stars all align, our next step is to produce the mask for the shuffle.
7355 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7356 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7357 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7358 SDValue Entry = Op.getOperand(i);
7359 if (Entry.isUndef())
7360 continue;
7362 auto Src = llvm::find(Sources, Entry.getOperand(0));
7363 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7365 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7366 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7367 // segment.
7368 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7369 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
7370 VT.getScalarSizeInBits());
7371 int LanesDefined = BitsDefined / BitsPerShuffleLane;
7373 // This source is expected to fill ResMultiplier lanes of the final shuffle,
7374 // starting at the appropriate offset.
7375 int *LaneMask = &Mask[i * ResMultiplier];
7377 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7378 ExtractBase += NumElts * (Src - Sources.begin());
7379 for (int j = 0; j < LanesDefined; ++j)
7380 LaneMask[j] = ExtractBase + j;
7384 // We can't handle more than two sources. This should have already
7385 // been checked before this point.
7386 assert(Sources.size() <= 2 && "Too many sources!");
7388 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7389 for (unsigned i = 0; i < Sources.size(); ++i)
7390 ShuffleOps[i] = Sources[i].ShuffleVec;
7392 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7393 ShuffleOps[1], Mask, DAG);
7394 if (!Shuffle)
7395 return SDValue();
7396 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7399 enum ShuffleOpCodes {
7400 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7401 OP_VREV,
7402 OP_VDUP0,
7403 OP_VDUP1,
7404 OP_VDUP2,
7405 OP_VDUP3,
7406 OP_VEXT1,
7407 OP_VEXT2,
7408 OP_VEXT3,
7409 OP_VUZPL, // VUZP, left result
7410 OP_VUZPR, // VUZP, right result
7411 OP_VZIPL, // VZIP, left result
7412 OP_VZIPR, // VZIP, right result
7413 OP_VTRNL, // VTRN, left result
7414 OP_VTRNR // VTRN, right result
7417 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7418 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7419 switch (OpNum) {
7420 case OP_COPY:
7421 case OP_VREV:
7422 case OP_VDUP0:
7423 case OP_VDUP1:
7424 case OP_VDUP2:
7425 case OP_VDUP3:
7426 return true;
7428 return false;
7431 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7432 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7433 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7434 /// are assumed to be legal.
7435 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7436 if (VT.getVectorNumElements() == 4 &&
7437 (VT.is128BitVector() || VT.is64BitVector())) {
7438 unsigned PFIndexes[4];
7439 for (unsigned i = 0; i != 4; ++i) {
7440 if (M[i] < 0)
7441 PFIndexes[i] = 8;
7442 else
7443 PFIndexes[i] = M[i];
7446 // Compute the index in the perfect shuffle table.
7447 unsigned PFTableIndex =
7448 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7449 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7450 unsigned Cost = (PFEntry >> 30);
7452 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7453 return true;
7456 bool ReverseVEXT, isV_UNDEF;
7457 unsigned Imm, WhichResult;
7459 unsigned EltSize = VT.getScalarSizeInBits();
7460 if (EltSize >= 32 ||
7461 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7462 isVREVMask(M, VT, 64) ||
7463 isVREVMask(M, VT, 32) ||
7464 isVREVMask(M, VT, 16))
7465 return true;
7466 else if (Subtarget->hasNEON() &&
7467 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7468 isVTBLMask(M, VT) ||
7469 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7470 return true;
7471 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7472 isReverseMask(M, VT))
7473 return true;
7474 else
7475 return false;
7478 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7479 /// the specified operations to build the shuffle.
7480 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7481 SDValue RHS, SelectionDAG &DAG,
7482 const SDLoc &dl) {
7483 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7484 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7485 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7487 if (OpNum == OP_COPY) {
7488 if (LHSID == (1*9+2)*9+3) return LHS;
7489 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7490 return RHS;
7493 SDValue OpLHS, OpRHS;
7494 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7495 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7496 EVT VT = OpLHS.getValueType();
7498 switch (OpNum) {
7499 default: llvm_unreachable("Unknown shuffle opcode!");
7500 case OP_VREV:
7501 // VREV divides the vector in half and swaps within the half.
7502 if (VT.getVectorElementType() == MVT::i32 ||
7503 VT.getVectorElementType() == MVT::f32)
7504 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
7505 // vrev <4 x i16> -> VREV32
7506 if (VT.getVectorElementType() == MVT::i16)
7507 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
7508 // vrev <4 x i8> -> VREV16
7509 assert(VT.getVectorElementType() == MVT::i8);
7510 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
7511 case OP_VDUP0:
7512 case OP_VDUP1:
7513 case OP_VDUP2:
7514 case OP_VDUP3:
7515 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7516 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
7517 case OP_VEXT1:
7518 case OP_VEXT2:
7519 case OP_VEXT3:
7520 return DAG.getNode(ARMISD::VEXT, dl, VT,
7521 OpLHS, OpRHS,
7522 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
7523 case OP_VUZPL:
7524 case OP_VUZPR:
7525 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
7526 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
7527 case OP_VZIPL:
7528 case OP_VZIPR:
7529 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
7530 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
7531 case OP_VTRNL:
7532 case OP_VTRNR:
7533 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
7534 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
7538 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
7539 ArrayRef<int> ShuffleMask,
7540 SelectionDAG &DAG) {
7541 // Check to see if we can use the VTBL instruction.
7542 SDValue V1 = Op.getOperand(0);
7543 SDValue V2 = Op.getOperand(1);
7544 SDLoc DL(Op);
7546 SmallVector<SDValue, 8> VTBLMask;
7547 for (ArrayRef<int>::iterator
7548 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
7549 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
7551 if (V2.getNode()->isUndef())
7552 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
7553 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7555 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
7556 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7559 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
7560 SelectionDAG &DAG) {
7561 SDLoc DL(Op);
7562 SDValue OpLHS = Op.getOperand(0);
7563 EVT VT = OpLHS.getValueType();
7565 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
7566 "Expect an v8i16/v16i8 type");
7567 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
7568 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
7569 // extract the first 8 bytes into the top double word and the last 8 bytes
7570 // into the bottom double word. The v8i16 case is similar.
7571 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
7572 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
7573 DAG.getConstant(ExtractNum, DL, MVT::i32));
7576 static EVT getVectorTyFromPredicateVector(EVT VT) {
7577 switch (VT.getSimpleVT().SimpleTy) {
7578 case MVT::v4i1:
7579 return MVT::v4i32;
7580 case MVT::v8i1:
7581 return MVT::v8i16;
7582 case MVT::v16i1:
7583 return MVT::v16i8;
7584 default:
7585 llvm_unreachable("Unexpected vector predicate type");
7589 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
7590 SelectionDAG &DAG) {
7591 // Converting from boolean predicates to integers involves creating a vector
7592 // of all ones or all zeroes and selecting the lanes based upon the real
7593 // predicate.
7594 SDValue AllOnes =
7595 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
7596 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
7598 SDValue AllZeroes =
7599 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
7600 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
7602 // Get full vector type from predicate type
7603 EVT NewVT = getVectorTyFromPredicateVector(VT);
7605 SDValue RecastV1;
7606 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
7607 // this to a v16i1. This cannot be done with an ordinary bitcast because the
7608 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
7609 // since we know in hardware the sizes are really the same.
7610 if (VT != MVT::v16i1)
7611 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
7612 else
7613 RecastV1 = Pred;
7615 // Select either all ones or zeroes depending upon the real predicate bits.
7616 SDValue PredAsVector =
7617 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
7619 // Recast our new predicate-as-integer v16i8 vector into something
7620 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
7621 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
7624 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
7625 const ARMSubtarget *ST) {
7626 EVT VT = Op.getValueType();
7627 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7628 ArrayRef<int> ShuffleMask = SVN->getMask();
7630 assert(ST->hasMVEIntegerOps() &&
7631 "No support for vector shuffle of boolean predicates");
7633 SDValue V1 = Op.getOperand(0);
7634 SDLoc dl(Op);
7635 if (isReverseMask(ShuffleMask, VT)) {
7636 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
7637 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
7638 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
7639 DAG.getConstant(16, dl, MVT::i32));
7640 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
7643 // Until we can come up with optimised cases for every single vector
7644 // shuffle in existence we have chosen the least painful strategy. This is
7645 // to essentially promote the boolean predicate to a 8-bit integer, where
7646 // each predicate represents a byte. Then we fall back on a normal integer
7647 // vector shuffle and convert the result back into a predicate vector. In
7648 // many cases the generated code might be even better than scalar code
7649 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
7650 // fields in a register into 8 other arbitrary 2-bit fields!
7651 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
7652 EVT NewVT = PredAsVector.getValueType();
7654 // Do the shuffle!
7655 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
7656 DAG.getUNDEF(NewVT), ShuffleMask);
7658 // Now return the result of comparing the shuffled vector with zero,
7659 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7660 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
7661 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
7664 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
7665 const ARMSubtarget *ST) {
7666 SDValue V1 = Op.getOperand(0);
7667 SDValue V2 = Op.getOperand(1);
7668 SDLoc dl(Op);
7669 EVT VT = Op.getValueType();
7670 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7671 unsigned EltSize = VT.getScalarSizeInBits();
7673 if (ST->hasMVEIntegerOps() && EltSize == 1)
7674 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
7676 // Convert shuffles that are directly supported on NEON to target-specific
7677 // DAG nodes, instead of keeping them as shuffles and matching them again
7678 // during code selection. This is more efficient and avoids the possibility
7679 // of inconsistencies between legalization and selection.
7680 // FIXME: floating-point vectors should be canonicalized to integer vectors
7681 // of the same time so that they get CSEd properly.
7682 ArrayRef<int> ShuffleMask = SVN->getMask();
7684 if (EltSize <= 32) {
7685 if (SVN->isSplat()) {
7686 int Lane = SVN->getSplatIndex();
7687 // If this is undef splat, generate it via "just" vdup, if possible.
7688 if (Lane == -1) Lane = 0;
7690 // Test if V1 is a SCALAR_TO_VECTOR.
7691 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7692 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7694 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
7695 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
7696 // reaches it).
7697 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
7698 !isa<ConstantSDNode>(V1.getOperand(0))) {
7699 bool IsScalarToVector = true;
7700 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
7701 if (!V1.getOperand(i).isUndef()) {
7702 IsScalarToVector = false;
7703 break;
7705 if (IsScalarToVector)
7706 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7708 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
7709 DAG.getConstant(Lane, dl, MVT::i32));
7712 bool ReverseVEXT = false;
7713 unsigned Imm = 0;
7714 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7715 if (ReverseVEXT)
7716 std::swap(V1, V2);
7717 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7718 DAG.getConstant(Imm, dl, MVT::i32));
7721 if (isVREVMask(ShuffleMask, VT, 64))
7722 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7723 if (isVREVMask(ShuffleMask, VT, 32))
7724 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7725 if (isVREVMask(ShuffleMask, VT, 16))
7726 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7728 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7729 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7730 DAG.getConstant(Imm, dl, MVT::i32));
7733 // Check for Neon shuffles that modify both input vectors in place.
7734 // If both results are used, i.e., if there are two shuffles with the same
7735 // source operands and with masks corresponding to both results of one of
7736 // these operations, DAG memoization will ensure that a single node is
7737 // used for both shuffles.
7738 unsigned WhichResult = 0;
7739 bool isV_UNDEF = false;
7740 if (ST->hasNEON()) {
7741 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7742 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7743 if (isV_UNDEF)
7744 V2 = V1;
7745 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7746 .getValue(WhichResult);
7750 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7751 // shuffles that produce a result larger than their operands with:
7752 // shuffle(concat(v1, undef), concat(v2, undef))
7753 // ->
7754 // shuffle(concat(v1, v2), undef)
7755 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7757 // This is useful in the general case, but there are special cases where
7758 // native shuffles produce larger results: the two-result ops.
7760 // Look through the concat when lowering them:
7761 // shuffle(concat(v1, v2), undef)
7762 // ->
7763 // concat(VZIP(v1, v2):0, :1)
7765 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7766 SDValue SubV1 = V1->getOperand(0);
7767 SDValue SubV2 = V1->getOperand(1);
7768 EVT SubVT = SubV1.getValueType();
7770 // We expect these to have been canonicalized to -1.
7771 assert(llvm::all_of(ShuffleMask, [&](int i) {
7772 return i < (int)VT.getVectorNumElements();
7773 }) && "Unexpected shuffle index into UNDEF operand!");
7775 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7776 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7777 if (isV_UNDEF)
7778 SubV2 = SubV1;
7779 assert((WhichResult == 0) &&
7780 "In-place shuffle of concat can only have one result!");
7781 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7782 SubV1, SubV2);
7783 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7784 Res.getValue(1));
7789 // If the shuffle is not directly supported and it has 4 elements, use
7790 // the PerfectShuffle-generated table to synthesize it from other shuffles.
7791 unsigned NumElts = VT.getVectorNumElements();
7792 if (NumElts == 4) {
7793 unsigned PFIndexes[4];
7794 for (unsigned i = 0; i != 4; ++i) {
7795 if (ShuffleMask[i] < 0)
7796 PFIndexes[i] = 8;
7797 else
7798 PFIndexes[i] = ShuffleMask[i];
7801 // Compute the index in the perfect shuffle table.
7802 unsigned PFTableIndex =
7803 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7804 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7805 unsigned Cost = (PFEntry >> 30);
7807 if (Cost <= 4) {
7808 if (ST->hasNEON())
7809 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7810 else if (isLegalMVEShuffleOp(PFEntry)) {
7811 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7812 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7813 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
7814 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
7815 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
7816 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7821 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7822 if (EltSize >= 32) {
7823 // Do the expansion with floating-point types, since that is what the VFP
7824 // registers are defined to use, and since i64 is not legal.
7825 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7826 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7827 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7828 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7829 SmallVector<SDValue, 8> Ops;
7830 for (unsigned i = 0; i < NumElts; ++i) {
7831 if (ShuffleMask[i] < 0)
7832 Ops.push_back(DAG.getUNDEF(EltVT));
7833 else
7834 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7835 ShuffleMask[i] < (int)NumElts ? V1 : V2,
7836 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7837 dl, MVT::i32)));
7839 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7840 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7843 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7844 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7846 if (ST->hasNEON() && VT == MVT::v8i8)
7847 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7848 return NewOp;
7850 return SDValue();
7853 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7854 const ARMSubtarget *ST) {
7855 EVT VecVT = Op.getOperand(0).getValueType();
7856 SDLoc dl(Op);
7858 assert(ST->hasMVEIntegerOps() &&
7859 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7861 SDValue Conv =
7862 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7863 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7864 unsigned LaneWidth =
7865 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7866 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
7867 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
7868 Op.getOperand(1), DAG.getValueType(MVT::i1));
7869 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
7870 DAG.getConstant(~Mask, dl, MVT::i32));
7871 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
7874 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7875 SelectionDAG &DAG) const {
7876 // INSERT_VECTOR_ELT is legal only for immediate indexes.
7877 SDValue Lane = Op.getOperand(2);
7878 if (!isa<ConstantSDNode>(Lane))
7879 return SDValue();
7881 SDValue Elt = Op.getOperand(1);
7882 EVT EltVT = Elt.getValueType();
7884 if (Subtarget->hasMVEIntegerOps() &&
7885 Op.getValueType().getScalarSizeInBits() == 1)
7886 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
7888 if (getTypeAction(*DAG.getContext(), EltVT) ==
7889 TargetLowering::TypePromoteFloat) {
7890 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
7891 // but the type system will try to do that if we don't intervene.
7892 // Reinterpret any such vector-element insertion as one with the
7893 // corresponding integer types.
7895 SDLoc dl(Op);
7897 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
7898 assert(getTypeAction(*DAG.getContext(), IEltVT) !=
7899 TargetLowering::TypePromoteFloat);
7901 SDValue VecIn = Op.getOperand(0);
7902 EVT VecVT = VecIn.getValueType();
7903 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
7904 VecVT.getVectorNumElements());
7906 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
7907 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
7908 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
7909 IVecIn, IElt, Lane);
7910 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
7913 return Op;
7916 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7917 const ARMSubtarget *ST) {
7918 EVT VecVT = Op.getOperand(0).getValueType();
7919 SDLoc dl(Op);
7921 assert(ST->hasMVEIntegerOps() &&
7922 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7924 SDValue Conv =
7925 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7926 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7927 unsigned LaneWidth =
7928 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7929 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
7930 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
7931 return Shift;
7934 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
7935 const ARMSubtarget *ST) {
7936 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
7937 SDValue Lane = Op.getOperand(1);
7938 if (!isa<ConstantSDNode>(Lane))
7939 return SDValue();
7941 SDValue Vec = Op.getOperand(0);
7942 EVT VT = Vec.getValueType();
7944 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7945 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
7947 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7948 SDLoc dl(Op);
7949 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7952 return Op;
7955 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
7956 const ARMSubtarget *ST) {
7957 SDValue V1 = Op.getOperand(0);
7958 SDValue V2 = Op.getOperand(1);
7959 SDLoc dl(Op);
7960 EVT VT = Op.getValueType();
7961 EVT Op1VT = V1.getValueType();
7962 EVT Op2VT = V2.getValueType();
7963 unsigned NumElts = VT.getVectorNumElements();
7965 assert(Op1VT == Op2VT && "Operand types don't match!");
7966 assert(VT.getScalarSizeInBits() == 1 &&
7967 "Unexpected custom CONCAT_VECTORS lowering");
7968 assert(ST->hasMVEIntegerOps() &&
7969 "CONCAT_VECTORS lowering only supported for MVE");
7971 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
7972 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
7974 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
7975 // promoted to v8i16, etc.
7977 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
7979 // Extract the vector elements from Op1 and Op2 one by one and truncate them
7980 // to be the right size for the destination. For example, if Op1 is v4i1 then
7981 // the promoted vector is v4i32. The result of concatentation gives a v8i1,
7982 // which when promoted is v8i16. That means each i32 element from Op1 needs
7983 // truncating to i16 and inserting in the result.
7984 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
7985 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
7986 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
7987 EVT NewVT = NewV.getValueType();
7988 EVT ConcatVT = ConVec.getValueType();
7989 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
7990 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
7991 DAG.getIntPtrConstant(i, dl));
7992 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
7993 DAG.getConstant(j, dl, MVT::i32));
7995 return ConVec;
7997 unsigned j = 0;
7998 ConVec = ExractInto(NewV1, ConVec, j);
7999 ConVec = ExractInto(NewV2, ConVec, j);
8001 // Now return the result of comparing the subvector with zero,
8002 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8003 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8004 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8007 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8008 const ARMSubtarget *ST) {
8009 EVT VT = Op->getValueType(0);
8010 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8011 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8013 // The only time a CONCAT_VECTORS operation can have legal types is when
8014 // two 64-bit vectors are concatenated to a 128-bit vector.
8015 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8016 "unexpected CONCAT_VECTORS");
8017 SDLoc dl(Op);
8018 SDValue Val = DAG.getUNDEF(MVT::v2f64);
8019 SDValue Op0 = Op.getOperand(0);
8020 SDValue Op1 = Op.getOperand(1);
8021 if (!Op0.isUndef())
8022 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8023 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8024 DAG.getIntPtrConstant(0, dl));
8025 if (!Op1.isUndef())
8026 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8027 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8028 DAG.getIntPtrConstant(1, dl));
8029 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8032 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8033 const ARMSubtarget *ST) {
8034 SDValue V1 = Op.getOperand(0);
8035 SDValue V2 = Op.getOperand(1);
8036 SDLoc dl(Op);
8037 EVT VT = Op.getValueType();
8038 EVT Op1VT = V1.getValueType();
8039 unsigned NumElts = VT.getVectorNumElements();
8040 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
8042 assert(VT.getScalarSizeInBits() == 1 &&
8043 "Unexpected custom EXTRACT_SUBVECTOR lowering");
8044 assert(ST->hasMVEIntegerOps() &&
8045 "EXTRACT_SUBVECTOR lowering only supported for MVE");
8047 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8049 // We now have Op1 promoted to a vector of integers, where v8i1 gets
8050 // promoted to v8i16, etc.
8052 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8054 EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8055 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8056 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8057 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8058 DAG.getIntPtrConstant(i, dl));
8059 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8060 DAG.getConstant(j, dl, MVT::i32));
8063 // Now return the result of comparing the subvector with zero,
8064 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8065 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8066 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8069 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
8070 /// element has been zero/sign-extended, depending on the isSigned parameter,
8071 /// from an integer type half its size.
8072 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
8073 bool isSigned) {
8074 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
8075 EVT VT = N->getValueType(0);
8076 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
8077 SDNode *BVN = N->getOperand(0).getNode();
8078 if (BVN->getValueType(0) != MVT::v4i32 ||
8079 BVN->getOpcode() != ISD::BUILD_VECTOR)
8080 return false;
8081 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8082 unsigned HiElt = 1 - LoElt;
8083 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
8084 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
8085 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
8086 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
8087 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
8088 return false;
8089 if (isSigned) {
8090 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
8091 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
8092 return true;
8093 } else {
8094 if (Hi0->isNullValue() && Hi1->isNullValue())
8095 return true;
8097 return false;
8100 if (N->getOpcode() != ISD::BUILD_VECTOR)
8101 return false;
8103 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8104 SDNode *Elt = N->getOperand(i).getNode();
8105 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
8106 unsigned EltSize = VT.getScalarSizeInBits();
8107 unsigned HalfSize = EltSize / 2;
8108 if (isSigned) {
8109 if (!isIntN(HalfSize, C->getSExtValue()))
8110 return false;
8111 } else {
8112 if (!isUIntN(HalfSize, C->getZExtValue()))
8113 return false;
8115 continue;
8117 return false;
8120 return true;
8123 /// isSignExtended - Check if a node is a vector value that is sign-extended
8124 /// or a constant BUILD_VECTOR with sign-extended elements.
8125 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
8126 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
8127 return true;
8128 if (isExtendedBUILD_VECTOR(N, DAG, true))
8129 return true;
8130 return false;
8133 /// isZeroExtended - Check if a node is a vector value that is zero-extended
8134 /// or a constant BUILD_VECTOR with zero-extended elements.
8135 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
8136 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
8137 return true;
8138 if (isExtendedBUILD_VECTOR(N, DAG, false))
8139 return true;
8140 return false;
8143 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
8144 if (OrigVT.getSizeInBits() >= 64)
8145 return OrigVT;
8147 assert(OrigVT.isSimple() && "Expecting a simple value type");
8149 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
8150 switch (OrigSimpleTy) {
8151 default: llvm_unreachable("Unexpected Vector Type");
8152 case MVT::v2i8:
8153 case MVT::v2i16:
8154 return MVT::v2i32;
8155 case MVT::v4i8:
8156 return MVT::v4i16;
8160 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
8161 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
8162 /// We insert the required extension here to get the vector to fill a D register.
8163 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
8164 const EVT &OrigTy,
8165 const EVT &ExtTy,
8166 unsigned ExtOpcode) {
8167 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
8168 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
8169 // 64-bits we need to insert a new extension so that it will be 64-bits.
8170 assert(ExtTy.is128BitVector() && "Unexpected extension size");
8171 if (OrigTy.getSizeInBits() >= 64)
8172 return N;
8174 // Must extend size to at least 64 bits to be used as an operand for VMULL.
8175 EVT NewVT = getExtensionTo64Bits(OrigTy);
8177 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
8180 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
8181 /// does not do any sign/zero extension. If the original vector is less
8182 /// than 64 bits, an appropriate extension will be added after the load to
8183 /// reach a total size of 64 bits. We have to add the extension separately
8184 /// because ARM does not have a sign/zero extending load for vectors.
8185 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
8186 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
8188 // The load already has the right type.
8189 if (ExtendedTy == LD->getMemoryVT())
8190 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
8191 LD->getBasePtr(), LD->getPointerInfo(),
8192 LD->getAlignment(), LD->getMemOperand()->getFlags());
8194 // We need to create a zextload/sextload. We cannot just create a load
8195 // followed by a zext/zext node because LowerMUL is also run during normal
8196 // operation legalization where we can't create illegal types.
8197 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8198 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8199 LD->getMemoryVT(), LD->getAlignment(),
8200 LD->getMemOperand()->getFlags());
8203 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8204 /// extending load, or BUILD_VECTOR with extended elements, return the
8205 /// unextended value. The unextended vector should be 64 bits so that it can
8206 /// be used as an operand to a VMULL instruction. If the original vector size
8207 /// before extension is less than 64 bits we add a an extension to resize
8208 /// the vector to 64 bits.
8209 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8210 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
8211 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8212 N->getOperand(0)->getValueType(0),
8213 N->getValueType(0),
8214 N->getOpcode());
8216 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8217 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8218 "Expected extending load");
8220 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8221 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8222 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8223 SDValue extLoad =
8224 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8225 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8227 return newLoad;
8230 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
8231 // have been legalized as a BITCAST from v4i32.
8232 if (N->getOpcode() == ISD::BITCAST) {
8233 SDNode *BVN = N->getOperand(0).getNode();
8234 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8235 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8236 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8237 return DAG.getBuildVector(
8238 MVT::v2i32, SDLoc(N),
8239 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8241 // Construct a new BUILD_VECTOR with elements truncated to half the size.
8242 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8243 EVT VT = N->getValueType(0);
8244 unsigned EltSize = VT.getScalarSizeInBits() / 2;
8245 unsigned NumElts = VT.getVectorNumElements();
8246 MVT TruncVT = MVT::getIntegerVT(EltSize);
8247 SmallVector<SDValue, 8> Ops;
8248 SDLoc dl(N);
8249 for (unsigned i = 0; i != NumElts; ++i) {
8250 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8251 const APInt &CInt = C->getAPIntValue();
8252 // Element types smaller than 32 bits are not legal, so use i32 elements.
8253 // The values are implicitly truncated so sext vs. zext doesn't matter.
8254 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8256 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8259 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8260 unsigned Opcode = N->getOpcode();
8261 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8262 SDNode *N0 = N->getOperand(0).getNode();
8263 SDNode *N1 = N->getOperand(1).getNode();
8264 return N0->hasOneUse() && N1->hasOneUse() &&
8265 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8267 return false;
8270 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8271 unsigned Opcode = N->getOpcode();
8272 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8273 SDNode *N0 = N->getOperand(0).getNode();
8274 SDNode *N1 = N->getOperand(1).getNode();
8275 return N0->hasOneUse() && N1->hasOneUse() &&
8276 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8278 return false;
8281 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8282 // Multiplications are only custom-lowered for 128-bit vectors so that
8283 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
8284 EVT VT = Op.getValueType();
8285 assert(VT.is128BitVector() && VT.isInteger() &&
8286 "unexpected type for custom-lowering ISD::MUL");
8287 SDNode *N0 = Op.getOperand(0).getNode();
8288 SDNode *N1 = Op.getOperand(1).getNode();
8289 unsigned NewOpc = 0;
8290 bool isMLA = false;
8291 bool isN0SExt = isSignExtended(N0, DAG);
8292 bool isN1SExt = isSignExtended(N1, DAG);
8293 if (isN0SExt && isN1SExt)
8294 NewOpc = ARMISD::VMULLs;
8295 else {
8296 bool isN0ZExt = isZeroExtended(N0, DAG);
8297 bool isN1ZExt = isZeroExtended(N1, DAG);
8298 if (isN0ZExt && isN1ZExt)
8299 NewOpc = ARMISD::VMULLu;
8300 else if (isN1SExt || isN1ZExt) {
8301 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8302 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8303 if (isN1SExt && isAddSubSExt(N0, DAG)) {
8304 NewOpc = ARMISD::VMULLs;
8305 isMLA = true;
8306 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8307 NewOpc = ARMISD::VMULLu;
8308 isMLA = true;
8309 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8310 std::swap(N0, N1);
8311 NewOpc = ARMISD::VMULLu;
8312 isMLA = true;
8316 if (!NewOpc) {
8317 if (VT == MVT::v2i64)
8318 // Fall through to expand this. It is not legal.
8319 return SDValue();
8320 else
8321 // Other vector multiplications are legal.
8322 return Op;
8326 // Legalize to a VMULL instruction.
8327 SDLoc DL(Op);
8328 SDValue Op0;
8329 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8330 if (!isMLA) {
8331 Op0 = SkipExtensionForVMULL(N0, DAG);
8332 assert(Op0.getValueType().is64BitVector() &&
8333 Op1.getValueType().is64BitVector() &&
8334 "unexpected types for extended operands to VMULL");
8335 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8338 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8339 // isel lowering to take advantage of no-stall back to back vmul + vmla.
8340 // vmull q0, d4, d6
8341 // vmlal q0, d5, d6
8342 // is faster than
8343 // vaddl q0, d4, d5
8344 // vmovl q1, d6
8345 // vmul q0, q0, q1
8346 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8347 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8348 EVT Op1VT = Op1.getValueType();
8349 return DAG.getNode(N0->getOpcode(), DL, VT,
8350 DAG.getNode(NewOpc, DL, VT,
8351 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8352 DAG.getNode(NewOpc, DL, VT,
8353 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8356 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8357 SelectionDAG &DAG) {
8358 // TODO: Should this propagate fast-math-flags?
8360 // Convert to float
8361 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8362 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8363 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8364 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8365 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8366 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8367 // Get reciprocal estimate.
8368 // float4 recip = vrecpeq_f32(yf);
8369 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8370 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8372 // Because char has a smaller range than uchar, we can actually get away
8373 // without any newton steps. This requires that we use a weird bias
8374 // of 0xb000, however (again, this has been exhaustively tested).
8375 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8376 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8377 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8378 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8379 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8380 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8381 // Convert back to short.
8382 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8383 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8384 return X;
8387 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
8388 SelectionDAG &DAG) {
8389 // TODO: Should this propagate fast-math-flags?
8391 SDValue N2;
8392 // Convert to float.
8393 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
8394 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
8395 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
8396 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
8397 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8398 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8400 // Use reciprocal estimate and one refinement step.
8401 // float4 recip = vrecpeq_f32(yf);
8402 // recip *= vrecpsq_f32(yf, recip);
8403 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8404 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8405 N1);
8406 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8407 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8408 N1, N2);
8409 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8410 // Because short has a smaller range than ushort, we can actually get away
8411 // with only a single newton step. This requires that we use a weird bias
8412 // of 89, however (again, this has been exhaustively tested).
8413 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
8414 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8415 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8416 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
8417 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8418 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8419 // Convert back to integer and return.
8420 // return vmovn_s32(vcvt_s32_f32(result));
8421 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8422 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8423 return N0;
8426 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
8427 const ARMSubtarget *ST) {
8428 EVT VT = Op.getValueType();
8429 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8430 "unexpected type for custom-lowering ISD::SDIV");
8432 SDLoc dl(Op);
8433 SDValue N0 = Op.getOperand(0);
8434 SDValue N1 = Op.getOperand(1);
8435 SDValue N2, N3;
8437 if (VT == MVT::v8i8) {
8438 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
8439 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
8441 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8442 DAG.getIntPtrConstant(4, dl));
8443 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8444 DAG.getIntPtrConstant(4, dl));
8445 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8446 DAG.getIntPtrConstant(0, dl));
8447 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8448 DAG.getIntPtrConstant(0, dl));
8450 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
8451 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
8453 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8454 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8456 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
8457 return N0;
8459 return LowerSDIV_v4i16(N0, N1, dl, DAG);
8462 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
8463 const ARMSubtarget *ST) {
8464 // TODO: Should this propagate fast-math-flags?
8465 EVT VT = Op.getValueType();
8466 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8467 "unexpected type for custom-lowering ISD::UDIV");
8469 SDLoc dl(Op);
8470 SDValue N0 = Op.getOperand(0);
8471 SDValue N1 = Op.getOperand(1);
8472 SDValue N2, N3;
8474 if (VT == MVT::v8i8) {
8475 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
8476 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
8478 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8479 DAG.getIntPtrConstant(4, dl));
8480 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8481 DAG.getIntPtrConstant(4, dl));
8482 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8483 DAG.getIntPtrConstant(0, dl));
8484 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8485 DAG.getIntPtrConstant(0, dl));
8487 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
8488 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
8490 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8491 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8493 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
8494 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
8495 MVT::i32),
8496 N0);
8497 return N0;
8500 // v4i16 sdiv ... Convert to float.
8501 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
8502 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
8503 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
8504 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
8505 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8506 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8508 // Use reciprocal estimate and two refinement steps.
8509 // float4 recip = vrecpeq_f32(yf);
8510 // recip *= vrecpsq_f32(yf, recip);
8511 // recip *= vrecpsq_f32(yf, recip);
8512 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8513 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8514 BN1);
8515 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8516 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8517 BN1, N2);
8518 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8519 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8520 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8521 BN1, N2);
8522 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8523 // Simply multiplying by the reciprocal estimate can leave us a few ulps
8524 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
8525 // and that it will never cause us to return an answer too large).
8526 // float4 result = as_float4(as_int4(xf*recip) + 2);
8527 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8528 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8529 N1 = DAG.getConstant(2, dl, MVT::v4i32);
8530 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8531 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8532 // Convert back to integer and return.
8533 // return vmovn_u32(vcvt_s32_f32(result));
8534 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8535 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8536 return N0;
8539 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
8540 SDNode *N = Op.getNode();
8541 EVT VT = N->getValueType(0);
8542 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8544 SDValue Carry = Op.getOperand(2);
8546 SDLoc DL(Op);
8548 SDValue Result;
8549 if (Op.getOpcode() == ISD::ADDCARRY) {
8550 // This converts the boolean value carry into the carry flag.
8551 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8553 // Do the addition proper using the carry flag we wanted.
8554 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
8555 Op.getOperand(1), Carry);
8557 // Now convert the carry flag into a boolean value.
8558 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8559 } else {
8560 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
8561 // have to invert the carry first.
8562 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8563 DAG.getConstant(1, DL, MVT::i32), Carry);
8564 // This converts the boolean value carry into the carry flag.
8565 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8567 // Do the subtraction proper using the carry flag we wanted.
8568 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
8569 Op.getOperand(1), Carry);
8571 // Now convert the carry flag into a boolean value.
8572 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8573 // But the carry returned by ARMISD::SUBE is not a borrow as expected
8574 // by ISD::SUBCARRY, so compute 1 - C.
8575 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8576 DAG.getConstant(1, DL, MVT::i32), Carry);
8579 // Return both values.
8580 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
8583 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
8584 assert(Subtarget->isTargetDarwin());
8586 // For iOS, we want to call an alternative entry point: __sincos_stret,
8587 // return values are passed via sret.
8588 SDLoc dl(Op);
8589 SDValue Arg = Op.getOperand(0);
8590 EVT ArgVT = Arg.getValueType();
8591 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8592 auto PtrVT = getPointerTy(DAG.getDataLayout());
8594 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8595 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8597 // Pair of floats / doubles used to pass the result.
8598 Type *RetTy = StructType::get(ArgTy, ArgTy);
8599 auto &DL = DAG.getDataLayout();
8601 ArgListTy Args;
8602 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
8603 SDValue SRet;
8604 if (ShouldUseSRet) {
8605 // Create stack object for sret.
8606 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
8607 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
8608 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
8609 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
8611 ArgListEntry Entry;
8612 Entry.Node = SRet;
8613 Entry.Ty = RetTy->getPointerTo();
8614 Entry.IsSExt = false;
8615 Entry.IsZExt = false;
8616 Entry.IsSRet = true;
8617 Args.push_back(Entry);
8618 RetTy = Type::getVoidTy(*DAG.getContext());
8621 ArgListEntry Entry;
8622 Entry.Node = Arg;
8623 Entry.Ty = ArgTy;
8624 Entry.IsSExt = false;
8625 Entry.IsZExt = false;
8626 Args.push_back(Entry);
8628 RTLIB::Libcall LC =
8629 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
8630 const char *LibcallName = getLibcallName(LC);
8631 CallingConv::ID CC = getLibcallCallingConv(LC);
8632 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
8634 TargetLowering::CallLoweringInfo CLI(DAG);
8635 CLI.setDebugLoc(dl)
8636 .setChain(DAG.getEntryNode())
8637 .setCallee(CC, RetTy, Callee, std::move(Args))
8638 .setDiscardResult(ShouldUseSRet);
8639 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8641 if (!ShouldUseSRet)
8642 return CallResult.first;
8644 SDValue LoadSin =
8645 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
8647 // Address of cos field.
8648 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
8649 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
8650 SDValue LoadCos =
8651 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
8653 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
8654 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
8655 LoadSin.getValue(0), LoadCos.getValue(0));
8658 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
8659 bool Signed,
8660 SDValue &Chain) const {
8661 EVT VT = Op.getValueType();
8662 assert((VT == MVT::i32 || VT == MVT::i64) &&
8663 "unexpected type for custom lowering DIV");
8664 SDLoc dl(Op);
8666 const auto &DL = DAG.getDataLayout();
8667 const auto &TLI = DAG.getTargetLoweringInfo();
8669 const char *Name = nullptr;
8670 if (Signed)
8671 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
8672 else
8673 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
8675 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
8677 ARMTargetLowering::ArgListTy Args;
8679 for (auto AI : {1, 0}) {
8680 ArgListEntry Arg;
8681 Arg.Node = Op.getOperand(AI);
8682 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
8683 Args.push_back(Arg);
8686 CallLoweringInfo CLI(DAG);
8687 CLI.setDebugLoc(dl)
8688 .setChain(Chain)
8689 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
8690 ES, std::move(Args));
8692 return LowerCallTo(CLI).first;
8695 // This is a code size optimisation: return the original SDIV node to
8696 // DAGCombiner when we don't want to expand SDIV into a sequence of
8697 // instructions, and an empty node otherwise which will cause the
8698 // SDIV to be expanded in DAGCombine.
8699 SDValue
8700 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8701 SelectionDAG &DAG,
8702 SmallVectorImpl<SDNode *> &Created) const {
8703 // TODO: Support SREM
8704 if (N->getOpcode() != ISD::SDIV)
8705 return SDValue();
8707 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
8708 const bool MinSize = ST.hasMinSize();
8709 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
8710 : ST.hasDivideInARMMode();
8712 // Don't touch vector types; rewriting this may lead to scalarizing
8713 // the int divs.
8714 if (N->getOperand(0).getValueType().isVector())
8715 return SDValue();
8717 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
8718 // hwdiv support for this to be really profitable.
8719 if (!(MinSize && HasDivide))
8720 return SDValue();
8722 // ARM mode is a bit simpler than Thumb: we can handle large power
8723 // of 2 immediates with 1 mov instruction; no further checks required,
8724 // just return the sdiv node.
8725 if (!ST.isThumb())
8726 return SDValue(N, 0);
8728 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
8729 // and thus lose the code size benefits of a MOVS that requires only 2.
8730 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
8731 // but as it's doing exactly this, it's not worth the trouble to get TTI.
8732 if (Divisor.sgt(128))
8733 return SDValue();
8735 return SDValue(N, 0);
8738 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
8739 bool Signed) const {
8740 assert(Op.getValueType() == MVT::i32 &&
8741 "unexpected type for custom lowering DIV");
8742 SDLoc dl(Op);
8744 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
8745 DAG.getEntryNode(), Op.getOperand(1));
8747 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8750 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
8751 SDLoc DL(N);
8752 SDValue Op = N->getOperand(1);
8753 if (N->getValueType(0) == MVT::i32)
8754 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
8755 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8756 DAG.getConstant(0, DL, MVT::i32));
8757 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8758 DAG.getConstant(1, DL, MVT::i32));
8759 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
8760 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
8763 void ARMTargetLowering::ExpandDIV_Windows(
8764 SDValue Op, SelectionDAG &DAG, bool Signed,
8765 SmallVectorImpl<SDValue> &Results) const {
8766 const auto &DL = DAG.getDataLayout();
8767 const auto &TLI = DAG.getTargetLoweringInfo();
8769 assert(Op.getValueType() == MVT::i64 &&
8770 "unexpected type for custom lowering DIV");
8771 SDLoc dl(Op);
8773 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
8775 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8777 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
8778 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
8779 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
8780 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
8782 Results.push_back(Lower);
8783 Results.push_back(Upper);
8786 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
8787 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
8788 // Acquire/Release load/store is not legal for targets without a dmb or
8789 // equivalent available.
8790 return SDValue();
8792 // Monotonic load/store is legal for all targets.
8793 return Op;
8796 static void ReplaceREADCYCLECOUNTER(SDNode *N,
8797 SmallVectorImpl<SDValue> &Results,
8798 SelectionDAG &DAG,
8799 const ARMSubtarget *Subtarget) {
8800 SDLoc DL(N);
8801 // Under Power Management extensions, the cycle-count is:
8802 // mrc p15, #0, <Rt>, c9, c13, #0
8803 SDValue Ops[] = { N->getOperand(0), // Chain
8804 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
8805 DAG.getConstant(15, DL, MVT::i32),
8806 DAG.getConstant(0, DL, MVT::i32),
8807 DAG.getConstant(9, DL, MVT::i32),
8808 DAG.getConstant(13, DL, MVT::i32),
8809 DAG.getConstant(0, DL, MVT::i32)
8812 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
8813 DAG.getVTList(MVT::i32, MVT::Other), Ops);
8814 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
8815 DAG.getConstant(0, DL, MVT::i32)));
8816 Results.push_back(Cycles32.getValue(1));
8819 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
8820 SDLoc dl(V.getNode());
8821 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
8822 SDValue VHi = DAG.getAnyExtOrTrunc(
8823 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
8824 dl, MVT::i32);
8825 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8826 if (isBigEndian)
8827 std::swap (VLo, VHi);
8828 SDValue RegClass =
8829 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
8830 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
8831 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
8832 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
8833 return SDValue(
8834 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
8837 static void ReplaceCMP_SWAP_64Results(SDNode *N,
8838 SmallVectorImpl<SDValue> & Results,
8839 SelectionDAG &DAG) {
8840 assert(N->getValueType(0) == MVT::i64 &&
8841 "AtomicCmpSwap on types less than 64 should be legal");
8842 SDValue Ops[] = {N->getOperand(1),
8843 createGPRPairNode(DAG, N->getOperand(2)),
8844 createGPRPairNode(DAG, N->getOperand(3)),
8845 N->getOperand(0)};
8846 SDNode *CmpSwap = DAG.getMachineNode(
8847 ARM::CMP_SWAP_64, SDLoc(N),
8848 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
8850 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
8851 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
8853 bool isBigEndian = DAG.getDataLayout().isBigEndian();
8855 Results.push_back(
8856 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
8857 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8858 Results.push_back(
8859 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
8860 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8861 Results.push_back(SDValue(CmpSwap, 2));
8864 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
8865 SelectionDAG &DAG) {
8866 const auto &TLI = DAG.getTargetLoweringInfo();
8868 assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
8869 "Custom lowering is MSVCRT specific!");
8871 SDLoc dl(Op);
8872 SDValue Val = Op.getOperand(0);
8873 MVT Ty = Val->getSimpleValueType(0);
8874 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
8875 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
8876 TLI.getPointerTy(DAG.getDataLayout()));
8878 TargetLowering::ArgListTy Args;
8879 TargetLowering::ArgListEntry Entry;
8881 Entry.Node = Val;
8882 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
8883 Entry.IsZExt = true;
8884 Args.push_back(Entry);
8886 Entry.Node = Exponent;
8887 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
8888 Entry.IsZExt = true;
8889 Args.push_back(Entry);
8891 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
8893 // In the in-chain to the call is the entry node If we are emitting a
8894 // tailcall, the chain will be mutated if the node has a non-entry input
8895 // chain.
8896 SDValue InChain = DAG.getEntryNode();
8897 SDValue TCChain = InChain;
8899 const Function &F = DAG.getMachineFunction().getFunction();
8900 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
8901 F.getReturnType() == LCRTy;
8902 if (IsTC)
8903 InChain = TCChain;
8905 TargetLowering::CallLoweringInfo CLI(DAG);
8906 CLI.setDebugLoc(dl)
8907 .setChain(InChain)
8908 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
8909 .setTailCall(IsTC);
8910 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
8912 // Return the chain (the DAG root) if it is a tail call
8913 return !CI.second.getNode() ? DAG.getRoot() : CI.first;
8916 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8917 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
8918 switch (Op.getOpcode()) {
8919 default: llvm_unreachable("Don't know how to custom lower this!");
8920 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
8921 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8922 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8923 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8924 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8925 case ISD::SELECT: return LowerSELECT(Op, DAG);
8926 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
8927 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8928 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
8929 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
8930 case ISD::VASTART: return LowerVASTART(Op, DAG);
8931 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
8932 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
8933 case ISD::SINT_TO_FP:
8934 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
8935 case ISD::FP_TO_SINT:
8936 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
8937 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8938 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8939 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8940 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
8941 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
8942 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
8943 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
8944 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
8945 Subtarget);
8946 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
8947 case ISD::SHL:
8948 case ISD::SRL:
8949 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
8950 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
8951 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
8952 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
8953 case ISD::SRL_PARTS:
8954 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
8955 case ISD::CTTZ:
8956 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
8957 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
8958 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget);
8959 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
8960 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
8961 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
8962 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
8963 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
8964 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8965 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
8966 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
8967 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8968 case ISD::MUL: return LowerMUL(Op, DAG);
8969 case ISD::SDIV:
8970 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8971 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
8972 return LowerSDIV(Op, DAG, Subtarget);
8973 case ISD::UDIV:
8974 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8975 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
8976 return LowerUDIV(Op, DAG, Subtarget);
8977 case ISD::ADDCARRY:
8978 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG);
8979 case ISD::SADDO:
8980 case ISD::SSUBO:
8981 return LowerSignedALUO(Op, DAG);
8982 case ISD::UADDO:
8983 case ISD::USUBO:
8984 return LowerUnsignedALUO(Op, DAG);
8985 case ISD::ATOMIC_LOAD:
8986 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
8987 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
8988 case ISD::SDIVREM:
8989 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
8990 case ISD::DYNAMIC_STACKALLOC:
8991 if (Subtarget->isTargetWindows())
8992 return LowerDYNAMIC_STACKALLOC(Op, DAG);
8993 llvm_unreachable("Don't know how to custom lower this!");
8994 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
8995 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
8996 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
8997 case ARMISD::WIN__DBZCHK: return SDValue();
9001 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
9002 SelectionDAG &DAG) {
9003 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9004 unsigned Opc = 0;
9005 if (IntNo == Intrinsic::arm_smlald)
9006 Opc = ARMISD::SMLALD;
9007 else if (IntNo == Intrinsic::arm_smlaldx)
9008 Opc = ARMISD::SMLALDX;
9009 else if (IntNo == Intrinsic::arm_smlsld)
9010 Opc = ARMISD::SMLSLD;
9011 else if (IntNo == Intrinsic::arm_smlsldx)
9012 Opc = ARMISD::SMLSLDX;
9013 else
9014 return;
9016 SDLoc dl(N);
9017 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9018 N->getOperand(3),
9019 DAG.getConstant(0, dl, MVT::i32));
9020 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9021 N->getOperand(3),
9022 DAG.getConstant(1, dl, MVT::i32));
9024 SDValue LongMul = DAG.getNode(Opc, dl,
9025 DAG.getVTList(MVT::i32, MVT::i32),
9026 N->getOperand(1), N->getOperand(2),
9027 Lo, Hi);
9028 Results.push_back(LongMul.getValue(0));
9029 Results.push_back(LongMul.getValue(1));
9032 /// ReplaceNodeResults - Replace the results of node with an illegal result
9033 /// type with new values built out of custom code.
9034 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
9035 SmallVectorImpl<SDValue> &Results,
9036 SelectionDAG &DAG) const {
9037 SDValue Res;
9038 switch (N->getOpcode()) {
9039 default:
9040 llvm_unreachable("Don't know how to custom expand this!");
9041 case ISD::READ_REGISTER:
9042 ExpandREAD_REGISTER(N, Results, DAG);
9043 break;
9044 case ISD::BITCAST:
9045 Res = ExpandBITCAST(N, DAG, Subtarget);
9046 break;
9047 case ISD::SRL:
9048 case ISD::SRA:
9049 case ISD::SHL:
9050 Res = Expand64BitShift(N, DAG, Subtarget);
9051 break;
9052 case ISD::SREM:
9053 case ISD::UREM:
9054 Res = LowerREM(N, DAG);
9055 break;
9056 case ISD::SDIVREM:
9057 case ISD::UDIVREM:
9058 Res = LowerDivRem(SDValue(N, 0), DAG);
9059 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
9060 Results.push_back(Res.getValue(0));
9061 Results.push_back(Res.getValue(1));
9062 return;
9063 case ISD::READCYCLECOUNTER:
9064 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
9065 return;
9066 case ISD::UDIV:
9067 case ISD::SDIV:
9068 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
9069 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
9070 Results);
9071 case ISD::ATOMIC_CMP_SWAP:
9072 ReplaceCMP_SWAP_64Results(N, Results, DAG);
9073 return;
9074 case ISD::INTRINSIC_WO_CHAIN:
9075 return ReplaceLongIntrinsic(N, Results, DAG);
9076 case ISD::ABS:
9077 lowerABS(N, Results, DAG);
9078 return ;
9081 if (Res.getNode())
9082 Results.push_back(Res);
9085 //===----------------------------------------------------------------------===//
9086 // ARM Scheduler Hooks
9087 //===----------------------------------------------------------------------===//
9089 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
9090 /// registers the function context.
9091 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
9092 MachineBasicBlock *MBB,
9093 MachineBasicBlock *DispatchBB,
9094 int FI) const {
9095 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
9096 "ROPI/RWPI not currently supported with SjLj");
9097 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9098 DebugLoc dl = MI.getDebugLoc();
9099 MachineFunction *MF = MBB->getParent();
9100 MachineRegisterInfo *MRI = &MF->getRegInfo();
9101 MachineConstantPool *MCP = MF->getConstantPool();
9102 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
9103 const Function &F = MF->getFunction();
9105 bool isThumb = Subtarget->isThumb();
9106 bool isThumb2 = Subtarget->isThumb2();
9108 unsigned PCLabelId = AFI->createPICLabelUId();
9109 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
9110 ARMConstantPoolValue *CPV =
9111 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
9112 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
9114 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
9115 : &ARM::GPRRegClass;
9117 // Grab constant pool and fixed stack memory operands.
9118 MachineMemOperand *CPMMO =
9119 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9120 MachineMemOperand::MOLoad, 4, 4);
9122 MachineMemOperand *FIMMOSt =
9123 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
9124 MachineMemOperand::MOStore, 4, 4);
9126 // Load the address of the dispatch MBB into the jump buffer.
9127 if (isThumb2) {
9128 // Incoming value: jbuf
9129 // ldr.n r5, LCPI1_1
9130 // orr r5, r5, #1
9131 // add r5, pc
9132 // str r5, [$jbuf, #+4] ; &jbuf[1]
9133 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9134 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
9135 .addConstantPoolIndex(CPI)
9136 .addMemOperand(CPMMO)
9137 .add(predOps(ARMCC::AL));
9138 // Set the low bit because of thumb mode.
9139 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9140 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
9141 .addReg(NewVReg1, RegState::Kill)
9142 .addImm(0x01)
9143 .add(predOps(ARMCC::AL))
9144 .add(condCodeOp());
9145 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9146 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
9147 .addReg(NewVReg2, RegState::Kill)
9148 .addImm(PCLabelId);
9149 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
9150 .addReg(NewVReg3, RegState::Kill)
9151 .addFrameIndex(FI)
9152 .addImm(36) // &jbuf[1] :: pc
9153 .addMemOperand(FIMMOSt)
9154 .add(predOps(ARMCC::AL));
9155 } else if (isThumb) {
9156 // Incoming value: jbuf
9157 // ldr.n r1, LCPI1_4
9158 // add r1, pc
9159 // mov r2, #1
9160 // orrs r1, r2
9161 // add r2, $jbuf, #+4 ; &jbuf[1]
9162 // str r1, [r2]
9163 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9164 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
9165 .addConstantPoolIndex(CPI)
9166 .addMemOperand(CPMMO)
9167 .add(predOps(ARMCC::AL));
9168 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9169 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
9170 .addReg(NewVReg1, RegState::Kill)
9171 .addImm(PCLabelId);
9172 // Set the low bit because of thumb mode.
9173 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9174 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
9175 .addReg(ARM::CPSR, RegState::Define)
9176 .addImm(1)
9177 .add(predOps(ARMCC::AL));
9178 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9179 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
9180 .addReg(ARM::CPSR, RegState::Define)
9181 .addReg(NewVReg2, RegState::Kill)
9182 .addReg(NewVReg3, RegState::Kill)
9183 .add(predOps(ARMCC::AL));
9184 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9185 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
9186 .addFrameIndex(FI)
9187 .addImm(36); // &jbuf[1] :: pc
9188 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
9189 .addReg(NewVReg4, RegState::Kill)
9190 .addReg(NewVReg5, RegState::Kill)
9191 .addImm(0)
9192 .addMemOperand(FIMMOSt)
9193 .add(predOps(ARMCC::AL));
9194 } else {
9195 // Incoming value: jbuf
9196 // ldr r1, LCPI1_1
9197 // add r1, pc, r1
9198 // str r1, [$jbuf, #+4] ; &jbuf[1]
9199 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9200 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
9201 .addConstantPoolIndex(CPI)
9202 .addImm(0)
9203 .addMemOperand(CPMMO)
9204 .add(predOps(ARMCC::AL));
9205 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9206 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
9207 .addReg(NewVReg1, RegState::Kill)
9208 .addImm(PCLabelId)
9209 .add(predOps(ARMCC::AL));
9210 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
9211 .addReg(NewVReg2, RegState::Kill)
9212 .addFrameIndex(FI)
9213 .addImm(36) // &jbuf[1] :: pc
9214 .addMemOperand(FIMMOSt)
9215 .add(predOps(ARMCC::AL));
9219 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
9220 MachineBasicBlock *MBB) const {
9221 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9222 DebugLoc dl = MI.getDebugLoc();
9223 MachineFunction *MF = MBB->getParent();
9224 MachineRegisterInfo *MRI = &MF->getRegInfo();
9225 MachineFrameInfo &MFI = MF->getFrameInfo();
9226 int FI = MFI.getFunctionContextIndex();
9228 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
9229 : &ARM::GPRnopcRegClass;
9231 // Get a mapping of the call site numbers to all of the landing pads they're
9232 // associated with.
9233 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
9234 unsigned MaxCSNum = 0;
9235 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
9236 ++BB) {
9237 if (!BB->isEHPad()) continue;
9239 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
9240 // pad.
9241 for (MachineBasicBlock::iterator
9242 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
9243 if (!II->isEHLabel()) continue;
9245 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
9246 if (!MF->hasCallSiteLandingPad(Sym)) continue;
9248 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
9249 for (SmallVectorImpl<unsigned>::iterator
9250 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
9251 CSI != CSE; ++CSI) {
9252 CallSiteNumToLPad[*CSI].push_back(&*BB);
9253 MaxCSNum = std::max(MaxCSNum, *CSI);
9255 break;
9259 // Get an ordered list of the machine basic blocks for the jump table.
9260 std::vector<MachineBasicBlock*> LPadList;
9261 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
9262 LPadList.reserve(CallSiteNumToLPad.size());
9263 for (unsigned I = 1; I <= MaxCSNum; ++I) {
9264 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
9265 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9266 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
9267 LPadList.push_back(*II);
9268 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
9272 assert(!LPadList.empty() &&
9273 "No landing pad destinations for the dispatch jump table!");
9275 // Create the jump table and associated information.
9276 MachineJumpTableInfo *JTI =
9277 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
9278 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
9280 // Create the MBBs for the dispatch code.
9282 // Shove the dispatch's address into the return slot in the function context.
9283 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
9284 DispatchBB->setIsEHPad();
9286 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9287 unsigned trap_opcode;
9288 if (Subtarget->isThumb())
9289 trap_opcode = ARM::tTRAP;
9290 else
9291 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
9293 BuildMI(TrapBB, dl, TII->get(trap_opcode));
9294 DispatchBB->addSuccessor(TrapBB);
9296 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
9297 DispatchBB->addSuccessor(DispContBB);
9299 // Insert and MBBs.
9300 MF->insert(MF->end(), DispatchBB);
9301 MF->insert(MF->end(), DispContBB);
9302 MF->insert(MF->end(), TrapBB);
9304 // Insert code into the entry block that creates and registers the function
9305 // context.
9306 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
9308 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
9309 MachinePointerInfo::getFixedStack(*MF, FI),
9310 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
9312 MachineInstrBuilder MIB;
9313 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
9315 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
9316 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
9318 // Add a register mask with no preserved registers. This results in all
9319 // registers being marked as clobbered. This can't work if the dispatch block
9320 // is in a Thumb1 function and is linked with ARM code which uses the FP
9321 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
9322 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
9324 bool IsPositionIndependent = isPositionIndependent();
9325 unsigned NumLPads = LPadList.size();
9326 if (Subtarget->isThumb2()) {
9327 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9328 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
9329 .addFrameIndex(FI)
9330 .addImm(4)
9331 .addMemOperand(FIMMOLd)
9332 .add(predOps(ARMCC::AL));
9334 if (NumLPads < 256) {
9335 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
9336 .addReg(NewVReg1)
9337 .addImm(LPadList.size())
9338 .add(predOps(ARMCC::AL));
9339 } else {
9340 Register VReg1 = MRI->createVirtualRegister(TRC);
9341 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
9342 .addImm(NumLPads & 0xFFFF)
9343 .add(predOps(ARMCC::AL));
9345 unsigned VReg2 = VReg1;
9346 if ((NumLPads & 0xFFFF0000) != 0) {
9347 VReg2 = MRI->createVirtualRegister(TRC);
9348 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
9349 .addReg(VReg1)
9350 .addImm(NumLPads >> 16)
9351 .add(predOps(ARMCC::AL));
9354 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
9355 .addReg(NewVReg1)
9356 .addReg(VReg2)
9357 .add(predOps(ARMCC::AL));
9360 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
9361 .addMBB(TrapBB)
9362 .addImm(ARMCC::HI)
9363 .addReg(ARM::CPSR);
9365 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9366 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
9367 .addJumpTableIndex(MJTI)
9368 .add(predOps(ARMCC::AL));
9370 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9371 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
9372 .addReg(NewVReg3, RegState::Kill)
9373 .addReg(NewVReg1)
9374 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9375 .add(predOps(ARMCC::AL))
9376 .add(condCodeOp());
9378 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
9379 .addReg(NewVReg4, RegState::Kill)
9380 .addReg(NewVReg1)
9381 .addJumpTableIndex(MJTI);
9382 } else if (Subtarget->isThumb()) {
9383 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9384 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
9385 .addFrameIndex(FI)
9386 .addImm(1)
9387 .addMemOperand(FIMMOLd)
9388 .add(predOps(ARMCC::AL));
9390 if (NumLPads < 256) {
9391 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
9392 .addReg(NewVReg1)
9393 .addImm(NumLPads)
9394 .add(predOps(ARMCC::AL));
9395 } else {
9396 MachineConstantPool *ConstantPool = MF->getConstantPool();
9397 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9398 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9400 // MachineConstantPool wants an explicit alignment.
9401 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9402 if (Align == 0)
9403 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9404 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9406 Register VReg1 = MRI->createVirtualRegister(TRC);
9407 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
9408 .addReg(VReg1, RegState::Define)
9409 .addConstantPoolIndex(Idx)
9410 .add(predOps(ARMCC::AL));
9411 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
9412 .addReg(NewVReg1)
9413 .addReg(VReg1)
9414 .add(predOps(ARMCC::AL));
9417 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
9418 .addMBB(TrapBB)
9419 .addImm(ARMCC::HI)
9420 .addReg(ARM::CPSR);
9422 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9423 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
9424 .addReg(ARM::CPSR, RegState::Define)
9425 .addReg(NewVReg1)
9426 .addImm(2)
9427 .add(predOps(ARMCC::AL));
9429 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9430 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
9431 .addJumpTableIndex(MJTI)
9432 .add(predOps(ARMCC::AL));
9434 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9435 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
9436 .addReg(ARM::CPSR, RegState::Define)
9437 .addReg(NewVReg2, RegState::Kill)
9438 .addReg(NewVReg3)
9439 .add(predOps(ARMCC::AL));
9441 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9442 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9444 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9445 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
9446 .addReg(NewVReg4, RegState::Kill)
9447 .addImm(0)
9448 .addMemOperand(JTMMOLd)
9449 .add(predOps(ARMCC::AL));
9451 unsigned NewVReg6 = NewVReg5;
9452 if (IsPositionIndependent) {
9453 NewVReg6 = MRI->createVirtualRegister(TRC);
9454 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
9455 .addReg(ARM::CPSR, RegState::Define)
9456 .addReg(NewVReg5, RegState::Kill)
9457 .addReg(NewVReg3)
9458 .add(predOps(ARMCC::AL));
9461 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
9462 .addReg(NewVReg6, RegState::Kill)
9463 .addJumpTableIndex(MJTI);
9464 } else {
9465 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9466 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
9467 .addFrameIndex(FI)
9468 .addImm(4)
9469 .addMemOperand(FIMMOLd)
9470 .add(predOps(ARMCC::AL));
9472 if (NumLPads < 256) {
9473 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
9474 .addReg(NewVReg1)
9475 .addImm(NumLPads)
9476 .add(predOps(ARMCC::AL));
9477 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
9478 Register VReg1 = MRI->createVirtualRegister(TRC);
9479 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
9480 .addImm(NumLPads & 0xFFFF)
9481 .add(predOps(ARMCC::AL));
9483 unsigned VReg2 = VReg1;
9484 if ((NumLPads & 0xFFFF0000) != 0) {
9485 VReg2 = MRI->createVirtualRegister(TRC);
9486 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
9487 .addReg(VReg1)
9488 .addImm(NumLPads >> 16)
9489 .add(predOps(ARMCC::AL));
9492 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9493 .addReg(NewVReg1)
9494 .addReg(VReg2)
9495 .add(predOps(ARMCC::AL));
9496 } else {
9497 MachineConstantPool *ConstantPool = MF->getConstantPool();
9498 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9499 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9501 // MachineConstantPool wants an explicit alignment.
9502 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9503 if (Align == 0)
9504 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9505 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9507 Register VReg1 = MRI->createVirtualRegister(TRC);
9508 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
9509 .addReg(VReg1, RegState::Define)
9510 .addConstantPoolIndex(Idx)
9511 .addImm(0)
9512 .add(predOps(ARMCC::AL));
9513 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9514 .addReg(NewVReg1)
9515 .addReg(VReg1, RegState::Kill)
9516 .add(predOps(ARMCC::AL));
9519 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
9520 .addMBB(TrapBB)
9521 .addImm(ARMCC::HI)
9522 .addReg(ARM::CPSR);
9524 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9525 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
9526 .addReg(NewVReg1)
9527 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9528 .add(predOps(ARMCC::AL))
9529 .add(condCodeOp());
9530 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9531 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
9532 .addJumpTableIndex(MJTI)
9533 .add(predOps(ARMCC::AL));
9535 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9536 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9537 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9538 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
9539 .addReg(NewVReg3, RegState::Kill)
9540 .addReg(NewVReg4)
9541 .addImm(0)
9542 .addMemOperand(JTMMOLd)
9543 .add(predOps(ARMCC::AL));
9545 if (IsPositionIndependent) {
9546 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
9547 .addReg(NewVReg5, RegState::Kill)
9548 .addReg(NewVReg4)
9549 .addJumpTableIndex(MJTI);
9550 } else {
9551 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
9552 .addReg(NewVReg5, RegState::Kill)
9553 .addJumpTableIndex(MJTI);
9557 // Add the jump table entries as successors to the MBB.
9558 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
9559 for (std::vector<MachineBasicBlock*>::iterator
9560 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
9561 MachineBasicBlock *CurMBB = *I;
9562 if (SeenMBBs.insert(CurMBB).second)
9563 DispContBB->addSuccessor(CurMBB);
9566 // N.B. the order the invoke BBs are processed in doesn't matter here.
9567 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
9568 SmallVector<MachineBasicBlock*, 64> MBBLPads;
9569 for (MachineBasicBlock *BB : InvokeBBs) {
9571 // Remove the landing pad successor from the invoke block and replace it
9572 // with the new dispatch block.
9573 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
9574 BB->succ_end());
9575 while (!Successors.empty()) {
9576 MachineBasicBlock *SMBB = Successors.pop_back_val();
9577 if (SMBB->isEHPad()) {
9578 BB->removeSuccessor(SMBB);
9579 MBBLPads.push_back(SMBB);
9583 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
9584 BB->normalizeSuccProbs();
9586 // Find the invoke call and mark all of the callee-saved registers as
9587 // 'implicit defined' so that they're spilled. This prevents code from
9588 // moving instructions to before the EH block, where they will never be
9589 // executed.
9590 for (MachineBasicBlock::reverse_iterator
9591 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
9592 if (!II->isCall()) continue;
9594 DenseMap<unsigned, bool> DefRegs;
9595 for (MachineInstr::mop_iterator
9596 OI = II->operands_begin(), OE = II->operands_end();
9597 OI != OE; ++OI) {
9598 if (!OI->isReg()) continue;
9599 DefRegs[OI->getReg()] = true;
9602 MachineInstrBuilder MIB(*MF, &*II);
9604 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
9605 unsigned Reg = SavedRegs[i];
9606 if (Subtarget->isThumb2() &&
9607 !ARM::tGPRRegClass.contains(Reg) &&
9608 !ARM::hGPRRegClass.contains(Reg))
9609 continue;
9610 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
9611 continue;
9612 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
9613 continue;
9614 if (!DefRegs[Reg])
9615 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
9618 break;
9622 // Mark all former landing pads as non-landing pads. The dispatch is the only
9623 // landing pad now.
9624 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9625 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
9626 (*I)->setIsEHPad(false);
9628 // The instruction is gone now.
9629 MI.eraseFromParent();
9632 static
9633 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
9634 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
9635 E = MBB->succ_end(); I != E; ++I)
9636 if (*I != Succ)
9637 return *I;
9638 llvm_unreachable("Expecting a BB with two successors!");
9641 /// Return the load opcode for a given load size. If load size >= 8,
9642 /// neon opcode will be returned.
9643 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
9644 if (LdSize >= 8)
9645 return LdSize == 16 ? ARM::VLD1q32wb_fixed
9646 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
9647 if (IsThumb1)
9648 return LdSize == 4 ? ARM::tLDRi
9649 : LdSize == 2 ? ARM::tLDRHi
9650 : LdSize == 1 ? ARM::tLDRBi : 0;
9651 if (IsThumb2)
9652 return LdSize == 4 ? ARM::t2LDR_POST
9653 : LdSize == 2 ? ARM::t2LDRH_POST
9654 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
9655 return LdSize == 4 ? ARM::LDR_POST_IMM
9656 : LdSize == 2 ? ARM::LDRH_POST
9657 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
9660 /// Return the store opcode for a given store size. If store size >= 8,
9661 /// neon opcode will be returned.
9662 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
9663 if (StSize >= 8)
9664 return StSize == 16 ? ARM::VST1q32wb_fixed
9665 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
9666 if (IsThumb1)
9667 return StSize == 4 ? ARM::tSTRi
9668 : StSize == 2 ? ARM::tSTRHi
9669 : StSize == 1 ? ARM::tSTRBi : 0;
9670 if (IsThumb2)
9671 return StSize == 4 ? ARM::t2STR_POST
9672 : StSize == 2 ? ARM::t2STRH_POST
9673 : StSize == 1 ? ARM::t2STRB_POST : 0;
9674 return StSize == 4 ? ARM::STR_POST_IMM
9675 : StSize == 2 ? ARM::STRH_POST
9676 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
9679 /// Emit a post-increment load operation with given size. The instructions
9680 /// will be added to BB at Pos.
9681 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9682 const TargetInstrInfo *TII, const DebugLoc &dl,
9683 unsigned LdSize, unsigned Data, unsigned AddrIn,
9684 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9685 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
9686 assert(LdOpc != 0 && "Should have a load opcode");
9687 if (LdSize >= 8) {
9688 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9689 .addReg(AddrOut, RegState::Define)
9690 .addReg(AddrIn)
9691 .addImm(0)
9692 .add(predOps(ARMCC::AL));
9693 } else if (IsThumb1) {
9694 // load + update AddrIn
9695 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9696 .addReg(AddrIn)
9697 .addImm(0)
9698 .add(predOps(ARMCC::AL));
9699 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9700 .add(t1CondCodeOp())
9701 .addReg(AddrIn)
9702 .addImm(LdSize)
9703 .add(predOps(ARMCC::AL));
9704 } else if (IsThumb2) {
9705 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9706 .addReg(AddrOut, RegState::Define)
9707 .addReg(AddrIn)
9708 .addImm(LdSize)
9709 .add(predOps(ARMCC::AL));
9710 } else { // arm
9711 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9712 .addReg(AddrOut, RegState::Define)
9713 .addReg(AddrIn)
9714 .addReg(0)
9715 .addImm(LdSize)
9716 .add(predOps(ARMCC::AL));
9720 /// Emit a post-increment store operation with given size. The instructions
9721 /// will be added to BB at Pos.
9722 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9723 const TargetInstrInfo *TII, const DebugLoc &dl,
9724 unsigned StSize, unsigned Data, unsigned AddrIn,
9725 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9726 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
9727 assert(StOpc != 0 && "Should have a store opcode");
9728 if (StSize >= 8) {
9729 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9730 .addReg(AddrIn)
9731 .addImm(0)
9732 .addReg(Data)
9733 .add(predOps(ARMCC::AL));
9734 } else if (IsThumb1) {
9735 // store + update AddrIn
9736 BuildMI(*BB, Pos, dl, TII->get(StOpc))
9737 .addReg(Data)
9738 .addReg(AddrIn)
9739 .addImm(0)
9740 .add(predOps(ARMCC::AL));
9741 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9742 .add(t1CondCodeOp())
9743 .addReg(AddrIn)
9744 .addImm(StSize)
9745 .add(predOps(ARMCC::AL));
9746 } else if (IsThumb2) {
9747 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9748 .addReg(Data)
9749 .addReg(AddrIn)
9750 .addImm(StSize)
9751 .add(predOps(ARMCC::AL));
9752 } else { // arm
9753 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9754 .addReg(Data)
9755 .addReg(AddrIn)
9756 .addReg(0)
9757 .addImm(StSize)
9758 .add(predOps(ARMCC::AL));
9762 MachineBasicBlock *
9763 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
9764 MachineBasicBlock *BB) const {
9765 // This pseudo instruction has 3 operands: dst, src, size
9766 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
9767 // Otherwise, we will generate unrolled scalar copies.
9768 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9769 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9770 MachineFunction::iterator It = ++BB->getIterator();
9772 Register dest = MI.getOperand(0).getReg();
9773 Register src = MI.getOperand(1).getReg();
9774 unsigned SizeVal = MI.getOperand(2).getImm();
9775 unsigned Align = MI.getOperand(3).getImm();
9776 DebugLoc dl = MI.getDebugLoc();
9778 MachineFunction *MF = BB->getParent();
9779 MachineRegisterInfo &MRI = MF->getRegInfo();
9780 unsigned UnitSize = 0;
9781 const TargetRegisterClass *TRC = nullptr;
9782 const TargetRegisterClass *VecTRC = nullptr;
9784 bool IsThumb1 = Subtarget->isThumb1Only();
9785 bool IsThumb2 = Subtarget->isThumb2();
9786 bool IsThumb = Subtarget->isThumb();
9788 if (Align & 1) {
9789 UnitSize = 1;
9790 } else if (Align & 2) {
9791 UnitSize = 2;
9792 } else {
9793 // Check whether we can use NEON instructions.
9794 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
9795 Subtarget->hasNEON()) {
9796 if ((Align % 16 == 0) && SizeVal >= 16)
9797 UnitSize = 16;
9798 else if ((Align % 8 == 0) && SizeVal >= 8)
9799 UnitSize = 8;
9801 // Can't use NEON instructions.
9802 if (UnitSize == 0)
9803 UnitSize = 4;
9806 // Select the correct opcode and register class for unit size load/store
9807 bool IsNeon = UnitSize >= 8;
9808 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
9809 if (IsNeon)
9810 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
9811 : UnitSize == 8 ? &ARM::DPRRegClass
9812 : nullptr;
9814 unsigned BytesLeft = SizeVal % UnitSize;
9815 unsigned LoopSize = SizeVal - BytesLeft;
9817 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
9818 // Use LDR and STR to copy.
9819 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
9820 // [destOut] = STR_POST(scratch, destIn, UnitSize)
9821 unsigned srcIn = src;
9822 unsigned destIn = dest;
9823 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
9824 Register srcOut = MRI.createVirtualRegister(TRC);
9825 Register destOut = MRI.createVirtualRegister(TRC);
9826 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9827 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
9828 IsThumb1, IsThumb2);
9829 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
9830 IsThumb1, IsThumb2);
9831 srcIn = srcOut;
9832 destIn = destOut;
9835 // Handle the leftover bytes with LDRB and STRB.
9836 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
9837 // [destOut] = STRB_POST(scratch, destIn, 1)
9838 for (unsigned i = 0; i < BytesLeft; i++) {
9839 Register srcOut = MRI.createVirtualRegister(TRC);
9840 Register destOut = MRI.createVirtualRegister(TRC);
9841 Register scratch = MRI.createVirtualRegister(TRC);
9842 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
9843 IsThumb1, IsThumb2);
9844 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
9845 IsThumb1, IsThumb2);
9846 srcIn = srcOut;
9847 destIn = destOut;
9849 MI.eraseFromParent(); // The instruction is gone now.
9850 return BB;
9853 // Expand the pseudo op to a loop.
9854 // thisMBB:
9855 // ...
9856 // movw varEnd, # --> with thumb2
9857 // movt varEnd, #
9858 // ldrcp varEnd, idx --> without thumb2
9859 // fallthrough --> loopMBB
9860 // loopMBB:
9861 // PHI varPhi, varEnd, varLoop
9862 // PHI srcPhi, src, srcLoop
9863 // PHI destPhi, dst, destLoop
9864 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9865 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
9866 // subs varLoop, varPhi, #UnitSize
9867 // bne loopMBB
9868 // fallthrough --> exitMBB
9869 // exitMBB:
9870 // epilogue to handle left-over bytes
9871 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9872 // [destOut] = STRB_POST(scratch, destLoop, 1)
9873 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9874 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9875 MF->insert(It, loopMBB);
9876 MF->insert(It, exitMBB);
9878 // Transfer the remainder of BB and its successor edges to exitMBB.
9879 exitMBB->splice(exitMBB->begin(), BB,
9880 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9881 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9883 // Load an immediate to varEnd.
9884 Register varEnd = MRI.createVirtualRegister(TRC);
9885 if (Subtarget->useMovt()) {
9886 unsigned Vtmp = varEnd;
9887 if ((LoopSize & 0xFFFF0000) != 0)
9888 Vtmp = MRI.createVirtualRegister(TRC);
9889 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
9890 .addImm(LoopSize & 0xFFFF)
9891 .add(predOps(ARMCC::AL));
9893 if ((LoopSize & 0xFFFF0000) != 0)
9894 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
9895 .addReg(Vtmp)
9896 .addImm(LoopSize >> 16)
9897 .add(predOps(ARMCC::AL));
9898 } else {
9899 MachineConstantPool *ConstantPool = MF->getConstantPool();
9900 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9901 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
9903 // MachineConstantPool wants an explicit alignment.
9904 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9905 if (Align == 0)
9906 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9907 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9908 MachineMemOperand *CPMMO =
9909 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9910 MachineMemOperand::MOLoad, 4, 4);
9912 if (IsThumb)
9913 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
9914 .addReg(varEnd, RegState::Define)
9915 .addConstantPoolIndex(Idx)
9916 .add(predOps(ARMCC::AL))
9917 .addMemOperand(CPMMO);
9918 else
9919 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
9920 .addReg(varEnd, RegState::Define)
9921 .addConstantPoolIndex(Idx)
9922 .addImm(0)
9923 .add(predOps(ARMCC::AL))
9924 .addMemOperand(CPMMO);
9926 BB->addSuccessor(loopMBB);
9928 // Generate the loop body:
9929 // varPhi = PHI(varLoop, varEnd)
9930 // srcPhi = PHI(srcLoop, src)
9931 // destPhi = PHI(destLoop, dst)
9932 MachineBasicBlock *entryBB = BB;
9933 BB = loopMBB;
9934 Register varLoop = MRI.createVirtualRegister(TRC);
9935 Register varPhi = MRI.createVirtualRegister(TRC);
9936 Register srcLoop = MRI.createVirtualRegister(TRC);
9937 Register srcPhi = MRI.createVirtualRegister(TRC);
9938 Register destLoop = MRI.createVirtualRegister(TRC);
9939 Register destPhi = MRI.createVirtualRegister(TRC);
9941 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
9942 .addReg(varLoop).addMBB(loopMBB)
9943 .addReg(varEnd).addMBB(entryBB);
9944 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
9945 .addReg(srcLoop).addMBB(loopMBB)
9946 .addReg(src).addMBB(entryBB);
9947 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
9948 .addReg(destLoop).addMBB(loopMBB)
9949 .addReg(dest).addMBB(entryBB);
9951 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9952 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
9953 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9954 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
9955 IsThumb1, IsThumb2);
9956 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
9957 IsThumb1, IsThumb2);
9959 // Decrement loop variable by UnitSize.
9960 if (IsThumb1) {
9961 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
9962 .add(t1CondCodeOp())
9963 .addReg(varPhi)
9964 .addImm(UnitSize)
9965 .add(predOps(ARMCC::AL));
9966 } else {
9967 MachineInstrBuilder MIB =
9968 BuildMI(*BB, BB->end(), dl,
9969 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
9970 MIB.addReg(varPhi)
9971 .addImm(UnitSize)
9972 .add(predOps(ARMCC::AL))
9973 .add(condCodeOp());
9974 MIB->getOperand(5).setReg(ARM::CPSR);
9975 MIB->getOperand(5).setIsDef(true);
9977 BuildMI(*BB, BB->end(), dl,
9978 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
9979 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
9981 // loopMBB can loop back to loopMBB or fall through to exitMBB.
9982 BB->addSuccessor(loopMBB);
9983 BB->addSuccessor(exitMBB);
9985 // Add epilogue to handle BytesLeft.
9986 BB = exitMBB;
9987 auto StartOfExit = exitMBB->begin();
9989 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9990 // [destOut] = STRB_POST(scratch, destLoop, 1)
9991 unsigned srcIn = srcLoop;
9992 unsigned destIn = destLoop;
9993 for (unsigned i = 0; i < BytesLeft; i++) {
9994 Register srcOut = MRI.createVirtualRegister(TRC);
9995 Register destOut = MRI.createVirtualRegister(TRC);
9996 Register scratch = MRI.createVirtualRegister(TRC);
9997 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
9998 IsThumb1, IsThumb2);
9999 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
10000 IsThumb1, IsThumb2);
10001 srcIn = srcOut;
10002 destIn = destOut;
10005 MI.eraseFromParent(); // The instruction is gone now.
10006 return BB;
10009 MachineBasicBlock *
10010 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
10011 MachineBasicBlock *MBB) const {
10012 const TargetMachine &TM = getTargetMachine();
10013 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
10014 DebugLoc DL = MI.getDebugLoc();
10016 assert(Subtarget->isTargetWindows() &&
10017 "__chkstk is only supported on Windows");
10018 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
10020 // __chkstk takes the number of words to allocate on the stack in R4, and
10021 // returns the stack adjustment in number of bytes in R4. This will not
10022 // clober any other registers (other than the obvious lr).
10024 // Although, technically, IP should be considered a register which may be
10025 // clobbered, the call itself will not touch it. Windows on ARM is a pure
10026 // thumb-2 environment, so there is no interworking required. As a result, we
10027 // do not expect a veneer to be emitted by the linker, clobbering IP.
10029 // Each module receives its own copy of __chkstk, so no import thunk is
10030 // required, again, ensuring that IP is not clobbered.
10032 // Finally, although some linkers may theoretically provide a trampoline for
10033 // out of range calls (which is quite common due to a 32M range limitation of
10034 // branches for Thumb), we can generate the long-call version via
10035 // -mcmodel=large, alleviating the need for the trampoline which may clobber
10036 // IP.
10038 switch (TM.getCodeModel()) {
10039 case CodeModel::Tiny:
10040 llvm_unreachable("Tiny code model not available on ARM.");
10041 case CodeModel::Small:
10042 case CodeModel::Medium:
10043 case CodeModel::Kernel:
10044 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
10045 .add(predOps(ARMCC::AL))
10046 .addExternalSymbol("__chkstk")
10047 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10048 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10049 .addReg(ARM::R12,
10050 RegState::Implicit | RegState::Define | RegState::Dead)
10051 .addReg(ARM::CPSR,
10052 RegState::Implicit | RegState::Define | RegState::Dead);
10053 break;
10054 case CodeModel::Large: {
10055 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10056 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
10058 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
10059 .addExternalSymbol("__chkstk");
10060 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
10061 .add(predOps(ARMCC::AL))
10062 .addReg(Reg, RegState::Kill)
10063 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10064 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10065 .addReg(ARM::R12,
10066 RegState::Implicit | RegState::Define | RegState::Dead)
10067 .addReg(ARM::CPSR,
10068 RegState::Implicit | RegState::Define | RegState::Dead);
10069 break;
10073 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
10074 .addReg(ARM::SP, RegState::Kill)
10075 .addReg(ARM::R4, RegState::Kill)
10076 .setMIFlags(MachineInstr::FrameSetup)
10077 .add(predOps(ARMCC::AL))
10078 .add(condCodeOp());
10080 MI.eraseFromParent();
10081 return MBB;
10084 MachineBasicBlock *
10085 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
10086 MachineBasicBlock *MBB) const {
10087 DebugLoc DL = MI.getDebugLoc();
10088 MachineFunction *MF = MBB->getParent();
10089 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10091 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
10092 MF->insert(++MBB->getIterator(), ContBB);
10093 ContBB->splice(ContBB->begin(), MBB,
10094 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10095 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
10096 MBB->addSuccessor(ContBB);
10098 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10099 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
10100 MF->push_back(TrapBB);
10101 MBB->addSuccessor(TrapBB);
10103 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
10104 .addReg(MI.getOperand(0).getReg())
10105 .addImm(0)
10106 .add(predOps(ARMCC::AL));
10107 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
10108 .addMBB(TrapBB)
10109 .addImm(ARMCC::EQ)
10110 .addReg(ARM::CPSR);
10112 MI.eraseFromParent();
10113 return ContBB;
10116 // The CPSR operand of SelectItr might be missing a kill marker
10117 // because there were multiple uses of CPSR, and ISel didn't know
10118 // which to mark. Figure out whether SelectItr should have had a
10119 // kill marker, and set it if it should. Returns the correct kill
10120 // marker value.
10121 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
10122 MachineBasicBlock* BB,
10123 const TargetRegisterInfo* TRI) {
10124 // Scan forward through BB for a use/def of CPSR.
10125 MachineBasicBlock::iterator miI(std::next(SelectItr));
10126 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
10127 const MachineInstr& mi = *miI;
10128 if (mi.readsRegister(ARM::CPSR))
10129 return false;
10130 if (mi.definesRegister(ARM::CPSR))
10131 break; // Should have kill-flag - update below.
10134 // If we hit the end of the block, check whether CPSR is live into a
10135 // successor.
10136 if (miI == BB->end()) {
10137 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
10138 sEnd = BB->succ_end();
10139 sItr != sEnd; ++sItr) {
10140 MachineBasicBlock* succ = *sItr;
10141 if (succ->isLiveIn(ARM::CPSR))
10142 return false;
10146 // We found a def, or hit the end of the basic block and CPSR wasn't live
10147 // out. SelectMI should have a kill flag on CPSR.
10148 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
10149 return true;
10152 MachineBasicBlock *
10153 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10154 MachineBasicBlock *BB) const {
10155 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10156 DebugLoc dl = MI.getDebugLoc();
10157 bool isThumb2 = Subtarget->isThumb2();
10158 switch (MI.getOpcode()) {
10159 default: {
10160 MI.print(errs());
10161 llvm_unreachable("Unexpected instr type to insert");
10164 // Thumb1 post-indexed loads are really just single-register LDMs.
10165 case ARM::tLDR_postidx: {
10166 MachineOperand Def(MI.getOperand(1));
10167 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
10168 .add(Def) // Rn_wb
10169 .add(MI.getOperand(2)) // Rn
10170 .add(MI.getOperand(3)) // PredImm
10171 .add(MI.getOperand(4)) // PredReg
10172 .add(MI.getOperand(0)) // Rt
10173 .cloneMemRefs(MI);
10174 MI.eraseFromParent();
10175 return BB;
10178 // The Thumb2 pre-indexed stores have the same MI operands, they just
10179 // define them differently in the .td files from the isel patterns, so
10180 // they need pseudos.
10181 case ARM::t2STR_preidx:
10182 MI.setDesc(TII->get(ARM::t2STR_PRE));
10183 return BB;
10184 case ARM::t2STRB_preidx:
10185 MI.setDesc(TII->get(ARM::t2STRB_PRE));
10186 return BB;
10187 case ARM::t2STRH_preidx:
10188 MI.setDesc(TII->get(ARM::t2STRH_PRE));
10189 return BB;
10191 case ARM::STRi_preidx:
10192 case ARM::STRBi_preidx: {
10193 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
10194 : ARM::STRB_PRE_IMM;
10195 // Decode the offset.
10196 unsigned Offset = MI.getOperand(4).getImm();
10197 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
10198 Offset = ARM_AM::getAM2Offset(Offset);
10199 if (isSub)
10200 Offset = -Offset;
10202 MachineMemOperand *MMO = *MI.memoperands_begin();
10203 BuildMI(*BB, MI, dl, TII->get(NewOpc))
10204 .add(MI.getOperand(0)) // Rn_wb
10205 .add(MI.getOperand(1)) // Rt
10206 .add(MI.getOperand(2)) // Rn
10207 .addImm(Offset) // offset (skip GPR==zero_reg)
10208 .add(MI.getOperand(5)) // pred
10209 .add(MI.getOperand(6))
10210 .addMemOperand(MMO);
10211 MI.eraseFromParent();
10212 return BB;
10214 case ARM::STRr_preidx:
10215 case ARM::STRBr_preidx:
10216 case ARM::STRH_preidx: {
10217 unsigned NewOpc;
10218 switch (MI.getOpcode()) {
10219 default: llvm_unreachable("unexpected opcode!");
10220 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
10221 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
10222 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
10224 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
10225 for (unsigned i = 0; i < MI.getNumOperands(); ++i)
10226 MIB.add(MI.getOperand(i));
10227 MI.eraseFromParent();
10228 return BB;
10231 case ARM::tMOVCCr_pseudo: {
10232 // To "insert" a SELECT_CC instruction, we actually have to insert the
10233 // diamond control-flow pattern. The incoming instruction knows the
10234 // destination vreg to set, the condition code register to branch on, the
10235 // true/false values to select between, and a branch opcode to use.
10236 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10237 MachineFunction::iterator It = ++BB->getIterator();
10239 // thisMBB:
10240 // ...
10241 // TrueVal = ...
10242 // cmpTY ccX, r1, r2
10243 // bCC copy1MBB
10244 // fallthrough --> copy0MBB
10245 MachineBasicBlock *thisMBB = BB;
10246 MachineFunction *F = BB->getParent();
10247 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10248 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10249 F->insert(It, copy0MBB);
10250 F->insert(It, sinkMBB);
10252 // Check whether CPSR is live past the tMOVCCr_pseudo.
10253 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
10254 if (!MI.killsRegister(ARM::CPSR) &&
10255 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
10256 copy0MBB->addLiveIn(ARM::CPSR);
10257 sinkMBB->addLiveIn(ARM::CPSR);
10260 // Transfer the remainder of BB and its successor edges to sinkMBB.
10261 sinkMBB->splice(sinkMBB->begin(), BB,
10262 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10263 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10265 BB->addSuccessor(copy0MBB);
10266 BB->addSuccessor(sinkMBB);
10268 BuildMI(BB, dl, TII->get(ARM::tBcc))
10269 .addMBB(sinkMBB)
10270 .addImm(MI.getOperand(3).getImm())
10271 .addReg(MI.getOperand(4).getReg());
10273 // copy0MBB:
10274 // %FalseValue = ...
10275 // # fallthrough to sinkMBB
10276 BB = copy0MBB;
10278 // Update machine-CFG edges
10279 BB->addSuccessor(sinkMBB);
10281 // sinkMBB:
10282 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10283 // ...
10284 BB = sinkMBB;
10285 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
10286 .addReg(MI.getOperand(1).getReg())
10287 .addMBB(copy0MBB)
10288 .addReg(MI.getOperand(2).getReg())
10289 .addMBB(thisMBB);
10291 MI.eraseFromParent(); // The pseudo instruction is gone now.
10292 return BB;
10295 case ARM::BCCi64:
10296 case ARM::BCCZi64: {
10297 // If there is an unconditional branch to the other successor, remove it.
10298 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
10300 // Compare both parts that make up the double comparison separately for
10301 // equality.
10302 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
10304 Register LHS1 = MI.getOperand(1).getReg();
10305 Register LHS2 = MI.getOperand(2).getReg();
10306 if (RHSisZero) {
10307 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10308 .addReg(LHS1)
10309 .addImm(0)
10310 .add(predOps(ARMCC::AL));
10311 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10312 .addReg(LHS2).addImm(0)
10313 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10314 } else {
10315 Register RHS1 = MI.getOperand(3).getReg();
10316 Register RHS2 = MI.getOperand(4).getReg();
10317 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10318 .addReg(LHS1)
10319 .addReg(RHS1)
10320 .add(predOps(ARMCC::AL));
10321 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10322 .addReg(LHS2).addReg(RHS2)
10323 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10326 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
10327 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
10328 if (MI.getOperand(0).getImm() == ARMCC::NE)
10329 std::swap(destMBB, exitMBB);
10331 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
10332 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
10333 if (isThumb2)
10334 BuildMI(BB, dl, TII->get(ARM::t2B))
10335 .addMBB(exitMBB)
10336 .add(predOps(ARMCC::AL));
10337 else
10338 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
10340 MI.eraseFromParent(); // The pseudo instruction is gone now.
10341 return BB;
10344 case ARM::Int_eh_sjlj_setjmp:
10345 case ARM::Int_eh_sjlj_setjmp_nofp:
10346 case ARM::tInt_eh_sjlj_setjmp:
10347 case ARM::t2Int_eh_sjlj_setjmp:
10348 case ARM::t2Int_eh_sjlj_setjmp_nofp:
10349 return BB;
10351 case ARM::Int_eh_sjlj_setup_dispatch:
10352 EmitSjLjDispatchBlock(MI, BB);
10353 return BB;
10355 case ARM::ABS:
10356 case ARM::t2ABS: {
10357 // To insert an ABS instruction, we have to insert the
10358 // diamond control-flow pattern. The incoming instruction knows the
10359 // source vreg to test against 0, the destination vreg to set,
10360 // the condition code register to branch on, the
10361 // true/false values to select between, and a branch opcode to use.
10362 // It transforms
10363 // V1 = ABS V0
10364 // into
10365 // V2 = MOVS V0
10366 // BCC (branch to SinkBB if V0 >= 0)
10367 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
10368 // SinkBB: V1 = PHI(V2, V3)
10369 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10370 MachineFunction::iterator BBI = ++BB->getIterator();
10371 MachineFunction *Fn = BB->getParent();
10372 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10373 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10374 Fn->insert(BBI, RSBBB);
10375 Fn->insert(BBI, SinkBB);
10377 Register ABSSrcReg = MI.getOperand(1).getReg();
10378 Register ABSDstReg = MI.getOperand(0).getReg();
10379 bool ABSSrcKIll = MI.getOperand(1).isKill();
10380 bool isThumb2 = Subtarget->isThumb2();
10381 MachineRegisterInfo &MRI = Fn->getRegInfo();
10382 // In Thumb mode S must not be specified if source register is the SP or
10383 // PC and if destination register is the SP, so restrict register class
10384 Register NewRsbDstReg = MRI.createVirtualRegister(
10385 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
10387 // Transfer the remainder of BB and its successor edges to sinkMBB.
10388 SinkBB->splice(SinkBB->begin(), BB,
10389 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10390 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
10392 BB->addSuccessor(RSBBB);
10393 BB->addSuccessor(SinkBB);
10395 // fall through to SinkMBB
10396 RSBBB->addSuccessor(SinkBB);
10398 // insert a cmp at the end of BB
10399 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10400 .addReg(ABSSrcReg)
10401 .addImm(0)
10402 .add(predOps(ARMCC::AL));
10404 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
10405 BuildMI(BB, dl,
10406 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
10407 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
10409 // insert rsbri in RSBBB
10410 // Note: BCC and rsbri will be converted into predicated rsbmi
10411 // by if-conversion pass
10412 BuildMI(*RSBBB, RSBBB->begin(), dl,
10413 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
10414 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
10415 .addImm(0)
10416 .add(predOps(ARMCC::AL))
10417 .add(condCodeOp());
10419 // insert PHI in SinkBB,
10420 // reuse ABSDstReg to not change uses of ABS instruction
10421 BuildMI(*SinkBB, SinkBB->begin(), dl,
10422 TII->get(ARM::PHI), ABSDstReg)
10423 .addReg(NewRsbDstReg).addMBB(RSBBB)
10424 .addReg(ABSSrcReg).addMBB(BB);
10426 // remove ABS instruction
10427 MI.eraseFromParent();
10429 // return last added BB
10430 return SinkBB;
10432 case ARM::COPY_STRUCT_BYVAL_I32:
10433 ++NumLoopByVals;
10434 return EmitStructByval(MI, BB);
10435 case ARM::WIN__CHKSTK:
10436 return EmitLowered__chkstk(MI, BB);
10437 case ARM::WIN__DBZCHK:
10438 return EmitLowered__dbzchk(MI, BB);
10442 /// Attaches vregs to MEMCPY that it will use as scratch registers
10443 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
10444 /// instead of as a custom inserter because we need the use list from the SDNode.
10445 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
10446 MachineInstr &MI, const SDNode *Node) {
10447 bool isThumb1 = Subtarget->isThumb1Only();
10449 DebugLoc DL = MI.getDebugLoc();
10450 MachineFunction *MF = MI.getParent()->getParent();
10451 MachineRegisterInfo &MRI = MF->getRegInfo();
10452 MachineInstrBuilder MIB(*MF, MI);
10454 // If the new dst/src is unused mark it as dead.
10455 if (!Node->hasAnyUseOfValue(0)) {
10456 MI.getOperand(0).setIsDead(true);
10458 if (!Node->hasAnyUseOfValue(1)) {
10459 MI.getOperand(1).setIsDead(true);
10462 // The MEMCPY both defines and kills the scratch registers.
10463 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
10464 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
10465 : &ARM::GPRRegClass);
10466 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
10470 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10471 SDNode *Node) const {
10472 if (MI.getOpcode() == ARM::MEMCPY) {
10473 attachMEMCPYScratchRegs(Subtarget, MI, Node);
10474 return;
10477 const MCInstrDesc *MCID = &MI.getDesc();
10478 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
10479 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
10480 // operand is still set to noreg. If needed, set the optional operand's
10481 // register to CPSR, and remove the redundant implicit def.
10483 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
10485 // Rename pseudo opcodes.
10486 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
10487 unsigned ccOutIdx;
10488 if (NewOpc) {
10489 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
10490 MCID = &TII->get(NewOpc);
10492 assert(MCID->getNumOperands() ==
10493 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
10494 && "converted opcode should be the same except for cc_out"
10495 " (and, on Thumb1, pred)");
10497 MI.setDesc(*MCID);
10499 // Add the optional cc_out operand
10500 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
10502 // On Thumb1, move all input operands to the end, then add the predicate
10503 if (Subtarget->isThumb1Only()) {
10504 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
10505 MI.addOperand(MI.getOperand(1));
10506 MI.RemoveOperand(1);
10509 // Restore the ties
10510 for (unsigned i = MI.getNumOperands(); i--;) {
10511 const MachineOperand& op = MI.getOperand(i);
10512 if (op.isReg() && op.isUse()) {
10513 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
10514 if (DefIdx != -1)
10515 MI.tieOperands(DefIdx, i);
10519 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
10520 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
10521 ccOutIdx = 1;
10522 } else
10523 ccOutIdx = MCID->getNumOperands() - 1;
10524 } else
10525 ccOutIdx = MCID->getNumOperands() - 1;
10527 // Any ARM instruction that sets the 's' bit should specify an optional
10528 // "cc_out" operand in the last operand position.
10529 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
10530 assert(!NewOpc && "Optional cc_out operand required");
10531 return;
10533 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
10534 // since we already have an optional CPSR def.
10535 bool definesCPSR = false;
10536 bool deadCPSR = false;
10537 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
10538 ++i) {
10539 const MachineOperand &MO = MI.getOperand(i);
10540 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
10541 definesCPSR = true;
10542 if (MO.isDead())
10543 deadCPSR = true;
10544 MI.RemoveOperand(i);
10545 break;
10548 if (!definesCPSR) {
10549 assert(!NewOpc && "Optional cc_out operand required");
10550 return;
10552 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
10553 if (deadCPSR) {
10554 assert(!MI.getOperand(ccOutIdx).getReg() &&
10555 "expect uninitialized optional cc_out operand");
10556 // Thumb1 instructions must have the S bit even if the CPSR is dead.
10557 if (!Subtarget->isThumb1Only())
10558 return;
10561 // If this instruction was defined with an optional CPSR def and its dag node
10562 // had a live implicit CPSR def, then activate the optional CPSR def.
10563 MachineOperand &MO = MI.getOperand(ccOutIdx);
10564 MO.setReg(ARM::CPSR);
10565 MO.setIsDef(true);
10568 //===----------------------------------------------------------------------===//
10569 // ARM Optimization Hooks
10570 //===----------------------------------------------------------------------===//
10572 // Helper function that checks if N is a null or all ones constant.
10573 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
10574 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
10577 // Return true if N is conditionally 0 or all ones.
10578 // Detects these expressions where cc is an i1 value:
10580 // (select cc 0, y) [AllOnes=0]
10581 // (select cc y, 0) [AllOnes=0]
10582 // (zext cc) [AllOnes=0]
10583 // (sext cc) [AllOnes=0/1]
10584 // (select cc -1, y) [AllOnes=1]
10585 // (select cc y, -1) [AllOnes=1]
10587 // Invert is set when N is the null/all ones constant when CC is false.
10588 // OtherOp is set to the alternative value of N.
10589 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
10590 SDValue &CC, bool &Invert,
10591 SDValue &OtherOp,
10592 SelectionDAG &DAG) {
10593 switch (N->getOpcode()) {
10594 default: return false;
10595 case ISD::SELECT: {
10596 CC = N->getOperand(0);
10597 SDValue N1 = N->getOperand(1);
10598 SDValue N2 = N->getOperand(2);
10599 if (isZeroOrAllOnes(N1, AllOnes)) {
10600 Invert = false;
10601 OtherOp = N2;
10602 return true;
10604 if (isZeroOrAllOnes(N2, AllOnes)) {
10605 Invert = true;
10606 OtherOp = N1;
10607 return true;
10609 return false;
10611 case ISD::ZERO_EXTEND:
10612 // (zext cc) can never be the all ones value.
10613 if (AllOnes)
10614 return false;
10615 LLVM_FALLTHROUGH;
10616 case ISD::SIGN_EXTEND: {
10617 SDLoc dl(N);
10618 EVT VT = N->getValueType(0);
10619 CC = N->getOperand(0);
10620 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
10621 return false;
10622 Invert = !AllOnes;
10623 if (AllOnes)
10624 // When looking for an AllOnes constant, N is an sext, and the 'other'
10625 // value is 0.
10626 OtherOp = DAG.getConstant(0, dl, VT);
10627 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10628 // When looking for a 0 constant, N can be zext or sext.
10629 OtherOp = DAG.getConstant(1, dl, VT);
10630 else
10631 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
10632 VT);
10633 return true;
10638 // Combine a constant select operand into its use:
10640 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10641 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10642 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
10643 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10644 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10646 // The transform is rejected if the select doesn't have a constant operand that
10647 // is null, or all ones when AllOnes is set.
10649 // Also recognize sext/zext from i1:
10651 // (add (zext cc), x) -> (select cc (add x, 1), x)
10652 // (add (sext cc), x) -> (select cc (add x, -1), x)
10654 // These transformations eventually create predicated instructions.
10656 // @param N The node to transform.
10657 // @param Slct The N operand that is a select.
10658 // @param OtherOp The other N operand (x above).
10659 // @param DCI Context.
10660 // @param AllOnes Require the select constant to be all ones instead of null.
10661 // @returns The new node, or SDValue() on failure.
10662 static
10663 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
10664 TargetLowering::DAGCombinerInfo &DCI,
10665 bool AllOnes = false) {
10666 SelectionDAG &DAG = DCI.DAG;
10667 EVT VT = N->getValueType(0);
10668 SDValue NonConstantVal;
10669 SDValue CCOp;
10670 bool SwapSelectOps;
10671 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
10672 NonConstantVal, DAG))
10673 return SDValue();
10675 // Slct is now know to be the desired identity constant when CC is true.
10676 SDValue TrueVal = OtherOp;
10677 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10678 OtherOp, NonConstantVal);
10679 // Unless SwapSelectOps says CC should be false.
10680 if (SwapSelectOps)
10681 std::swap(TrueVal, FalseVal);
10683 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
10684 CCOp, TrueVal, FalseVal);
10687 // Attempt combineSelectAndUse on each operand of a commutative operator N.
10688 static
10689 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
10690 TargetLowering::DAGCombinerInfo &DCI) {
10691 SDValue N0 = N->getOperand(0);
10692 SDValue N1 = N->getOperand(1);
10693 if (N0.getNode()->hasOneUse())
10694 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
10695 return Result;
10696 if (N1.getNode()->hasOneUse())
10697 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
10698 return Result;
10699 return SDValue();
10702 static bool IsVUZPShuffleNode(SDNode *N) {
10703 // VUZP shuffle node.
10704 if (N->getOpcode() == ARMISD::VUZP)
10705 return true;
10707 // "VUZP" on i32 is an alias for VTRN.
10708 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
10709 return true;
10711 return false;
10714 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
10715 TargetLowering::DAGCombinerInfo &DCI,
10716 const ARMSubtarget *Subtarget) {
10717 // Look for ADD(VUZP.0, VUZP.1).
10718 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
10719 N0 == N1)
10720 return SDValue();
10722 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
10723 if (!N->getValueType(0).is64BitVector())
10724 return SDValue();
10726 // Generate vpadd.
10727 SelectionDAG &DAG = DCI.DAG;
10728 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10729 SDLoc dl(N);
10730 SDNode *Unzip = N0.getNode();
10731 EVT VT = N->getValueType(0);
10733 SmallVector<SDValue, 8> Ops;
10734 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
10735 TLI.getPointerTy(DAG.getDataLayout())));
10736 Ops.push_back(Unzip->getOperand(0));
10737 Ops.push_back(Unzip->getOperand(1));
10739 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10742 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10743 TargetLowering::DAGCombinerInfo &DCI,
10744 const ARMSubtarget *Subtarget) {
10745 // Check for two extended operands.
10746 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
10747 N1.getOpcode() == ISD::SIGN_EXTEND) &&
10748 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
10749 N1.getOpcode() == ISD::ZERO_EXTEND))
10750 return SDValue();
10752 SDValue N00 = N0.getOperand(0);
10753 SDValue N10 = N1.getOperand(0);
10755 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
10756 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
10757 N00 == N10)
10758 return SDValue();
10760 // We only recognize Q register paddl here; this can't be reached until
10761 // after type legalization.
10762 if (!N00.getValueType().is64BitVector() ||
10763 !N0.getValueType().is128BitVector())
10764 return SDValue();
10766 // Generate vpaddl.
10767 SelectionDAG &DAG = DCI.DAG;
10768 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10769 SDLoc dl(N);
10770 EVT VT = N->getValueType(0);
10772 SmallVector<SDValue, 8> Ops;
10773 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
10774 unsigned Opcode;
10775 if (N0.getOpcode() == ISD::SIGN_EXTEND)
10776 Opcode = Intrinsic::arm_neon_vpaddls;
10777 else
10778 Opcode = Intrinsic::arm_neon_vpaddlu;
10779 Ops.push_back(DAG.getConstant(Opcode, dl,
10780 TLI.getPointerTy(DAG.getDataLayout())));
10781 EVT ElemTy = N00.getValueType().getVectorElementType();
10782 unsigned NumElts = VT.getVectorNumElements();
10783 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
10784 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
10785 N00.getOperand(0), N00.getOperand(1));
10786 Ops.push_back(Concat);
10788 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10791 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
10792 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
10793 // much easier to match.
10794 static SDValue
10795 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10796 TargetLowering::DAGCombinerInfo &DCI,
10797 const ARMSubtarget *Subtarget) {
10798 // Only perform optimization if after legalize, and if NEON is available. We
10799 // also expected both operands to be BUILD_VECTORs.
10800 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
10801 || N0.getOpcode() != ISD::BUILD_VECTOR
10802 || N1.getOpcode() != ISD::BUILD_VECTOR)
10803 return SDValue();
10805 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
10806 EVT VT = N->getValueType(0);
10807 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
10808 return SDValue();
10810 // Check that the vector operands are of the right form.
10811 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
10812 // operands, where N is the size of the formed vector.
10813 // Each EXTRACT_VECTOR should have the same input vector and odd or even
10814 // index such that we have a pair wise add pattern.
10816 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
10817 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10818 return SDValue();
10819 SDValue Vec = N0->getOperand(0)->getOperand(0);
10820 SDNode *V = Vec.getNode();
10821 unsigned nextIndex = 0;
10823 // For each operands to the ADD which are BUILD_VECTORs,
10824 // check to see if each of their operands are an EXTRACT_VECTOR with
10825 // the same vector and appropriate index.
10826 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
10827 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
10828 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10830 SDValue ExtVec0 = N0->getOperand(i);
10831 SDValue ExtVec1 = N1->getOperand(i);
10833 // First operand is the vector, verify its the same.
10834 if (V != ExtVec0->getOperand(0).getNode() ||
10835 V != ExtVec1->getOperand(0).getNode())
10836 return SDValue();
10838 // Second is the constant, verify its correct.
10839 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
10840 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
10842 // For the constant, we want to see all the even or all the odd.
10843 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
10844 || C1->getZExtValue() != nextIndex+1)
10845 return SDValue();
10847 // Increment index.
10848 nextIndex+=2;
10849 } else
10850 return SDValue();
10853 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
10854 // we're using the entire input vector, otherwise there's a size/legality
10855 // mismatch somewhere.
10856 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
10857 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
10858 return SDValue();
10860 // Create VPADDL node.
10861 SelectionDAG &DAG = DCI.DAG;
10862 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10864 SDLoc dl(N);
10866 // Build operand list.
10867 SmallVector<SDValue, 8> Ops;
10868 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
10869 TLI.getPointerTy(DAG.getDataLayout())));
10871 // Input is the vector.
10872 Ops.push_back(Vec);
10874 // Get widened type and narrowed type.
10875 MVT widenType;
10876 unsigned numElem = VT.getVectorNumElements();
10878 EVT inputLaneType = Vec.getValueType().getVectorElementType();
10879 switch (inputLaneType.getSimpleVT().SimpleTy) {
10880 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
10881 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
10882 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
10883 default:
10884 llvm_unreachable("Invalid vector element type for padd optimization.");
10887 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
10888 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
10889 return DAG.getNode(ExtOp, dl, VT, tmp);
10892 static SDValue findMUL_LOHI(SDValue V) {
10893 if (V->getOpcode() == ISD::UMUL_LOHI ||
10894 V->getOpcode() == ISD::SMUL_LOHI)
10895 return V;
10896 return SDValue();
10899 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
10900 TargetLowering::DAGCombinerInfo &DCI,
10901 const ARMSubtarget *Subtarget) {
10902 if (Subtarget->isThumb()) {
10903 if (!Subtarget->hasDSP())
10904 return SDValue();
10905 } else if (!Subtarget->hasV5TEOps())
10906 return SDValue();
10908 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
10909 // accumulates the product into a 64-bit value. The 16-bit values will
10910 // be sign extended somehow or SRA'd into 32-bit values
10911 // (addc (adde (mul 16bit, 16bit), lo), hi)
10912 SDValue Mul = AddcNode->getOperand(0);
10913 SDValue Lo = AddcNode->getOperand(1);
10914 if (Mul.getOpcode() != ISD::MUL) {
10915 Lo = AddcNode->getOperand(0);
10916 Mul = AddcNode->getOperand(1);
10917 if (Mul.getOpcode() != ISD::MUL)
10918 return SDValue();
10921 SDValue SRA = AddeNode->getOperand(0);
10922 SDValue Hi = AddeNode->getOperand(1);
10923 if (SRA.getOpcode() != ISD::SRA) {
10924 SRA = AddeNode->getOperand(1);
10925 Hi = AddeNode->getOperand(0);
10926 if (SRA.getOpcode() != ISD::SRA)
10927 return SDValue();
10929 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
10930 if (Const->getZExtValue() != 31)
10931 return SDValue();
10932 } else
10933 return SDValue();
10935 if (SRA.getOperand(0) != Mul)
10936 return SDValue();
10938 SelectionDAG &DAG = DCI.DAG;
10939 SDLoc dl(AddcNode);
10940 unsigned Opcode = 0;
10941 SDValue Op0;
10942 SDValue Op1;
10944 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
10945 Opcode = ARMISD::SMLALBB;
10946 Op0 = Mul.getOperand(0);
10947 Op1 = Mul.getOperand(1);
10948 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
10949 Opcode = ARMISD::SMLALBT;
10950 Op0 = Mul.getOperand(0);
10951 Op1 = Mul.getOperand(1).getOperand(0);
10952 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
10953 Opcode = ARMISD::SMLALTB;
10954 Op0 = Mul.getOperand(0).getOperand(0);
10955 Op1 = Mul.getOperand(1);
10956 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
10957 Opcode = ARMISD::SMLALTT;
10958 Op0 = Mul->getOperand(0).getOperand(0);
10959 Op1 = Mul->getOperand(1).getOperand(0);
10962 if (!Op0 || !Op1)
10963 return SDValue();
10965 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
10966 Op0, Op1, Lo, Hi);
10967 // Replace the ADDs' nodes uses by the MLA node's values.
10968 SDValue HiMLALResult(SMLAL.getNode(), 1);
10969 SDValue LoMLALResult(SMLAL.getNode(), 0);
10971 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
10972 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
10974 // Return original node to notify the driver to stop replacing.
10975 SDValue resNode(AddcNode, 0);
10976 return resNode;
10979 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
10980 TargetLowering::DAGCombinerInfo &DCI,
10981 const ARMSubtarget *Subtarget) {
10982 // Look for multiply add opportunities.
10983 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
10984 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
10985 // a glue link from the first add to the second add.
10986 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
10987 // a S/UMLAL instruction.
10988 // UMUL_LOHI
10989 // / :lo \ :hi
10990 // V \ [no multiline comment]
10991 // loAdd -> ADDC |
10992 // \ :carry /
10993 // V V
10994 // ADDE <- hiAdd
10996 // In the special case where only the higher part of a signed result is used
10997 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
10998 // a constant with the exact value of 0x80000000, we recognize we are dealing
10999 // with a "rounded multiply and add" (or subtract) and transform it into
11000 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
11002 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
11003 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
11004 "Expect an ADDE or SUBE");
11006 assert(AddeSubeNode->getNumOperands() == 3 &&
11007 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
11008 "ADDE node has the wrong inputs");
11010 // Check that we are chained to the right ADDC or SUBC node.
11011 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
11012 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11013 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
11014 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
11015 AddcSubcNode->getOpcode() != ARMISD::SUBC))
11016 return SDValue();
11018 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
11019 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
11021 // Check if the two operands are from the same mul_lohi node.
11022 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
11023 return SDValue();
11025 assert(AddcSubcNode->getNumValues() == 2 &&
11026 AddcSubcNode->getValueType(0) == MVT::i32 &&
11027 "Expect ADDC with two result values. First: i32");
11029 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
11030 // maybe a SMLAL which multiplies two 16-bit values.
11031 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11032 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
11033 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
11034 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
11035 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
11036 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
11038 // Check for the triangle shape.
11039 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
11040 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
11042 // Make sure that the ADDE/SUBE operands are not coming from the same node.
11043 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
11044 return SDValue();
11046 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
11047 bool IsLeftOperandMUL = false;
11048 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
11049 if (MULOp == SDValue())
11050 MULOp = findMUL_LOHI(AddeSubeOp1);
11051 else
11052 IsLeftOperandMUL = true;
11053 if (MULOp == SDValue())
11054 return SDValue();
11056 // Figure out the right opcode.
11057 unsigned Opc = MULOp->getOpcode();
11058 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
11060 // Figure out the high and low input values to the MLAL node.
11061 SDValue *HiAddSub = nullptr;
11062 SDValue *LoMul = nullptr;
11063 SDValue *LowAddSub = nullptr;
11065 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
11066 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
11067 return SDValue();
11069 if (IsLeftOperandMUL)
11070 HiAddSub = &AddeSubeOp1;
11071 else
11072 HiAddSub = &AddeSubeOp0;
11074 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
11075 // whose low result is fed to the ADDC/SUBC we are checking.
11077 if (AddcSubcOp0 == MULOp.getValue(0)) {
11078 LoMul = &AddcSubcOp0;
11079 LowAddSub = &AddcSubcOp1;
11081 if (AddcSubcOp1 == MULOp.getValue(0)) {
11082 LoMul = &AddcSubcOp1;
11083 LowAddSub = &AddcSubcOp0;
11086 if (!LoMul)
11087 return SDValue();
11089 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
11090 // the replacement below will create a cycle.
11091 if (AddcSubcNode == HiAddSub->getNode() ||
11092 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
11093 return SDValue();
11095 // Create the merged node.
11096 SelectionDAG &DAG = DCI.DAG;
11098 // Start building operand list.
11099 SmallVector<SDValue, 8> Ops;
11100 Ops.push_back(LoMul->getOperand(0));
11101 Ops.push_back(LoMul->getOperand(1));
11103 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
11104 // the case, we must be doing signed multiplication and only use the higher
11105 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
11106 // addition or subtraction with the value of 0x800000.
11107 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
11108 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
11109 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
11110 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
11111 0x80000000) {
11112 Ops.push_back(*HiAddSub);
11113 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
11114 FinalOpc = ARMISD::SMMLSR;
11115 } else {
11116 FinalOpc = ARMISD::SMMLAR;
11118 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
11119 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
11121 return SDValue(AddeSubeNode, 0);
11122 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
11123 // SMMLS is generated during instruction selection and the rest of this
11124 // function can not handle the case where AddcSubcNode is a SUBC.
11125 return SDValue();
11127 // Finish building the operand list for {U/S}MLAL
11128 Ops.push_back(*LowAddSub);
11129 Ops.push_back(*HiAddSub);
11131 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
11132 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11134 // Replace the ADDs' nodes uses by the MLA node's values.
11135 SDValue HiMLALResult(MLALNode.getNode(), 1);
11136 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
11138 SDValue LoMLALResult(MLALNode.getNode(), 0);
11139 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
11141 // Return original node to notify the driver to stop replacing.
11142 return SDValue(AddeSubeNode, 0);
11145 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
11146 TargetLowering::DAGCombinerInfo &DCI,
11147 const ARMSubtarget *Subtarget) {
11148 // UMAAL is similar to UMLAL except that it adds two unsigned values.
11149 // While trying to combine for the other MLAL nodes, first search for the
11150 // chance to use UMAAL. Check if Addc uses a node which has already
11151 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
11152 // as the addend, and it's handled in PerformUMLALCombine.
11154 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11155 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11157 // Check that we have a glued ADDC node.
11158 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
11159 if (AddcNode->getOpcode() != ARMISD::ADDC)
11160 return SDValue();
11162 // Find the converted UMAAL or quit if it doesn't exist.
11163 SDNode *UmlalNode = nullptr;
11164 SDValue AddHi;
11165 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
11166 UmlalNode = AddcNode->getOperand(0).getNode();
11167 AddHi = AddcNode->getOperand(1);
11168 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
11169 UmlalNode = AddcNode->getOperand(1).getNode();
11170 AddHi = AddcNode->getOperand(0);
11171 } else {
11172 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11175 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
11176 // the ADDC as well as Zero.
11177 if (!isNullConstant(UmlalNode->getOperand(3)))
11178 return SDValue();
11180 if ((isNullConstant(AddeNode->getOperand(0)) &&
11181 AddeNode->getOperand(1).getNode() == UmlalNode) ||
11182 (AddeNode->getOperand(0).getNode() == UmlalNode &&
11183 isNullConstant(AddeNode->getOperand(1)))) {
11184 SelectionDAG &DAG = DCI.DAG;
11185 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
11186 UmlalNode->getOperand(2), AddHi };
11187 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
11188 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11190 // Replace the ADDs' nodes uses by the UMAAL node's values.
11191 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
11192 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
11194 // Return original node to notify the driver to stop replacing.
11195 return SDValue(AddeNode, 0);
11197 return SDValue();
11200 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
11201 const ARMSubtarget *Subtarget) {
11202 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11203 return SDValue();
11205 // Check that we have a pair of ADDC and ADDE as operands.
11206 // Both addends of the ADDE must be zero.
11207 SDNode* AddcNode = N->getOperand(2).getNode();
11208 SDNode* AddeNode = N->getOperand(3).getNode();
11209 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
11210 (AddeNode->getOpcode() == ARMISD::ADDE) &&
11211 isNullConstant(AddeNode->getOperand(0)) &&
11212 isNullConstant(AddeNode->getOperand(1)) &&
11213 (AddeNode->getOperand(2).getNode() == AddcNode))
11214 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
11215 DAG.getVTList(MVT::i32, MVT::i32),
11216 {N->getOperand(0), N->getOperand(1),
11217 AddcNode->getOperand(0), AddcNode->getOperand(1)});
11218 else
11219 return SDValue();
11222 static SDValue PerformAddcSubcCombine(SDNode *N,
11223 TargetLowering::DAGCombinerInfo &DCI,
11224 const ARMSubtarget *Subtarget) {
11225 SelectionDAG &DAG(DCI.DAG);
11227 if (N->getOpcode() == ARMISD::SUBC) {
11228 // (SUBC (ADDE 0, 0, C), 1) -> C
11229 SDValue LHS = N->getOperand(0);
11230 SDValue RHS = N->getOperand(1);
11231 if (LHS->getOpcode() == ARMISD::ADDE &&
11232 isNullConstant(LHS->getOperand(0)) &&
11233 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
11234 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
11238 if (Subtarget->isThumb1Only()) {
11239 SDValue RHS = N->getOperand(1);
11240 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11241 int32_t imm = C->getSExtValue();
11242 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
11243 SDLoc DL(N);
11244 RHS = DAG.getConstant(-imm, DL, MVT::i32);
11245 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
11246 : ARMISD::ADDC;
11247 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
11252 return SDValue();
11255 static SDValue PerformAddeSubeCombine(SDNode *N,
11256 TargetLowering::DAGCombinerInfo &DCI,
11257 const ARMSubtarget *Subtarget) {
11258 if (Subtarget->isThumb1Only()) {
11259 SelectionDAG &DAG = DCI.DAG;
11260 SDValue RHS = N->getOperand(1);
11261 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11262 int64_t imm = C->getSExtValue();
11263 if (imm < 0) {
11264 SDLoc DL(N);
11266 // The with-carry-in form matches bitwise not instead of the negation.
11267 // Effectively, the inverse interpretation of the carry flag already
11268 // accounts for part of the negation.
11269 RHS = DAG.getConstant(~imm, DL, MVT::i32);
11271 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
11272 : ARMISD::ADDE;
11273 return DAG.getNode(Opcode, DL, N->getVTList(),
11274 N->getOperand(0), RHS, N->getOperand(2));
11277 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
11278 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
11280 return SDValue();
11283 static SDValue PerformABSCombine(SDNode *N,
11284 TargetLowering::DAGCombinerInfo &DCI,
11285 const ARMSubtarget *Subtarget) {
11286 SDValue res;
11287 SelectionDAG &DAG = DCI.DAG;
11288 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11290 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
11291 return SDValue();
11293 if (!TLI.expandABS(N, res, DAG))
11294 return SDValue();
11296 return res;
11299 /// PerformADDECombine - Target-specific dag combine transform from
11300 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
11301 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
11302 static SDValue PerformADDECombine(SDNode *N,
11303 TargetLowering::DAGCombinerInfo &DCI,
11304 const ARMSubtarget *Subtarget) {
11305 // Only ARM and Thumb2 support UMLAL/SMLAL.
11306 if (Subtarget->isThumb1Only())
11307 return PerformAddeSubeCombine(N, DCI, Subtarget);
11309 // Only perform the checks after legalize when the pattern is available.
11310 if (DCI.isBeforeLegalize()) return SDValue();
11312 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
11315 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
11316 /// operands N0 and N1. This is a helper for PerformADDCombine that is
11317 /// called with the default operands, and if that fails, with commuted
11318 /// operands.
11319 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
11320 TargetLowering::DAGCombinerInfo &DCI,
11321 const ARMSubtarget *Subtarget){
11322 // Attempt to create vpadd for this add.
11323 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
11324 return Result;
11326 // Attempt to create vpaddl for this add.
11327 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
11328 return Result;
11329 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
11330 Subtarget))
11331 return Result;
11333 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
11334 if (N0.getNode()->hasOneUse())
11335 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
11336 return Result;
11337 return SDValue();
11340 bool
11341 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
11342 CombineLevel Level) const {
11343 if (Level == BeforeLegalizeTypes)
11344 return true;
11346 if (N->getOpcode() != ISD::SHL)
11347 return true;
11349 if (Subtarget->isThumb1Only()) {
11350 // Avoid making expensive immediates by commuting shifts. (This logic
11351 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
11352 // for free.)
11353 if (N->getOpcode() != ISD::SHL)
11354 return true;
11355 SDValue N1 = N->getOperand(0);
11356 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
11357 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
11358 return true;
11359 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
11360 if (Const->getAPIntValue().ult(256))
11361 return false;
11362 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
11363 Const->getAPIntValue().sgt(-256))
11364 return false;
11366 return true;
11369 // Turn off commute-with-shift transform after legalization, so it doesn't
11370 // conflict with PerformSHLSimplify. (We could try to detect when
11371 // PerformSHLSimplify would trigger more precisely, but it isn't
11372 // really necessary.)
11373 return false;
11376 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
11377 const SDNode *N, CombineLevel Level) const {
11378 if (!Subtarget->isThumb1Only())
11379 return true;
11381 if (Level == BeforeLegalizeTypes)
11382 return true;
11384 return false;
11387 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
11388 if (!Subtarget->hasNEON()) {
11389 if (Subtarget->isThumb1Only())
11390 return VT.getScalarSizeInBits() <= 32;
11391 return true;
11393 return VT.isScalarInteger();
11396 static SDValue PerformSHLSimplify(SDNode *N,
11397 TargetLowering::DAGCombinerInfo &DCI,
11398 const ARMSubtarget *ST) {
11399 // Allow the generic combiner to identify potential bswaps.
11400 if (DCI.isBeforeLegalize())
11401 return SDValue();
11403 // DAG combiner will fold:
11404 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
11405 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
11406 // Other code patterns that can be also be modified have the following form:
11407 // b + ((a << 1) | 510)
11408 // b + ((a << 1) & 510)
11409 // b + ((a << 1) ^ 510)
11410 // b + ((a << 1) + 510)
11412 // Many instructions can perform the shift for free, but it requires both
11413 // the operands to be registers. If c1 << c2 is too large, a mov immediate
11414 // instruction will needed. So, unfold back to the original pattern if:
11415 // - if c1 and c2 are small enough that they don't require mov imms.
11416 // - the user(s) of the node can perform an shl
11418 // No shifted operands for 16-bit instructions.
11419 if (ST->isThumb() && ST->isThumb1Only())
11420 return SDValue();
11422 // Check that all the users could perform the shl themselves.
11423 for (auto U : N->uses()) {
11424 switch(U->getOpcode()) {
11425 default:
11426 return SDValue();
11427 case ISD::SUB:
11428 case ISD::ADD:
11429 case ISD::AND:
11430 case ISD::OR:
11431 case ISD::XOR:
11432 case ISD::SETCC:
11433 case ARMISD::CMP:
11434 // Check that the user isn't already using a constant because there
11435 // aren't any instructions that support an immediate operand and a
11436 // shifted operand.
11437 if (isa<ConstantSDNode>(U->getOperand(0)) ||
11438 isa<ConstantSDNode>(U->getOperand(1)))
11439 return SDValue();
11441 // Check that it's not already using a shift.
11442 if (U->getOperand(0).getOpcode() == ISD::SHL ||
11443 U->getOperand(1).getOpcode() == ISD::SHL)
11444 return SDValue();
11445 break;
11449 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
11450 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
11451 return SDValue();
11453 if (N->getOperand(0).getOpcode() != ISD::SHL)
11454 return SDValue();
11456 SDValue SHL = N->getOperand(0);
11458 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
11459 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
11460 if (!C1ShlC2 || !C2)
11461 return SDValue();
11463 APInt C2Int = C2->getAPIntValue();
11464 APInt C1Int = C1ShlC2->getAPIntValue();
11466 // Check that performing a lshr will not lose any information.
11467 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
11468 C2Int.getBitWidth() - C2->getZExtValue());
11469 if ((C1Int & Mask) != C1Int)
11470 return SDValue();
11472 // Shift the first constant.
11473 C1Int.lshrInPlace(C2Int);
11475 // The immediates are encoded as an 8-bit value that can be rotated.
11476 auto LargeImm = [](const APInt &Imm) {
11477 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
11478 return Imm.getBitWidth() - Zeros > 8;
11481 if (LargeImm(C1Int) || LargeImm(C2Int))
11482 return SDValue();
11484 SelectionDAG &DAG = DCI.DAG;
11485 SDLoc dl(N);
11486 SDValue X = SHL.getOperand(0);
11487 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
11488 DAG.getConstant(C1Int, dl, MVT::i32));
11489 // Shift left to compensate for the lshr of C1Int.
11490 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
11492 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
11493 SHL.dump(); N->dump());
11494 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
11495 return Res;
11499 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
11501 static SDValue PerformADDCombine(SDNode *N,
11502 TargetLowering::DAGCombinerInfo &DCI,
11503 const ARMSubtarget *Subtarget) {
11504 SDValue N0 = N->getOperand(0);
11505 SDValue N1 = N->getOperand(1);
11507 // Only works one way, because it needs an immediate operand.
11508 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11509 return Result;
11511 // First try with the default operand order.
11512 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
11513 return Result;
11515 // If that didn't work, try again with the operands commuted.
11516 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
11519 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
11521 static SDValue PerformSUBCombine(SDNode *N,
11522 TargetLowering::DAGCombinerInfo &DCI) {
11523 SDValue N0 = N->getOperand(0);
11524 SDValue N1 = N->getOperand(1);
11526 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
11527 if (N1.getNode()->hasOneUse())
11528 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
11529 return Result;
11531 return SDValue();
11534 /// PerformVMULCombine
11535 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
11536 /// special multiplier accumulator forwarding.
11537 /// vmul d3, d0, d2
11538 /// vmla d3, d1, d2
11539 /// is faster than
11540 /// vadd d3, d0, d1
11541 /// vmul d3, d3, d2
11542 // However, for (A + B) * (A + B),
11543 // vadd d2, d0, d1
11544 // vmul d3, d0, d2
11545 // vmla d3, d1, d2
11546 // is slower than
11547 // vadd d2, d0, d1
11548 // vmul d3, d2, d2
11549 static SDValue PerformVMULCombine(SDNode *N,
11550 TargetLowering::DAGCombinerInfo &DCI,
11551 const ARMSubtarget *Subtarget) {
11552 if (!Subtarget->hasVMLxForwarding())
11553 return SDValue();
11555 SelectionDAG &DAG = DCI.DAG;
11556 SDValue N0 = N->getOperand(0);
11557 SDValue N1 = N->getOperand(1);
11558 unsigned Opcode = N0.getOpcode();
11559 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11560 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
11561 Opcode = N1.getOpcode();
11562 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11563 Opcode != ISD::FADD && Opcode != ISD::FSUB)
11564 return SDValue();
11565 std::swap(N0, N1);
11568 if (N0 == N1)
11569 return SDValue();
11571 EVT VT = N->getValueType(0);
11572 SDLoc DL(N);
11573 SDValue N00 = N0->getOperand(0);
11574 SDValue N01 = N0->getOperand(1);
11575 return DAG.getNode(Opcode, DL, VT,
11576 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
11577 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
11580 static SDValue PerformMULCombine(SDNode *N,
11581 TargetLowering::DAGCombinerInfo &DCI,
11582 const ARMSubtarget *Subtarget) {
11583 SelectionDAG &DAG = DCI.DAG;
11585 if (Subtarget->isThumb1Only())
11586 return SDValue();
11588 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11589 return SDValue();
11591 EVT VT = N->getValueType(0);
11592 if (VT.is64BitVector() || VT.is128BitVector())
11593 return PerformVMULCombine(N, DCI, Subtarget);
11594 if (VT != MVT::i32)
11595 return SDValue();
11597 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11598 if (!C)
11599 return SDValue();
11601 int64_t MulAmt = C->getSExtValue();
11602 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
11604 ShiftAmt = ShiftAmt & (32 - 1);
11605 SDValue V = N->getOperand(0);
11606 SDLoc DL(N);
11608 SDValue Res;
11609 MulAmt >>= ShiftAmt;
11611 if (MulAmt >= 0) {
11612 if (isPowerOf2_32(MulAmt - 1)) {
11613 // (mul x, 2^N + 1) => (add (shl x, N), x)
11614 Res = DAG.getNode(ISD::ADD, DL, VT,
11616 DAG.getNode(ISD::SHL, DL, VT,
11618 DAG.getConstant(Log2_32(MulAmt - 1), DL,
11619 MVT::i32)));
11620 } else if (isPowerOf2_32(MulAmt + 1)) {
11621 // (mul x, 2^N - 1) => (sub (shl x, N), x)
11622 Res = DAG.getNode(ISD::SUB, DL, VT,
11623 DAG.getNode(ISD::SHL, DL, VT,
11625 DAG.getConstant(Log2_32(MulAmt + 1), DL,
11626 MVT::i32)),
11628 } else
11629 return SDValue();
11630 } else {
11631 uint64_t MulAmtAbs = -MulAmt;
11632 if (isPowerOf2_32(MulAmtAbs + 1)) {
11633 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
11634 Res = DAG.getNode(ISD::SUB, DL, VT,
11636 DAG.getNode(ISD::SHL, DL, VT,
11638 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
11639 MVT::i32)));
11640 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
11641 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
11642 Res = DAG.getNode(ISD::ADD, DL, VT,
11644 DAG.getNode(ISD::SHL, DL, VT,
11646 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
11647 MVT::i32)));
11648 Res = DAG.getNode(ISD::SUB, DL, VT,
11649 DAG.getConstant(0, DL, MVT::i32), Res);
11650 } else
11651 return SDValue();
11654 if (ShiftAmt != 0)
11655 Res = DAG.getNode(ISD::SHL, DL, VT,
11656 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
11658 // Do not add new nodes to DAG combiner worklist.
11659 DCI.CombineTo(N, Res, false);
11660 return SDValue();
11663 static SDValue CombineANDShift(SDNode *N,
11664 TargetLowering::DAGCombinerInfo &DCI,
11665 const ARMSubtarget *Subtarget) {
11666 // Allow DAGCombine to pattern-match before we touch the canonical form.
11667 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11668 return SDValue();
11670 if (N->getValueType(0) != MVT::i32)
11671 return SDValue();
11673 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11674 if (!N1C)
11675 return SDValue();
11677 uint32_t C1 = (uint32_t)N1C->getZExtValue();
11678 // Don't transform uxtb/uxth.
11679 if (C1 == 255 || C1 == 65535)
11680 return SDValue();
11682 SDNode *N0 = N->getOperand(0).getNode();
11683 if (!N0->hasOneUse())
11684 return SDValue();
11686 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
11687 return SDValue();
11689 bool LeftShift = N0->getOpcode() == ISD::SHL;
11691 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11692 if (!N01C)
11693 return SDValue();
11695 uint32_t C2 = (uint32_t)N01C->getZExtValue();
11696 if (!C2 || C2 >= 32)
11697 return SDValue();
11699 // Clear irrelevant bits in the mask.
11700 if (LeftShift)
11701 C1 &= (-1U << C2);
11702 else
11703 C1 &= (-1U >> C2);
11705 SelectionDAG &DAG = DCI.DAG;
11706 SDLoc DL(N);
11708 // We have a pattern of the form "(and (shl x, c2) c1)" or
11709 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
11710 // transform to a pair of shifts, to save materializing c1.
11712 // First pattern: right shift, then mask off leading bits.
11713 // FIXME: Use demanded bits?
11714 if (!LeftShift && isMask_32(C1)) {
11715 uint32_t C3 = countLeadingZeros(C1);
11716 if (C2 < C3) {
11717 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11718 DAG.getConstant(C3 - C2, DL, MVT::i32));
11719 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11720 DAG.getConstant(C3, DL, MVT::i32));
11724 // First pattern, reversed: left shift, then mask off trailing bits.
11725 if (LeftShift && isMask_32(~C1)) {
11726 uint32_t C3 = countTrailingZeros(C1);
11727 if (C2 < C3) {
11728 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11729 DAG.getConstant(C3 - C2, DL, MVT::i32));
11730 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11731 DAG.getConstant(C3, DL, MVT::i32));
11735 // Second pattern: left shift, then mask off leading bits.
11736 // FIXME: Use demanded bits?
11737 if (LeftShift && isShiftedMask_32(C1)) {
11738 uint32_t Trailing = countTrailingZeros(C1);
11739 uint32_t C3 = countLeadingZeros(C1);
11740 if (Trailing == C2 && C2 + C3 < 32) {
11741 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11742 DAG.getConstant(C2 + C3, DL, MVT::i32));
11743 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11744 DAG.getConstant(C3, DL, MVT::i32));
11748 // Second pattern, reversed: right shift, then mask off trailing bits.
11749 // FIXME: Handle other patterns of known/demanded bits.
11750 if (!LeftShift && isShiftedMask_32(C1)) {
11751 uint32_t Leading = countLeadingZeros(C1);
11752 uint32_t C3 = countTrailingZeros(C1);
11753 if (Leading == C2 && C2 + C3 < 32) {
11754 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11755 DAG.getConstant(C2 + C3, DL, MVT::i32));
11756 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11757 DAG.getConstant(C3, DL, MVT::i32));
11761 // FIXME: Transform "(and (shl x, c2) c1)" ->
11762 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
11763 // c1.
11764 return SDValue();
11767 static SDValue PerformANDCombine(SDNode *N,
11768 TargetLowering::DAGCombinerInfo &DCI,
11769 const ARMSubtarget *Subtarget) {
11770 // Attempt to use immediate-form VBIC
11771 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11772 SDLoc dl(N);
11773 EVT VT = N->getValueType(0);
11774 SelectionDAG &DAG = DCI.DAG;
11776 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11777 return SDValue();
11779 APInt SplatBits, SplatUndef;
11780 unsigned SplatBitSize;
11781 bool HasAnyUndefs;
11782 if (BVN && Subtarget->hasNEON() &&
11783 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11784 if (SplatBitSize <= 64) {
11785 EVT VbicVT;
11786 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
11787 SplatUndef.getZExtValue(), SplatBitSize,
11788 DAG, dl, VbicVT, VT.is128BitVector(),
11789 OtherModImm);
11790 if (Val.getNode()) {
11791 SDValue Input =
11792 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
11793 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
11794 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
11799 if (!Subtarget->isThumb1Only()) {
11800 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
11801 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
11802 return Result;
11804 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11805 return Result;
11808 if (Subtarget->isThumb1Only())
11809 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
11810 return Result;
11812 return SDValue();
11815 // Try combining OR nodes to SMULWB, SMULWT.
11816 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
11817 TargetLowering::DAGCombinerInfo &DCI,
11818 const ARMSubtarget *Subtarget) {
11819 if (!Subtarget->hasV6Ops() ||
11820 (Subtarget->isThumb() &&
11821 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
11822 return SDValue();
11824 SDValue SRL = OR->getOperand(0);
11825 SDValue SHL = OR->getOperand(1);
11827 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
11828 SRL = OR->getOperand(1);
11829 SHL = OR->getOperand(0);
11831 if (!isSRL16(SRL) || !isSHL16(SHL))
11832 return SDValue();
11834 // The first operands to the shifts need to be the two results from the
11835 // same smul_lohi node.
11836 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
11837 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
11838 return SDValue();
11840 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
11841 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
11842 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
11843 return SDValue();
11845 // Now we have:
11846 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
11847 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
11848 // For SMUWB the 16-bit value will signed extended somehow.
11849 // For SMULWT only the SRA is required.
11850 // Check both sides of SMUL_LOHI
11851 SDValue OpS16 = SMULLOHI->getOperand(0);
11852 SDValue OpS32 = SMULLOHI->getOperand(1);
11854 SelectionDAG &DAG = DCI.DAG;
11855 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
11856 OpS16 = OpS32;
11857 OpS32 = SMULLOHI->getOperand(0);
11860 SDLoc dl(OR);
11861 unsigned Opcode = 0;
11862 if (isS16(OpS16, DAG))
11863 Opcode = ARMISD::SMULWB;
11864 else if (isSRA16(OpS16)) {
11865 Opcode = ARMISD::SMULWT;
11866 OpS16 = OpS16->getOperand(0);
11868 else
11869 return SDValue();
11871 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
11872 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
11873 return SDValue(OR, 0);
11876 static SDValue PerformORCombineToBFI(SDNode *N,
11877 TargetLowering::DAGCombinerInfo &DCI,
11878 const ARMSubtarget *Subtarget) {
11879 // BFI is only available on V6T2+
11880 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
11881 return SDValue();
11883 EVT VT = N->getValueType(0);
11884 SDValue N0 = N->getOperand(0);
11885 SDValue N1 = N->getOperand(1);
11886 SelectionDAG &DAG = DCI.DAG;
11887 SDLoc DL(N);
11888 // 1) or (and A, mask), val => ARMbfi A, val, mask
11889 // iff (val & mask) == val
11891 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11892 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
11893 // && mask == ~mask2
11894 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
11895 // && ~mask == mask2
11896 // (i.e., copy a bitfield value into another bitfield of the same width)
11898 if (VT != MVT::i32)
11899 return SDValue();
11901 SDValue N00 = N0.getOperand(0);
11903 // The value and the mask need to be constants so we can verify this is
11904 // actually a bitfield set. If the mask is 0xffff, we can do better
11905 // via a movt instruction, so don't use BFI in that case.
11906 SDValue MaskOp = N0.getOperand(1);
11907 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
11908 if (!MaskC)
11909 return SDValue();
11910 unsigned Mask = MaskC->getZExtValue();
11911 if (Mask == 0xffff)
11912 return SDValue();
11913 SDValue Res;
11914 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
11915 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11916 if (N1C) {
11917 unsigned Val = N1C->getZExtValue();
11918 if ((Val & ~Mask) != Val)
11919 return SDValue();
11921 if (ARM::isBitFieldInvertedMask(Mask)) {
11922 Val >>= countTrailingZeros(~Mask);
11924 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
11925 DAG.getConstant(Val, DL, MVT::i32),
11926 DAG.getConstant(Mask, DL, MVT::i32));
11928 DCI.CombineTo(N, Res, false);
11929 // Return value from the original node to inform the combiner than N is
11930 // now dead.
11931 return SDValue(N, 0);
11933 } else if (N1.getOpcode() == ISD::AND) {
11934 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
11935 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
11936 if (!N11C)
11937 return SDValue();
11938 unsigned Mask2 = N11C->getZExtValue();
11940 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
11941 // as is to match.
11942 if (ARM::isBitFieldInvertedMask(Mask) &&
11943 (Mask == ~Mask2)) {
11944 // The pack halfword instruction works better for masks that fit it,
11945 // so use that when it's available.
11946 if (Subtarget->hasDSP() &&
11947 (Mask == 0xffff || Mask == 0xffff0000))
11948 return SDValue();
11949 // 2a
11950 unsigned amt = countTrailingZeros(Mask2);
11951 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
11952 DAG.getConstant(amt, DL, MVT::i32));
11953 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
11954 DAG.getConstant(Mask, DL, MVT::i32));
11955 DCI.CombineTo(N, Res, false);
11956 // Return value from the original node to inform the combiner than N is
11957 // now dead.
11958 return SDValue(N, 0);
11959 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
11960 (~Mask == Mask2)) {
11961 // The pack halfword instruction works better for masks that fit it,
11962 // so use that when it's available.
11963 if (Subtarget->hasDSP() &&
11964 (Mask2 == 0xffff || Mask2 == 0xffff0000))
11965 return SDValue();
11966 // 2b
11967 unsigned lsb = countTrailingZeros(Mask);
11968 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
11969 DAG.getConstant(lsb, DL, MVT::i32));
11970 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
11971 DAG.getConstant(Mask2, DL, MVT::i32));
11972 DCI.CombineTo(N, Res, false);
11973 // Return value from the original node to inform the combiner than N is
11974 // now dead.
11975 return SDValue(N, 0);
11979 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
11980 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
11981 ARM::isBitFieldInvertedMask(~Mask)) {
11982 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
11983 // where lsb(mask) == #shamt and masked bits of B are known zero.
11984 SDValue ShAmt = N00.getOperand(1);
11985 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
11986 unsigned LSB = countTrailingZeros(Mask);
11987 if (ShAmtC != LSB)
11988 return SDValue();
11990 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
11991 DAG.getConstant(~Mask, DL, MVT::i32));
11993 DCI.CombineTo(N, Res, false);
11994 // Return value from the original node to inform the combiner than N is
11995 // now dead.
11996 return SDValue(N, 0);
11999 return SDValue();
12002 static bool isValidMVECond(unsigned CC, bool IsFloat) {
12003 switch (CC) {
12004 case ARMCC::EQ:
12005 case ARMCC::NE:
12006 case ARMCC::LE:
12007 case ARMCC::GT:
12008 case ARMCC::GE:
12009 case ARMCC::LT:
12010 return true;
12011 case ARMCC::HS:
12012 case ARMCC::HI:
12013 return !IsFloat;
12014 default:
12015 return false;
12019 static SDValue PerformORCombine_i1(SDNode *N,
12020 TargetLowering::DAGCombinerInfo &DCI,
12021 const ARMSubtarget *Subtarget) {
12022 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
12023 // together with predicates
12024 EVT VT = N->getValueType(0);
12025 SDValue N0 = N->getOperand(0);
12026 SDValue N1 = N->getOperand(1);
12028 ARMCC::CondCodes CondCode0 = ARMCC::AL;
12029 ARMCC::CondCodes CondCode1 = ARMCC::AL;
12030 if (N0->getOpcode() == ARMISD::VCMP)
12031 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(2))
12032 ->getZExtValue();
12033 else if (N0->getOpcode() == ARMISD::VCMPZ)
12034 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(1))
12035 ->getZExtValue();
12036 if (N1->getOpcode() == ARMISD::VCMP)
12037 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(2))
12038 ->getZExtValue();
12039 else if (N1->getOpcode() == ARMISD::VCMPZ)
12040 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(1))
12041 ->getZExtValue();
12043 if (CondCode0 == ARMCC::AL || CondCode1 == ARMCC::AL)
12044 return SDValue();
12046 unsigned Opposite0 = ARMCC::getOppositeCondition(CondCode0);
12047 unsigned Opposite1 = ARMCC::getOppositeCondition(CondCode1);
12049 if (!isValidMVECond(Opposite0,
12050 N0->getOperand(0)->getValueType(0).isFloatingPoint()) ||
12051 !isValidMVECond(Opposite1,
12052 N1->getOperand(0)->getValueType(0).isFloatingPoint()))
12053 return SDValue();
12055 SmallVector<SDValue, 4> Ops0;
12056 Ops0.push_back(N0->getOperand(0));
12057 if (N0->getOpcode() == ARMISD::VCMP)
12058 Ops0.push_back(N0->getOperand(1));
12059 Ops0.push_back(DCI.DAG.getConstant(Opposite0, SDLoc(N0), MVT::i32));
12060 SmallVector<SDValue, 4> Ops1;
12061 Ops1.push_back(N1->getOperand(0));
12062 if (N1->getOpcode() == ARMISD::VCMP)
12063 Ops1.push_back(N1->getOperand(1));
12064 Ops1.push_back(DCI.DAG.getConstant(Opposite1, SDLoc(N1), MVT::i32));
12066 SDValue NewN0 = DCI.DAG.getNode(N0->getOpcode(), SDLoc(N0), VT, Ops0);
12067 SDValue NewN1 = DCI.DAG.getNode(N1->getOpcode(), SDLoc(N1), VT, Ops1);
12068 SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1);
12069 return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And,
12070 DCI.DAG.getAllOnesConstant(SDLoc(N), VT));
12073 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
12074 static SDValue PerformORCombine(SDNode *N,
12075 TargetLowering::DAGCombinerInfo &DCI,
12076 const ARMSubtarget *Subtarget) {
12077 // Attempt to use immediate-form VORR
12078 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12079 SDLoc dl(N);
12080 EVT VT = N->getValueType(0);
12081 SelectionDAG &DAG = DCI.DAG;
12083 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12084 return SDValue();
12086 APInt SplatBits, SplatUndef;
12087 unsigned SplatBitSize;
12088 bool HasAnyUndefs;
12089 if (BVN && Subtarget->hasNEON() &&
12090 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12091 if (SplatBitSize <= 64) {
12092 EVT VorrVT;
12093 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
12094 SplatUndef.getZExtValue(), SplatBitSize,
12095 DAG, dl, VorrVT, VT.is128BitVector(),
12096 OtherModImm);
12097 if (Val.getNode()) {
12098 SDValue Input =
12099 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
12100 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
12101 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
12106 if (!Subtarget->isThumb1Only()) {
12107 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12108 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12109 return Result;
12110 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
12111 return Result;
12114 SDValue N0 = N->getOperand(0);
12115 SDValue N1 = N->getOperand(1);
12117 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
12118 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
12119 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12121 // The code below optimizes (or (and X, Y), Z).
12122 // The AND operand needs to have a single user to make these optimizations
12123 // profitable.
12124 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
12125 return SDValue();
12127 APInt SplatUndef;
12128 unsigned SplatBitSize;
12129 bool HasAnyUndefs;
12131 APInt SplatBits0, SplatBits1;
12132 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
12133 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
12134 // Ensure that the second operand of both ands are constants
12135 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
12136 HasAnyUndefs) && !HasAnyUndefs) {
12137 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
12138 HasAnyUndefs) && !HasAnyUndefs) {
12139 // Ensure that the bit width of the constants are the same and that
12140 // the splat arguments are logical inverses as per the pattern we
12141 // are trying to simplify.
12142 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
12143 SplatBits0 == ~SplatBits1) {
12144 // Canonicalize the vector type to make instruction selection
12145 // simpler.
12146 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
12147 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
12148 N0->getOperand(1),
12149 N0->getOperand(0),
12150 N1->getOperand(0));
12151 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12157 if (Subtarget->hasMVEIntegerOps() &&
12158 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
12159 return PerformORCombine_i1(N, DCI, Subtarget);
12161 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
12162 // reasonable.
12163 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
12164 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
12165 return Res;
12168 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12169 return Result;
12171 return SDValue();
12174 static SDValue PerformXORCombine(SDNode *N,
12175 TargetLowering::DAGCombinerInfo &DCI,
12176 const ARMSubtarget *Subtarget) {
12177 EVT VT = N->getValueType(0);
12178 SelectionDAG &DAG = DCI.DAG;
12180 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12181 return SDValue();
12183 if (!Subtarget->isThumb1Only()) {
12184 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12185 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12186 return Result;
12188 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12189 return Result;
12192 return SDValue();
12195 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
12196 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
12197 // their position in "to" (Rd).
12198 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
12199 assert(N->getOpcode() == ARMISD::BFI);
12201 SDValue From = N->getOperand(1);
12202 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
12203 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
12205 // If the Base came from a SHR #C, we can deduce that it is really testing bit
12206 // #C in the base of the SHR.
12207 if (From->getOpcode() == ISD::SRL &&
12208 isa<ConstantSDNode>(From->getOperand(1))) {
12209 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
12210 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
12211 FromMask <<= Shift.getLimitedValue(31);
12212 From = From->getOperand(0);
12215 return From;
12218 // If A and B contain one contiguous set of bits, does A | B == A . B?
12220 // Neither A nor B must be zero.
12221 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
12222 unsigned LastActiveBitInA = A.countTrailingZeros();
12223 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
12224 return LastActiveBitInA - 1 == FirstActiveBitInB;
12227 static SDValue FindBFIToCombineWith(SDNode *N) {
12228 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
12229 // if one exists.
12230 APInt ToMask, FromMask;
12231 SDValue From = ParseBFI(N, ToMask, FromMask);
12232 SDValue To = N->getOperand(0);
12234 // Now check for a compatible BFI to merge with. We can pass through BFIs that
12235 // aren't compatible, but not if they set the same bit in their destination as
12236 // we do (or that of any BFI we're going to combine with).
12237 SDValue V = To;
12238 APInt CombinedToMask = ToMask;
12239 while (V.getOpcode() == ARMISD::BFI) {
12240 APInt NewToMask, NewFromMask;
12241 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
12242 if (NewFrom != From) {
12243 // This BFI has a different base. Keep going.
12244 CombinedToMask |= NewToMask;
12245 V = V.getOperand(0);
12246 continue;
12249 // Do the written bits conflict with any we've seen so far?
12250 if ((NewToMask & CombinedToMask).getBoolValue())
12251 // Conflicting bits - bail out because going further is unsafe.
12252 return SDValue();
12254 // Are the new bits contiguous when combined with the old bits?
12255 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
12256 BitsProperlyConcatenate(FromMask, NewFromMask))
12257 return V;
12258 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
12259 BitsProperlyConcatenate(NewFromMask, FromMask))
12260 return V;
12262 // We've seen a write to some bits, so track it.
12263 CombinedToMask |= NewToMask;
12264 // Keep going...
12265 V = V.getOperand(0);
12268 return SDValue();
12271 static SDValue PerformBFICombine(SDNode *N,
12272 TargetLowering::DAGCombinerInfo &DCI) {
12273 SDValue N1 = N->getOperand(1);
12274 if (N1.getOpcode() == ISD::AND) {
12275 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
12276 // the bits being cleared by the AND are not demanded by the BFI.
12277 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12278 if (!N11C)
12279 return SDValue();
12280 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12281 unsigned LSB = countTrailingZeros(~InvMask);
12282 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
12283 assert(Width <
12284 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
12285 "undefined behavior");
12286 unsigned Mask = (1u << Width) - 1;
12287 unsigned Mask2 = N11C->getZExtValue();
12288 if ((Mask & (~Mask2)) == 0)
12289 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
12290 N->getOperand(0), N1.getOperand(0),
12291 N->getOperand(2));
12292 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
12293 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
12294 // Keep track of any consecutive bits set that all come from the same base
12295 // value. We can combine these together into a single BFI.
12296 SDValue CombineBFI = FindBFIToCombineWith(N);
12297 if (CombineBFI == SDValue())
12298 return SDValue();
12300 // We've found a BFI.
12301 APInt ToMask1, FromMask1;
12302 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
12304 APInt ToMask2, FromMask2;
12305 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
12306 assert(From1 == From2);
12307 (void)From2;
12309 // First, unlink CombineBFI.
12310 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
12311 // Then create a new BFI, combining the two together.
12312 APInt NewFromMask = FromMask1 | FromMask2;
12313 APInt NewToMask = ToMask1 | ToMask2;
12315 EVT VT = N->getValueType(0);
12316 SDLoc dl(N);
12318 if (NewFromMask[0] == 0)
12319 From1 = DCI.DAG.getNode(
12320 ISD::SRL, dl, VT, From1,
12321 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
12322 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
12323 DCI.DAG.getConstant(~NewToMask, dl, VT));
12325 return SDValue();
12328 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
12329 /// ARMISD::VMOVRRD.
12330 static SDValue PerformVMOVRRDCombine(SDNode *N,
12331 TargetLowering::DAGCombinerInfo &DCI,
12332 const ARMSubtarget *Subtarget) {
12333 // vmovrrd(vmovdrr x, y) -> x,y
12334 SDValue InDouble = N->getOperand(0);
12335 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
12336 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
12338 // vmovrrd(load f64) -> (load i32), (load i32)
12339 SDNode *InNode = InDouble.getNode();
12340 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
12341 InNode->getValueType(0) == MVT::f64 &&
12342 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
12343 !cast<LoadSDNode>(InNode)->isVolatile()) {
12344 // TODO: Should this be done for non-FrameIndex operands?
12345 LoadSDNode *LD = cast<LoadSDNode>(InNode);
12347 SelectionDAG &DAG = DCI.DAG;
12348 SDLoc DL(LD);
12349 SDValue BasePtr = LD->getBasePtr();
12350 SDValue NewLD1 =
12351 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
12352 LD->getAlignment(), LD->getMemOperand()->getFlags());
12354 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12355 DAG.getConstant(4, DL, MVT::i32));
12357 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
12358 LD->getPointerInfo().getWithOffset(4),
12359 std::min(4U, LD->getAlignment()),
12360 LD->getMemOperand()->getFlags());
12362 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
12363 if (DCI.DAG.getDataLayout().isBigEndian())
12364 std::swap (NewLD1, NewLD2);
12365 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
12366 return Result;
12369 return SDValue();
12372 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
12373 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
12374 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
12375 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
12376 SDValue Op0 = N->getOperand(0);
12377 SDValue Op1 = N->getOperand(1);
12378 if (Op0.getOpcode() == ISD::BITCAST)
12379 Op0 = Op0.getOperand(0);
12380 if (Op1.getOpcode() == ISD::BITCAST)
12381 Op1 = Op1.getOperand(0);
12382 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
12383 Op0.getNode() == Op1.getNode() &&
12384 Op0.getResNo() == 0 && Op1.getResNo() == 1)
12385 return DAG.getNode(ISD::BITCAST, SDLoc(N),
12386 N->getValueType(0), Op0.getOperand(0));
12387 return SDValue();
12390 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
12391 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
12392 /// i64 vector to have f64 elements, since the value can then be loaded
12393 /// directly into a VFP register.
12394 static bool hasNormalLoadOperand(SDNode *N) {
12395 unsigned NumElts = N->getValueType(0).getVectorNumElements();
12396 for (unsigned i = 0; i < NumElts; ++i) {
12397 SDNode *Elt = N->getOperand(i).getNode();
12398 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
12399 return true;
12401 return false;
12404 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
12405 /// ISD::BUILD_VECTOR.
12406 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
12407 TargetLowering::DAGCombinerInfo &DCI,
12408 const ARMSubtarget *Subtarget) {
12409 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
12410 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
12411 // into a pair of GPRs, which is fine when the value is used as a scalar,
12412 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
12413 SelectionDAG &DAG = DCI.DAG;
12414 if (N->getNumOperands() == 2)
12415 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
12416 return RV;
12418 // Load i64 elements as f64 values so that type legalization does not split
12419 // them up into i32 values.
12420 EVT VT = N->getValueType(0);
12421 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
12422 return SDValue();
12423 SDLoc dl(N);
12424 SmallVector<SDValue, 8> Ops;
12425 unsigned NumElts = VT.getVectorNumElements();
12426 for (unsigned i = 0; i < NumElts; ++i) {
12427 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
12428 Ops.push_back(V);
12429 // Make the DAGCombiner fold the bitcast.
12430 DCI.AddToWorklist(V.getNode());
12432 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
12433 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
12434 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12437 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
12438 static SDValue
12439 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12440 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
12441 // At that time, we may have inserted bitcasts from integer to float.
12442 // If these bitcasts have survived DAGCombine, change the lowering of this
12443 // BUILD_VECTOR in something more vector friendly, i.e., that does not
12444 // force to use floating point types.
12446 // Make sure we can change the type of the vector.
12447 // This is possible iff:
12448 // 1. The vector is only used in a bitcast to a integer type. I.e.,
12449 // 1.1. Vector is used only once.
12450 // 1.2. Use is a bit convert to an integer type.
12451 // 2. The size of its operands are 32-bits (64-bits are not legal).
12452 EVT VT = N->getValueType(0);
12453 EVT EltVT = VT.getVectorElementType();
12455 // Check 1.1. and 2.
12456 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
12457 return SDValue();
12459 // By construction, the input type must be float.
12460 assert(EltVT == MVT::f32 && "Unexpected type!");
12462 // Check 1.2.
12463 SDNode *Use = *N->use_begin();
12464 if (Use->getOpcode() != ISD::BITCAST ||
12465 Use->getValueType(0).isFloatingPoint())
12466 return SDValue();
12468 // Check profitability.
12469 // Model is, if more than half of the relevant operands are bitcast from
12470 // i32, turn the build_vector into a sequence of insert_vector_elt.
12471 // Relevant operands are everything that is not statically
12472 // (i.e., at compile time) bitcasted.
12473 unsigned NumOfBitCastedElts = 0;
12474 unsigned NumElts = VT.getVectorNumElements();
12475 unsigned NumOfRelevantElts = NumElts;
12476 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
12477 SDValue Elt = N->getOperand(Idx);
12478 if (Elt->getOpcode() == ISD::BITCAST) {
12479 // Assume only bit cast to i32 will go away.
12480 if (Elt->getOperand(0).getValueType() == MVT::i32)
12481 ++NumOfBitCastedElts;
12482 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
12483 // Constants are statically casted, thus do not count them as
12484 // relevant operands.
12485 --NumOfRelevantElts;
12488 // Check if more than half of the elements require a non-free bitcast.
12489 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
12490 return SDValue();
12492 SelectionDAG &DAG = DCI.DAG;
12493 // Create the new vector type.
12494 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
12495 // Check if the type is legal.
12496 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12497 if (!TLI.isTypeLegal(VecVT))
12498 return SDValue();
12500 // Combine:
12501 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
12502 // => BITCAST INSERT_VECTOR_ELT
12503 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
12504 // (BITCAST EN), N.
12505 SDValue Vec = DAG.getUNDEF(VecVT);
12506 SDLoc dl(N);
12507 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
12508 SDValue V = N->getOperand(Idx);
12509 if (V.isUndef())
12510 continue;
12511 if (V.getOpcode() == ISD::BITCAST &&
12512 V->getOperand(0).getValueType() == MVT::i32)
12513 // Fold obvious case.
12514 V = V.getOperand(0);
12515 else {
12516 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
12517 // Make the DAGCombiner fold the bitcasts.
12518 DCI.AddToWorklist(V.getNode());
12520 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
12521 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
12523 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
12524 // Make the DAGCombiner fold the bitcasts.
12525 DCI.AddToWorklist(Vec.getNode());
12526 return Vec;
12529 /// PerformInsertEltCombine - Target-specific dag combine xforms for
12530 /// ISD::INSERT_VECTOR_ELT.
12531 static SDValue PerformInsertEltCombine(SDNode *N,
12532 TargetLowering::DAGCombinerInfo &DCI) {
12533 // Bitcast an i64 load inserted into a vector to f64.
12534 // Otherwise, the i64 value will be legalized to a pair of i32 values.
12535 EVT VT = N->getValueType(0);
12536 SDNode *Elt = N->getOperand(1).getNode();
12537 if (VT.getVectorElementType() != MVT::i64 ||
12538 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
12539 return SDValue();
12541 SelectionDAG &DAG = DCI.DAG;
12542 SDLoc dl(N);
12543 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12544 VT.getVectorNumElements());
12545 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
12546 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
12547 // Make the DAGCombiner fold the bitcasts.
12548 DCI.AddToWorklist(Vec.getNode());
12549 DCI.AddToWorklist(V.getNode());
12550 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
12551 Vec, V, N->getOperand(2));
12552 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
12555 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
12556 /// ISD::VECTOR_SHUFFLE.
12557 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
12558 // The LLVM shufflevector instruction does not require the shuffle mask
12559 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
12560 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
12561 // operands do not match the mask length, they are extended by concatenating
12562 // them with undef vectors. That is probably the right thing for other
12563 // targets, but for NEON it is better to concatenate two double-register
12564 // size vector operands into a single quad-register size vector. Do that
12565 // transformation here:
12566 // shuffle(concat(v1, undef), concat(v2, undef)) ->
12567 // shuffle(concat(v1, v2), undef)
12568 SDValue Op0 = N->getOperand(0);
12569 SDValue Op1 = N->getOperand(1);
12570 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
12571 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
12572 Op0.getNumOperands() != 2 ||
12573 Op1.getNumOperands() != 2)
12574 return SDValue();
12575 SDValue Concat0Op1 = Op0.getOperand(1);
12576 SDValue Concat1Op1 = Op1.getOperand(1);
12577 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
12578 return SDValue();
12579 // Skip the transformation if any of the types are illegal.
12580 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12581 EVT VT = N->getValueType(0);
12582 if (!TLI.isTypeLegal(VT) ||
12583 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
12584 !TLI.isTypeLegal(Concat1Op1.getValueType()))
12585 return SDValue();
12587 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12588 Op0.getOperand(0), Op1.getOperand(0));
12589 // Translate the shuffle mask.
12590 SmallVector<int, 16> NewMask;
12591 unsigned NumElts = VT.getVectorNumElements();
12592 unsigned HalfElts = NumElts/2;
12593 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12594 for (unsigned n = 0; n < NumElts; ++n) {
12595 int MaskElt = SVN->getMaskElt(n);
12596 int NewElt = -1;
12597 if (MaskElt < (int)HalfElts)
12598 NewElt = MaskElt;
12599 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
12600 NewElt = HalfElts + MaskElt - NumElts;
12601 NewMask.push_back(NewElt);
12603 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
12604 DAG.getUNDEF(VT), NewMask);
12607 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
12608 /// NEON load/store intrinsics, and generic vector load/stores, to merge
12609 /// base address updates.
12610 /// For generic load/stores, the memory type is assumed to be a vector.
12611 /// The caller is assumed to have checked legality.
12612 static SDValue CombineBaseUpdate(SDNode *N,
12613 TargetLowering::DAGCombinerInfo &DCI) {
12614 SelectionDAG &DAG = DCI.DAG;
12615 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
12616 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
12617 const bool isStore = N->getOpcode() == ISD::STORE;
12618 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
12619 SDValue Addr = N->getOperand(AddrOpIdx);
12620 MemSDNode *MemN = cast<MemSDNode>(N);
12621 SDLoc dl(N);
12623 // Search for a use of the address operand that is an increment.
12624 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
12625 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
12626 SDNode *User = *UI;
12627 if (User->getOpcode() != ISD::ADD ||
12628 UI.getUse().getResNo() != Addr.getResNo())
12629 continue;
12631 // Check that the add is independent of the load/store. Otherwise, folding
12632 // it would create a cycle. We can avoid searching through Addr as it's a
12633 // predecessor to both.
12634 SmallPtrSet<const SDNode *, 32> Visited;
12635 SmallVector<const SDNode *, 16> Worklist;
12636 Visited.insert(Addr.getNode());
12637 Worklist.push_back(N);
12638 Worklist.push_back(User);
12639 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
12640 SDNode::hasPredecessorHelper(User, Visited, Worklist))
12641 continue;
12643 // Find the new opcode for the updating load/store.
12644 bool isLoadOp = true;
12645 bool isLaneOp = false;
12646 unsigned NewOpc = 0;
12647 unsigned NumVecs = 0;
12648 if (isIntrinsic) {
12649 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
12650 switch (IntNo) {
12651 default: llvm_unreachable("unexpected intrinsic for Neon base update");
12652 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
12653 NumVecs = 1; break;
12654 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
12655 NumVecs = 2; break;
12656 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
12657 NumVecs = 3; break;
12658 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
12659 NumVecs = 4; break;
12660 case Intrinsic::arm_neon_vld2dup:
12661 case Intrinsic::arm_neon_vld3dup:
12662 case Intrinsic::arm_neon_vld4dup:
12663 // TODO: Support updating VLDxDUP nodes. For now, we just skip
12664 // combining base updates for such intrinsics.
12665 continue;
12666 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
12667 NumVecs = 2; isLaneOp = true; break;
12668 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
12669 NumVecs = 3; isLaneOp = true; break;
12670 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
12671 NumVecs = 4; isLaneOp = true; break;
12672 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
12673 NumVecs = 1; isLoadOp = false; break;
12674 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
12675 NumVecs = 2; isLoadOp = false; break;
12676 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
12677 NumVecs = 3; isLoadOp = false; break;
12678 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
12679 NumVecs = 4; isLoadOp = false; break;
12680 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
12681 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
12682 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
12683 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
12684 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
12685 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
12687 } else {
12688 isLaneOp = true;
12689 switch (N->getOpcode()) {
12690 default: llvm_unreachable("unexpected opcode for Neon base update");
12691 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
12692 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
12693 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
12694 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
12695 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
12696 NumVecs = 1; isLaneOp = false; break;
12697 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
12698 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
12702 // Find the size of memory referenced by the load/store.
12703 EVT VecTy;
12704 if (isLoadOp) {
12705 VecTy = N->getValueType(0);
12706 } else if (isIntrinsic) {
12707 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
12708 } else {
12709 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
12710 VecTy = N->getOperand(1).getValueType();
12713 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
12714 if (isLaneOp)
12715 NumBytes /= VecTy.getVectorNumElements();
12717 // If the increment is a constant, it must match the memory ref size.
12718 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12719 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
12720 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
12721 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
12722 // separate instructions that make it harder to use a non-constant update.
12723 continue;
12726 // OK, we found an ADD we can fold into the base update.
12727 // Now, create a _UPD node, taking care of not breaking alignment.
12729 EVT AlignedVecTy = VecTy;
12730 unsigned Alignment = MemN->getAlignment();
12732 // If this is a less-than-standard-aligned load/store, change the type to
12733 // match the standard alignment.
12734 // The alignment is overlooked when selecting _UPD variants; and it's
12735 // easier to introduce bitcasts here than fix that.
12736 // There are 3 ways to get to this base-update combine:
12737 // - intrinsics: they are assumed to be properly aligned (to the standard
12738 // alignment of the memory type), so we don't need to do anything.
12739 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
12740 // intrinsics, so, likewise, there's nothing to do.
12741 // - generic load/store instructions: the alignment is specified as an
12742 // explicit operand, rather than implicitly as the standard alignment
12743 // of the memory type (like the intrisics). We need to change the
12744 // memory type to match the explicit alignment. That way, we don't
12745 // generate non-standard-aligned ARMISD::VLDx nodes.
12746 if (isa<LSBaseSDNode>(N)) {
12747 if (Alignment == 0)
12748 Alignment = 1;
12749 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
12750 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
12751 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
12752 assert(!isLaneOp && "Unexpected generic load/store lane.");
12753 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
12754 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
12756 // Don't set an explicit alignment on regular load/stores that we want
12757 // to transform to VLD/VST 1_UPD nodes.
12758 // This matches the behavior of regular load/stores, which only get an
12759 // explicit alignment if the MMO alignment is larger than the standard
12760 // alignment of the memory type.
12761 // Intrinsics, however, always get an explicit alignment, set to the
12762 // alignment of the MMO.
12763 Alignment = 1;
12766 // Create the new updating load/store node.
12767 // First, create an SDVTList for the new updating node's results.
12768 EVT Tys[6];
12769 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
12770 unsigned n;
12771 for (n = 0; n < NumResultVecs; ++n)
12772 Tys[n] = AlignedVecTy;
12773 Tys[n++] = MVT::i32;
12774 Tys[n] = MVT::Other;
12775 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
12777 // Then, gather the new node's operands.
12778 SmallVector<SDValue, 8> Ops;
12779 Ops.push_back(N->getOperand(0)); // incoming chain
12780 Ops.push_back(N->getOperand(AddrOpIdx));
12781 Ops.push_back(Inc);
12783 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
12784 // Try to match the intrinsic's signature
12785 Ops.push_back(StN->getValue());
12786 } else {
12787 // Loads (and of course intrinsics) match the intrinsics' signature,
12788 // so just add all but the alignment operand.
12789 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
12790 Ops.push_back(N->getOperand(i));
12793 // For all node types, the alignment operand is always the last one.
12794 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
12796 // If this is a non-standard-aligned STORE, the penultimate operand is the
12797 // stored value. Bitcast it to the aligned type.
12798 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
12799 SDValue &StVal = Ops[Ops.size()-2];
12800 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
12803 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
12804 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
12805 MemN->getMemOperand());
12807 // Update the uses.
12808 SmallVector<SDValue, 5> NewResults;
12809 for (unsigned i = 0; i < NumResultVecs; ++i)
12810 NewResults.push_back(SDValue(UpdN.getNode(), i));
12812 // If this is an non-standard-aligned LOAD, the first result is the loaded
12813 // value. Bitcast it to the expected result type.
12814 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
12815 SDValue &LdVal = NewResults[0];
12816 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
12819 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
12820 DCI.CombineTo(N, NewResults);
12821 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
12823 break;
12825 return SDValue();
12828 static SDValue PerformVLDCombine(SDNode *N,
12829 TargetLowering::DAGCombinerInfo &DCI) {
12830 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12831 return SDValue();
12833 return CombineBaseUpdate(N, DCI);
12836 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
12837 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
12838 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
12839 /// return true.
12840 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12841 SelectionDAG &DAG = DCI.DAG;
12842 EVT VT = N->getValueType(0);
12843 // vldN-dup instructions only support 64-bit vectors for N > 1.
12844 if (!VT.is64BitVector())
12845 return false;
12847 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
12848 SDNode *VLD = N->getOperand(0).getNode();
12849 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
12850 return false;
12851 unsigned NumVecs = 0;
12852 unsigned NewOpc = 0;
12853 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
12854 if (IntNo == Intrinsic::arm_neon_vld2lane) {
12855 NumVecs = 2;
12856 NewOpc = ARMISD::VLD2DUP;
12857 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
12858 NumVecs = 3;
12859 NewOpc = ARMISD::VLD3DUP;
12860 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
12861 NumVecs = 4;
12862 NewOpc = ARMISD::VLD4DUP;
12863 } else {
12864 return false;
12867 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
12868 // numbers match the load.
12869 unsigned VLDLaneNo =
12870 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
12871 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
12872 UI != UE; ++UI) {
12873 // Ignore uses of the chain result.
12874 if (UI.getUse().getResNo() == NumVecs)
12875 continue;
12876 SDNode *User = *UI;
12877 if (User->getOpcode() != ARMISD::VDUPLANE ||
12878 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
12879 return false;
12882 // Create the vldN-dup node.
12883 EVT Tys[5];
12884 unsigned n;
12885 for (n = 0; n < NumVecs; ++n)
12886 Tys[n] = VT;
12887 Tys[n] = MVT::Other;
12888 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
12889 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
12890 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
12891 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
12892 Ops, VLDMemInt->getMemoryVT(),
12893 VLDMemInt->getMemOperand());
12895 // Update the uses.
12896 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
12897 UI != UE; ++UI) {
12898 unsigned ResNo = UI.getUse().getResNo();
12899 // Ignore uses of the chain result.
12900 if (ResNo == NumVecs)
12901 continue;
12902 SDNode *User = *UI;
12903 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
12906 // Now the vldN-lane intrinsic is dead except for its chain result.
12907 // Update uses of the chain.
12908 std::vector<SDValue> VLDDupResults;
12909 for (unsigned n = 0; n < NumVecs; ++n)
12910 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
12911 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
12912 DCI.CombineTo(VLD, VLDDupResults);
12914 return true;
12917 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
12918 /// ARMISD::VDUPLANE.
12919 static SDValue PerformVDUPLANECombine(SDNode *N,
12920 TargetLowering::DAGCombinerInfo &DCI) {
12921 SDValue Op = N->getOperand(0);
12923 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
12924 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
12925 if (CombineVLDDUP(N, DCI))
12926 return SDValue(N, 0);
12928 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
12929 // redundant. Ignore bit_converts for now; element sizes are checked below.
12930 while (Op.getOpcode() == ISD::BITCAST)
12931 Op = Op.getOperand(0);
12932 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
12933 return SDValue();
12935 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
12936 unsigned EltSize = Op.getScalarValueSizeInBits();
12937 // The canonical VMOV for a zero vector uses a 32-bit element size.
12938 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12939 unsigned EltBits;
12940 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
12941 EltSize = 8;
12942 EVT VT = N->getValueType(0);
12943 if (EltSize > VT.getScalarSizeInBits())
12944 return SDValue();
12946 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
12949 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
12950 static SDValue PerformVDUPCombine(SDNode *N,
12951 TargetLowering::DAGCombinerInfo &DCI,
12952 const ARMSubtarget *Subtarget) {
12953 SelectionDAG &DAG = DCI.DAG;
12954 SDValue Op = N->getOperand(0);
12956 if (!Subtarget->hasNEON())
12957 return SDValue();
12959 // Match VDUP(LOAD) -> VLD1DUP.
12960 // We match this pattern here rather than waiting for isel because the
12961 // transform is only legal for unindexed loads.
12962 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
12963 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
12964 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
12965 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
12966 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
12967 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
12968 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
12969 Ops, LD->getMemoryVT(),
12970 LD->getMemOperand());
12971 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
12972 return VLDDup;
12975 return SDValue();
12978 static SDValue PerformLOADCombine(SDNode *N,
12979 TargetLowering::DAGCombinerInfo &DCI) {
12980 EVT VT = N->getValueType(0);
12982 // If this is a legal vector load, try to combine it into a VLD1_UPD.
12983 if (ISD::isNormalLoad(N) && VT.isVector() &&
12984 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
12985 return CombineBaseUpdate(N, DCI);
12987 return SDValue();
12990 /// PerformSTORECombine - Target-specific dag combine xforms for
12991 /// ISD::STORE.
12992 static SDValue PerformSTORECombine(SDNode *N,
12993 TargetLowering::DAGCombinerInfo &DCI) {
12994 StoreSDNode *St = cast<StoreSDNode>(N);
12995 if (St->isVolatile())
12996 return SDValue();
12998 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
12999 // pack all of the elements in one place. Next, store to memory in fewer
13000 // chunks.
13001 SDValue StVal = St->getValue();
13002 EVT VT = StVal.getValueType();
13003 if (St->isTruncatingStore() && VT.isVector()) {
13004 SelectionDAG &DAG = DCI.DAG;
13005 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13006 EVT StVT = St->getMemoryVT();
13007 unsigned NumElems = VT.getVectorNumElements();
13008 assert(StVT != VT && "Cannot truncate to the same type");
13009 unsigned FromEltSz = VT.getScalarSizeInBits();
13010 unsigned ToEltSz = StVT.getScalarSizeInBits();
13012 // From, To sizes and ElemCount must be pow of two
13013 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
13015 // We are going to use the original vector elt for storing.
13016 // Accumulated smaller vector elements must be a multiple of the store size.
13017 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
13019 unsigned SizeRatio = FromEltSz / ToEltSz;
13020 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
13022 // Create a type on which we perform the shuffle.
13023 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
13024 NumElems*SizeRatio);
13025 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13027 SDLoc DL(St);
13028 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
13029 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13030 for (unsigned i = 0; i < NumElems; ++i)
13031 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
13032 ? (i + 1) * SizeRatio - 1
13033 : i * SizeRatio;
13035 // Can't shuffle using an illegal type.
13036 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13038 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
13039 DAG.getUNDEF(WideVec.getValueType()),
13040 ShuffleVec);
13041 // At this point all of the data is stored at the bottom of the
13042 // register. We now need to save it to mem.
13044 // Find the largest store unit
13045 MVT StoreType = MVT::i8;
13046 for (MVT Tp : MVT::integer_valuetypes()) {
13047 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
13048 StoreType = Tp;
13050 // Didn't find a legal store type.
13051 if (!TLI.isTypeLegal(StoreType))
13052 return SDValue();
13054 // Bitcast the original vector into a vector of store-size units
13055 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13056 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13057 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13058 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
13059 SmallVector<SDValue, 8> Chains;
13060 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
13061 TLI.getPointerTy(DAG.getDataLayout()));
13062 SDValue BasePtr = St->getBasePtr();
13064 // Perform one or more big stores into memory.
13065 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
13066 for (unsigned I = 0; I < E; I++) {
13067 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
13068 StoreType, ShuffWide,
13069 DAG.getIntPtrConstant(I, DL));
13070 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
13071 St->getPointerInfo(), St->getAlignment(),
13072 St->getMemOperand()->getFlags());
13073 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
13074 Increment);
13075 Chains.push_back(Ch);
13077 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
13080 if (!ISD::isNormalStore(St))
13081 return SDValue();
13083 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
13084 // ARM stores of arguments in the same cache line.
13085 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
13086 StVal.getNode()->hasOneUse()) {
13087 SelectionDAG &DAG = DCI.DAG;
13088 bool isBigEndian = DAG.getDataLayout().isBigEndian();
13089 SDLoc DL(St);
13090 SDValue BasePtr = St->getBasePtr();
13091 SDValue NewST1 = DAG.getStore(
13092 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
13093 BasePtr, St->getPointerInfo(), St->getAlignment(),
13094 St->getMemOperand()->getFlags());
13096 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
13097 DAG.getConstant(4, DL, MVT::i32));
13098 return DAG.getStore(NewST1.getValue(0), DL,
13099 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
13100 OffsetPtr, St->getPointerInfo(),
13101 std::min(4U, St->getAlignment() / 2),
13102 St->getMemOperand()->getFlags());
13105 if (StVal.getValueType() == MVT::i64 &&
13106 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13108 // Bitcast an i64 store extracted from a vector to f64.
13109 // Otherwise, the i64 value will be legalized to a pair of i32 values.
13110 SelectionDAG &DAG = DCI.DAG;
13111 SDLoc dl(StVal);
13112 SDValue IntVec = StVal.getOperand(0);
13113 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
13114 IntVec.getValueType().getVectorNumElements());
13115 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
13116 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13117 Vec, StVal.getOperand(1));
13118 dl = SDLoc(N);
13119 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
13120 // Make the DAGCombiner fold the bitcasts.
13121 DCI.AddToWorklist(Vec.getNode());
13122 DCI.AddToWorklist(ExtElt.getNode());
13123 DCI.AddToWorklist(V.getNode());
13124 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
13125 St->getPointerInfo(), St->getAlignment(),
13126 St->getMemOperand()->getFlags(), St->getAAInfo());
13129 // If this is a legal vector store, try to combine it into a VST1_UPD.
13130 if (ISD::isNormalStore(N) && VT.isVector() &&
13131 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13132 return CombineBaseUpdate(N, DCI);
13134 return SDValue();
13137 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
13138 /// can replace combinations of VMUL and VCVT (floating-point to integer)
13139 /// when the VMUL has a constant operand that is a power of 2.
13141 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13142 /// vmul.f32 d16, d17, d16
13143 /// vcvt.s32.f32 d16, d16
13144 /// becomes:
13145 /// vcvt.s32.f32 d16, d16, #3
13146 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
13147 const ARMSubtarget *Subtarget) {
13148 if (!Subtarget->hasNEON())
13149 return SDValue();
13151 SDValue Op = N->getOperand(0);
13152 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
13153 Op.getOpcode() != ISD::FMUL)
13154 return SDValue();
13156 SDValue ConstVec = Op->getOperand(1);
13157 if (!isa<BuildVectorSDNode>(ConstVec))
13158 return SDValue();
13160 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
13161 uint32_t FloatBits = FloatTy.getSizeInBits();
13162 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
13163 uint32_t IntBits = IntTy.getSizeInBits();
13164 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13165 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13166 // These instructions only exist converting from f32 to i32. We can handle
13167 // smaller integers by generating an extra truncate, but larger ones would
13168 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13169 // these intructions only support v2i32/v4i32 types.
13170 return SDValue();
13173 BitVector UndefElements;
13174 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13175 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13176 if (C == -1 || C == 0 || C > 32)
13177 return SDValue();
13179 SDLoc dl(N);
13180 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
13181 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
13182 Intrinsic::arm_neon_vcvtfp2fxu;
13183 SDValue FixConv = DAG.getNode(
13184 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13185 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
13186 DAG.getConstant(C, dl, MVT::i32));
13188 if (IntBits < FloatBits)
13189 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
13191 return FixConv;
13194 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
13195 /// can replace combinations of VCVT (integer to floating-point) and VDIV
13196 /// when the VDIV has a constant operand that is a power of 2.
13198 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13199 /// vcvt.f32.s32 d16, d16
13200 /// vdiv.f32 d16, d17, d16
13201 /// becomes:
13202 /// vcvt.f32.s32 d16, d16, #3
13203 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
13204 const ARMSubtarget *Subtarget) {
13205 if (!Subtarget->hasNEON())
13206 return SDValue();
13208 SDValue Op = N->getOperand(0);
13209 unsigned OpOpcode = Op.getNode()->getOpcode();
13210 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
13211 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
13212 return SDValue();
13214 SDValue ConstVec = N->getOperand(1);
13215 if (!isa<BuildVectorSDNode>(ConstVec))
13216 return SDValue();
13218 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
13219 uint32_t FloatBits = FloatTy.getSizeInBits();
13220 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
13221 uint32_t IntBits = IntTy.getSizeInBits();
13222 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13223 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13224 // These instructions only exist converting from i32 to f32. We can handle
13225 // smaller integers by generating an extra extend, but larger ones would
13226 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13227 // these intructions only support v2i32/v4i32 types.
13228 return SDValue();
13231 BitVector UndefElements;
13232 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13233 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13234 if (C == -1 || C == 0 || C > 32)
13235 return SDValue();
13237 SDLoc dl(N);
13238 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
13239 SDValue ConvInput = Op.getOperand(0);
13240 if (IntBits < FloatBits)
13241 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
13242 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13243 ConvInput);
13245 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
13246 Intrinsic::arm_neon_vcvtfxu2fp;
13247 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
13248 Op.getValueType(),
13249 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
13250 ConvInput, DAG.getConstant(C, dl, MVT::i32));
13253 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
13254 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
13255 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13256 switch (IntNo) {
13257 default:
13258 // Don't do anything for most intrinsics.
13259 break;
13261 // Vector shifts: check for immediate versions and lower them.
13262 // Note: This is done during DAG combining instead of DAG legalizing because
13263 // the build_vectors for 64-bit vector element shift counts are generally
13264 // not legal, and it is hard to see their values after they get legalized to
13265 // loads from a constant pool.
13266 case Intrinsic::arm_neon_vshifts:
13267 case Intrinsic::arm_neon_vshiftu:
13268 case Intrinsic::arm_neon_vrshifts:
13269 case Intrinsic::arm_neon_vrshiftu:
13270 case Intrinsic::arm_neon_vrshiftn:
13271 case Intrinsic::arm_neon_vqshifts:
13272 case Intrinsic::arm_neon_vqshiftu:
13273 case Intrinsic::arm_neon_vqshiftsu:
13274 case Intrinsic::arm_neon_vqshiftns:
13275 case Intrinsic::arm_neon_vqshiftnu:
13276 case Intrinsic::arm_neon_vqshiftnsu:
13277 case Intrinsic::arm_neon_vqrshiftns:
13278 case Intrinsic::arm_neon_vqrshiftnu:
13279 case Intrinsic::arm_neon_vqrshiftnsu: {
13280 EVT VT = N->getOperand(1).getValueType();
13281 int64_t Cnt;
13282 unsigned VShiftOpc = 0;
13284 switch (IntNo) {
13285 case Intrinsic::arm_neon_vshifts:
13286 case Intrinsic::arm_neon_vshiftu:
13287 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
13288 VShiftOpc = ARMISD::VSHLIMM;
13289 break;
13291 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
13292 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
13293 : ARMISD::VSHRuIMM);
13294 break;
13296 return SDValue();
13298 case Intrinsic::arm_neon_vrshifts:
13299 case Intrinsic::arm_neon_vrshiftu:
13300 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
13301 break;
13302 return SDValue();
13304 case Intrinsic::arm_neon_vqshifts:
13305 case Intrinsic::arm_neon_vqshiftu:
13306 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13307 break;
13308 return SDValue();
13310 case Intrinsic::arm_neon_vqshiftsu:
13311 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13312 break;
13313 llvm_unreachable("invalid shift count for vqshlu intrinsic");
13315 case Intrinsic::arm_neon_vrshiftn:
13316 case Intrinsic::arm_neon_vqshiftns:
13317 case Intrinsic::arm_neon_vqshiftnu:
13318 case Intrinsic::arm_neon_vqshiftnsu:
13319 case Intrinsic::arm_neon_vqrshiftns:
13320 case Intrinsic::arm_neon_vqrshiftnu:
13321 case Intrinsic::arm_neon_vqrshiftnsu:
13322 // Narrowing shifts require an immediate right shift.
13323 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
13324 break;
13325 llvm_unreachable("invalid shift count for narrowing vector shift "
13326 "intrinsic");
13328 default:
13329 llvm_unreachable("unhandled vector shift");
13332 switch (IntNo) {
13333 case Intrinsic::arm_neon_vshifts:
13334 case Intrinsic::arm_neon_vshiftu:
13335 // Opcode already set above.
13336 break;
13337 case Intrinsic::arm_neon_vrshifts:
13338 VShiftOpc = ARMISD::VRSHRsIMM;
13339 break;
13340 case Intrinsic::arm_neon_vrshiftu:
13341 VShiftOpc = ARMISD::VRSHRuIMM;
13342 break;
13343 case Intrinsic::arm_neon_vrshiftn:
13344 VShiftOpc = ARMISD::VRSHRNIMM;
13345 break;
13346 case Intrinsic::arm_neon_vqshifts:
13347 VShiftOpc = ARMISD::VQSHLsIMM;
13348 break;
13349 case Intrinsic::arm_neon_vqshiftu:
13350 VShiftOpc = ARMISD::VQSHLuIMM;
13351 break;
13352 case Intrinsic::arm_neon_vqshiftsu:
13353 VShiftOpc = ARMISD::VQSHLsuIMM;
13354 break;
13355 case Intrinsic::arm_neon_vqshiftns:
13356 VShiftOpc = ARMISD::VQSHRNsIMM;
13357 break;
13358 case Intrinsic::arm_neon_vqshiftnu:
13359 VShiftOpc = ARMISD::VQSHRNuIMM;
13360 break;
13361 case Intrinsic::arm_neon_vqshiftnsu:
13362 VShiftOpc = ARMISD::VQSHRNsuIMM;
13363 break;
13364 case Intrinsic::arm_neon_vqrshiftns:
13365 VShiftOpc = ARMISD::VQRSHRNsIMM;
13366 break;
13367 case Intrinsic::arm_neon_vqrshiftnu:
13368 VShiftOpc = ARMISD::VQRSHRNuIMM;
13369 break;
13370 case Intrinsic::arm_neon_vqrshiftnsu:
13371 VShiftOpc = ARMISD::VQRSHRNsuIMM;
13372 break;
13375 SDLoc dl(N);
13376 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13377 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
13380 case Intrinsic::arm_neon_vshiftins: {
13381 EVT VT = N->getOperand(1).getValueType();
13382 int64_t Cnt;
13383 unsigned VShiftOpc = 0;
13385 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
13386 VShiftOpc = ARMISD::VSLIIMM;
13387 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
13388 VShiftOpc = ARMISD::VSRIIMM;
13389 else {
13390 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
13393 SDLoc dl(N);
13394 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13395 N->getOperand(1), N->getOperand(2),
13396 DAG.getConstant(Cnt, dl, MVT::i32));
13399 case Intrinsic::arm_neon_vqrshifts:
13400 case Intrinsic::arm_neon_vqrshiftu:
13401 // No immediate versions of these to check for.
13402 break;
13405 return SDValue();
13408 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
13409 /// lowers them. As with the vector shift intrinsics, this is done during DAG
13410 /// combining instead of DAG legalizing because the build_vectors for 64-bit
13411 /// vector element shift counts are generally not legal, and it is hard to see
13412 /// their values after they get legalized to loads from a constant pool.
13413 static SDValue PerformShiftCombine(SDNode *N,
13414 TargetLowering::DAGCombinerInfo &DCI,
13415 const ARMSubtarget *ST) {
13416 SelectionDAG &DAG = DCI.DAG;
13417 EVT VT = N->getValueType(0);
13418 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
13419 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
13420 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
13421 SDValue N1 = N->getOperand(1);
13422 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
13423 SDValue N0 = N->getOperand(0);
13424 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
13425 DAG.MaskedValueIsZero(N0.getOperand(0),
13426 APInt::getHighBitsSet(32, 16)))
13427 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
13431 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
13432 N->getOperand(0)->getOpcode() == ISD::AND &&
13433 N->getOperand(0)->hasOneUse()) {
13434 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13435 return SDValue();
13436 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
13437 // usually show up because instcombine prefers to canonicalize it to
13438 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
13439 // out of GEP lowering in some cases.
13440 SDValue N0 = N->getOperand(0);
13441 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
13442 if (!ShiftAmtNode)
13443 return SDValue();
13444 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
13445 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13446 if (!AndMaskNode)
13447 return SDValue();
13448 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
13449 // Don't transform uxtb/uxth.
13450 if (AndMask == 255 || AndMask == 65535)
13451 return SDValue();
13452 if (isMask_32(AndMask)) {
13453 uint32_t MaskedBits = countLeadingZeros(AndMask);
13454 if (MaskedBits > ShiftAmt) {
13455 SDLoc DL(N);
13456 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
13457 DAG.getConstant(MaskedBits, DL, MVT::i32));
13458 return DAG.getNode(
13459 ISD::SRL, DL, MVT::i32, SHL,
13460 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
13465 // Nothing to be done for scalar shifts.
13466 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13467 if (!VT.isVector() || !TLI.isTypeLegal(VT))
13468 return SDValue();
13469 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
13470 return SDValue();
13472 int64_t Cnt;
13474 switch (N->getOpcode()) {
13475 default: llvm_unreachable("unexpected shift opcode");
13477 case ISD::SHL:
13478 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
13479 SDLoc dl(N);
13480 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
13481 DAG.getConstant(Cnt, dl, MVT::i32));
13483 break;
13485 case ISD::SRA:
13486 case ISD::SRL:
13487 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
13488 unsigned VShiftOpc =
13489 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
13490 SDLoc dl(N);
13491 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
13492 DAG.getConstant(Cnt, dl, MVT::i32));
13495 return SDValue();
13498 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
13499 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
13500 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
13501 const ARMSubtarget *ST) {
13502 SDValue N0 = N->getOperand(0);
13504 // Check for sign- and zero-extensions of vector extract operations of 8-
13505 // and 16-bit vector elements. NEON supports these directly. They are
13506 // handled during DAG combining because type legalization will promote them
13507 // to 32-bit types and it is messy to recognize the operations after that.
13508 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13509 SDValue Vec = N0.getOperand(0);
13510 SDValue Lane = N0.getOperand(1);
13511 EVT VT = N->getValueType(0);
13512 EVT EltVT = N0.getValueType();
13513 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13515 if (VT == MVT::i32 &&
13516 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
13517 TLI.isTypeLegal(Vec.getValueType()) &&
13518 isa<ConstantSDNode>(Lane)) {
13520 unsigned Opc = 0;
13521 switch (N->getOpcode()) {
13522 default: llvm_unreachable("unexpected opcode");
13523 case ISD::SIGN_EXTEND:
13524 Opc = ARMISD::VGETLANEs;
13525 break;
13526 case ISD::ZERO_EXTEND:
13527 case ISD::ANY_EXTEND:
13528 Opc = ARMISD::VGETLANEu;
13529 break;
13531 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
13535 return SDValue();
13538 static const APInt *isPowerOf2Constant(SDValue V) {
13539 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13540 if (!C)
13541 return nullptr;
13542 const APInt *CV = &C->getAPIntValue();
13543 return CV->isPowerOf2() ? CV : nullptr;
13546 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
13547 // If we have a CMOV, OR and AND combination such as:
13548 // if (x & CN)
13549 // y |= CM;
13551 // And:
13552 // * CN is a single bit;
13553 // * All bits covered by CM are known zero in y
13555 // Then we can convert this into a sequence of BFI instructions. This will
13556 // always be a win if CM is a single bit, will always be no worse than the
13557 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
13558 // three bits (due to the extra IT instruction).
13560 SDValue Op0 = CMOV->getOperand(0);
13561 SDValue Op1 = CMOV->getOperand(1);
13562 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
13563 auto CC = CCNode->getAPIntValue().getLimitedValue();
13564 SDValue CmpZ = CMOV->getOperand(4);
13566 // The compare must be against zero.
13567 if (!isNullConstant(CmpZ->getOperand(1)))
13568 return SDValue();
13570 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
13571 SDValue And = CmpZ->getOperand(0);
13572 if (And->getOpcode() != ISD::AND)
13573 return SDValue();
13574 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
13575 if (!AndC)
13576 return SDValue();
13577 SDValue X = And->getOperand(0);
13579 if (CC == ARMCC::EQ) {
13580 // We're performing an "equal to zero" compare. Swap the operands so we
13581 // canonicalize on a "not equal to zero" compare.
13582 std::swap(Op0, Op1);
13583 } else {
13584 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
13587 if (Op1->getOpcode() != ISD::OR)
13588 return SDValue();
13590 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
13591 if (!OrC)
13592 return SDValue();
13593 SDValue Y = Op1->getOperand(0);
13595 if (Op0 != Y)
13596 return SDValue();
13598 // Now, is it profitable to continue?
13599 APInt OrCI = OrC->getAPIntValue();
13600 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
13601 if (OrCI.countPopulation() > Heuristic)
13602 return SDValue();
13604 // Lastly, can we determine that the bits defined by OrCI
13605 // are zero in Y?
13606 KnownBits Known = DAG.computeKnownBits(Y);
13607 if ((OrCI & Known.Zero) != OrCI)
13608 return SDValue();
13610 // OK, we can do the combine.
13611 SDValue V = Y;
13612 SDLoc dl(X);
13613 EVT VT = X.getValueType();
13614 unsigned BitInX = AndC->logBase2();
13616 if (BitInX != 0) {
13617 // We must shift X first.
13618 X = DAG.getNode(ISD::SRL, dl, VT, X,
13619 DAG.getConstant(BitInX, dl, VT));
13622 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
13623 BitInY < NumActiveBits; ++BitInY) {
13624 if (OrCI[BitInY] == 0)
13625 continue;
13626 APInt Mask(VT.getSizeInBits(), 0);
13627 Mask.setBit(BitInY);
13628 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
13629 // Confusingly, the operand is an *inverted* mask.
13630 DAG.getConstant(~Mask, dl, VT));
13633 return V;
13636 // Given N, the value controlling the conditional branch, search for the loop
13637 // intrinsic, returning it, along with how the value is used. We need to handle
13638 // patterns such as the following:
13639 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
13640 // (brcond (setcc (loop.decrement), 0, eq), exit)
13641 // (brcond (setcc (loop.decrement), 0, ne), header)
13642 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
13643 bool &Negate) {
13644 switch (N->getOpcode()) {
13645 default:
13646 break;
13647 case ISD::XOR: {
13648 if (!isa<ConstantSDNode>(N.getOperand(1)))
13649 return SDValue();
13650 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
13651 return SDValue();
13652 Negate = !Negate;
13653 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
13655 case ISD::SETCC: {
13656 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
13657 if (!Const)
13658 return SDValue();
13659 if (Const->isNullValue())
13660 Imm = 0;
13661 else if (Const->isOne())
13662 Imm = 1;
13663 else
13664 return SDValue();
13665 CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
13666 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
13668 case ISD::INTRINSIC_W_CHAIN: {
13669 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
13670 if (IntOp != Intrinsic::test_set_loop_iterations &&
13671 IntOp != Intrinsic::loop_decrement_reg)
13672 return SDValue();
13673 return N;
13676 return SDValue();
13679 static SDValue PerformHWLoopCombine(SDNode *N,
13680 TargetLowering::DAGCombinerInfo &DCI,
13681 const ARMSubtarget *ST) {
13683 // The hwloop intrinsics that we're interested are used for control-flow,
13684 // either for entering or exiting the loop:
13685 // - test.set.loop.iterations will test whether its operand is zero. If it
13686 // is zero, the proceeding branch should not enter the loop.
13687 // - loop.decrement.reg also tests whether its operand is zero. If it is
13688 // zero, the proceeding branch should not branch back to the beginning of
13689 // the loop.
13690 // So here, we need to check that how the brcond is using the result of each
13691 // of the intrinsics to ensure that we're branching to the right place at the
13692 // right time.
13694 ISD::CondCode CC;
13695 SDValue Cond;
13696 int Imm = 1;
13697 bool Negate = false;
13698 SDValue Chain = N->getOperand(0);
13699 SDValue Dest;
13701 if (N->getOpcode() == ISD::BRCOND) {
13702 CC = ISD::SETEQ;
13703 Cond = N->getOperand(1);
13704 Dest = N->getOperand(2);
13705 } else {
13706 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
13707 CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
13708 Cond = N->getOperand(2);
13709 Dest = N->getOperand(4);
13710 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
13711 if (!Const->isOne() && !Const->isNullValue())
13712 return SDValue();
13713 Imm = Const->getZExtValue();
13714 } else
13715 return SDValue();
13718 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
13719 if (!Int)
13720 return SDValue();
13722 if (Negate)
13723 CC = ISD::getSetCCInverse(CC, true);
13725 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
13726 return (CC == ISD::SETEQ && Imm == 0) ||
13727 (CC == ISD::SETNE && Imm == 1) ||
13728 (CC == ISD::SETLT && Imm == 1) ||
13729 (CC == ISD::SETULT && Imm == 1);
13732 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
13733 return (CC == ISD::SETEQ && Imm == 1) ||
13734 (CC == ISD::SETNE && Imm == 0) ||
13735 (CC == ISD::SETGT && Imm == 0) ||
13736 (CC == ISD::SETUGT && Imm == 0) ||
13737 (CC == ISD::SETGE && Imm == 1) ||
13738 (CC == ISD::SETUGE && Imm == 1);
13741 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
13742 "unsupported condition");
13744 SDLoc dl(Int);
13745 SelectionDAG &DAG = DCI.DAG;
13746 SDValue Elements = Int.getOperand(2);
13747 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
13748 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
13749 && "expected single br user");
13750 SDNode *Br = *N->use_begin();
13751 SDValue OtherTarget = Br->getOperand(1);
13753 // Update the unconditional branch to branch to the given Dest.
13754 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
13755 SDValue NewBrOps[] = { Br->getOperand(0), Dest };
13756 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
13757 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
13760 if (IntOp == Intrinsic::test_set_loop_iterations) {
13761 SDValue Res;
13762 // We expect this 'instruction' to branch when the counter is zero.
13763 if (IsTrueIfZero(CC, Imm)) {
13764 SDValue Ops[] = { Chain, Elements, Dest };
13765 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
13766 } else {
13767 // The logic is the reverse of what we need for WLS, so find the other
13768 // basic block target: the target of the proceeding br.
13769 UpdateUncondBr(Br, Dest, DAG);
13771 SDValue Ops[] = { Chain, Elements, OtherTarget };
13772 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
13774 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
13775 return Res;
13776 } else {
13777 SDValue Size = DAG.getTargetConstant(
13778 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
13779 SDValue Args[] = { Int.getOperand(0), Elements, Size, };
13780 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
13781 DAG.getVTList(MVT::i32, MVT::Other), Args);
13782 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
13784 // We expect this instruction to branch when the count is not zero.
13785 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
13787 // Update the unconditional branch to target the loop preheader if we've
13788 // found the condition has been reversed.
13789 if (Target == OtherTarget)
13790 UpdateUncondBr(Br, Dest, DAG);
13792 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13793 SDValue(LoopDec.getNode(), 1), Chain);
13795 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
13796 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
13798 return SDValue();
13801 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
13802 SDValue
13803 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
13804 SDValue Cmp = N->getOperand(4);
13805 if (Cmp.getOpcode() != ARMISD::CMPZ)
13806 // Only looking at NE cases.
13807 return SDValue();
13809 EVT VT = N->getValueType(0);
13810 SDLoc dl(N);
13811 SDValue LHS = Cmp.getOperand(0);
13812 SDValue RHS = Cmp.getOperand(1);
13813 SDValue Chain = N->getOperand(0);
13814 SDValue BB = N->getOperand(1);
13815 SDValue ARMcc = N->getOperand(2);
13816 ARMCC::CondCodes CC =
13817 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
13819 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
13820 // -> (brcond Chain BB CC CPSR Cmp)
13821 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
13822 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
13823 LHS->getOperand(0)->hasOneUse()) {
13824 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
13825 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
13826 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
13827 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
13828 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
13829 (LHS01C && LHS01C->getZExtValue() == 1) &&
13830 (LHS1C && LHS1C->getZExtValue() == 1) &&
13831 (RHSC && RHSC->getZExtValue() == 0)) {
13832 return DAG.getNode(
13833 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
13834 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
13838 return SDValue();
13841 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
13842 SDValue
13843 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
13844 SDValue Cmp = N->getOperand(4);
13845 if (Cmp.getOpcode() != ARMISD::CMPZ)
13846 // Only looking at EQ and NE cases.
13847 return SDValue();
13849 EVT VT = N->getValueType(0);
13850 SDLoc dl(N);
13851 SDValue LHS = Cmp.getOperand(0);
13852 SDValue RHS = Cmp.getOperand(1);
13853 SDValue FalseVal = N->getOperand(0);
13854 SDValue TrueVal = N->getOperand(1);
13855 SDValue ARMcc = N->getOperand(2);
13856 ARMCC::CondCodes CC =
13857 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
13859 // BFI is only available on V6T2+.
13860 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
13861 SDValue R = PerformCMOVToBFICombine(N, DAG);
13862 if (R)
13863 return R;
13866 // Simplify
13867 // mov r1, r0
13868 // cmp r1, x
13869 // mov r0, y
13870 // moveq r0, x
13871 // to
13872 // cmp r0, x
13873 // movne r0, y
13875 // mov r1, r0
13876 // cmp r1, x
13877 // mov r0, x
13878 // movne r0, y
13879 // to
13880 // cmp r0, x
13881 // movne r0, y
13882 /// FIXME: Turn this into a target neutral optimization?
13883 SDValue Res;
13884 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
13885 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
13886 N->getOperand(3), Cmp);
13887 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
13888 SDValue ARMcc;
13889 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
13890 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
13891 N->getOperand(3), NewCmp);
13894 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
13895 // -> (cmov F T CC CPSR Cmp)
13896 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
13897 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
13898 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
13899 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
13900 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
13901 (LHS1C && LHS1C->getZExtValue() == 1) &&
13902 (RHSC && RHSC->getZExtValue() == 0)) {
13903 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
13904 LHS->getOperand(2), LHS->getOperand(3),
13905 LHS->getOperand(4));
13909 if (!VT.isInteger())
13910 return SDValue();
13912 // Materialize a boolean comparison for integers so we can avoid branching.
13913 if (isNullConstant(FalseVal)) {
13914 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
13915 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
13916 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
13917 // right 5 bits will make that 32 be 1, otherwise it will be 0.
13918 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
13919 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
13920 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
13921 DAG.getConstant(5, dl, MVT::i32));
13922 } else {
13923 // CMOV 0, 1, ==, (CMPZ x, y) ->
13924 // (ADDCARRY (SUB x, y), t:0, t:1)
13925 // where t = (SUBCARRY 0, (SUB x, y), 0)
13927 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
13928 // x != y. In other words, a carry C == 1 when x == y, C == 0
13929 // otherwise.
13930 // The final ADDCARRY computes
13931 // x - y + (0 - (x - y)) + C == C
13932 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
13933 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13934 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
13935 // ISD::SUBCARRY returns a borrow but we want the carry here
13936 // actually.
13937 SDValue Carry =
13938 DAG.getNode(ISD::SUB, dl, MVT::i32,
13939 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
13940 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
13942 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
13943 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
13944 // This seems pointless but will allow us to combine it further below.
13945 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
13946 SDValue Sub =
13947 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
13948 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
13949 Sub.getValue(1), SDValue());
13950 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
13951 N->getOperand(3), CPSRGlue.getValue(1));
13952 FalseVal = Sub;
13954 } else if (isNullConstant(TrueVal)) {
13955 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
13956 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
13957 // This seems pointless but will allow us to combine it further below
13958 // Note that we change == for != as this is the dual for the case above.
13959 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
13960 SDValue Sub =
13961 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
13962 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
13963 Sub.getValue(1), SDValue());
13964 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
13965 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
13966 N->getOperand(3), CPSRGlue.getValue(1));
13967 FalseVal = Sub;
13971 // On Thumb1, the DAG above may be further combined if z is a power of 2
13972 // (z == 2 ^ K).
13973 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
13974 // t1 = (USUBO (SUB x, y), 1)
13975 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
13976 // Result = if K != 0 then (SHL t2:0, K) else t2:0
13978 // This also handles the special case of comparing against zero; it's
13979 // essentially, the same pattern, except there's no SUBS:
13980 // CMOV x, z, !=, (CMPZ x, 0) ->
13981 // t1 = (USUBO x, 1)
13982 // t2 = (SUBCARRY x, t1:0, t1:1)
13983 // Result = if K != 0 then (SHL t2:0, K) else t2:0
13984 const APInt *TrueConst;
13985 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
13986 ((FalseVal.getOpcode() == ARMISD::SUBS &&
13987 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
13988 (FalseVal == LHS && isNullConstant(RHS))) &&
13989 (TrueConst = isPowerOf2Constant(TrueVal))) {
13990 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13991 unsigned ShiftAmount = TrueConst->logBase2();
13992 if (ShiftAmount)
13993 TrueVal = DAG.getConstant(1, dl, VT);
13994 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
13995 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
13997 if (ShiftAmount)
13998 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
13999 DAG.getConstant(ShiftAmount, dl, MVT::i32));
14002 if (Res.getNode()) {
14003 KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
14004 // Capture demanded bits information that would be otherwise lost.
14005 if (Known.Zero == 0xfffffffe)
14006 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14007 DAG.getValueType(MVT::i1));
14008 else if (Known.Zero == 0xffffff00)
14009 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14010 DAG.getValueType(MVT::i8));
14011 else if (Known.Zero == 0xffff0000)
14012 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14013 DAG.getValueType(MVT::i16));
14016 return Res;
14019 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
14020 DAGCombinerInfo &DCI) const {
14021 switch (N->getOpcode()) {
14022 default: break;
14023 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget);
14024 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
14025 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
14026 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
14027 case ISD::SUB: return PerformSUBCombine(N, DCI);
14028 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
14029 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
14030 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
14031 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
14032 case ISD::BRCOND:
14033 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget);
14034 case ARMISD::ADDC:
14035 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
14036 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
14037 case ARMISD::BFI: return PerformBFICombine(N, DCI);
14038 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
14039 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
14040 case ISD::STORE: return PerformSTORECombine(N, DCI);
14041 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
14042 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
14043 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
14044 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
14045 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
14046 case ISD::FP_TO_SINT:
14047 case ISD::FP_TO_UINT:
14048 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
14049 case ISD::FDIV:
14050 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
14051 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
14052 case ISD::SHL:
14053 case ISD::SRA:
14054 case ISD::SRL:
14055 return PerformShiftCombine(N, DCI, Subtarget);
14056 case ISD::SIGN_EXTEND:
14057 case ISD::ZERO_EXTEND:
14058 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
14059 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
14060 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
14061 case ISD::LOAD: return PerformLOADCombine(N, DCI);
14062 case ARMISD::VLD1DUP:
14063 case ARMISD::VLD2DUP:
14064 case ARMISD::VLD3DUP:
14065 case ARMISD::VLD4DUP:
14066 return PerformVLDCombine(N, DCI);
14067 case ARMISD::BUILD_VECTOR:
14068 return PerformARMBUILD_VECTORCombine(N, DCI);
14069 case ARMISD::SMULWB: {
14070 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14071 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14072 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14073 return SDValue();
14074 break;
14076 case ARMISD::SMULWT: {
14077 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14078 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14079 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14080 return SDValue();
14081 break;
14083 case ARMISD::SMLALBB: {
14084 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14085 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14086 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14087 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14088 return SDValue();
14089 break;
14091 case ARMISD::SMLALBT: {
14092 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
14093 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14094 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
14095 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14096 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
14097 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
14098 return SDValue();
14099 break;
14101 case ARMISD::SMLALTB: {
14102 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
14103 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14104 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
14105 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14106 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
14107 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
14108 return SDValue();
14109 break;
14111 case ARMISD::SMLALTT: {
14112 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14113 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14114 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14115 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14116 return SDValue();
14117 break;
14119 case ISD::INTRINSIC_VOID:
14120 case ISD::INTRINSIC_W_CHAIN:
14121 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14122 case Intrinsic::arm_neon_vld1:
14123 case Intrinsic::arm_neon_vld1x2:
14124 case Intrinsic::arm_neon_vld1x3:
14125 case Intrinsic::arm_neon_vld1x4:
14126 case Intrinsic::arm_neon_vld2:
14127 case Intrinsic::arm_neon_vld3:
14128 case Intrinsic::arm_neon_vld4:
14129 case Intrinsic::arm_neon_vld2lane:
14130 case Intrinsic::arm_neon_vld3lane:
14131 case Intrinsic::arm_neon_vld4lane:
14132 case Intrinsic::arm_neon_vld2dup:
14133 case Intrinsic::arm_neon_vld3dup:
14134 case Intrinsic::arm_neon_vld4dup:
14135 case Intrinsic::arm_neon_vst1:
14136 case Intrinsic::arm_neon_vst1x2:
14137 case Intrinsic::arm_neon_vst1x3:
14138 case Intrinsic::arm_neon_vst1x4:
14139 case Intrinsic::arm_neon_vst2:
14140 case Intrinsic::arm_neon_vst3:
14141 case Intrinsic::arm_neon_vst4:
14142 case Intrinsic::arm_neon_vst2lane:
14143 case Intrinsic::arm_neon_vst3lane:
14144 case Intrinsic::arm_neon_vst4lane:
14145 return PerformVLDCombine(N, DCI);
14146 default: break;
14148 break;
14150 return SDValue();
14153 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
14154 EVT VT) const {
14155 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
14158 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
14159 unsigned Alignment,
14160 MachineMemOperand::Flags,
14161 bool *Fast) const {
14162 // Depends what it gets converted into if the type is weird.
14163 if (!VT.isSimple())
14164 return false;
14166 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
14167 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
14168 auto Ty = VT.getSimpleVT().SimpleTy;
14170 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
14171 // Unaligned access can use (for example) LRDB, LRDH, LDR
14172 if (AllowsUnaligned) {
14173 if (Fast)
14174 *Fast = Subtarget->hasV7Ops();
14175 return true;
14179 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
14180 // For any little-endian targets with neon, we can support unaligned ld/st
14181 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
14182 // A big-endian target may also explicitly support unaligned accesses
14183 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
14184 if (Fast)
14185 *Fast = true;
14186 return true;
14190 if (!Subtarget->hasMVEIntegerOps())
14191 return false;
14193 // These are for predicates
14194 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
14195 if (Fast)
14196 *Fast = true;
14197 return true;
14200 // These are for truncated stores/narrowing loads. They are fine so long as
14201 // the alignment is at least the size of the item being loaded
14202 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
14203 Alignment >= VT.getScalarSizeInBits() / 8) {
14204 if (Fast)
14205 *Fast = true;
14206 return true;
14209 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
14210 // VSTRW.U32 all store the vector register in exactly the same format, and
14211 // differ only in the range of their immediate offset field and the required
14212 // alignment. So there is always a store that can be used, regardless of
14213 // actual type.
14215 // For big endian, that is not the case. But can still emit a (VSTRB.U8;
14216 // VREV64.8) pair and get the same effect. This will likely be better than
14217 // aligning the vector through the stack.
14218 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
14219 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
14220 Ty == MVT::v2f64) {
14221 if (Fast)
14222 *Fast = true;
14223 return true;
14226 return false;
14229 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
14230 unsigned AlignCheck) {
14231 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
14232 (DstAlign == 0 || DstAlign % AlignCheck == 0));
14235 EVT ARMTargetLowering::getOptimalMemOpType(
14236 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14237 bool ZeroMemset, bool MemcpyStrSrc,
14238 const AttributeList &FuncAttributes) const {
14239 // See if we can use NEON instructions for this...
14240 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
14241 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
14242 bool Fast;
14243 if (Size >= 16 &&
14244 (memOpAlign(SrcAlign, DstAlign, 16) ||
14245 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
14246 MachineMemOperand::MONone, &Fast) &&
14247 Fast))) {
14248 return MVT::v2f64;
14249 } else if (Size >= 8 &&
14250 (memOpAlign(SrcAlign, DstAlign, 8) ||
14251 (allowsMisalignedMemoryAccesses(
14252 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
14253 Fast))) {
14254 return MVT::f64;
14258 // Let the target-independent logic figure it out.
14259 return MVT::Other;
14262 // 64-bit integers are split into their high and low parts and held in two
14263 // different registers, so the trunc is free since the low register can just
14264 // be used.
14265 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
14266 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
14267 return false;
14268 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
14269 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
14270 return (SrcBits == 64 && DestBits == 32);
14273 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
14274 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
14275 !DstVT.isInteger())
14276 return false;
14277 unsigned SrcBits = SrcVT.getSizeInBits();
14278 unsigned DestBits = DstVT.getSizeInBits();
14279 return (SrcBits == 64 && DestBits == 32);
14282 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14283 if (Val.getOpcode() != ISD::LOAD)
14284 return false;
14286 EVT VT1 = Val.getValueType();
14287 if (!VT1.isSimple() || !VT1.isInteger() ||
14288 !VT2.isSimple() || !VT2.isInteger())
14289 return false;
14291 switch (VT1.getSimpleVT().SimpleTy) {
14292 default: break;
14293 case MVT::i1:
14294 case MVT::i8:
14295 case MVT::i16:
14296 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
14297 return true;
14300 return false;
14303 bool ARMTargetLowering::isFNegFree(EVT VT) const {
14304 if (!VT.isSimple())
14305 return false;
14307 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
14308 // negate values directly (fneg is free). So, we don't want to let the DAG
14309 // combiner rewrite fneg into xors and some other instructions. For f16 and
14310 // FullFP16 argument passing, some bitcast nodes may be introduced,
14311 // triggering this DAG combine rewrite, so we are avoiding that with this.
14312 switch (VT.getSimpleVT().SimpleTy) {
14313 default: break;
14314 case MVT::f16:
14315 return Subtarget->hasFullFP16();
14318 return false;
14321 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
14322 /// of the vector elements.
14323 static bool areExtractExts(Value *Ext1, Value *Ext2) {
14324 auto areExtDoubled = [](Instruction *Ext) {
14325 return Ext->getType()->getScalarSizeInBits() ==
14326 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
14329 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
14330 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
14331 !areExtDoubled(cast<Instruction>(Ext1)) ||
14332 !areExtDoubled(cast<Instruction>(Ext2)))
14333 return false;
14335 return true;
14338 /// Check if sinking \p I's operands to I's basic block is profitable, because
14339 /// the operands can be folded into a target instruction, e.g.
14340 /// sext/zext can be folded into vsubl.
14341 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
14342 SmallVectorImpl<Use *> &Ops) const {
14343 if (!Subtarget->hasNEON() || !I->getType()->isVectorTy())
14344 return false;
14346 switch (I->getOpcode()) {
14347 case Instruction::Sub:
14348 case Instruction::Add: {
14349 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
14350 return false;
14351 Ops.push_back(&I->getOperandUse(0));
14352 Ops.push_back(&I->getOperandUse(1));
14353 return true;
14355 default:
14356 return false;
14358 return false;
14361 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
14362 EVT VT = ExtVal.getValueType();
14364 if (!isTypeLegal(VT))
14365 return false;
14367 // Don't create a loadext if we can fold the extension into a wide/long
14368 // instruction.
14369 // If there's more than one user instruction, the loadext is desirable no
14370 // matter what. There can be two uses by the same instruction.
14371 if (ExtVal->use_empty() ||
14372 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
14373 return true;
14375 SDNode *U = *ExtVal->use_begin();
14376 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
14377 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
14378 return false;
14380 return true;
14383 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14384 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14385 return false;
14387 if (!isTypeLegal(EVT::getEVT(Ty1)))
14388 return false;
14390 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14392 // Assuming the caller doesn't have a zeroext or signext return parameter,
14393 // truncation all the way down to i1 is valid.
14394 return true;
14397 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
14398 const AddrMode &AM, Type *Ty,
14399 unsigned AS) const {
14400 if (isLegalAddressingMode(DL, AM, Ty, AS)) {
14401 if (Subtarget->hasFPAO())
14402 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
14403 return 0;
14405 return -1;
14408 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
14409 if (V < 0)
14410 return false;
14412 unsigned Scale = 1;
14413 switch (VT.getSimpleVT().SimpleTy) {
14414 case MVT::i1:
14415 case MVT::i8:
14416 // Scale == 1;
14417 break;
14418 case MVT::i16:
14419 // Scale == 2;
14420 Scale = 2;
14421 break;
14422 default:
14423 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
14424 // Scale == 4;
14425 Scale = 4;
14426 break;
14429 if ((V & (Scale - 1)) != 0)
14430 return false;
14431 return isUInt<5>(V / Scale);
14434 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
14435 const ARMSubtarget *Subtarget) {
14436 if (!VT.isInteger() && !VT.isFloatingPoint())
14437 return false;
14438 if (VT.isVector() && Subtarget->hasNEON())
14439 return false;
14440 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
14441 !Subtarget->hasMVEFloatOps())
14442 return false;
14444 bool IsNeg = false;
14445 if (V < 0) {
14446 IsNeg = true;
14447 V = -V;
14450 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U);
14452 // MVE: size * imm7
14453 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
14454 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
14455 case MVT::i32:
14456 case MVT::f32:
14457 return isShiftedUInt<7,2>(V);
14458 case MVT::i16:
14459 case MVT::f16:
14460 return isShiftedUInt<7,1>(V);
14461 case MVT::i8:
14462 return isUInt<7>(V);
14463 default:
14464 return false;
14468 // half VLDR: 2 * imm8
14469 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
14470 return isShiftedUInt<8, 1>(V);
14471 // VLDR and LDRD: 4 * imm8
14472 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
14473 return isShiftedUInt<8, 2>(V);
14475 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
14476 // + imm12 or - imm8
14477 if (IsNeg)
14478 return isUInt<8>(V);
14479 return isUInt<12>(V);
14482 return false;
14485 /// isLegalAddressImmediate - Return true if the integer value can be used
14486 /// as the offset of the target addressing mode for load / store of the
14487 /// given type.
14488 static bool isLegalAddressImmediate(int64_t V, EVT VT,
14489 const ARMSubtarget *Subtarget) {
14490 if (V == 0)
14491 return true;
14493 if (!VT.isSimple())
14494 return false;
14496 if (Subtarget->isThumb1Only())
14497 return isLegalT1AddressImmediate(V, VT);
14498 else if (Subtarget->isThumb2())
14499 return isLegalT2AddressImmediate(V, VT, Subtarget);
14501 // ARM mode.
14502 if (V < 0)
14503 V = - V;
14504 switch (VT.getSimpleVT().SimpleTy) {
14505 default: return false;
14506 case MVT::i1:
14507 case MVT::i8:
14508 case MVT::i32:
14509 // +- imm12
14510 return isUInt<12>(V);
14511 case MVT::i16:
14512 // +- imm8
14513 return isUInt<8>(V);
14514 case MVT::f32:
14515 case MVT::f64:
14516 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
14517 return false;
14518 return isShiftedUInt<8, 2>(V);
14522 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
14523 EVT VT) const {
14524 int Scale = AM.Scale;
14525 if (Scale < 0)
14526 return false;
14528 switch (VT.getSimpleVT().SimpleTy) {
14529 default: return false;
14530 case MVT::i1:
14531 case MVT::i8:
14532 case MVT::i16:
14533 case MVT::i32:
14534 if (Scale == 1)
14535 return true;
14536 // r + r << imm
14537 Scale = Scale & ~1;
14538 return Scale == 2 || Scale == 4 || Scale == 8;
14539 case MVT::i64:
14540 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
14541 // version in Thumb mode.
14542 // r + r
14543 if (Scale == 1)
14544 return true;
14545 // r * 2 (this can be lowered to r + r).
14546 if (!AM.HasBaseReg && Scale == 2)
14547 return true;
14548 return false;
14549 case MVT::isVoid:
14550 // Note, we allow "void" uses (basically, uses that aren't loads or
14551 // stores), because arm allows folding a scale into many arithmetic
14552 // operations. This should be made more precise and revisited later.
14554 // Allow r << imm, but the imm has to be a multiple of two.
14555 if (Scale & 1) return false;
14556 return isPowerOf2_32(Scale);
14560 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
14561 EVT VT) const {
14562 const int Scale = AM.Scale;
14564 // Negative scales are not supported in Thumb1.
14565 if (Scale < 0)
14566 return false;
14568 // Thumb1 addressing modes do not support register scaling excepting the
14569 // following cases:
14570 // 1. Scale == 1 means no scaling.
14571 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
14572 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
14575 /// isLegalAddressingMode - Return true if the addressing mode represented
14576 /// by AM is legal for this target, for a load/store of the specified type.
14577 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14578 const AddrMode &AM, Type *Ty,
14579 unsigned AS, Instruction *I) const {
14580 EVT VT = getValueType(DL, Ty, true);
14581 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
14582 return false;
14584 // Can never fold addr of global into load/store.
14585 if (AM.BaseGV)
14586 return false;
14588 switch (AM.Scale) {
14589 case 0: // no scale reg, must be "r+i" or "r", or "i".
14590 break;
14591 default:
14592 // ARM doesn't support any R+R*scale+imm addr modes.
14593 if (AM.BaseOffs)
14594 return false;
14596 if (!VT.isSimple())
14597 return false;
14599 if (Subtarget->isThumb1Only())
14600 return isLegalT1ScaledAddressingMode(AM, VT);
14602 if (Subtarget->isThumb2())
14603 return isLegalT2ScaledAddressingMode(AM, VT);
14605 int Scale = AM.Scale;
14606 switch (VT.getSimpleVT().SimpleTy) {
14607 default: return false;
14608 case MVT::i1:
14609 case MVT::i8:
14610 case MVT::i32:
14611 if (Scale < 0) Scale = -Scale;
14612 if (Scale == 1)
14613 return true;
14614 // r + r << imm
14615 return isPowerOf2_32(Scale & ~1);
14616 case MVT::i16:
14617 case MVT::i64:
14618 // r +/- r
14619 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
14620 return true;
14621 // r * 2 (this can be lowered to r + r).
14622 if (!AM.HasBaseReg && Scale == 2)
14623 return true;
14624 return false;
14626 case MVT::isVoid:
14627 // Note, we allow "void" uses (basically, uses that aren't loads or
14628 // stores), because arm allows folding a scale into many arithmetic
14629 // operations. This should be made more precise and revisited later.
14631 // Allow r << imm, but the imm has to be a multiple of two.
14632 if (Scale & 1) return false;
14633 return isPowerOf2_32(Scale);
14636 return true;
14639 /// isLegalICmpImmediate - Return true if the specified immediate is legal
14640 /// icmp immediate, that is the target has icmp instructions which can compare
14641 /// a register against the immediate without having to materialize the
14642 /// immediate into a register.
14643 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14644 // Thumb2 and ARM modes can use cmn for negative immediates.
14645 if (!Subtarget->isThumb())
14646 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
14647 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
14648 if (Subtarget->isThumb2())
14649 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
14650 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
14651 // Thumb1 doesn't have cmn, and only 8-bit immediates.
14652 return Imm >= 0 && Imm <= 255;
14655 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
14656 /// *or sub* immediate, that is the target has add or sub instructions which can
14657 /// add a register with the immediate without having to materialize the
14658 /// immediate into a register.
14659 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
14660 // Same encoding for add/sub, just flip the sign.
14661 int64_t AbsImm = std::abs(Imm);
14662 if (!Subtarget->isThumb())
14663 return ARM_AM::getSOImmVal(AbsImm) != -1;
14664 if (Subtarget->isThumb2())
14665 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
14666 // Thumb1 only has 8-bit unsigned immediate.
14667 return AbsImm >= 0 && AbsImm <= 255;
14670 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
14671 bool isSEXTLoad, SDValue &Base,
14672 SDValue &Offset, bool &isInc,
14673 SelectionDAG &DAG) {
14674 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14675 return false;
14677 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
14678 // AddressingMode 3
14679 Base = Ptr->getOperand(0);
14680 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14681 int RHSC = (int)RHS->getZExtValue();
14682 if (RHSC < 0 && RHSC > -256) {
14683 assert(Ptr->getOpcode() == ISD::ADD);
14684 isInc = false;
14685 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14686 return true;
14689 isInc = (Ptr->getOpcode() == ISD::ADD);
14690 Offset = Ptr->getOperand(1);
14691 return true;
14692 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
14693 // AddressingMode 2
14694 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14695 int RHSC = (int)RHS->getZExtValue();
14696 if (RHSC < 0 && RHSC > -0x1000) {
14697 assert(Ptr->getOpcode() == ISD::ADD);
14698 isInc = false;
14699 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14700 Base = Ptr->getOperand(0);
14701 return true;
14705 if (Ptr->getOpcode() == ISD::ADD) {
14706 isInc = true;
14707 ARM_AM::ShiftOpc ShOpcVal=
14708 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
14709 if (ShOpcVal != ARM_AM::no_shift) {
14710 Base = Ptr->getOperand(1);
14711 Offset = Ptr->getOperand(0);
14712 } else {
14713 Base = Ptr->getOperand(0);
14714 Offset = Ptr->getOperand(1);
14716 return true;
14719 isInc = (Ptr->getOpcode() == ISD::ADD);
14720 Base = Ptr->getOperand(0);
14721 Offset = Ptr->getOperand(1);
14722 return true;
14725 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
14726 return false;
14729 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
14730 bool isSEXTLoad, SDValue &Base,
14731 SDValue &Offset, bool &isInc,
14732 SelectionDAG &DAG) {
14733 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14734 return false;
14736 Base = Ptr->getOperand(0);
14737 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
14738 int RHSC = (int)RHS->getZExtValue();
14739 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
14740 assert(Ptr->getOpcode() == ISD::ADD);
14741 isInc = false;
14742 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14743 return true;
14744 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
14745 isInc = Ptr->getOpcode() == ISD::ADD;
14746 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
14747 return true;
14751 return false;
14754 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, unsigned Align,
14755 bool isSEXTLoad, bool isLE, SDValue &Base,
14756 SDValue &Offset, bool &isInc,
14757 SelectionDAG &DAG) {
14758 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
14759 return false;
14760 if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
14761 return false;
14763 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
14764 int RHSC = (int)RHS->getZExtValue();
14766 auto IsInRange = [&](int RHSC, int Limit, int Scale) {
14767 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
14768 assert(Ptr->getOpcode() == ISD::ADD);
14769 isInc = false;
14770 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
14771 return true;
14772 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
14773 isInc = Ptr->getOpcode() == ISD::ADD;
14774 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
14775 return true;
14777 return false;
14780 // Try to find a matching instruction based on s/zext, Alignment, Offset and
14781 // (in BE) type.
14782 Base = Ptr->getOperand(0);
14783 if (VT == MVT::v4i16) {
14784 if (Align >= 2 && IsInRange(RHSC, 0x80, 2))
14785 return true;
14786 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
14787 if (IsInRange(RHSC, 0x80, 1))
14788 return true;
14789 } else if (Align >= 4 && (isLE || VT == MVT::v4i32 || VT == MVT::v4f32) &&
14790 IsInRange(RHSC, 0x80, 4))
14791 return true;
14792 else if (Align >= 2 && (isLE || VT == MVT::v8i16 || VT == MVT::v8f16) &&
14793 IsInRange(RHSC, 0x80, 2))
14794 return true;
14795 else if ((isLE || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
14796 return true;
14797 return false;
14800 /// getPreIndexedAddressParts - returns true by value, base pointer and
14801 /// offset pointer and addressing mode by reference if the node's address
14802 /// can be legally represented as pre-indexed load / store address.
14803 bool
14804 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
14805 SDValue &Offset,
14806 ISD::MemIndexedMode &AM,
14807 SelectionDAG &DAG) const {
14808 if (Subtarget->isThumb1Only())
14809 return false;
14811 EVT VT;
14812 SDValue Ptr;
14813 unsigned Align;
14814 bool isSEXTLoad = false;
14815 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14816 Ptr = LD->getBasePtr();
14817 VT = LD->getMemoryVT();
14818 Align = LD->getAlignment();
14819 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
14820 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14821 Ptr = ST->getBasePtr();
14822 VT = ST->getMemoryVT();
14823 Align = ST->getAlignment();
14824 } else
14825 return false;
14827 bool isInc;
14828 bool isLegal = false;
14829 if (VT.isVector())
14830 isLegal = Subtarget->hasMVEIntegerOps() &&
14831 getMVEIndexedAddressParts(Ptr.getNode(), VT, Align, isSEXTLoad,
14832 Subtarget->isLittle(), Base, Offset,
14833 isInc, DAG);
14834 else {
14835 if (Subtarget->isThumb2())
14836 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
14837 Offset, isInc, DAG);
14838 else
14839 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
14840 Offset, isInc, DAG);
14842 if (!isLegal)
14843 return false;
14845 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
14846 return true;
14849 /// getPostIndexedAddressParts - returns true by value, base pointer and
14850 /// offset pointer and addressing mode by reference if this node can be
14851 /// combined with a load / store to form a post-indexed load / store.
14852 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
14853 SDValue &Base,
14854 SDValue &Offset,
14855 ISD::MemIndexedMode &AM,
14856 SelectionDAG &DAG) const {
14857 EVT VT;
14858 SDValue Ptr;
14859 unsigned Align;
14860 bool isSEXTLoad = false, isNonExt;
14861 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14862 VT = LD->getMemoryVT();
14863 Ptr = LD->getBasePtr();
14864 Align = LD->getAlignment();
14865 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
14866 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
14867 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14868 VT = ST->getMemoryVT();
14869 Ptr = ST->getBasePtr();
14870 Align = ST->getAlignment();
14871 isNonExt = !ST->isTruncatingStore();
14872 } else
14873 return false;
14875 if (Subtarget->isThumb1Only()) {
14876 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
14877 // must be non-extending/truncating, i32, with an offset of 4.
14878 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
14879 if (Op->getOpcode() != ISD::ADD || !isNonExt)
14880 return false;
14881 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
14882 if (!RHS || RHS->getZExtValue() != 4)
14883 return false;
14885 Offset = Op->getOperand(1);
14886 Base = Op->getOperand(0);
14887 AM = ISD::POST_INC;
14888 return true;
14891 bool isInc;
14892 bool isLegal = false;
14893 if (VT.isVector())
14894 isLegal = Subtarget->hasMVEIntegerOps() &&
14895 getMVEIndexedAddressParts(Op, VT, Align, isSEXTLoad,
14896 Subtarget->isLittle(), Base, Offset,
14897 isInc, DAG);
14898 else {
14899 if (Subtarget->isThumb2())
14900 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
14901 isInc, DAG);
14902 else
14903 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
14904 isInc, DAG);
14906 if (!isLegal)
14907 return false;
14909 if (Ptr != Base) {
14910 // Swap base ptr and offset to catch more post-index load / store when
14911 // it's legal. In Thumb2 mode, offset must be an immediate.
14912 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
14913 !Subtarget->isThumb2())
14914 std::swap(Base, Offset);
14916 // Post-indexed load / store update the base pointer.
14917 if (Ptr != Base)
14918 return false;
14921 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
14922 return true;
14925 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14926 KnownBits &Known,
14927 const APInt &DemandedElts,
14928 const SelectionDAG &DAG,
14929 unsigned Depth) const {
14930 unsigned BitWidth = Known.getBitWidth();
14931 Known.resetAll();
14932 switch (Op.getOpcode()) {
14933 default: break;
14934 case ARMISD::ADDC:
14935 case ARMISD::ADDE:
14936 case ARMISD::SUBC:
14937 case ARMISD::SUBE:
14938 // Special cases when we convert a carry to a boolean.
14939 if (Op.getResNo() == 0) {
14940 SDValue LHS = Op.getOperand(0);
14941 SDValue RHS = Op.getOperand(1);
14942 // (ADDE 0, 0, C) will give us a single bit.
14943 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
14944 isNullConstant(RHS)) {
14945 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14946 return;
14949 break;
14950 case ARMISD::CMOV: {
14951 // Bits are known zero/one if known on the LHS and RHS.
14952 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
14953 if (Known.isUnknown())
14954 return;
14956 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
14957 Known.Zero &= KnownRHS.Zero;
14958 Known.One &= KnownRHS.One;
14959 return;
14961 case ISD::INTRINSIC_W_CHAIN: {
14962 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
14963 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
14964 switch (IntID) {
14965 default: return;
14966 case Intrinsic::arm_ldaex:
14967 case Intrinsic::arm_ldrex: {
14968 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
14969 unsigned MemBits = VT.getScalarSizeInBits();
14970 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
14971 return;
14975 case ARMISD::BFI: {
14976 // Conservatively, we can recurse down the first operand
14977 // and just mask out all affected bits.
14978 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
14980 // The operand to BFI is already a mask suitable for removing the bits it
14981 // sets.
14982 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
14983 const APInt &Mask = CI->getAPIntValue();
14984 Known.Zero &= Mask;
14985 Known.One &= Mask;
14986 return;
14988 case ARMISD::VGETLANEs:
14989 case ARMISD::VGETLANEu: {
14990 const SDValue &SrcSV = Op.getOperand(0);
14991 EVT VecVT = SrcSV.getValueType();
14992 assert(VecVT.isVector() && "VGETLANE expected a vector type");
14993 const unsigned NumSrcElts = VecVT.getVectorNumElements();
14994 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
14995 assert(Pos->getAPIntValue().ult(NumSrcElts) &&
14996 "VGETLANE index out of bounds");
14997 unsigned Idx = Pos->getZExtValue();
14998 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
14999 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
15001 EVT VT = Op.getValueType();
15002 const unsigned DstSz = VT.getScalarSizeInBits();
15003 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
15004 (void)SrcSz;
15005 assert(SrcSz == Known.getBitWidth());
15006 assert(DstSz > SrcSz);
15007 if (Op.getOpcode() == ARMISD::VGETLANEs)
15008 Known = Known.sext(DstSz);
15009 else {
15010 Known = Known.zext(DstSz, true /* extended bits are known zero */);
15012 assert(DstSz == Known.getBitWidth());
15013 break;
15018 bool
15019 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
15020 const APInt &DemandedAPInt,
15021 TargetLoweringOpt &TLO) const {
15022 // Delay optimization, so we don't have to deal with illegal types, or block
15023 // optimizations.
15024 if (!TLO.LegalOps)
15025 return false;
15027 // Only optimize AND for now.
15028 if (Op.getOpcode() != ISD::AND)
15029 return false;
15031 EVT VT = Op.getValueType();
15033 // Ignore vectors.
15034 if (VT.isVector())
15035 return false;
15037 assert(VT == MVT::i32 && "Unexpected integer type");
15039 // Make sure the RHS really is a constant.
15040 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15041 if (!C)
15042 return false;
15044 unsigned Mask = C->getZExtValue();
15046 unsigned Demanded = DemandedAPInt.getZExtValue();
15047 unsigned ShrunkMask = Mask & Demanded;
15048 unsigned ExpandedMask = Mask | ~Demanded;
15050 // If the mask is all zeros, let the target-independent code replace the
15051 // result with zero.
15052 if (ShrunkMask == 0)
15053 return false;
15055 // If the mask is all ones, erase the AND. (Currently, the target-independent
15056 // code won't do this, so we have to do it explicitly to avoid an infinite
15057 // loop in obscure cases.)
15058 if (ExpandedMask == ~0U)
15059 return TLO.CombineTo(Op, Op.getOperand(0));
15061 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
15062 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
15064 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
15065 if (NewMask == Mask)
15066 return true;
15067 SDLoc DL(Op);
15068 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
15069 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
15070 return TLO.CombineTo(Op, NewOp);
15073 // Prefer uxtb mask.
15074 if (IsLegalMask(0xFF))
15075 return UseMask(0xFF);
15077 // Prefer uxth mask.
15078 if (IsLegalMask(0xFFFF))
15079 return UseMask(0xFFFF);
15081 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
15082 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15083 if (ShrunkMask < 256)
15084 return UseMask(ShrunkMask);
15086 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
15087 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15088 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
15089 return UseMask(ExpandedMask);
15091 // Potential improvements:
15093 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
15094 // We could try to prefer Thumb1 immediates which can be lowered to a
15095 // two-instruction sequence.
15096 // We could try to recognize more legal ARM/Thumb2 immediates here.
15098 return false;
15102 //===----------------------------------------------------------------------===//
15103 // ARM Inline Assembly Support
15104 //===----------------------------------------------------------------------===//
15106 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
15107 // Looking for "rev" which is V6+.
15108 if (!Subtarget->hasV6Ops())
15109 return false;
15111 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15112 std::string AsmStr = IA->getAsmString();
15113 SmallVector<StringRef, 4> AsmPieces;
15114 SplitString(AsmStr, AsmPieces, ";\n");
15116 switch (AsmPieces.size()) {
15117 default: return false;
15118 case 1:
15119 AsmStr = AsmPieces[0];
15120 AsmPieces.clear();
15121 SplitString(AsmStr, AsmPieces, " \t,");
15123 // rev $0, $1
15124 if (AsmPieces.size() == 3 &&
15125 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
15126 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
15127 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15128 if (Ty && Ty->getBitWidth() == 32)
15129 return IntrinsicLowering::LowerToByteSwap(CI);
15131 break;
15134 return false;
15137 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
15138 // At this point, we have to lower this constraint to something else, so we
15139 // lower it to an "r" or "w". However, by doing this we will force the result
15140 // to be in register, while the X constraint is much more permissive.
15142 // Although we are correct (we are free to emit anything, without
15143 // constraints), we might break use cases that would expect us to be more
15144 // efficient and emit something else.
15145 if (!Subtarget->hasVFP2Base())
15146 return "r";
15147 if (ConstraintVT.isFloatingPoint())
15148 return "w";
15149 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
15150 (ConstraintVT.getSizeInBits() == 64 ||
15151 ConstraintVT.getSizeInBits() == 128))
15152 return "w";
15154 return "r";
15157 /// getConstraintType - Given a constraint letter, return the type of
15158 /// constraint it is for this target.
15159 ARMTargetLowering::ConstraintType
15160 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
15161 unsigned S = Constraint.size();
15162 if (S == 1) {
15163 switch (Constraint[0]) {
15164 default: break;
15165 case 'l': return C_RegisterClass;
15166 case 'w': return C_RegisterClass;
15167 case 'h': return C_RegisterClass;
15168 case 'x': return C_RegisterClass;
15169 case 't': return C_RegisterClass;
15170 case 'j': return C_Immediate; // Constant for movw.
15171 // An address with a single base register. Due to the way we
15172 // currently handle addresses it is the same as an 'r' memory constraint.
15173 case 'Q': return C_Memory;
15175 } else if (S == 2) {
15176 switch (Constraint[0]) {
15177 default: break;
15178 case 'T': return C_RegisterClass;
15179 // All 'U+' constraints are addresses.
15180 case 'U': return C_Memory;
15183 return TargetLowering::getConstraintType(Constraint);
15186 /// Examine constraint type and operand type and determine a weight value.
15187 /// This object must already have been set up with the operand type
15188 /// and the current alternative constraint selected.
15189 TargetLowering::ConstraintWeight
15190 ARMTargetLowering::getSingleConstraintMatchWeight(
15191 AsmOperandInfo &info, const char *constraint) const {
15192 ConstraintWeight weight = CW_Invalid;
15193 Value *CallOperandVal = info.CallOperandVal;
15194 // If we don't have a value, we can't do a match,
15195 // but allow it at the lowest weight.
15196 if (!CallOperandVal)
15197 return CW_Default;
15198 Type *type = CallOperandVal->getType();
15199 // Look at the constraint type.
15200 switch (*constraint) {
15201 default:
15202 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15203 break;
15204 case 'l':
15205 if (type->isIntegerTy()) {
15206 if (Subtarget->isThumb())
15207 weight = CW_SpecificReg;
15208 else
15209 weight = CW_Register;
15211 break;
15212 case 'w':
15213 if (type->isFloatingPointTy())
15214 weight = CW_Register;
15215 break;
15217 return weight;
15220 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
15222 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
15223 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
15224 switch (Constraint.size()) {
15225 case 1:
15226 // GCC ARM Constraint Letters
15227 switch (Constraint[0]) {
15228 case 'l': // Low regs or general regs.
15229 if (Subtarget->isThumb())
15230 return RCPair(0U, &ARM::tGPRRegClass);
15231 return RCPair(0U, &ARM::GPRRegClass);
15232 case 'h': // High regs or no regs.
15233 if (Subtarget->isThumb())
15234 return RCPair(0U, &ARM::hGPRRegClass);
15235 break;
15236 case 'r':
15237 if (Subtarget->isThumb1Only())
15238 return RCPair(0U, &ARM::tGPRRegClass);
15239 return RCPair(0U, &ARM::GPRRegClass);
15240 case 'w':
15241 if (VT == MVT::Other)
15242 break;
15243 if (VT == MVT::f32)
15244 return RCPair(0U, &ARM::SPRRegClass);
15245 if (VT.getSizeInBits() == 64)
15246 return RCPair(0U, &ARM::DPRRegClass);
15247 if (VT.getSizeInBits() == 128)
15248 return RCPair(0U, &ARM::QPRRegClass);
15249 break;
15250 case 'x':
15251 if (VT == MVT::Other)
15252 break;
15253 if (VT == MVT::f32)
15254 return RCPair(0U, &ARM::SPR_8RegClass);
15255 if (VT.getSizeInBits() == 64)
15256 return RCPair(0U, &ARM::DPR_8RegClass);
15257 if (VT.getSizeInBits() == 128)
15258 return RCPair(0U, &ARM::QPR_8RegClass);
15259 break;
15260 case 't':
15261 if (VT == MVT::Other)
15262 break;
15263 if (VT == MVT::f32 || VT == MVT::i32)
15264 return RCPair(0U, &ARM::SPRRegClass);
15265 if (VT.getSizeInBits() == 64)
15266 return RCPair(0U, &ARM::DPR_VFP2RegClass);
15267 if (VT.getSizeInBits() == 128)
15268 return RCPair(0U, &ARM::QPR_VFP2RegClass);
15269 break;
15271 break;
15273 case 2:
15274 if (Constraint[0] == 'T') {
15275 switch (Constraint[1]) {
15276 default:
15277 break;
15278 case 'e':
15279 return RCPair(0U, &ARM::tGPREvenRegClass);
15280 case 'o':
15281 return RCPair(0U, &ARM::tGPROddRegClass);
15284 break;
15286 default:
15287 break;
15290 if (StringRef("{cc}").equals_lower(Constraint))
15291 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
15293 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15296 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15297 /// vector. If it is invalid, don't add anything to Ops.
15298 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15299 std::string &Constraint,
15300 std::vector<SDValue>&Ops,
15301 SelectionDAG &DAG) const {
15302 SDValue Result;
15304 // Currently only support length 1 constraints.
15305 if (Constraint.length() != 1) return;
15307 char ConstraintLetter = Constraint[0];
15308 switch (ConstraintLetter) {
15309 default: break;
15310 case 'j':
15311 case 'I': case 'J': case 'K': case 'L':
15312 case 'M': case 'N': case 'O':
15313 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
15314 if (!C)
15315 return;
15317 int64_t CVal64 = C->getSExtValue();
15318 int CVal = (int) CVal64;
15319 // None of these constraints allow values larger than 32 bits. Check
15320 // that the value fits in an int.
15321 if (CVal != CVal64)
15322 return;
15324 switch (ConstraintLetter) {
15325 case 'j':
15326 // Constant suitable for movw, must be between 0 and
15327 // 65535.
15328 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
15329 if (CVal >= 0 && CVal <= 65535)
15330 break;
15331 return;
15332 case 'I':
15333 if (Subtarget->isThumb1Only()) {
15334 // This must be a constant between 0 and 255, for ADD
15335 // immediates.
15336 if (CVal >= 0 && CVal <= 255)
15337 break;
15338 } else if (Subtarget->isThumb2()) {
15339 // A constant that can be used as an immediate value in a
15340 // data-processing instruction.
15341 if (ARM_AM::getT2SOImmVal(CVal) != -1)
15342 break;
15343 } else {
15344 // A constant that can be used as an immediate value in a
15345 // data-processing instruction.
15346 if (ARM_AM::getSOImmVal(CVal) != -1)
15347 break;
15349 return;
15351 case 'J':
15352 if (Subtarget->isThumb1Only()) {
15353 // This must be a constant between -255 and -1, for negated ADD
15354 // immediates. This can be used in GCC with an "n" modifier that
15355 // prints the negated value, for use with SUB instructions. It is
15356 // not useful otherwise but is implemented for compatibility.
15357 if (CVal >= -255 && CVal <= -1)
15358 break;
15359 } else {
15360 // This must be a constant between -4095 and 4095. It is not clear
15361 // what this constraint is intended for. Implemented for
15362 // compatibility with GCC.
15363 if (CVal >= -4095 && CVal <= 4095)
15364 break;
15366 return;
15368 case 'K':
15369 if (Subtarget->isThumb1Only()) {
15370 // A 32-bit value where only one byte has a nonzero value. Exclude
15371 // zero to match GCC. This constraint is used by GCC internally for
15372 // constants that can be loaded with a move/shift combination.
15373 // It is not useful otherwise but is implemented for compatibility.
15374 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
15375 break;
15376 } else if (Subtarget->isThumb2()) {
15377 // A constant whose bitwise inverse can be used as an immediate
15378 // value in a data-processing instruction. This can be used in GCC
15379 // with a "B" modifier that prints the inverted value, for use with
15380 // BIC and MVN instructions. It is not useful otherwise but is
15381 // implemented for compatibility.
15382 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
15383 break;
15384 } else {
15385 // A constant whose bitwise inverse can be used as an immediate
15386 // value in a data-processing instruction. This can be used in GCC
15387 // with a "B" modifier that prints the inverted value, for use with
15388 // BIC and MVN instructions. It is not useful otherwise but is
15389 // implemented for compatibility.
15390 if (ARM_AM::getSOImmVal(~CVal) != -1)
15391 break;
15393 return;
15395 case 'L':
15396 if (Subtarget->isThumb1Only()) {
15397 // This must be a constant between -7 and 7,
15398 // for 3-operand ADD/SUB immediate instructions.
15399 if (CVal >= -7 && CVal < 7)
15400 break;
15401 } else if (Subtarget->isThumb2()) {
15402 // A constant whose negation can be used as an immediate value in a
15403 // data-processing instruction. This can be used in GCC with an "n"
15404 // modifier that prints the negated value, for use with SUB
15405 // instructions. It is not useful otherwise but is implemented for
15406 // compatibility.
15407 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
15408 break;
15409 } else {
15410 // A constant whose negation can be used as an immediate value in a
15411 // data-processing instruction. This can be used in GCC with an "n"
15412 // modifier that prints the negated value, for use with SUB
15413 // instructions. It is not useful otherwise but is implemented for
15414 // compatibility.
15415 if (ARM_AM::getSOImmVal(-CVal) != -1)
15416 break;
15418 return;
15420 case 'M':
15421 if (Subtarget->isThumb1Only()) {
15422 // This must be a multiple of 4 between 0 and 1020, for
15423 // ADD sp + immediate.
15424 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
15425 break;
15426 } else {
15427 // A power of two or a constant between 0 and 32. This is used in
15428 // GCC for the shift amount on shifted register operands, but it is
15429 // useful in general for any shift amounts.
15430 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
15431 break;
15433 return;
15435 case 'N':
15436 if (Subtarget->isThumb1Only()) {
15437 // This must be a constant between 0 and 31, for shift amounts.
15438 if (CVal >= 0 && CVal <= 31)
15439 break;
15441 return;
15443 case 'O':
15444 if (Subtarget->isThumb1Only()) {
15445 // This must be a multiple of 4 between -508 and 508, for
15446 // ADD/SUB sp = sp + immediate.
15447 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
15448 break;
15450 return;
15452 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
15453 break;
15456 if (Result.getNode()) {
15457 Ops.push_back(Result);
15458 return;
15460 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15463 static RTLIB::Libcall getDivRemLibcall(
15464 const SDNode *N, MVT::SimpleValueType SVT) {
15465 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15466 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15467 "Unhandled Opcode in getDivRemLibcall");
15468 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15469 N->getOpcode() == ISD::SREM;
15470 RTLIB::Libcall LC;
15471 switch (SVT) {
15472 default: llvm_unreachable("Unexpected request for libcall!");
15473 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
15474 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
15475 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
15476 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
15478 return LC;
15481 static TargetLowering::ArgListTy getDivRemArgList(
15482 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
15483 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15484 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15485 "Unhandled Opcode in getDivRemArgList");
15486 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15487 N->getOpcode() == ISD::SREM;
15488 TargetLowering::ArgListTy Args;
15489 TargetLowering::ArgListEntry Entry;
15490 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15491 EVT ArgVT = N->getOperand(i).getValueType();
15492 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
15493 Entry.Node = N->getOperand(i);
15494 Entry.Ty = ArgTy;
15495 Entry.IsSExt = isSigned;
15496 Entry.IsZExt = !isSigned;
15497 Args.push_back(Entry);
15499 if (Subtarget->isTargetWindows() && Args.size() >= 2)
15500 std::swap(Args[0], Args[1]);
15501 return Args;
15504 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
15505 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
15506 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
15507 Subtarget->isTargetWindows()) &&
15508 "Register-based DivRem lowering only");
15509 unsigned Opcode = Op->getOpcode();
15510 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
15511 "Invalid opcode for Div/Rem lowering");
15512 bool isSigned = (Opcode == ISD::SDIVREM);
15513 EVT VT = Op->getValueType(0);
15514 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
15515 SDLoc dl(Op);
15517 // If the target has hardware divide, use divide + multiply + subtract:
15518 // div = a / b
15519 // rem = a - b * div
15520 // return {div, rem}
15521 // This should be lowered into UDIV/SDIV + MLS later on.
15522 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
15523 : Subtarget->hasDivideInARMMode();
15524 if (hasDivide && Op->getValueType(0).isSimple() &&
15525 Op->getSimpleValueType(0) == MVT::i32) {
15526 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
15527 const SDValue Dividend = Op->getOperand(0);
15528 const SDValue Divisor = Op->getOperand(1);
15529 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
15530 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
15531 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
15533 SDValue Values[2] = {Div, Rem};
15534 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
15537 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
15538 VT.getSimpleVT().SimpleTy);
15539 SDValue InChain = DAG.getEntryNode();
15541 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
15542 DAG.getContext(),
15543 Subtarget);
15545 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15546 getPointerTy(DAG.getDataLayout()));
15548 Type *RetTy = StructType::get(Ty, Ty);
15550 if (Subtarget->isTargetWindows())
15551 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
15553 TargetLowering::CallLoweringInfo CLI(DAG);
15554 CLI.setDebugLoc(dl).setChain(InChain)
15555 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
15556 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15558 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15559 return CallInfo.first;
15562 // Lowers REM using divmod helpers
15563 // see RTABI section 4.2/4.3
15564 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
15565 // Build return types (div and rem)
15566 std::vector<Type*> RetTyParams;
15567 Type *RetTyElement;
15569 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
15570 default: llvm_unreachable("Unexpected request for libcall!");
15571 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
15572 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
15573 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
15574 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
15577 RetTyParams.push_back(RetTyElement);
15578 RetTyParams.push_back(RetTyElement);
15579 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
15580 Type *RetTy = StructType::get(*DAG.getContext(), ret);
15582 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
15583 SimpleTy);
15584 SDValue InChain = DAG.getEntryNode();
15585 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
15586 Subtarget);
15587 bool isSigned = N->getOpcode() == ISD::SREM;
15588 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15589 getPointerTy(DAG.getDataLayout()));
15591 if (Subtarget->isTargetWindows())
15592 InChain = WinDBZCheckDenominator(DAG, N, InChain);
15594 // Lower call
15595 CallLoweringInfo CLI(DAG);
15596 CLI.setChain(InChain)
15597 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
15598 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
15599 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
15601 // Return second (rem) result operand (first contains div)
15602 SDNode *ResNode = CallResult.first.getNode();
15603 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
15604 return ResNode->getOperand(1);
15607 SDValue
15608 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
15609 assert(Subtarget->isTargetWindows() && "unsupported target platform");
15610 SDLoc DL(Op);
15612 // Get the inputs.
15613 SDValue Chain = Op.getOperand(0);
15614 SDValue Size = Op.getOperand(1);
15616 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
15617 "no-stack-arg-probe")) {
15618 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15619 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
15620 Chain = SP.getValue(1);
15621 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
15622 if (Align)
15623 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
15624 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
15625 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
15626 SDValue Ops[2] = { SP, Chain };
15627 return DAG.getMergeValues(Ops, DL);
15630 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
15631 DAG.getConstant(2, DL, MVT::i32));
15633 SDValue Flag;
15634 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
15635 Flag = Chain.getValue(1);
15637 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15638 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
15640 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
15641 Chain = NewSP.getValue(1);
15643 SDValue Ops[2] = { NewSP, Chain };
15644 return DAG.getMergeValues(Ops, DL);
15647 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
15648 SDValue SrcVal = Op.getOperand(0);
15649 const unsigned DstSz = Op.getValueType().getSizeInBits();
15650 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
15651 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
15652 "Unexpected type for custom-lowering FP_EXTEND");
15654 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
15655 "With both FP DP and 16, any FP conversion is legal!");
15657 assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
15658 "With FP16, 16 to 32 conversion is legal!");
15660 // Either we are converting from 16 -> 64, without FP16 and/or
15661 // FP.double-precision or without Armv8-fp. So we must do it in two
15662 // steps.
15663 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
15664 // without FP16. So we must do a function call.
15665 SDLoc Loc(Op);
15666 RTLIB::Libcall LC;
15667 MakeLibCallOptions CallOptions;
15668 if (SrcSz == 16) {
15669 // Instruction from 16 -> 32
15670 if (Subtarget->hasFP16())
15671 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal);
15672 // Lib call from 16 -> 32
15673 else {
15674 LC = RTLIB::getFPEXT(MVT::f16, MVT::f32);
15675 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15676 "Unexpected type for custom-lowering FP_EXTEND");
15677 SrcVal =
15678 makeLibCall(DAG, LC, MVT::f32, SrcVal, CallOptions, Loc).first;
15682 if (DstSz != 64)
15683 return SrcVal;
15684 // For sure now SrcVal is 32 bits
15685 if (Subtarget->hasFP64()) // Instruction from 32 -> 64
15686 return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal);
15688 LC = RTLIB::getFPEXT(MVT::f32, MVT::f64);
15689 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15690 "Unexpected type for custom-lowering FP_EXTEND");
15691 return makeLibCall(DAG, LC, MVT::f64, SrcVal, CallOptions, Loc).first;
15694 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
15695 SDValue SrcVal = Op.getOperand(0);
15696 EVT SrcVT = SrcVal.getValueType();
15697 EVT DstVT = Op.getValueType();
15698 const unsigned DstSz = Op.getValueType().getSizeInBits();
15699 const unsigned SrcSz = SrcVT.getSizeInBits();
15700 (void)DstSz;
15701 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
15702 "Unexpected type for custom-lowering FP_ROUND");
15704 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
15705 "With both FP DP and 16, any FP conversion is legal!");
15707 SDLoc Loc(Op);
15709 // Instruction from 32 -> 16 if hasFP16 is valid
15710 if (SrcSz == 32 && Subtarget->hasFP16())
15711 return Op;
15713 // Lib call from 32 -> 16 / 64 -> [32, 16]
15714 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
15715 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
15716 "Unexpected type for custom-lowering FP_ROUND");
15717 MakeLibCallOptions CallOptions;
15718 return makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, Loc).first;
15721 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
15722 SelectionDAG &DAG) const {
15723 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
15724 MVT HalfT = MVT::i32;
15725 SDLoc dl(N);
15726 SDValue Hi, Lo, Tmp;
15728 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
15729 !isOperationLegalOrCustom(ISD::UADDO, HalfT))
15730 return ;
15732 unsigned OpTypeBits = HalfT.getScalarSizeInBits();
15733 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
15735 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
15736 DAG.getConstant(0, dl, HalfT));
15737 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
15738 DAG.getConstant(1, dl, HalfT));
15740 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
15741 DAG.getConstant(OpTypeBits - 1, dl,
15742 getShiftAmountTy(HalfT, DAG.getDataLayout())));
15743 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
15744 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
15745 SDValue(Lo.getNode(), 1));
15746 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
15747 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
15749 Results.push_back(Lo);
15750 Results.push_back(Hi);
15753 bool
15754 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15755 // The ARM target isn't yet aware of offsets.
15756 return false;
15759 bool ARM::isBitFieldInvertedMask(unsigned v) {
15760 if (v == 0xffffffff)
15761 return false;
15763 // there can be 1's on either or both "outsides", all the "inside"
15764 // bits must be 0's
15765 return isShiftedMask_32(~v);
15768 /// isFPImmLegal - Returns true if the target can instruction select the
15769 /// specified FP immediate natively. If false, the legalizer will
15770 /// materialize the FP immediate as a load from a constant pool.
15771 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15772 bool ForCodeSize) const {
15773 if (!Subtarget->hasVFP3Base())
15774 return false;
15775 if (VT == MVT::f16 && Subtarget->hasFullFP16())
15776 return ARM_AM::getFP16Imm(Imm) != -1;
15777 if (VT == MVT::f32)
15778 return ARM_AM::getFP32Imm(Imm) != -1;
15779 if (VT == MVT::f64 && Subtarget->hasFP64())
15780 return ARM_AM::getFP64Imm(Imm) != -1;
15781 return false;
15784 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
15785 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
15786 /// specified in the intrinsic calls.
15787 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15788 const CallInst &I,
15789 MachineFunction &MF,
15790 unsigned Intrinsic) const {
15791 switch (Intrinsic) {
15792 case Intrinsic::arm_neon_vld1:
15793 case Intrinsic::arm_neon_vld2:
15794 case Intrinsic::arm_neon_vld3:
15795 case Intrinsic::arm_neon_vld4:
15796 case Intrinsic::arm_neon_vld2lane:
15797 case Intrinsic::arm_neon_vld3lane:
15798 case Intrinsic::arm_neon_vld4lane:
15799 case Intrinsic::arm_neon_vld2dup:
15800 case Intrinsic::arm_neon_vld3dup:
15801 case Intrinsic::arm_neon_vld4dup: {
15802 Info.opc = ISD::INTRINSIC_W_CHAIN;
15803 // Conservatively set memVT to the entire set of vectors loaded.
15804 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15805 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
15806 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15807 Info.ptrVal = I.getArgOperand(0);
15808 Info.offset = 0;
15809 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
15810 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
15811 // volatile loads with NEON intrinsics not supported
15812 Info.flags = MachineMemOperand::MOLoad;
15813 return true;
15815 case Intrinsic::arm_neon_vld1x2:
15816 case Intrinsic::arm_neon_vld1x3:
15817 case Intrinsic::arm_neon_vld1x4: {
15818 Info.opc = ISD::INTRINSIC_W_CHAIN;
15819 // Conservatively set memVT to the entire set of vectors loaded.
15820 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15821 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
15822 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15823 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
15824 Info.offset = 0;
15825 Info.align.reset();
15826 // volatile loads with NEON intrinsics not supported
15827 Info.flags = MachineMemOperand::MOLoad;
15828 return true;
15830 case Intrinsic::arm_neon_vst1:
15831 case Intrinsic::arm_neon_vst2:
15832 case Intrinsic::arm_neon_vst3:
15833 case Intrinsic::arm_neon_vst4:
15834 case Intrinsic::arm_neon_vst2lane:
15835 case Intrinsic::arm_neon_vst3lane:
15836 case Intrinsic::arm_neon_vst4lane: {
15837 Info.opc = ISD::INTRINSIC_VOID;
15838 // Conservatively set memVT to the entire set of vectors stored.
15839 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15840 unsigned NumElts = 0;
15841 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
15842 Type *ArgTy = I.getArgOperand(ArgI)->getType();
15843 if (!ArgTy->isVectorTy())
15844 break;
15845 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
15847 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15848 Info.ptrVal = I.getArgOperand(0);
15849 Info.offset = 0;
15850 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
15851 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
15852 // volatile stores with NEON intrinsics not supported
15853 Info.flags = MachineMemOperand::MOStore;
15854 return true;
15856 case Intrinsic::arm_neon_vst1x2:
15857 case Intrinsic::arm_neon_vst1x3:
15858 case Intrinsic::arm_neon_vst1x4: {
15859 Info.opc = ISD::INTRINSIC_VOID;
15860 // Conservatively set memVT to the entire set of vectors stored.
15861 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15862 unsigned NumElts = 0;
15863 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
15864 Type *ArgTy = I.getArgOperand(ArgI)->getType();
15865 if (!ArgTy->isVectorTy())
15866 break;
15867 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
15869 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
15870 Info.ptrVal = I.getArgOperand(0);
15871 Info.offset = 0;
15872 Info.align.reset();
15873 // volatile stores with NEON intrinsics not supported
15874 Info.flags = MachineMemOperand::MOStore;
15875 return true;
15877 case Intrinsic::arm_ldaex:
15878 case Intrinsic::arm_ldrex: {
15879 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15880 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
15881 Info.opc = ISD::INTRINSIC_W_CHAIN;
15882 Info.memVT = MVT::getVT(PtrTy->getElementType());
15883 Info.ptrVal = I.getArgOperand(0);
15884 Info.offset = 0;
15885 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
15886 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
15887 return true;
15889 case Intrinsic::arm_stlex:
15890 case Intrinsic::arm_strex: {
15891 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
15892 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
15893 Info.opc = ISD::INTRINSIC_W_CHAIN;
15894 Info.memVT = MVT::getVT(PtrTy->getElementType());
15895 Info.ptrVal = I.getArgOperand(1);
15896 Info.offset = 0;
15897 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
15898 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
15899 return true;
15901 case Intrinsic::arm_stlexd:
15902 case Intrinsic::arm_strexd:
15903 Info.opc = ISD::INTRINSIC_W_CHAIN;
15904 Info.memVT = MVT::i64;
15905 Info.ptrVal = I.getArgOperand(2);
15906 Info.offset = 0;
15907 Info.align = Align(8);
15908 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
15909 return true;
15911 case Intrinsic::arm_ldaexd:
15912 case Intrinsic::arm_ldrexd:
15913 Info.opc = ISD::INTRINSIC_W_CHAIN;
15914 Info.memVT = MVT::i64;
15915 Info.ptrVal = I.getArgOperand(0);
15916 Info.offset = 0;
15917 Info.align = Align(8);
15918 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
15919 return true;
15921 default:
15922 break;
15925 return false;
15928 /// Returns true if it is beneficial to convert a load of a constant
15929 /// to just the constant itself.
15930 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15931 Type *Ty) const {
15932 assert(Ty->isIntegerTy());
15934 unsigned Bits = Ty->getPrimitiveSizeInBits();
15935 if (Bits == 0 || Bits > 32)
15936 return false;
15937 return true;
15940 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
15941 unsigned Index) const {
15942 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
15943 return false;
15945 return (Index == 0 || Index == ResVT.getVectorNumElements());
15948 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
15949 ARM_MB::MemBOpt Domain) const {
15950 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15952 // First, if the target has no DMB, see what fallback we can use.
15953 if (!Subtarget->hasDataBarrier()) {
15954 // Some ARMv6 cpus can support data barriers with an mcr instruction.
15955 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
15956 // here.
15957 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
15958 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
15959 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
15960 Builder.getInt32(0), Builder.getInt32(7),
15961 Builder.getInt32(10), Builder.getInt32(5)};
15962 return Builder.CreateCall(MCR, args);
15963 } else {
15964 // Instead of using barriers, atomic accesses on these subtargets use
15965 // libcalls.
15966 llvm_unreachable("makeDMB on a target so old that it has no barriers");
15968 } else {
15969 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
15970 // Only a full system barrier exists in the M-class architectures.
15971 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
15972 Constant *CDomain = Builder.getInt32(Domain);
15973 return Builder.CreateCall(DMB, CDomain);
15977 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
15978 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
15979 Instruction *Inst,
15980 AtomicOrdering Ord) const {
15981 switch (Ord) {
15982 case AtomicOrdering::NotAtomic:
15983 case AtomicOrdering::Unordered:
15984 llvm_unreachable("Invalid fence: unordered/non-atomic");
15985 case AtomicOrdering::Monotonic:
15986 case AtomicOrdering::Acquire:
15987 return nullptr; // Nothing to do
15988 case AtomicOrdering::SequentiallyConsistent:
15989 if (!Inst->hasAtomicStore())
15990 return nullptr; // Nothing to do
15991 LLVM_FALLTHROUGH;
15992 case AtomicOrdering::Release:
15993 case AtomicOrdering::AcquireRelease:
15994 if (Subtarget->preferISHSTBarriers())
15995 return makeDMB(Builder, ARM_MB::ISHST);
15996 // FIXME: add a comment with a link to documentation justifying this.
15997 else
15998 return makeDMB(Builder, ARM_MB::ISH);
16000 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
16003 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
16004 Instruction *Inst,
16005 AtomicOrdering Ord) const {
16006 switch (Ord) {
16007 case AtomicOrdering::NotAtomic:
16008 case AtomicOrdering::Unordered:
16009 llvm_unreachable("Invalid fence: unordered/not-atomic");
16010 case AtomicOrdering::Monotonic:
16011 case AtomicOrdering::Release:
16012 return nullptr; // Nothing to do
16013 case AtomicOrdering::Acquire:
16014 case AtomicOrdering::AcquireRelease:
16015 case AtomicOrdering::SequentiallyConsistent:
16016 return makeDMB(Builder, ARM_MB::ISH);
16018 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
16021 // Loads and stores less than 64-bits are already atomic; ones above that
16022 // are doomed anyway, so defer to the default libcall and blame the OS when
16023 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
16024 // anything for those.
16025 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16026 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
16027 return (Size == 64) && !Subtarget->isMClass();
16030 // Loads and stores less than 64-bits are already atomic; ones above that
16031 // are doomed anyway, so defer to the default libcall and blame the OS when
16032 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
16033 // anything for those.
16034 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
16035 // guarantee, see DDI0406C ARM architecture reference manual,
16036 // sections A8.8.72-74 LDRD)
16037 TargetLowering::AtomicExpansionKind
16038 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16039 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
16040 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
16041 : AtomicExpansionKind::None;
16044 // For the real atomic operations, we have ldrex/strex up to 32 bits,
16045 // and up to 64 bits on the non-M profiles
16046 TargetLowering::AtomicExpansionKind
16047 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16048 if (AI->isFloatingPointOperation())
16049 return AtomicExpansionKind::CmpXChg;
16051 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
16052 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
16053 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
16054 ? AtomicExpansionKind::LLSC
16055 : AtomicExpansionKind::None;
16058 TargetLowering::AtomicExpansionKind
16059 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
16060 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
16061 // implement cmpxchg without spilling. If the address being exchanged is also
16062 // on the stack and close enough to the spill slot, this can lead to a
16063 // situation where the monitor always gets cleared and the atomic operation
16064 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
16065 bool HasAtomicCmpXchg =
16066 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
16067 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
16068 return AtomicExpansionKind::LLSC;
16069 return AtomicExpansionKind::None;
16072 bool ARMTargetLowering::shouldInsertFencesForAtomic(
16073 const Instruction *I) const {
16074 return InsertFencesForAtomic;
16077 // This has so far only been implemented for MachO.
16078 bool ARMTargetLowering::useLoadStackGuardNode() const {
16079 return Subtarget->isTargetMachO();
16082 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
16083 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16084 return TargetLowering::insertSSPDeclarations(M);
16086 // MSVC CRT has a global variable holding security cookie.
16087 M.getOrInsertGlobal("__security_cookie",
16088 Type::getInt8PtrTy(M.getContext()));
16090 // MSVC CRT has a function to validate security cookie.
16091 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
16092 "__security_check_cookie", Type::getVoidTy(M.getContext()),
16093 Type::getInt8PtrTy(M.getContext()));
16094 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
16095 F->addAttribute(1, Attribute::AttrKind::InReg);
16098 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
16099 // MSVC CRT has a global variable holding security cookie.
16100 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16101 return M.getGlobalVariable("__security_cookie");
16102 return TargetLowering::getSDagStackGuard(M);
16105 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
16106 // MSVC CRT has a function to validate security cookie.
16107 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16108 return M.getFunction("__security_check_cookie");
16109 return TargetLowering::getSSPStackGuardCheck(M);
16112 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
16113 unsigned &Cost) const {
16114 // If we do not have NEON, vector types are not natively supported.
16115 if (!Subtarget->hasNEON())
16116 return false;
16118 // Floating point values and vector values map to the same register file.
16119 // Therefore, although we could do a store extract of a vector type, this is
16120 // better to leave at float as we have more freedom in the addressing mode for
16121 // those.
16122 if (VectorTy->isFPOrFPVectorTy())
16123 return false;
16125 // If the index is unknown at compile time, this is very expensive to lower
16126 // and it is not possible to combine the store with the extract.
16127 if (!isa<ConstantInt>(Idx))
16128 return false;
16130 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
16131 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
16132 // We can do a store + vector extract on any vector that fits perfectly in a D
16133 // or Q register.
16134 if (BitWidth == 64 || BitWidth == 128) {
16135 Cost = 0;
16136 return true;
16138 return false;
16141 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
16142 return Subtarget->hasV6T2Ops();
16145 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
16146 return Subtarget->hasV6T2Ops();
16149 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
16150 return !Subtarget->hasMinSize();
16153 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
16154 AtomicOrdering Ord) const {
16155 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16156 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
16157 bool IsAcquire = isAcquireOrStronger(Ord);
16159 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
16160 // intrinsic must return {i32, i32} and we have to recombine them into a
16161 // single i64 here.
16162 if (ValTy->getPrimitiveSizeInBits() == 64) {
16163 Intrinsic::ID Int =
16164 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
16165 Function *Ldrex = Intrinsic::getDeclaration(M, Int);
16167 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16168 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
16170 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
16171 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
16172 if (!Subtarget->isLittle())
16173 std::swap (Lo, Hi);
16174 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
16175 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
16176 return Builder.CreateOr(
16177 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
16180 Type *Tys[] = { Addr->getType() };
16181 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
16182 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
16184 return Builder.CreateTruncOrBitCast(
16185 Builder.CreateCall(Ldrex, Addr),
16186 cast<PointerType>(Addr->getType())->getElementType());
16189 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
16190 IRBuilder<> &Builder) const {
16191 if (!Subtarget->hasV7Ops())
16192 return;
16193 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16194 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
16197 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
16198 Value *Addr,
16199 AtomicOrdering Ord) const {
16200 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16201 bool IsRelease = isReleaseOrStronger(Ord);
16203 // Since the intrinsics must have legal type, the i64 intrinsics take two
16204 // parameters: "i32, i32". We must marshal Val into the appropriate form
16205 // before the call.
16206 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
16207 Intrinsic::ID Int =
16208 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
16209 Function *Strex = Intrinsic::getDeclaration(M, Int);
16210 Type *Int32Ty = Type::getInt32Ty(M->getContext());
16212 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
16213 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
16214 if (!Subtarget->isLittle())
16215 std::swap(Lo, Hi);
16216 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16217 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
16220 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
16221 Type *Tys[] = { Addr->getType() };
16222 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
16224 return Builder.CreateCall(
16225 Strex, {Builder.CreateZExtOrBitCast(
16226 Val, Strex->getFunctionType()->getParamType(0)),
16227 Addr});
16231 bool ARMTargetLowering::alignLoopsWithOptSize() const {
16232 return Subtarget->isMClass();
16235 /// A helper function for determining the number of interleaved accesses we
16236 /// will generate when lowering accesses of the given type.
16237 unsigned
16238 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
16239 const DataLayout &DL) const {
16240 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
16243 bool ARMTargetLowering::isLegalInterleavedAccessType(
16244 VectorType *VecTy, const DataLayout &DL) const {
16246 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
16247 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
16249 // Ensure the vector doesn't have f16 elements. Even though we could do an
16250 // i16 vldN, we can't hold the f16 vectors and will end up converting via
16251 // f32.
16252 if (VecTy->getElementType()->isHalfTy())
16253 return false;
16255 // Ensure the number of vector elements is greater than 1.
16256 if (VecTy->getNumElements() < 2)
16257 return false;
16259 // Ensure the element type is legal.
16260 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
16261 return false;
16263 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
16264 // 128 will be split into multiple interleaved accesses.
16265 return VecSize == 64 || VecSize % 128 == 0;
16268 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
16269 if (Subtarget->hasNEON())
16270 return 4;
16271 return TargetLoweringBase::getMaxSupportedInterleaveFactor();
16274 /// Lower an interleaved load into a vldN intrinsic.
16276 /// E.g. Lower an interleaved load (Factor = 2):
16277 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
16278 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
16279 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
16281 /// Into:
16282 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
16283 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
16284 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
16285 bool ARMTargetLowering::lowerInterleavedLoad(
16286 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
16287 ArrayRef<unsigned> Indices, unsigned Factor) const {
16288 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16289 "Invalid interleave factor");
16290 assert(!Shuffles.empty() && "Empty shufflevector input");
16291 assert(Shuffles.size() == Indices.size() &&
16292 "Unmatched number of shufflevectors and indices");
16294 VectorType *VecTy = Shuffles[0]->getType();
16295 Type *EltTy = VecTy->getVectorElementType();
16297 const DataLayout &DL = LI->getModule()->getDataLayout();
16299 // Skip if we do not have NEON and skip illegal vector types. We can
16300 // "legalize" wide vector types into multiple interleaved accesses as long as
16301 // the vector types are divisible by 128.
16302 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
16303 return false;
16305 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
16307 // A pointer vector can not be the return type of the ldN intrinsics. Need to
16308 // load integer vectors first and then convert to pointer vectors.
16309 if (EltTy->isPointerTy())
16310 VecTy =
16311 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
16313 IRBuilder<> Builder(LI);
16315 // The base address of the load.
16316 Value *BaseAddr = LI->getPointerOperand();
16318 if (NumLoads > 1) {
16319 // If we're going to generate more than one load, reset the sub-vector type
16320 // to something legal.
16321 VecTy = VectorType::get(VecTy->getVectorElementType(),
16322 VecTy->getVectorNumElements() / NumLoads);
16324 // We will compute the pointer operand of each load from the original base
16325 // address using GEPs. Cast the base address to a pointer to the scalar
16326 // element type.
16327 BaseAddr = Builder.CreateBitCast(
16328 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
16329 LI->getPointerAddressSpace()));
16332 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
16334 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
16335 Type *Tys[] = {VecTy, Int8Ptr};
16336 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
16337 Intrinsic::arm_neon_vld3,
16338 Intrinsic::arm_neon_vld4};
16339 Function *VldnFunc =
16340 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
16342 // Holds sub-vectors extracted from the load intrinsic return values. The
16343 // sub-vectors are associated with the shufflevector instructions they will
16344 // replace.
16345 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
16347 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
16348 // If we're generating more than one load, compute the base address of
16349 // subsequent loads as an offset from the previous.
16350 if (LoadCount > 0)
16351 BaseAddr =
16352 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
16353 VecTy->getVectorNumElements() * Factor);
16355 SmallVector<Value *, 2> Ops;
16356 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16357 Ops.push_back(Builder.getInt32(LI->getAlignment()));
16359 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
16361 // Replace uses of each shufflevector with the corresponding vector loaded
16362 // by ldN.
16363 for (unsigned i = 0; i < Shuffles.size(); i++) {
16364 ShuffleVectorInst *SV = Shuffles[i];
16365 unsigned Index = Indices[i];
16367 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
16369 // Convert the integer vector to pointer vector if the element is pointer.
16370 if (EltTy->isPointerTy())
16371 SubVec = Builder.CreateIntToPtr(
16372 SubVec, VectorType::get(SV->getType()->getVectorElementType(),
16373 VecTy->getVectorNumElements()));
16375 SubVecs[SV].push_back(SubVec);
16379 // Replace uses of the shufflevector instructions with the sub-vectors
16380 // returned by the load intrinsic. If a shufflevector instruction is
16381 // associated with more than one sub-vector, those sub-vectors will be
16382 // concatenated into a single wide vector.
16383 for (ShuffleVectorInst *SVI : Shuffles) {
16384 auto &SubVec = SubVecs[SVI];
16385 auto *WideVec =
16386 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
16387 SVI->replaceAllUsesWith(WideVec);
16390 return true;
16393 /// Lower an interleaved store into a vstN intrinsic.
16395 /// E.g. Lower an interleaved store (Factor = 3):
16396 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
16397 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
16398 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
16400 /// Into:
16401 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
16402 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
16403 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
16404 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16406 /// Note that the new shufflevectors will be removed and we'll only generate one
16407 /// vst3 instruction in CodeGen.
16409 /// Example for a more general valid mask (Factor 3). Lower:
16410 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
16411 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
16412 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
16414 /// Into:
16415 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
16416 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
16417 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
16418 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16419 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
16420 ShuffleVectorInst *SVI,
16421 unsigned Factor) const {
16422 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16423 "Invalid interleave factor");
16425 VectorType *VecTy = SVI->getType();
16426 assert(VecTy->getVectorNumElements() % Factor == 0 &&
16427 "Invalid interleaved store");
16429 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
16430 Type *EltTy = VecTy->getVectorElementType();
16431 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
16433 const DataLayout &DL = SI->getModule()->getDataLayout();
16435 // Skip if we do not have NEON and skip illegal vector types. We can
16436 // "legalize" wide vector types into multiple interleaved accesses as long as
16437 // the vector types are divisible by 128.
16438 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
16439 return false;
16441 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
16443 Value *Op0 = SVI->getOperand(0);
16444 Value *Op1 = SVI->getOperand(1);
16445 IRBuilder<> Builder(SI);
16447 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
16448 // vectors to integer vectors.
16449 if (EltTy->isPointerTy()) {
16450 Type *IntTy = DL.getIntPtrType(EltTy);
16452 // Convert to the corresponding integer vector.
16453 Type *IntVecTy =
16454 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
16455 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
16456 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
16458 SubVecTy = VectorType::get(IntTy, LaneLen);
16461 // The base address of the store.
16462 Value *BaseAddr = SI->getPointerOperand();
16464 if (NumStores > 1) {
16465 // If we're going to generate more than one store, reset the lane length
16466 // and sub-vector type to something legal.
16467 LaneLen /= NumStores;
16468 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
16470 // We will compute the pointer operand of each store from the original base
16471 // address using GEPs. Cast the base address to a pointer to the scalar
16472 // element type.
16473 BaseAddr = Builder.CreateBitCast(
16474 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
16475 SI->getPointerAddressSpace()));
16478 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
16480 auto Mask = SVI->getShuffleMask();
16482 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
16483 Type *Tys[] = {Int8Ptr, SubVecTy};
16484 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
16485 Intrinsic::arm_neon_vst3,
16486 Intrinsic::arm_neon_vst4};
16488 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
16489 // If we generating more than one store, we compute the base address of
16490 // subsequent stores as an offset from the previous.
16491 if (StoreCount > 0)
16492 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
16493 BaseAddr, LaneLen * Factor);
16495 SmallVector<Value *, 6> Ops;
16496 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16498 Function *VstNFunc =
16499 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
16501 // Split the shufflevector operands into sub vectors for the new vstN call.
16502 for (unsigned i = 0; i < Factor; i++) {
16503 unsigned IdxI = StoreCount * LaneLen * Factor + i;
16504 if (Mask[IdxI] >= 0) {
16505 Ops.push_back(Builder.CreateShuffleVector(
16506 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
16507 } else {
16508 unsigned StartMask = 0;
16509 for (unsigned j = 1; j < LaneLen; j++) {
16510 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
16511 if (Mask[IdxJ * Factor + IdxI] >= 0) {
16512 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
16513 break;
16516 // Note: If all elements in a chunk are undefs, StartMask=0!
16517 // Note: Filling undef gaps with random elements is ok, since
16518 // those elements were being written anyway (with undefs).
16519 // In the case of all undefs we're defaulting to using elems from 0
16520 // Note: StartMask cannot be negative, it's checked in
16521 // isReInterleaveMask
16522 Ops.push_back(Builder.CreateShuffleVector(
16523 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
16527 Ops.push_back(Builder.getInt32(SI->getAlignment()));
16528 Builder.CreateCall(VstNFunc, Ops);
16530 return true;
16533 enum HABaseType {
16534 HA_UNKNOWN = 0,
16535 HA_FLOAT,
16536 HA_DOUBLE,
16537 HA_VECT64,
16538 HA_VECT128
16541 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
16542 uint64_t &Members) {
16543 if (auto *ST = dyn_cast<StructType>(Ty)) {
16544 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
16545 uint64_t SubMembers = 0;
16546 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
16547 return false;
16548 Members += SubMembers;
16550 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
16551 uint64_t SubMembers = 0;
16552 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
16553 return false;
16554 Members += SubMembers * AT->getNumElements();
16555 } else if (Ty->isFloatTy()) {
16556 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
16557 return false;
16558 Members = 1;
16559 Base = HA_FLOAT;
16560 } else if (Ty->isDoubleTy()) {
16561 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
16562 return false;
16563 Members = 1;
16564 Base = HA_DOUBLE;
16565 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
16566 Members = 1;
16567 switch (Base) {
16568 case HA_FLOAT:
16569 case HA_DOUBLE:
16570 return false;
16571 case HA_VECT64:
16572 return VT->getBitWidth() == 64;
16573 case HA_VECT128:
16574 return VT->getBitWidth() == 128;
16575 case HA_UNKNOWN:
16576 switch (VT->getBitWidth()) {
16577 case 64:
16578 Base = HA_VECT64;
16579 return true;
16580 case 128:
16581 Base = HA_VECT128;
16582 return true;
16583 default:
16584 return false;
16589 return (Members > 0 && Members <= 4);
16592 /// Return the correct alignment for the current calling convention.
16593 unsigned
16594 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
16595 DataLayout DL) const {
16596 if (!ArgTy->isVectorTy())
16597 return DL.getABITypeAlignment(ArgTy);
16599 // Avoid over-aligning vector parameters. It would require realigning the
16600 // stack and waste space for no real benefit.
16601 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment());
16604 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
16605 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
16606 /// passing according to AAPCS rules.
16607 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
16608 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
16609 if (getEffectiveCallingConv(CallConv, isVarArg) !=
16610 CallingConv::ARM_AAPCS_VFP)
16611 return false;
16613 HABaseType Base = HA_UNKNOWN;
16614 uint64_t Members = 0;
16615 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
16616 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
16618 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
16619 return IsHA || IsIntArray;
16622 unsigned ARMTargetLowering::getExceptionPointerRegister(
16623 const Constant *PersonalityFn) const {
16624 // Platforms which do not use SjLj EH may return values in these registers
16625 // via the personality function.
16626 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
16629 unsigned ARMTargetLowering::getExceptionSelectorRegister(
16630 const Constant *PersonalityFn) const {
16631 // Platforms which do not use SjLj EH may return values in these registers
16632 // via the personality function.
16633 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
16636 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
16637 // Update IsSplitCSR in ARMFunctionInfo.
16638 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
16639 AFI->setIsSplitCSR(true);
16642 void ARMTargetLowering::insertCopiesSplitCSR(
16643 MachineBasicBlock *Entry,
16644 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
16645 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
16646 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
16647 if (!IStart)
16648 return;
16650 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
16651 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
16652 MachineBasicBlock::iterator MBBI = Entry->begin();
16653 for (const MCPhysReg *I = IStart; *I; ++I) {
16654 const TargetRegisterClass *RC = nullptr;
16655 if (ARM::GPRRegClass.contains(*I))
16656 RC = &ARM::GPRRegClass;
16657 else if (ARM::DPRRegClass.contains(*I))
16658 RC = &ARM::DPRRegClass;
16659 else
16660 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
16662 Register NewVR = MRI->createVirtualRegister(RC);
16663 // Create copy from CSR to a virtual register.
16664 // FIXME: this currently does not emit CFI pseudo-instructions, it works
16665 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
16666 // nounwind. If we want to generalize this later, we may need to emit
16667 // CFI pseudo-instructions.
16668 assert(Entry->getParent()->getFunction().hasFnAttribute(
16669 Attribute::NoUnwind) &&
16670 "Function should be nounwind in insertCopiesSplitCSR!");
16671 Entry->addLiveIn(*I);
16672 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
16673 .addReg(*I);
16675 // Insert the copy-back instructions right before the terminator.
16676 for (auto *Exit : Exits)
16677 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
16678 TII->get(TargetOpcode::COPY), *I)
16679 .addReg(NewVR);
16683 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
16684 MF.getFrameInfo().computeMaxCallFrameSize(MF);
16685 TargetLoweringBase::finalizeLowering(MF);