[ARM] Lower sadd_sat to qadd8 and qadd16
[llvm-complete.git] / lib / Target / ARM / ARMISelLowering.cpp
blob8fac2435951375d1645dc0de76f2b9a170c84254
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);
262 setOperationAction(ISD::MLOAD, VT, Custom);
263 setOperationAction(ISD::MSTORE, VT, Legal);
264 setOperationAction(ISD::CTLZ, VT, Legal);
265 setOperationAction(ISD::CTTZ, VT, Custom);
266 setOperationAction(ISD::BITREVERSE, VT, Legal);
267 setOperationAction(ISD::BSWAP, VT, Legal);
268 setOperationAction(ISD::SADDSAT, VT, Legal);
269 setOperationAction(ISD::UADDSAT, VT, Legal);
270 setOperationAction(ISD::SSUBSAT, VT, Legal);
271 setOperationAction(ISD::USUBSAT, VT, Legal);
273 // No native support for these.
274 setOperationAction(ISD::UDIV, VT, Expand);
275 setOperationAction(ISD::SDIV, VT, Expand);
276 setOperationAction(ISD::UREM, VT, Expand);
277 setOperationAction(ISD::SREM, VT, Expand);
278 setOperationAction(ISD::CTPOP, VT, Expand);
280 // Vector reductions
281 setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
282 setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal);
283 setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal);
284 setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal);
285 setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal);
287 if (!HasMVEFP) {
288 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
289 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
290 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
291 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
294 // Pre and Post inc are supported on loads and stores
295 for (unsigned im = (unsigned)ISD::PRE_INC;
296 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
297 setIndexedLoadAction(im, VT, Legal);
298 setIndexedStoreAction(im, VT, Legal);
302 const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
303 for (auto VT : FloatTypes) {
304 addRegisterClass(VT, &ARM::MQPRRegClass);
305 if (!HasMVEFP)
306 setAllExpand(VT);
308 // These are legal or custom whether we have MVE.fp or not
309 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
310 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
311 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
312 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
313 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
314 setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
315 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
316 setOperationAction(ISD::SETCC, VT, Custom);
317 setOperationAction(ISD::MLOAD, VT, Custom);
318 setOperationAction(ISD::MSTORE, VT, Legal);
320 // Pre and Post inc are supported on loads and stores
321 for (unsigned im = (unsigned)ISD::PRE_INC;
322 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
323 setIndexedLoadAction(im, VT, Legal);
324 setIndexedStoreAction(im, VT, Legal);
327 if (HasMVEFP) {
328 setOperationAction(ISD::FMINNUM, VT, Legal);
329 setOperationAction(ISD::FMAXNUM, VT, Legal);
330 setOperationAction(ISD::FROUND, VT, Legal);
332 // No native support for these.
333 setOperationAction(ISD::FDIV, VT, Expand);
334 setOperationAction(ISD::FREM, VT, Expand);
335 setOperationAction(ISD::FSQRT, VT, Expand);
336 setOperationAction(ISD::FSIN, VT, Expand);
337 setOperationAction(ISD::FCOS, VT, Expand);
338 setOperationAction(ISD::FPOW, VT, Expand);
339 setOperationAction(ISD::FLOG, VT, Expand);
340 setOperationAction(ISD::FLOG2, VT, Expand);
341 setOperationAction(ISD::FLOG10, VT, Expand);
342 setOperationAction(ISD::FEXP, VT, Expand);
343 setOperationAction(ISD::FEXP2, VT, Expand);
344 setOperationAction(ISD::FNEARBYINT, VT, Expand);
348 // We 'support' these types up to bitcast/load/store level, regardless of
349 // MVE integer-only / float support. Only doing FP data processing on the FP
350 // vector types is inhibited at integer-only level.
351 const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
352 for (auto VT : LongTypes) {
353 addRegisterClass(VT, &ARM::MQPRRegClass);
354 setAllExpand(VT);
355 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
356 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
357 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
359 // We can do bitwise operations on v2i64 vectors
360 setOperationAction(ISD::AND, MVT::v2i64, Legal);
361 setOperationAction(ISD::OR, MVT::v2i64, Legal);
362 setOperationAction(ISD::XOR, MVT::v2i64, Legal);
364 // It is legal to extload from v4i8 to v4i16 or v4i32.
365 addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
366 addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
367 addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
369 // Some truncating stores are legal too.
370 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
371 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
372 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
374 // Pre and Post inc on these are legal, given the correct extends
375 for (unsigned im = (unsigned)ISD::PRE_INC;
376 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
377 setIndexedLoadAction(im, MVT::v8i8, Legal);
378 setIndexedStoreAction(im, MVT::v8i8, Legal);
379 setIndexedLoadAction(im, MVT::v4i8, Legal);
380 setIndexedStoreAction(im, MVT::v4i8, Legal);
381 setIndexedLoadAction(im, MVT::v4i16, Legal);
382 setIndexedStoreAction(im, MVT::v4i16, Legal);
385 // Predicate types
386 const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1};
387 for (auto VT : pTypes) {
388 addRegisterClass(VT, &ARM::VCCRRegClass);
389 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
390 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
391 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
392 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
393 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
394 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
395 setOperationAction(ISD::SETCC, VT, Custom);
396 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
397 setOperationAction(ISD::LOAD, VT, Custom);
398 setOperationAction(ISD::STORE, VT, Custom);
402 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
403 const ARMSubtarget &STI)
404 : TargetLowering(TM), Subtarget(&STI) {
405 RegInfo = Subtarget->getRegisterInfo();
406 Itins = Subtarget->getInstrItineraryData();
408 setBooleanContents(ZeroOrOneBooleanContent);
409 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
411 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
412 !Subtarget->isTargetWatchOS()) {
413 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
414 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
415 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
416 IsHFTarget ? CallingConv::ARM_AAPCS_VFP
417 : CallingConv::ARM_AAPCS);
420 if (Subtarget->isTargetMachO()) {
421 // Uses VFP for Thumb libfuncs if available.
422 if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
423 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
424 static const struct {
425 const RTLIB::Libcall Op;
426 const char * const Name;
427 const ISD::CondCode Cond;
428 } LibraryCalls[] = {
429 // Single-precision floating-point arithmetic.
430 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
431 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
432 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
433 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
435 // Double-precision floating-point arithmetic.
436 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
437 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
438 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
439 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
441 // Single-precision comparisons.
442 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
443 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
444 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
445 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
446 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
447 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
448 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
449 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
451 // Double-precision comparisons.
452 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
453 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
454 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
455 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
456 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
457 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
458 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
459 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
461 // Floating-point to integer conversions.
462 // i64 conversions are done via library routines even when generating VFP
463 // instructions, so use the same ones.
464 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
465 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
466 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
467 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
469 // Conversions between floating types.
470 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
471 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
473 // Integer to floating-point conversions.
474 // i64 conversions are done via library routines even when generating VFP
475 // instructions, so use the same ones.
476 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
477 // e.g., __floatunsidf vs. __floatunssidfvfp.
478 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
479 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
480 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
481 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
484 for (const auto &LC : LibraryCalls) {
485 setLibcallName(LC.Op, LC.Name);
486 if (LC.Cond != ISD::SETCC_INVALID)
487 setCmpLibcallCC(LC.Op, LC.Cond);
492 // These libcalls are not available in 32-bit.
493 setLibcallName(RTLIB::SHL_I128, nullptr);
494 setLibcallName(RTLIB::SRL_I128, nullptr);
495 setLibcallName(RTLIB::SRA_I128, nullptr);
497 // RTLIB
498 if (Subtarget->isAAPCS_ABI() &&
499 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
500 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
501 static const struct {
502 const RTLIB::Libcall Op;
503 const char * const Name;
504 const CallingConv::ID CC;
505 const ISD::CondCode Cond;
506 } LibraryCalls[] = {
507 // Double-precision floating-point arithmetic helper functions
508 // RTABI chapter 4.1.2, Table 2
509 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
510 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
511 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
512 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
514 // Double-precision floating-point comparison helper functions
515 // RTABI chapter 4.1.2, Table 3
516 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
517 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
518 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
519 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
520 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
521 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
522 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
523 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
525 // Single-precision floating-point arithmetic helper functions
526 // RTABI chapter 4.1.2, Table 4
527 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
528 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
529 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
530 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
532 // Single-precision floating-point comparison helper functions
533 // RTABI chapter 4.1.2, Table 5
534 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
535 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
536 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
537 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
538 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
539 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
540 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
541 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
543 // Floating-point to integer conversions.
544 // RTABI chapter 4.1.2, Table 6
545 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
546 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
547 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
548 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
549 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
550 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
551 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
552 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
554 // Conversions between floating types.
555 // RTABI chapter 4.1.2, Table 7
556 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
557 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
558 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
560 // Integer to floating-point conversions.
561 // RTABI chapter 4.1.2, Table 8
562 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
563 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
564 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
565 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
566 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
567 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
568 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
569 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
571 // Long long helper functions
572 // RTABI chapter 4.2, Table 9
573 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
574 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
575 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
576 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
578 // Integer division functions
579 // RTABI chapter 4.3.1
580 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
581 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
582 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
583 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
584 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
585 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
586 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
587 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
590 for (const auto &LC : LibraryCalls) {
591 setLibcallName(LC.Op, LC.Name);
592 setLibcallCallingConv(LC.Op, LC.CC);
593 if (LC.Cond != ISD::SETCC_INVALID)
594 setCmpLibcallCC(LC.Op, LC.Cond);
597 // EABI dependent RTLIB
598 if (TM.Options.EABIVersion == EABI::EABI4 ||
599 TM.Options.EABIVersion == EABI::EABI5) {
600 static const struct {
601 const RTLIB::Libcall Op;
602 const char *const Name;
603 const CallingConv::ID CC;
604 const ISD::CondCode Cond;
605 } MemOpsLibraryCalls[] = {
606 // Memory operations
607 // RTABI chapter 4.3.4
608 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
609 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
610 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
613 for (const auto &LC : MemOpsLibraryCalls) {
614 setLibcallName(LC.Op, LC.Name);
615 setLibcallCallingConv(LC.Op, LC.CC);
616 if (LC.Cond != ISD::SETCC_INVALID)
617 setCmpLibcallCC(LC.Op, LC.Cond);
622 if (Subtarget->isTargetWindows()) {
623 static const struct {
624 const RTLIB::Libcall Op;
625 const char * const Name;
626 const CallingConv::ID CC;
627 } LibraryCalls[] = {
628 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
629 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
630 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
631 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
632 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
633 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
634 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
635 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
638 for (const auto &LC : LibraryCalls) {
639 setLibcallName(LC.Op, LC.Name);
640 setLibcallCallingConv(LC.Op, LC.CC);
644 // Use divmod compiler-rt calls for iOS 5.0 and later.
645 if (Subtarget->isTargetMachO() &&
646 !(Subtarget->isTargetIOS() &&
647 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
648 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
649 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
652 // The half <-> float conversion functions are always soft-float on
653 // non-watchos platforms, but are needed for some targets which use a
654 // hard-float calling convention by default.
655 if (!Subtarget->isTargetWatchABI()) {
656 if (Subtarget->isAAPCS_ABI()) {
657 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
658 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
659 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
660 } else {
661 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
662 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
663 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
667 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
668 // a __gnu_ prefix (which is the default).
669 if (Subtarget->isTargetAEABI()) {
670 static const struct {
671 const RTLIB::Libcall Op;
672 const char * const Name;
673 const CallingConv::ID CC;
674 } LibraryCalls[] = {
675 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
676 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
677 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
680 for (const auto &LC : LibraryCalls) {
681 setLibcallName(LC.Op, LC.Name);
682 setLibcallCallingConv(LC.Op, LC.CC);
686 if (Subtarget->isThumb1Only())
687 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
688 else
689 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
691 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
692 Subtarget->hasFPRegs()) {
693 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
694 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
695 if (!Subtarget->hasVFP2Base())
696 setAllExpand(MVT::f32);
697 if (!Subtarget->hasFP64())
698 setAllExpand(MVT::f64);
701 if (Subtarget->hasFullFP16()) {
702 addRegisterClass(MVT::f16, &ARM::HPRRegClass);
703 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
704 setOperationAction(ISD::BITCAST, MVT::i32, Custom);
705 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
707 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
708 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
711 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
712 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
713 setTruncStoreAction(VT, InnerVT, Expand);
714 addAllExtLoads(VT, InnerVT, Expand);
717 setOperationAction(ISD::MULHS, VT, Expand);
718 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
719 setOperationAction(ISD::MULHU, VT, Expand);
720 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
722 setOperationAction(ISD::BSWAP, VT, Expand);
725 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
726 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
728 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
729 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
731 if (Subtarget->hasMVEIntegerOps())
732 addMVEVectorTypes(Subtarget->hasMVEFloatOps());
734 // Combine low-overhead loop intrinsics so that we can lower i1 types.
735 if (Subtarget->hasLOB()) {
736 setTargetDAGCombine(ISD::BRCOND);
737 setTargetDAGCombine(ISD::BR_CC);
740 if (Subtarget->hasNEON()) {
741 addDRTypeForNEON(MVT::v2f32);
742 addDRTypeForNEON(MVT::v8i8);
743 addDRTypeForNEON(MVT::v4i16);
744 addDRTypeForNEON(MVT::v2i32);
745 addDRTypeForNEON(MVT::v1i64);
747 addQRTypeForNEON(MVT::v4f32);
748 addQRTypeForNEON(MVT::v2f64);
749 addQRTypeForNEON(MVT::v16i8);
750 addQRTypeForNEON(MVT::v8i16);
751 addQRTypeForNEON(MVT::v4i32);
752 addQRTypeForNEON(MVT::v2i64);
754 if (Subtarget->hasFullFP16()) {
755 addQRTypeForNEON(MVT::v8f16);
756 addDRTypeForNEON(MVT::v4f16);
760 if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
761 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
762 // none of Neon, MVE or VFP supports any arithmetic operations on it.
763 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
764 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
765 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
766 // FIXME: Code duplication: FDIV and FREM are expanded always, see
767 // ARMTargetLowering::addTypeForNEON method for details.
768 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
769 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
770 // FIXME: Create unittest.
771 // In another words, find a way when "copysign" appears in DAG with vector
772 // operands.
773 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
774 // FIXME: Code duplication: SETCC has custom operation action, see
775 // ARMTargetLowering::addTypeForNEON method for details.
776 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
777 // FIXME: Create unittest for FNEG and for FABS.
778 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
779 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
780 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
781 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
782 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
783 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
784 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
785 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
786 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
787 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
788 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
789 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
790 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
791 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
792 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
793 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
794 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
795 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
798 if (Subtarget->hasNEON()) {
799 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
800 // supported for v4f32.
801 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
802 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
803 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
804 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
805 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
806 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
807 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
808 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
809 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
810 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
811 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
812 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
813 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
814 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
816 // Mark v2f32 intrinsics.
817 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
818 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
819 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
820 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
821 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
822 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
823 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
824 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
825 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
826 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
827 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
828 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
829 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
830 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
832 // Neon does not support some operations on v1i64 and v2i64 types.
833 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
834 // Custom handling for some quad-vector types to detect VMULL.
835 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
836 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
837 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
838 // Custom handling for some vector types to avoid expensive expansions
839 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
840 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
841 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
842 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
843 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
844 // a destination type that is wider than the source, and nor does
845 // it have a FP_TO_[SU]INT instruction with a narrower destination than
846 // source.
847 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
848 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
849 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
850 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
851 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
852 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
853 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
854 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
856 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
857 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
859 // NEON does not have single instruction CTPOP for vectors with element
860 // types wider than 8-bits. However, custom lowering can leverage the
861 // v8i8/v16i8 vcnt instruction.
862 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
863 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
864 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
865 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
866 setOperationAction(ISD::CTPOP, MVT::v1i64, Custom);
867 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
869 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
870 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
872 // NEON does not have single instruction CTTZ for vectors.
873 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
874 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
875 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
876 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
878 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
879 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
880 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
881 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
883 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
884 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
885 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
886 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
888 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
889 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
890 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
891 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
893 // NEON only has FMA instructions as of VFP4.
894 if (!Subtarget->hasVFP4Base()) {
895 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
896 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
899 setTargetDAGCombine(ISD::INTRINSIC_VOID);
900 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
901 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
902 setTargetDAGCombine(ISD::SHL);
903 setTargetDAGCombine(ISD::SRL);
904 setTargetDAGCombine(ISD::SRA);
905 setTargetDAGCombine(ISD::FP_TO_SINT);
906 setTargetDAGCombine(ISD::FP_TO_UINT);
907 setTargetDAGCombine(ISD::FDIV);
908 setTargetDAGCombine(ISD::LOAD);
910 // It is legal to extload from v4i8 to v4i16 or v4i32.
911 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
912 MVT::v2i32}) {
913 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
914 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
915 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
916 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
921 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
922 setTargetDAGCombine(ISD::BUILD_VECTOR);
923 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
924 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
925 setTargetDAGCombine(ISD::STORE);
926 setTargetDAGCombine(ISD::SIGN_EXTEND);
927 setTargetDAGCombine(ISD::ZERO_EXTEND);
928 setTargetDAGCombine(ISD::ANY_EXTEND);
931 if (!Subtarget->hasFP64()) {
932 // When targeting a floating-point unit with only single-precision
933 // operations, f64 is legal for the few double-precision instructions which
934 // are present However, no double-precision operations other than moves,
935 // loads and stores are provided by the hardware.
936 setOperationAction(ISD::FADD, MVT::f64, Expand);
937 setOperationAction(ISD::FSUB, MVT::f64, Expand);
938 setOperationAction(ISD::FMUL, MVT::f64, Expand);
939 setOperationAction(ISD::FMA, MVT::f64, Expand);
940 setOperationAction(ISD::FDIV, MVT::f64, Expand);
941 setOperationAction(ISD::FREM, MVT::f64, Expand);
942 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
943 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
944 setOperationAction(ISD::FNEG, MVT::f64, Expand);
945 setOperationAction(ISD::FABS, MVT::f64, Expand);
946 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
947 setOperationAction(ISD::FSIN, MVT::f64, Expand);
948 setOperationAction(ISD::FCOS, MVT::f64, Expand);
949 setOperationAction(ISD::FPOW, MVT::f64, Expand);
950 setOperationAction(ISD::FLOG, MVT::f64, Expand);
951 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
952 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
953 setOperationAction(ISD::FEXP, MVT::f64, Expand);
954 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
955 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
956 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
957 setOperationAction(ISD::FRINT, MVT::f64, Expand);
958 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
959 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
960 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
961 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
962 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
963 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
964 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
965 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
966 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
969 if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
970 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
971 if (Subtarget->hasFullFP16())
972 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
975 if (!Subtarget->hasFP16())
976 setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom);
978 if (!Subtarget->hasFP64())
979 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
981 computeRegisterProperties(Subtarget->getRegisterInfo());
983 // ARM does not have floating-point extending loads.
984 for (MVT VT : MVT::fp_valuetypes()) {
985 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
986 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
989 // ... or truncating stores
990 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
991 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
992 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
994 // ARM does not have i1 sign extending load.
995 for (MVT VT : MVT::integer_valuetypes())
996 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
998 // ARM supports all 4 flavors of integer indexed load / store.
999 if (!Subtarget->isThumb1Only()) {
1000 for (unsigned im = (unsigned)ISD::PRE_INC;
1001 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1002 setIndexedLoadAction(im, MVT::i1, Legal);
1003 setIndexedLoadAction(im, MVT::i8, Legal);
1004 setIndexedLoadAction(im, MVT::i16, Legal);
1005 setIndexedLoadAction(im, MVT::i32, Legal);
1006 setIndexedStoreAction(im, MVT::i1, Legal);
1007 setIndexedStoreAction(im, MVT::i8, Legal);
1008 setIndexedStoreAction(im, MVT::i16, Legal);
1009 setIndexedStoreAction(im, MVT::i32, Legal);
1011 } else {
1012 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
1013 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
1014 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
1017 setOperationAction(ISD::SADDO, MVT::i32, Custom);
1018 setOperationAction(ISD::UADDO, MVT::i32, Custom);
1019 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1020 setOperationAction(ISD::USUBO, MVT::i32, Custom);
1022 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1023 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1024 if (Subtarget->hasDSP()) {
1025 setOperationAction(ISD::SADDSAT, MVT::i8, Custom);
1026 setOperationAction(ISD::SSUBSAT, MVT::i8, Custom);
1027 setOperationAction(ISD::SADDSAT, MVT::i16, Custom);
1028 setOperationAction(ISD::SSUBSAT, MVT::i16, Custom);
1031 // i64 operation support.
1032 setOperationAction(ISD::MUL, MVT::i64, Expand);
1033 setOperationAction(ISD::MULHU, MVT::i32, Expand);
1034 if (Subtarget->isThumb1Only()) {
1035 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1036 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1038 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1039 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1040 setOperationAction(ISD::MULHS, MVT::i32, Expand);
1042 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1043 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1044 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1045 setOperationAction(ISD::SRL, MVT::i64, Custom);
1046 setOperationAction(ISD::SRA, MVT::i64, Custom);
1047 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1048 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1050 // MVE lowers 64 bit shifts to lsll and lsrl
1051 // assuming that ISD::SRL and SRA of i64 are already marked custom
1052 if (Subtarget->hasMVEIntegerOps())
1053 setOperationAction(ISD::SHL, MVT::i64, Custom);
1055 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1056 if (Subtarget->isThumb1Only()) {
1057 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1058 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1059 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1062 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1063 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1065 // ARM does not have ROTL.
1066 setOperationAction(ISD::ROTL, MVT::i32, Expand);
1067 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1068 setOperationAction(ISD::ROTL, VT, Expand);
1069 setOperationAction(ISD::ROTR, VT, Expand);
1071 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
1072 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1073 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1074 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1075 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1078 // @llvm.readcyclecounter requires the Performance Monitors extension.
1079 // Default to the 0 expansion on unsupported platforms.
1080 // FIXME: Technically there are older ARM CPUs that have
1081 // implementation-specific ways of obtaining this information.
1082 if (Subtarget->hasPerfMon())
1083 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1085 // Only ARMv6 has BSWAP.
1086 if (!Subtarget->hasV6Ops())
1087 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1089 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1090 : Subtarget->hasDivideInARMMode();
1091 if (!hasDivide) {
1092 // These are expanded into libcalls if the cpu doesn't have HW divider.
1093 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
1094 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
1097 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1098 setOperationAction(ISD::SDIV, MVT::i32, Custom);
1099 setOperationAction(ISD::UDIV, MVT::i32, Custom);
1101 setOperationAction(ISD::SDIV, MVT::i64, Custom);
1102 setOperationAction(ISD::UDIV, MVT::i64, Custom);
1105 setOperationAction(ISD::SREM, MVT::i32, Expand);
1106 setOperationAction(ISD::UREM, MVT::i32, Expand);
1108 // Register based DivRem for AEABI (RTABI 4.2)
1109 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1110 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1111 Subtarget->isTargetWindows()) {
1112 setOperationAction(ISD::SREM, MVT::i64, Custom);
1113 setOperationAction(ISD::UREM, MVT::i64, Custom);
1114 HasStandaloneRem = false;
1116 if (Subtarget->isTargetWindows()) {
1117 const struct {
1118 const RTLIB::Libcall Op;
1119 const char * const Name;
1120 const CallingConv::ID CC;
1121 } LibraryCalls[] = {
1122 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1123 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1124 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1125 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1127 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1128 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1129 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1130 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1133 for (const auto &LC : LibraryCalls) {
1134 setLibcallName(LC.Op, LC.Name);
1135 setLibcallCallingConv(LC.Op, LC.CC);
1137 } else {
1138 const struct {
1139 const RTLIB::Libcall Op;
1140 const char * const Name;
1141 const CallingConv::ID CC;
1142 } LibraryCalls[] = {
1143 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1144 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1145 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1146 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1148 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1149 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1150 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1151 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1154 for (const auto &LC : LibraryCalls) {
1155 setLibcallName(LC.Op, LC.Name);
1156 setLibcallCallingConv(LC.Op, LC.CC);
1160 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1161 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1162 setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1163 setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1164 } else {
1165 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1166 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1169 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
1170 for (auto &VT : {MVT::f32, MVT::f64})
1171 setOperationAction(ISD::FPOWI, VT, Custom);
1173 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1174 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
1175 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1176 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1178 setOperationAction(ISD::TRAP, MVT::Other, Legal);
1179 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1181 // Use the default implementation.
1182 setOperationAction(ISD::VASTART, MVT::Other, Custom);
1183 setOperationAction(ISD::VAARG, MVT::Other, Expand);
1184 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
1185 setOperationAction(ISD::VAEND, MVT::Other, Expand);
1186 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1187 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1189 if (Subtarget->isTargetWindows())
1190 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1191 else
1192 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1194 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1195 // the default expansion.
1196 InsertFencesForAtomic = false;
1197 if (Subtarget->hasAnyDataBarrier() &&
1198 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1199 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1200 // to ldrex/strex loops already.
1201 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1202 if (!Subtarget->isThumb() || !Subtarget->isMClass())
1203 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
1205 // On v8, we have particularly efficient implementations of atomic fences
1206 // if they can be combined with nearby atomic loads and stores.
1207 if (!Subtarget->hasAcquireRelease() ||
1208 getTargetMachine().getOptLevel() == 0) {
1209 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1210 InsertFencesForAtomic = true;
1212 } else {
1213 // If there's anything we can use as a barrier, go through custom lowering
1214 // for ATOMIC_FENCE.
1215 // If target has DMB in thumb, Fences can be inserted.
1216 if (Subtarget->hasDataBarrier())
1217 InsertFencesForAtomic = true;
1219 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
1220 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1222 // Set them all for expansion, which will force libcalls.
1223 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
1224 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
1225 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
1226 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
1227 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
1228 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
1229 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
1230 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1231 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1232 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1233 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1234 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1235 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1236 // Unordered/Monotonic case.
1237 if (!InsertFencesForAtomic) {
1238 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1239 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1243 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
1245 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1246 if (!Subtarget->hasV6Ops()) {
1247 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1248 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
1250 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1252 if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1253 !Subtarget->isThumb1Only()) {
1254 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1255 // iff target supports vfp2.
1256 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1257 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1260 // We want to custom lower some of our intrinsics.
1261 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1262 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1263 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1264 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1265 if (Subtarget->useSjLjEH())
1266 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1268 setOperationAction(ISD::SETCC, MVT::i32, Expand);
1269 setOperationAction(ISD::SETCC, MVT::f32, Expand);
1270 setOperationAction(ISD::SETCC, MVT::f64, Expand);
1271 setOperationAction(ISD::SELECT, MVT::i32, Custom);
1272 setOperationAction(ISD::SELECT, MVT::f32, Custom);
1273 setOperationAction(ISD::SELECT, MVT::f64, Custom);
1274 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1275 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1276 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1277 if (Subtarget->hasFullFP16()) {
1278 setOperationAction(ISD::SETCC, MVT::f16, Expand);
1279 setOperationAction(ISD::SELECT, MVT::f16, Custom);
1280 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1283 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1285 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
1286 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1287 if (Subtarget->hasFullFP16())
1288 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
1289 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1290 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1291 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1293 // We don't support sin/cos/fmod/copysign/pow
1294 setOperationAction(ISD::FSIN, MVT::f64, Expand);
1295 setOperationAction(ISD::FSIN, MVT::f32, Expand);
1296 setOperationAction(ISD::FCOS, MVT::f32, Expand);
1297 setOperationAction(ISD::FCOS, MVT::f64, Expand);
1298 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1299 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1300 setOperationAction(ISD::FREM, MVT::f64, Expand);
1301 setOperationAction(ISD::FREM, MVT::f32, Expand);
1302 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1303 !Subtarget->isThumb1Only()) {
1304 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1305 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1307 setOperationAction(ISD::FPOW, MVT::f64, Expand);
1308 setOperationAction(ISD::FPOW, MVT::f32, Expand);
1310 if (!Subtarget->hasVFP4Base()) {
1311 setOperationAction(ISD::FMA, MVT::f64, Expand);
1312 setOperationAction(ISD::FMA, MVT::f32, Expand);
1315 // Various VFP goodness
1316 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1317 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1318 if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1319 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1320 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1323 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1324 if (!Subtarget->hasFP16()) {
1325 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1326 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1330 // Use __sincos_stret if available.
1331 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1332 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1333 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1334 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1337 // FP-ARMv8 implements a lot of rounding-like FP operations.
1338 if (Subtarget->hasFPARMv8Base()) {
1339 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1340 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1341 setOperationAction(ISD::FROUND, MVT::f32, Legal);
1342 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1343 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1344 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1345 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1346 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1347 if (Subtarget->hasNEON()) {
1348 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1349 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1350 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1351 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1354 if (Subtarget->hasFP64()) {
1355 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1356 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1357 setOperationAction(ISD::FROUND, MVT::f64, Legal);
1358 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1359 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1360 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1361 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1362 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1366 // FP16 often need to be promoted to call lib functions
1367 if (Subtarget->hasFullFP16()) {
1368 setOperationAction(ISD::FREM, MVT::f16, Promote);
1369 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1370 setOperationAction(ISD::FSIN, MVT::f16, Promote);
1371 setOperationAction(ISD::FCOS, MVT::f16, Promote);
1372 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1373 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1374 setOperationAction(ISD::FPOW, MVT::f16, Promote);
1375 setOperationAction(ISD::FEXP, MVT::f16, Promote);
1376 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1377 setOperationAction(ISD::FLOG, MVT::f16, Promote);
1378 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1379 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1381 setOperationAction(ISD::FROUND, MVT::f16, Legal);
1384 if (Subtarget->hasNEON()) {
1385 // vmin and vmax aren't available in a scalar form, so we use
1386 // a NEON instruction with an undef lane instead.
1387 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1388 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1389 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1390 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1391 setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1392 setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1393 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1394 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1396 if (Subtarget->hasFullFP16()) {
1397 setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1398 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1399 setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1400 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1402 setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1403 setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1404 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1405 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1409 // We have target-specific dag combine patterns for the following nodes:
1410 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1411 setTargetDAGCombine(ISD::ADD);
1412 setTargetDAGCombine(ISD::SUB);
1413 setTargetDAGCombine(ISD::MUL);
1414 setTargetDAGCombine(ISD::AND);
1415 setTargetDAGCombine(ISD::OR);
1416 setTargetDAGCombine(ISD::XOR);
1418 if (Subtarget->hasV6Ops())
1419 setTargetDAGCombine(ISD::SRL);
1420 if (Subtarget->isThumb1Only())
1421 setTargetDAGCombine(ISD::SHL);
1423 setStackPointerRegisterToSaveRestore(ARM::SP);
1425 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1426 !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1427 setSchedulingPreference(Sched::RegPressure);
1428 else
1429 setSchedulingPreference(Sched::Hybrid);
1431 //// temporary - rewrite interface to use type
1432 MaxStoresPerMemset = 8;
1433 MaxStoresPerMemsetOptSize = 4;
1434 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1435 MaxStoresPerMemcpyOptSize = 2;
1436 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1437 MaxStoresPerMemmoveOptSize = 2;
1439 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1440 // are at least 4 bytes aligned.
1441 setMinStackArgumentAlignment(Align(4));
1443 // Prefer likely predicted branches to selects on out-of-order cores.
1444 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1446 setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment()));
1448 setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1450 if (Subtarget->isThumb() || Subtarget->isThumb2())
1451 setTargetDAGCombine(ISD::ABS);
1454 bool ARMTargetLowering::useSoftFloat() const {
1455 return Subtarget->useSoftFloat();
1458 // FIXME: It might make sense to define the representative register class as the
1459 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1460 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1461 // SPR's representative would be DPR_VFP2. This should work well if register
1462 // pressure tracking were modified such that a register use would increment the
1463 // pressure of the register class's representative and all of it's super
1464 // classes' representatives transitively. We have not implemented this because
1465 // of the difficulty prior to coalescing of modeling operand register classes
1466 // due to the common occurrence of cross class copies and subregister insertions
1467 // and extractions.
1468 std::pair<const TargetRegisterClass *, uint8_t>
1469 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1470 MVT VT) const {
1471 const TargetRegisterClass *RRC = nullptr;
1472 uint8_t Cost = 1;
1473 switch (VT.SimpleTy) {
1474 default:
1475 return TargetLowering::findRepresentativeClass(TRI, VT);
1476 // Use DPR as representative register class for all floating point
1477 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1478 // the cost is 1 for both f32 and f64.
1479 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1480 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1481 RRC = &ARM::DPRRegClass;
1482 // When NEON is used for SP, only half of the register file is available
1483 // because operations that define both SP and DP results will be constrained
1484 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1485 // coalescing by double-counting the SP regs. See the FIXME above.
1486 if (Subtarget->useNEONForSinglePrecisionFP())
1487 Cost = 2;
1488 break;
1489 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1490 case MVT::v4f32: case MVT::v2f64:
1491 RRC = &ARM::DPRRegClass;
1492 Cost = 2;
1493 break;
1494 case MVT::v4i64:
1495 RRC = &ARM::DPRRegClass;
1496 Cost = 4;
1497 break;
1498 case MVT::v8i64:
1499 RRC = &ARM::DPRRegClass;
1500 Cost = 8;
1501 break;
1503 return std::make_pair(RRC, Cost);
1506 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1507 switch ((ARMISD::NodeType)Opcode) {
1508 case ARMISD::FIRST_NUMBER: break;
1509 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1510 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1511 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1512 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1513 case ARMISD::CALL: return "ARMISD::CALL";
1514 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1515 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1516 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1517 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1518 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1519 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1520 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1521 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1522 case ARMISD::CMP: return "ARMISD::CMP";
1523 case ARMISD::CMN: return "ARMISD::CMN";
1524 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1525 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1526 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1527 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1528 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1530 case ARMISD::CMOV: return "ARMISD::CMOV";
1531 case ARMISD::SUBS: return "ARMISD::SUBS";
1533 case ARMISD::SSAT: return "ARMISD::SSAT";
1534 case ARMISD::USAT: return "ARMISD::USAT";
1536 case ARMISD::ASRL: return "ARMISD::ASRL";
1537 case ARMISD::LSRL: return "ARMISD::LSRL";
1538 case ARMISD::LSLL: return "ARMISD::LSLL";
1540 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1541 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1542 case ARMISD::RRX: return "ARMISD::RRX";
1544 case ARMISD::ADDC: return "ARMISD::ADDC";
1545 case ARMISD::ADDE: return "ARMISD::ADDE";
1546 case ARMISD::SUBC: return "ARMISD::SUBC";
1547 case ARMISD::SUBE: return "ARMISD::SUBE";
1548 case ARMISD::LSLS: return "ARMISD::LSLS";
1550 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1551 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1552 case ARMISD::VMOVhr: return "ARMISD::VMOVhr";
1553 case ARMISD::VMOVrh: return "ARMISD::VMOVrh";
1554 case ARMISD::VMOVSR: return "ARMISD::VMOVSR";
1556 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1557 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1558 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1560 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1562 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1564 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1566 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1568 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1570 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK";
1571 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1573 case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST";
1574 case ARMISD::VCMP: return "ARMISD::VCMP";
1575 case ARMISD::VCMPZ: return "ARMISD::VCMPZ";
1576 case ARMISD::VTST: return "ARMISD::VTST";
1578 case ARMISD::VSHLs: return "ARMISD::VSHLs";
1579 case ARMISD::VSHLu: return "ARMISD::VSHLu";
1580 case ARMISD::VSHLIMM: return "ARMISD::VSHLIMM";
1581 case ARMISD::VSHRsIMM: return "ARMISD::VSHRsIMM";
1582 case ARMISD::VSHRuIMM: return "ARMISD::VSHRuIMM";
1583 case ARMISD::VRSHRsIMM: return "ARMISD::VRSHRsIMM";
1584 case ARMISD::VRSHRuIMM: return "ARMISD::VRSHRuIMM";
1585 case ARMISD::VRSHRNIMM: return "ARMISD::VRSHRNIMM";
1586 case ARMISD::VQSHLsIMM: return "ARMISD::VQSHLsIMM";
1587 case ARMISD::VQSHLuIMM: return "ARMISD::VQSHLuIMM";
1588 case ARMISD::VQSHLsuIMM: return "ARMISD::VQSHLsuIMM";
1589 case ARMISD::VQSHRNsIMM: return "ARMISD::VQSHRNsIMM";
1590 case ARMISD::VQSHRNuIMM: return "ARMISD::VQSHRNuIMM";
1591 case ARMISD::VQSHRNsuIMM: return "ARMISD::VQSHRNsuIMM";
1592 case ARMISD::VQRSHRNsIMM: return "ARMISD::VQRSHRNsIMM";
1593 case ARMISD::VQRSHRNuIMM: return "ARMISD::VQRSHRNuIMM";
1594 case ARMISD::VQRSHRNsuIMM: return "ARMISD::VQRSHRNsuIMM";
1595 case ARMISD::VSLIIMM: return "ARMISD::VSLIIMM";
1596 case ARMISD::VSRIIMM: return "ARMISD::VSRIIMM";
1597 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1598 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1599 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1600 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1601 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1602 case ARMISD::VDUP: return "ARMISD::VDUP";
1603 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1604 case ARMISD::VEXT: return "ARMISD::VEXT";
1605 case ARMISD::VREV64: return "ARMISD::VREV64";
1606 case ARMISD::VREV32: return "ARMISD::VREV32";
1607 case ARMISD::VREV16: return "ARMISD::VREV16";
1608 case ARMISD::VZIP: return "ARMISD::VZIP";
1609 case ARMISD::VUZP: return "ARMISD::VUZP";
1610 case ARMISD::VTRN: return "ARMISD::VTRN";
1611 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1612 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1613 case ARMISD::VMOVN: return "ARMISD::VMOVN";
1614 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1615 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1616 case ARMISD::UMAAL: return "ARMISD::UMAAL";
1617 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1618 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1619 case ARMISD::SMLALBB: return "ARMISD::SMLALBB";
1620 case ARMISD::SMLALBT: return "ARMISD::SMLALBT";
1621 case ARMISD::SMLALTB: return "ARMISD::SMLALTB";
1622 case ARMISD::SMLALTT: return "ARMISD::SMLALTT";
1623 case ARMISD::SMULWB: return "ARMISD::SMULWB";
1624 case ARMISD::SMULWT: return "ARMISD::SMULWT";
1625 case ARMISD::SMLALD: return "ARMISD::SMLALD";
1626 case ARMISD::SMLALDX: return "ARMISD::SMLALDX";
1627 case ARMISD::SMLSLD: return "ARMISD::SMLSLD";
1628 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX";
1629 case ARMISD::SMMLAR: return "ARMISD::SMMLAR";
1630 case ARMISD::SMMLSR: return "ARMISD::SMMLSR";
1631 case ARMISD::QADD16b: return "ARMISD::QADD16b";
1632 case ARMISD::QSUB16b: return "ARMISD::QSUB16b";
1633 case ARMISD::QADD8b: return "ARMISD::QADD8b";
1634 case ARMISD::QSUB8b: return "ARMISD::QSUB8b";
1635 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1636 case ARMISD::BFI: return "ARMISD::BFI";
1637 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1638 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1639 case ARMISD::VBSL: return "ARMISD::VBSL";
1640 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1641 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP";
1642 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1643 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1644 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1645 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1646 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1647 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1648 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1649 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1650 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1651 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1652 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD";
1653 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1654 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1655 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1656 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1657 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1658 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1659 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1660 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1661 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1662 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1663 case ARMISD::WLS: return "ARMISD::WLS";
1664 case ARMISD::LE: return "ARMISD::LE";
1665 case ARMISD::LOOP_DEC: return "ARMISD::LOOP_DEC";
1666 case ARMISD::CSINV: return "ARMISD::CSINV";
1667 case ARMISD::CSNEG: return "ARMISD::CSNEG";
1668 case ARMISD::CSINC: return "ARMISD::CSINC";
1670 return nullptr;
1673 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1674 EVT VT) const {
1675 if (!VT.isVector())
1676 return getPointerTy(DL);
1678 // MVE has a predicate register.
1679 if (Subtarget->hasMVEIntegerOps() &&
1680 (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1681 return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1682 return VT.changeVectorElementTypeToInteger();
1685 /// getRegClassFor - Return the register class that should be used for the
1686 /// specified value type.
1687 const TargetRegisterClass *
1688 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1689 (void)isDivergent;
1690 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1691 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1692 // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1693 // MVE Q registers.
1694 if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1695 if (VT == MVT::v4i64)
1696 return &ARM::QQPRRegClass;
1697 if (VT == MVT::v8i64)
1698 return &ARM::QQQQPRRegClass;
1700 return TargetLowering::getRegClassFor(VT);
1703 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1704 // source/dest is aligned and the copy size is large enough. We therefore want
1705 // to align such objects passed to memory intrinsics.
1706 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1707 unsigned &PrefAlign) const {
1708 if (!isa<MemIntrinsic>(CI))
1709 return false;
1710 MinSize = 8;
1711 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1712 // cycle faster than 4-byte aligned LDM.
1713 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1714 return true;
1717 // Create a fast isel object.
1718 FastISel *
1719 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1720 const TargetLibraryInfo *libInfo) const {
1721 return ARM::createFastISel(funcInfo, libInfo);
1724 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1725 unsigned NumVals = N->getNumValues();
1726 if (!NumVals)
1727 return Sched::RegPressure;
1729 for (unsigned i = 0; i != NumVals; ++i) {
1730 EVT VT = N->getValueType(i);
1731 if (VT == MVT::Glue || VT == MVT::Other)
1732 continue;
1733 if (VT.isFloatingPoint() || VT.isVector())
1734 return Sched::ILP;
1737 if (!N->isMachineOpcode())
1738 return Sched::RegPressure;
1740 // Load are scheduled for latency even if there instruction itinerary
1741 // is not available.
1742 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1743 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1745 if (MCID.getNumDefs() == 0)
1746 return Sched::RegPressure;
1747 if (!Itins->isEmpty() &&
1748 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1749 return Sched::ILP;
1751 return Sched::RegPressure;
1754 //===----------------------------------------------------------------------===//
1755 // Lowering Code
1756 //===----------------------------------------------------------------------===//
1758 static bool isSRL16(const SDValue &Op) {
1759 if (Op.getOpcode() != ISD::SRL)
1760 return false;
1761 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1762 return Const->getZExtValue() == 16;
1763 return false;
1766 static bool isSRA16(const SDValue &Op) {
1767 if (Op.getOpcode() != ISD::SRA)
1768 return false;
1769 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1770 return Const->getZExtValue() == 16;
1771 return false;
1774 static bool isSHL16(const SDValue &Op) {
1775 if (Op.getOpcode() != ISD::SHL)
1776 return false;
1777 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1778 return Const->getZExtValue() == 16;
1779 return false;
1782 // Check for a signed 16-bit value. We special case SRA because it makes it
1783 // more simple when also looking for SRAs that aren't sign extending a
1784 // smaller value. Without the check, we'd need to take extra care with
1785 // checking order for some operations.
1786 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1787 if (isSRA16(Op))
1788 return isSHL16(Op.getOperand(0));
1789 return DAG.ComputeNumSignBits(Op) == 17;
1792 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1793 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1794 switch (CC) {
1795 default: llvm_unreachable("Unknown condition code!");
1796 case ISD::SETNE: return ARMCC::NE;
1797 case ISD::SETEQ: return ARMCC::EQ;
1798 case ISD::SETGT: return ARMCC::GT;
1799 case ISD::SETGE: return ARMCC::GE;
1800 case ISD::SETLT: return ARMCC::LT;
1801 case ISD::SETLE: return ARMCC::LE;
1802 case ISD::SETUGT: return ARMCC::HI;
1803 case ISD::SETUGE: return ARMCC::HS;
1804 case ISD::SETULT: return ARMCC::LO;
1805 case ISD::SETULE: return ARMCC::LS;
1809 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1810 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1811 ARMCC::CondCodes &CondCode2) {
1812 CondCode2 = ARMCC::AL;
1813 switch (CC) {
1814 default: llvm_unreachable("Unknown FP condition!");
1815 case ISD::SETEQ:
1816 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1817 case ISD::SETGT:
1818 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1819 case ISD::SETGE:
1820 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1821 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1822 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1823 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1824 case ISD::SETO: CondCode = ARMCC::VC; break;
1825 case ISD::SETUO: CondCode = ARMCC::VS; break;
1826 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1827 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1828 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1829 case ISD::SETLT:
1830 case ISD::SETULT: CondCode = ARMCC::LT; break;
1831 case ISD::SETLE:
1832 case ISD::SETULE: CondCode = ARMCC::LE; break;
1833 case ISD::SETNE:
1834 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1838 //===----------------------------------------------------------------------===//
1839 // Calling Convention Implementation
1840 //===----------------------------------------------------------------------===//
1842 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1843 /// account presence of floating point hardware and calling convention
1844 /// limitations, such as support for variadic functions.
1845 CallingConv::ID
1846 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1847 bool isVarArg) const {
1848 switch (CC) {
1849 default:
1850 report_fatal_error("Unsupported calling convention");
1851 case CallingConv::ARM_AAPCS:
1852 case CallingConv::ARM_APCS:
1853 case CallingConv::GHC:
1854 return CC;
1855 case CallingConv::PreserveMost:
1856 return CallingConv::PreserveMost;
1857 case CallingConv::ARM_AAPCS_VFP:
1858 case CallingConv::Swift:
1859 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1860 case CallingConv::C:
1861 if (!Subtarget->isAAPCS_ABI())
1862 return CallingConv::ARM_APCS;
1863 else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1864 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1865 !isVarArg)
1866 return CallingConv::ARM_AAPCS_VFP;
1867 else
1868 return CallingConv::ARM_AAPCS;
1869 case CallingConv::Fast:
1870 case CallingConv::CXX_FAST_TLS:
1871 if (!Subtarget->isAAPCS_ABI()) {
1872 if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
1873 return CallingConv::Fast;
1874 return CallingConv::ARM_APCS;
1875 } else if (Subtarget->hasVFP2Base() &&
1876 !Subtarget->isThumb1Only() && !isVarArg)
1877 return CallingConv::ARM_AAPCS_VFP;
1878 else
1879 return CallingConv::ARM_AAPCS;
1883 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1884 bool isVarArg) const {
1885 return CCAssignFnForNode(CC, false, isVarArg);
1888 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1889 bool isVarArg) const {
1890 return CCAssignFnForNode(CC, true, isVarArg);
1893 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1894 /// CallingConvention.
1895 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1896 bool Return,
1897 bool isVarArg) const {
1898 switch (getEffectiveCallingConv(CC, isVarArg)) {
1899 default:
1900 report_fatal_error("Unsupported calling convention");
1901 case CallingConv::ARM_APCS:
1902 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1903 case CallingConv::ARM_AAPCS:
1904 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1905 case CallingConv::ARM_AAPCS_VFP:
1906 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1907 case CallingConv::Fast:
1908 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1909 case CallingConv::GHC:
1910 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1911 case CallingConv::PreserveMost:
1912 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1916 /// LowerCallResult - Lower the result values of a call into the
1917 /// appropriate copies out of appropriate physical registers.
1918 SDValue ARMTargetLowering::LowerCallResult(
1919 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1920 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1921 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1922 SDValue ThisVal) const {
1923 // Assign locations to each value returned by this call.
1924 SmallVector<CCValAssign, 16> RVLocs;
1925 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1926 *DAG.getContext());
1927 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1929 // Copy all of the result registers out of their specified physreg.
1930 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1931 CCValAssign VA = RVLocs[i];
1933 // Pass 'this' value directly from the argument to return value, to avoid
1934 // reg unit interference
1935 if (i == 0 && isThisReturn) {
1936 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1937 "unexpected return calling convention register assignment");
1938 InVals.push_back(ThisVal);
1939 continue;
1942 SDValue Val;
1943 if (VA.needsCustom()) {
1944 // Handle f64 or half of a v2f64.
1945 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1946 InFlag);
1947 Chain = Lo.getValue(1);
1948 InFlag = Lo.getValue(2);
1949 VA = RVLocs[++i]; // skip ahead to next loc
1950 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1951 InFlag);
1952 Chain = Hi.getValue(1);
1953 InFlag = Hi.getValue(2);
1954 if (!Subtarget->isLittle())
1955 std::swap (Lo, Hi);
1956 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1958 if (VA.getLocVT() == MVT::v2f64) {
1959 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1960 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1961 DAG.getConstant(0, dl, MVT::i32));
1963 VA = RVLocs[++i]; // skip ahead to next loc
1964 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1965 Chain = Lo.getValue(1);
1966 InFlag = Lo.getValue(2);
1967 VA = RVLocs[++i]; // skip ahead to next loc
1968 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1969 Chain = Hi.getValue(1);
1970 InFlag = Hi.getValue(2);
1971 if (!Subtarget->isLittle())
1972 std::swap (Lo, Hi);
1973 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1974 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1975 DAG.getConstant(1, dl, MVT::i32));
1977 } else {
1978 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1979 InFlag);
1980 Chain = Val.getValue(1);
1981 InFlag = Val.getValue(2);
1984 switch (VA.getLocInfo()) {
1985 default: llvm_unreachable("Unknown loc info!");
1986 case CCValAssign::Full: break;
1987 case CCValAssign::BCvt:
1988 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1989 break;
1992 InVals.push_back(Val);
1995 return Chain;
1998 /// LowerMemOpCallTo - Store the argument to the stack.
1999 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
2000 SDValue Arg, const SDLoc &dl,
2001 SelectionDAG &DAG,
2002 const CCValAssign &VA,
2003 ISD::ArgFlagsTy Flags) const {
2004 unsigned LocMemOffset = VA.getLocMemOffset();
2005 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2006 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2007 StackPtr, PtrOff);
2008 return DAG.getStore(
2009 Chain, dl, Arg, PtrOff,
2010 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
2013 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2014 SDValue Chain, SDValue &Arg,
2015 RegsToPassVector &RegsToPass,
2016 CCValAssign &VA, CCValAssign &NextVA,
2017 SDValue &StackPtr,
2018 SmallVectorImpl<SDValue> &MemOpChains,
2019 ISD::ArgFlagsTy Flags) const {
2020 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2021 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2022 unsigned id = Subtarget->isLittle() ? 0 : 1;
2023 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2025 if (NextVA.isRegLoc())
2026 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2027 else {
2028 assert(NextVA.isMemLoc());
2029 if (!StackPtr.getNode())
2030 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2031 getPointerTy(DAG.getDataLayout()));
2033 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
2034 dl, DAG, NextVA,
2035 Flags));
2039 /// LowerCall - Lowering a call into a callseq_start <-
2040 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2041 /// nodes.
2042 SDValue
2043 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2044 SmallVectorImpl<SDValue> &InVals) const {
2045 SelectionDAG &DAG = CLI.DAG;
2046 SDLoc &dl = CLI.DL;
2047 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2048 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2049 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2050 SDValue Chain = CLI.Chain;
2051 SDValue Callee = CLI.Callee;
2052 bool &isTailCall = CLI.IsTailCall;
2053 CallingConv::ID CallConv = CLI.CallConv;
2054 bool doesNotRet = CLI.DoesNotReturn;
2055 bool isVarArg = CLI.IsVarArg;
2057 MachineFunction &MF = DAG.getMachineFunction();
2058 MachineFunction::CallSiteInfo CSInfo;
2059 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2060 bool isThisReturn = false;
2061 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
2062 bool PreferIndirect = false;
2064 // Disable tail calls if they're not supported.
2065 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
2066 isTailCall = false;
2068 if (isa<GlobalAddressSDNode>(Callee)) {
2069 // If we're optimizing for minimum size and the function is called three or
2070 // more times in this block, we can improve codesize by calling indirectly
2071 // as BLXr has a 16-bit encoding.
2072 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2073 if (CLI.CS) {
2074 auto *BB = CLI.CS.getParent();
2075 PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2076 count_if(GV->users(), [&BB](const User *U) {
2077 return isa<Instruction>(U) &&
2078 cast<Instruction>(U)->getParent() == BB;
2079 }) > 2;
2082 if (isTailCall) {
2083 // Check if it's really possible to do a tail call.
2084 isTailCall = IsEligibleForTailCallOptimization(
2085 Callee, CallConv, isVarArg, isStructRet,
2086 MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2087 PreferIndirect);
2088 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
2089 report_fatal_error("failed to perform tail call elimination on a call "
2090 "site marked musttail");
2091 // We don't support GuaranteedTailCallOpt for ARM, only automatically
2092 // detected sibcalls.
2093 if (isTailCall)
2094 ++NumTailCalls;
2097 // Analyze operands of the call, assigning locations to each operand.
2098 SmallVector<CCValAssign, 16> ArgLocs;
2099 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2100 *DAG.getContext());
2101 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2103 // Get a count of how many bytes are to be pushed on the stack.
2104 unsigned NumBytes = CCInfo.getNextStackOffset();
2106 if (isTailCall) {
2107 // For tail calls, memory operands are available in our caller's stack.
2108 NumBytes = 0;
2109 } else {
2110 // Adjust the stack pointer for the new arguments...
2111 // These operations are automatically eliminated by the prolog/epilog pass
2112 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2115 SDValue StackPtr =
2116 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2118 RegsToPassVector RegsToPass;
2119 SmallVector<SDValue, 8> MemOpChains;
2121 // Walk the register/memloc assignments, inserting copies/loads. In the case
2122 // of tail call optimization, arguments are handled later.
2123 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2124 i != e;
2125 ++i, ++realArgIdx) {
2126 CCValAssign &VA = ArgLocs[i];
2127 SDValue Arg = OutVals[realArgIdx];
2128 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2129 bool isByVal = Flags.isByVal();
2131 // Promote the value if needed.
2132 switch (VA.getLocInfo()) {
2133 default: llvm_unreachable("Unknown loc info!");
2134 case CCValAssign::Full: break;
2135 case CCValAssign::SExt:
2136 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2137 break;
2138 case CCValAssign::ZExt:
2139 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2140 break;
2141 case CCValAssign::AExt:
2142 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2143 break;
2144 case CCValAssign::BCvt:
2145 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2146 break;
2149 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2150 if (VA.needsCustom()) {
2151 if (VA.getLocVT() == MVT::v2f64) {
2152 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2153 DAG.getConstant(0, dl, MVT::i32));
2154 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2155 DAG.getConstant(1, dl, MVT::i32));
2157 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
2158 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2160 VA = ArgLocs[++i]; // skip ahead to next loc
2161 if (VA.isRegLoc()) {
2162 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
2163 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2164 } else {
2165 assert(VA.isMemLoc());
2167 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
2168 dl, DAG, VA, Flags));
2170 } else {
2171 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2172 StackPtr, MemOpChains, Flags);
2174 } else if (VA.isRegLoc()) {
2175 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2176 Outs[0].VT == MVT::i32) {
2177 assert(VA.getLocVT() == MVT::i32 &&
2178 "unexpected calling convention register assignment");
2179 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2180 "unexpected use of 'returned'");
2181 isThisReturn = true;
2183 const TargetOptions &Options = DAG.getTarget().Options;
2184 if (Options.EnableDebugEntryValues)
2185 CSInfo.emplace_back(VA.getLocReg(), i);
2186 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2187 } else if (isByVal) {
2188 assert(VA.isMemLoc());
2189 unsigned offset = 0;
2191 // True if this byval aggregate will be split between registers
2192 // and memory.
2193 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2194 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2196 if (CurByValIdx < ByValArgsCount) {
2198 unsigned RegBegin, RegEnd;
2199 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2201 EVT PtrVT =
2202 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2203 unsigned int i, j;
2204 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2205 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2206 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2207 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
2208 MachinePointerInfo(),
2209 DAG.InferPtrAlignment(AddArg));
2210 MemOpChains.push_back(Load.getValue(1));
2211 RegsToPass.push_back(std::make_pair(j, Load));
2214 // If parameter size outsides register area, "offset" value
2215 // helps us to calculate stack slot for remained part properly.
2216 offset = RegEnd - RegBegin;
2218 CCInfo.nextInRegsParam();
2221 if (Flags.getByValSize() > 4*offset) {
2222 auto PtrVT = getPointerTy(DAG.getDataLayout());
2223 unsigned LocMemOffset = VA.getLocMemOffset();
2224 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2225 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2226 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2227 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2228 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2229 MVT::i32);
2230 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
2231 MVT::i32);
2233 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2234 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2235 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2236 Ops));
2238 } else if (!isTailCall) {
2239 assert(VA.isMemLoc());
2241 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2242 dl, DAG, VA, Flags));
2246 if (!MemOpChains.empty())
2247 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2249 // Build a sequence of copy-to-reg nodes chained together with token chain
2250 // and flag operands which copy the outgoing args into the appropriate regs.
2251 SDValue InFlag;
2252 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2253 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2254 RegsToPass[i].second, InFlag);
2255 InFlag = Chain.getValue(1);
2258 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2259 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2260 // node so that legalize doesn't hack it.
2261 bool isDirect = false;
2263 const TargetMachine &TM = getTargetMachine();
2264 const Module *Mod = MF.getFunction().getParent();
2265 const GlobalValue *GV = nullptr;
2266 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2267 GV = G->getGlobal();
2268 bool isStub =
2269 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2271 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2272 bool isLocalARMFunc = false;
2273 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2274 auto PtrVt = getPointerTy(DAG.getDataLayout());
2276 if (Subtarget->genLongCalls()) {
2277 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2278 "long-calls codegen is not position independent!");
2279 // Handle a global address or an external symbol. If it's not one of
2280 // those, the target's already in a register, so we don't need to do
2281 // anything extra.
2282 if (isa<GlobalAddressSDNode>(Callee)) {
2283 // Create a constant pool entry for the callee address
2284 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2285 ARMConstantPoolValue *CPV =
2286 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2288 // Get the address of the callee into a register
2289 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2290 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2291 Callee = DAG.getLoad(
2292 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2293 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2294 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2295 const char *Sym = S->getSymbol();
2297 // Create a constant pool entry for the callee address
2298 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2299 ARMConstantPoolValue *CPV =
2300 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2301 ARMPCLabelIndex, 0);
2302 // Get the address of the callee into a register
2303 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2304 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2305 Callee = DAG.getLoad(
2306 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2307 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2309 } else if (isa<GlobalAddressSDNode>(Callee)) {
2310 if (!PreferIndirect) {
2311 isDirect = true;
2312 bool isDef = GV->isStrongDefinitionForLinker();
2314 // ARM call to a local ARM function is predicable.
2315 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2316 // tBX takes a register source operand.
2317 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2318 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2319 Callee = DAG.getNode(
2320 ARMISD::WrapperPIC, dl, PtrVt,
2321 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2322 Callee = DAG.getLoad(
2323 PtrVt, dl, DAG.getEntryNode(), Callee,
2324 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2325 /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2326 MachineMemOperand::MOInvariant);
2327 } else if (Subtarget->isTargetCOFF()) {
2328 assert(Subtarget->isTargetWindows() &&
2329 "Windows is the only supported COFF target");
2330 unsigned TargetFlags = GV->hasDLLImportStorageClass()
2331 ? ARMII::MO_DLLIMPORT
2332 : ARMII::MO_NO_FLAG;
2333 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2334 TargetFlags);
2335 if (GV->hasDLLImportStorageClass())
2336 Callee =
2337 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2338 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2339 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2340 } else {
2341 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2344 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2345 isDirect = true;
2346 // tBX takes a register source operand.
2347 const char *Sym = S->getSymbol();
2348 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2349 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2350 ARMConstantPoolValue *CPV =
2351 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2352 ARMPCLabelIndex, 4);
2353 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2354 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2355 Callee = DAG.getLoad(
2356 PtrVt, dl, DAG.getEntryNode(), CPAddr,
2357 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2358 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2359 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2360 } else {
2361 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2365 // FIXME: handle tail calls differently.
2366 unsigned CallOpc;
2367 if (Subtarget->isThumb()) {
2368 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2369 CallOpc = ARMISD::CALL_NOLINK;
2370 else
2371 CallOpc = ARMISD::CALL;
2372 } else {
2373 if (!isDirect && !Subtarget->hasV5TOps())
2374 CallOpc = ARMISD::CALL_NOLINK;
2375 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2376 // Emit regular call when code size is the priority
2377 !Subtarget->hasMinSize())
2378 // "mov lr, pc; b _foo" to avoid confusing the RSP
2379 CallOpc = ARMISD::CALL_NOLINK;
2380 else
2381 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2384 std::vector<SDValue> Ops;
2385 Ops.push_back(Chain);
2386 Ops.push_back(Callee);
2388 // Add argument registers to the end of the list so that they are known live
2389 // into the call.
2390 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2391 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2392 RegsToPass[i].second.getValueType()));
2394 // Add a register mask operand representing the call-preserved registers.
2395 if (!isTailCall) {
2396 const uint32_t *Mask;
2397 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2398 if (isThisReturn) {
2399 // For 'this' returns, use the R0-preserving mask if applicable
2400 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2401 if (!Mask) {
2402 // Set isThisReturn to false if the calling convention is not one that
2403 // allows 'returned' to be modeled in this way, so LowerCallResult does
2404 // not try to pass 'this' straight through
2405 isThisReturn = false;
2406 Mask = ARI->getCallPreservedMask(MF, CallConv);
2408 } else
2409 Mask = ARI->getCallPreservedMask(MF, CallConv);
2411 assert(Mask && "Missing call preserved mask for calling convention");
2412 Ops.push_back(DAG.getRegisterMask(Mask));
2415 if (InFlag.getNode())
2416 Ops.push_back(InFlag);
2418 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2419 if (isTailCall) {
2420 MF.getFrameInfo().setHasTailCall();
2421 SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2422 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2423 return Ret;
2426 // Returns a chain and a flag for retval copy to use.
2427 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2428 InFlag = Chain.getValue(1);
2429 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2431 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2432 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2433 if (!Ins.empty())
2434 InFlag = Chain.getValue(1);
2436 // Handle result values, copying them out of physregs into vregs that we
2437 // return.
2438 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2439 InVals, isThisReturn,
2440 isThisReturn ? OutVals[0] : SDValue());
2443 /// HandleByVal - Every parameter *after* a byval parameter is passed
2444 /// on the stack. Remember the next parameter register to allocate,
2445 /// and then confiscate the rest of the parameter registers to insure
2446 /// this.
2447 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2448 unsigned Align) const {
2449 // Byval (as with any stack) slots are always at least 4 byte aligned.
2450 Align = std::max(Align, 4U);
2452 unsigned Reg = State->AllocateReg(GPRArgRegs);
2453 if (!Reg)
2454 return;
2456 unsigned AlignInRegs = Align / 4;
2457 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2458 for (unsigned i = 0; i < Waste; ++i)
2459 Reg = State->AllocateReg(GPRArgRegs);
2461 if (!Reg)
2462 return;
2464 unsigned Excess = 4 * (ARM::R4 - Reg);
2466 // Special case when NSAA != SP and parameter size greater than size of
2467 // all remained GPR regs. In that case we can't split parameter, we must
2468 // send it to stack. We also must set NCRN to R4, so waste all
2469 // remained registers.
2470 const unsigned NSAAOffset = State->getNextStackOffset();
2471 if (NSAAOffset != 0 && Size > Excess) {
2472 while (State->AllocateReg(GPRArgRegs))
2474 return;
2477 // First register for byval parameter is the first register that wasn't
2478 // allocated before this method call, so it would be "reg".
2479 // If parameter is small enough to be saved in range [reg, r4), then
2480 // the end (first after last) register would be reg + param-size-in-regs,
2481 // else parameter would be splitted between registers and stack,
2482 // end register would be r4 in this case.
2483 unsigned ByValRegBegin = Reg;
2484 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2485 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2486 // Note, first register is allocated in the beginning of function already,
2487 // allocate remained amount of registers we need.
2488 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2489 State->AllocateReg(GPRArgRegs);
2490 // A byval parameter that is split between registers and memory needs its
2491 // size truncated here.
2492 // In the case where the entire structure fits in registers, we set the
2493 // size in memory to zero.
2494 Size = std::max<int>(Size - Excess, 0);
2497 /// MatchingStackOffset - Return true if the given stack call argument is
2498 /// already available in the same position (relatively) of the caller's
2499 /// incoming argument stack.
2500 static
2501 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2502 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2503 const TargetInstrInfo *TII) {
2504 unsigned Bytes = Arg.getValueSizeInBits() / 8;
2505 int FI = std::numeric_limits<int>::max();
2506 if (Arg.getOpcode() == ISD::CopyFromReg) {
2507 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2508 if (!Register::isVirtualRegister(VR))
2509 return false;
2510 MachineInstr *Def = MRI->getVRegDef(VR);
2511 if (!Def)
2512 return false;
2513 if (!Flags.isByVal()) {
2514 if (!TII->isLoadFromStackSlot(*Def, FI))
2515 return false;
2516 } else {
2517 return false;
2519 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2520 if (Flags.isByVal())
2521 // ByVal argument is passed in as a pointer but it's now being
2522 // dereferenced. e.g.
2523 // define @foo(%struct.X* %A) {
2524 // tail call @bar(%struct.X* byval %A)
2525 // }
2526 return false;
2527 SDValue Ptr = Ld->getBasePtr();
2528 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2529 if (!FINode)
2530 return false;
2531 FI = FINode->getIndex();
2532 } else
2533 return false;
2535 assert(FI != std::numeric_limits<int>::max());
2536 if (!MFI.isFixedObjectIndex(FI))
2537 return false;
2538 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2541 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2542 /// for tail call optimization. Targets which want to do tail call
2543 /// optimization should implement this function.
2544 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2545 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2546 bool isCalleeStructRet, bool isCallerStructRet,
2547 const SmallVectorImpl<ISD::OutputArg> &Outs,
2548 const SmallVectorImpl<SDValue> &OutVals,
2549 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2550 const bool isIndirect) const {
2551 MachineFunction &MF = DAG.getMachineFunction();
2552 const Function &CallerF = MF.getFunction();
2553 CallingConv::ID CallerCC = CallerF.getCallingConv();
2555 assert(Subtarget->supportsTailCall());
2557 // Indirect tail calls cannot be optimized for Thumb1 if the args
2558 // to the call take up r0-r3. The reason is that there are no legal registers
2559 // left to hold the pointer to the function to be called.
2560 if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2561 (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2562 return false;
2564 // Look for obvious safe cases to perform tail call optimization that do not
2565 // require ABI changes. This is what gcc calls sibcall.
2567 // Exception-handling functions need a special set of instructions to indicate
2568 // a return to the hardware. Tail-calling another function would probably
2569 // break this.
2570 if (CallerF.hasFnAttribute("interrupt"))
2571 return false;
2573 // Also avoid sibcall optimization if either caller or callee uses struct
2574 // return semantics.
2575 if (isCalleeStructRet || isCallerStructRet)
2576 return false;
2578 // Externally-defined functions with weak linkage should not be
2579 // tail-called on ARM when the OS does not support dynamic
2580 // pre-emption of symbols, as the AAELF spec requires normal calls
2581 // to undefined weak functions to be replaced with a NOP or jump to the
2582 // next instruction. The behaviour of branch instructions in this
2583 // situation (as used for tail calls) is implementation-defined, so we
2584 // cannot rely on the linker replacing the tail call with a return.
2585 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2586 const GlobalValue *GV = G->getGlobal();
2587 const Triple &TT = getTargetMachine().getTargetTriple();
2588 if (GV->hasExternalWeakLinkage() &&
2589 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2590 return false;
2593 // Check that the call results are passed in the same way.
2594 LLVMContext &C = *DAG.getContext();
2595 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2596 CCAssignFnForReturn(CalleeCC, isVarArg),
2597 CCAssignFnForReturn(CallerCC, isVarArg)))
2598 return false;
2599 // The callee has to preserve all registers the caller needs to preserve.
2600 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2601 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2602 if (CalleeCC != CallerCC) {
2603 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2604 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2605 return false;
2608 // If Caller's vararg or byval argument has been split between registers and
2609 // stack, do not perform tail call, since part of the argument is in caller's
2610 // local frame.
2611 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2612 if (AFI_Caller->getArgRegsSaveSize())
2613 return false;
2615 // If the callee takes no arguments then go on to check the results of the
2616 // call.
2617 if (!Outs.empty()) {
2618 // Check if stack adjustment is needed. For now, do not do this if any
2619 // argument is passed on the stack.
2620 SmallVector<CCValAssign, 16> ArgLocs;
2621 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2622 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2623 if (CCInfo.getNextStackOffset()) {
2624 // Check if the arguments are already laid out in the right way as
2625 // the caller's fixed stack objects.
2626 MachineFrameInfo &MFI = MF.getFrameInfo();
2627 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2628 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2629 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2630 i != e;
2631 ++i, ++realArgIdx) {
2632 CCValAssign &VA = ArgLocs[i];
2633 EVT RegVT = VA.getLocVT();
2634 SDValue Arg = OutVals[realArgIdx];
2635 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2636 if (VA.getLocInfo() == CCValAssign::Indirect)
2637 return false;
2638 if (VA.needsCustom()) {
2639 // f64 and vector types are split into multiple registers or
2640 // register/stack-slot combinations. The types will not match
2641 // the registers; give up on memory f64 refs until we figure
2642 // out what to do about this.
2643 if (!VA.isRegLoc())
2644 return false;
2645 if (!ArgLocs[++i].isRegLoc())
2646 return false;
2647 if (RegVT == MVT::v2f64) {
2648 if (!ArgLocs[++i].isRegLoc())
2649 return false;
2650 if (!ArgLocs[++i].isRegLoc())
2651 return false;
2653 } else if (!VA.isRegLoc()) {
2654 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2655 MFI, MRI, TII))
2656 return false;
2661 const MachineRegisterInfo &MRI = MF.getRegInfo();
2662 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2663 return false;
2666 return true;
2669 bool
2670 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2671 MachineFunction &MF, bool isVarArg,
2672 const SmallVectorImpl<ISD::OutputArg> &Outs,
2673 LLVMContext &Context) const {
2674 SmallVector<CCValAssign, 16> RVLocs;
2675 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2676 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2679 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2680 const SDLoc &DL, SelectionDAG &DAG) {
2681 const MachineFunction &MF = DAG.getMachineFunction();
2682 const Function &F = MF.getFunction();
2684 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2686 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2687 // version of the "preferred return address". These offsets affect the return
2688 // instruction if this is a return from PL1 without hypervisor extensions.
2689 // IRQ/FIQ: +4 "subs pc, lr, #4"
2690 // SWI: 0 "subs pc, lr, #0"
2691 // ABORT: +4 "subs pc, lr, #4"
2692 // UNDEF: +4/+2 "subs pc, lr, #0"
2693 // UNDEF varies depending on where the exception came from ARM or Thumb
2694 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2696 int64_t LROffset;
2697 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2698 IntKind == "ABORT")
2699 LROffset = 4;
2700 else if (IntKind == "SWI" || IntKind == "UNDEF")
2701 LROffset = 0;
2702 else
2703 report_fatal_error("Unsupported interrupt attribute. If present, value "
2704 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2706 RetOps.insert(RetOps.begin() + 1,
2707 DAG.getConstant(LROffset, DL, MVT::i32, false));
2709 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2712 SDValue
2713 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2714 bool isVarArg,
2715 const SmallVectorImpl<ISD::OutputArg> &Outs,
2716 const SmallVectorImpl<SDValue> &OutVals,
2717 const SDLoc &dl, SelectionDAG &DAG) const {
2718 // CCValAssign - represent the assignment of the return value to a location.
2719 SmallVector<CCValAssign, 16> RVLocs;
2721 // CCState - Info about the registers and stack slots.
2722 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2723 *DAG.getContext());
2725 // Analyze outgoing return values.
2726 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2728 SDValue Flag;
2729 SmallVector<SDValue, 4> RetOps;
2730 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2731 bool isLittleEndian = Subtarget->isLittle();
2733 MachineFunction &MF = DAG.getMachineFunction();
2734 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2735 AFI->setReturnRegsCount(RVLocs.size());
2737 // Copy the result values into the output registers.
2738 for (unsigned i = 0, realRVLocIdx = 0;
2739 i != RVLocs.size();
2740 ++i, ++realRVLocIdx) {
2741 CCValAssign &VA = RVLocs[i];
2742 assert(VA.isRegLoc() && "Can only return in registers!");
2744 SDValue Arg = OutVals[realRVLocIdx];
2745 bool ReturnF16 = false;
2747 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2748 // Half-precision return values can be returned like this:
2750 // t11 f16 = fadd ...
2751 // t12: i16 = bitcast t11
2752 // t13: i32 = zero_extend t12
2753 // t14: f32 = bitcast t13 <~~~~~~~ Arg
2755 // to avoid code generation for bitcasts, we simply set Arg to the node
2756 // that produces the f16 value, t11 in this case.
2758 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2759 SDValue ZE = Arg.getOperand(0);
2760 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2761 SDValue BC = ZE.getOperand(0);
2762 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2763 Arg = BC.getOperand(0);
2764 ReturnF16 = true;
2770 switch (VA.getLocInfo()) {
2771 default: llvm_unreachable("Unknown loc info!");
2772 case CCValAssign::Full: break;
2773 case CCValAssign::BCvt:
2774 if (!ReturnF16)
2775 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2776 break;
2779 if (VA.needsCustom()) {
2780 if (VA.getLocVT() == MVT::v2f64) {
2781 // Extract the first half and return it in two registers.
2782 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2783 DAG.getConstant(0, dl, MVT::i32));
2784 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2785 DAG.getVTList(MVT::i32, MVT::i32), Half);
2787 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2788 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2789 Flag);
2790 Flag = Chain.getValue(1);
2791 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2792 VA = RVLocs[++i]; // skip ahead to next loc
2793 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2794 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2795 Flag);
2796 Flag = Chain.getValue(1);
2797 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2798 VA = RVLocs[++i]; // skip ahead to next loc
2800 // Extract the 2nd half and fall through to handle it as an f64 value.
2801 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2802 DAG.getConstant(1, dl, MVT::i32));
2804 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2805 // available.
2806 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2807 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2808 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2809 fmrrd.getValue(isLittleEndian ? 0 : 1),
2810 Flag);
2811 Flag = Chain.getValue(1);
2812 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2813 VA = RVLocs[++i]; // skip ahead to next loc
2814 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2815 fmrrd.getValue(isLittleEndian ? 1 : 0),
2816 Flag);
2817 } else
2818 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2820 // Guarantee that all emitted copies are
2821 // stuck together, avoiding something bad.
2822 Flag = Chain.getValue(1);
2823 RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2824 ReturnF16 ? MVT::f16 : VA.getLocVT()));
2826 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2827 const MCPhysReg *I =
2828 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2829 if (I) {
2830 for (; *I; ++I) {
2831 if (ARM::GPRRegClass.contains(*I))
2832 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2833 else if (ARM::DPRRegClass.contains(*I))
2834 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2835 else
2836 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2840 // Update chain and glue.
2841 RetOps[0] = Chain;
2842 if (Flag.getNode())
2843 RetOps.push_back(Flag);
2845 // CPUs which aren't M-class use a special sequence to return from
2846 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2847 // though we use "subs pc, lr, #N").
2849 // M-class CPUs actually use a normal return sequence with a special
2850 // (hardware-provided) value in LR, so the normal code path works.
2851 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2852 !Subtarget->isMClass()) {
2853 if (Subtarget->isThumb1Only())
2854 report_fatal_error("interrupt attribute is not supported in Thumb1");
2855 return LowerInterruptReturn(RetOps, dl, DAG);
2858 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2861 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2862 if (N->getNumValues() != 1)
2863 return false;
2864 if (!N->hasNUsesOfValue(1, 0))
2865 return false;
2867 SDValue TCChain = Chain;
2868 SDNode *Copy = *N->use_begin();
2869 if (Copy->getOpcode() == ISD::CopyToReg) {
2870 // If the copy has a glue operand, we conservatively assume it isn't safe to
2871 // perform a tail call.
2872 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2873 return false;
2874 TCChain = Copy->getOperand(0);
2875 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2876 SDNode *VMov = Copy;
2877 // f64 returned in a pair of GPRs.
2878 SmallPtrSet<SDNode*, 2> Copies;
2879 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2880 UI != UE; ++UI) {
2881 if (UI->getOpcode() != ISD::CopyToReg)
2882 return false;
2883 Copies.insert(*UI);
2885 if (Copies.size() > 2)
2886 return false;
2888 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2889 UI != UE; ++UI) {
2890 SDValue UseChain = UI->getOperand(0);
2891 if (Copies.count(UseChain.getNode()))
2892 // Second CopyToReg
2893 Copy = *UI;
2894 else {
2895 // We are at the top of this chain.
2896 // If the copy has a glue operand, we conservatively assume it
2897 // isn't safe to perform a tail call.
2898 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2899 return false;
2900 // First CopyToReg
2901 TCChain = UseChain;
2904 } else if (Copy->getOpcode() == ISD::BITCAST) {
2905 // f32 returned in a single GPR.
2906 if (!Copy->hasOneUse())
2907 return false;
2908 Copy = *Copy->use_begin();
2909 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2910 return false;
2911 // If the copy has a glue operand, we conservatively assume it isn't safe to
2912 // perform a tail call.
2913 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2914 return false;
2915 TCChain = Copy->getOperand(0);
2916 } else {
2917 return false;
2920 bool HasRet = false;
2921 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2922 UI != UE; ++UI) {
2923 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2924 UI->getOpcode() != ARMISD::INTRET_FLAG)
2925 return false;
2926 HasRet = true;
2929 if (!HasRet)
2930 return false;
2932 Chain = TCChain;
2933 return true;
2936 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2937 if (!Subtarget->supportsTailCall())
2938 return false;
2940 auto Attr =
2941 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2942 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2943 return false;
2945 return true;
2948 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2949 // and pass the lower and high parts through.
2950 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2951 SDLoc DL(Op);
2952 SDValue WriteValue = Op->getOperand(2);
2954 // This function is only supposed to be called for i64 type argument.
2955 assert(WriteValue.getValueType() == MVT::i64
2956 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2958 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2959 DAG.getConstant(0, DL, MVT::i32));
2960 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2961 DAG.getConstant(1, DL, MVT::i32));
2962 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2963 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2966 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2967 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2968 // one of the above mentioned nodes. It has to be wrapped because otherwise
2969 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2970 // be used to form addressing mode. These wrapped nodes will be selected
2971 // into MOVi.
2972 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2973 SelectionDAG &DAG) const {
2974 EVT PtrVT = Op.getValueType();
2975 // FIXME there is no actual debug info here
2976 SDLoc dl(Op);
2977 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2978 SDValue Res;
2980 // When generating execute-only code Constant Pools must be promoted to the
2981 // global data section. It's a bit ugly that we can't share them across basic
2982 // blocks, but this way we guarantee that execute-only behaves correct with
2983 // position-independent addressing modes.
2984 if (Subtarget->genExecuteOnly()) {
2985 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2986 auto T = const_cast<Type*>(CP->getType());
2987 auto C = const_cast<Constant*>(CP->getConstVal());
2988 auto M = const_cast<Module*>(DAG.getMachineFunction().
2989 getFunction().getParent());
2990 auto GV = new GlobalVariable(
2991 *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
2992 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2993 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2994 Twine(AFI->createPICLabelUId())
2996 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2997 dl, PtrVT);
2998 return LowerGlobalAddress(GA, DAG);
3001 if (CP->isMachineConstantPoolEntry())
3002 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
3003 CP->getAlignment());
3004 else
3005 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
3006 CP->getAlignment());
3007 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3010 unsigned ARMTargetLowering::getJumpTableEncoding() const {
3011 return MachineJumpTableInfo::EK_Inline;
3014 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3015 SelectionDAG &DAG) const {
3016 MachineFunction &MF = DAG.getMachineFunction();
3017 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3018 unsigned ARMPCLabelIndex = 0;
3019 SDLoc DL(Op);
3020 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3021 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3022 SDValue CPAddr;
3023 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3024 if (!IsPositionIndependent) {
3025 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
3026 } else {
3027 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3028 ARMPCLabelIndex = AFI->createPICLabelUId();
3029 ARMConstantPoolValue *CPV =
3030 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3031 ARMCP::CPBlockAddress, PCAdj);
3032 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3034 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3035 SDValue Result = DAG.getLoad(
3036 PtrVT, DL, DAG.getEntryNode(), CPAddr,
3037 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3038 if (!IsPositionIndependent)
3039 return Result;
3040 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3041 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3044 /// Convert a TLS address reference into the correct sequence of loads
3045 /// and calls to compute the variable's address for Darwin, and return an
3046 /// SDValue containing the final node.
3048 /// Darwin only has one TLS scheme which must be capable of dealing with the
3049 /// fully general situation, in the worst case. This means:
3050 /// + "extern __thread" declaration.
3051 /// + Defined in a possibly unknown dynamic library.
3053 /// The general system is that each __thread variable has a [3 x i32] descriptor
3054 /// which contains information used by the runtime to calculate the address. The
3055 /// only part of this the compiler needs to know about is the first word, which
3056 /// contains a function pointer that must be called with the address of the
3057 /// entire descriptor in "r0".
3059 /// Since this descriptor may be in a different unit, in general access must
3060 /// proceed along the usual ARM rules. A common sequence to produce is:
3062 /// movw rT1, :lower16:_var$non_lazy_ptr
3063 /// movt rT1, :upper16:_var$non_lazy_ptr
3064 /// ldr r0, [rT1]
3065 /// ldr rT2, [r0]
3066 /// blx rT2
3067 /// [...address now in r0...]
3068 SDValue
3069 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3070 SelectionDAG &DAG) const {
3071 assert(Subtarget->isTargetDarwin() &&
3072 "This function expects a Darwin target");
3073 SDLoc DL(Op);
3075 // First step is to get the address of the actua global symbol. This is where
3076 // the TLS descriptor lives.
3077 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3079 // The first entry in the descriptor is a function pointer that we must call
3080 // to obtain the address of the variable.
3081 SDValue Chain = DAG.getEntryNode();
3082 SDValue FuncTLVGet = DAG.getLoad(
3083 MVT::i32, DL, Chain, DescAddr,
3084 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3085 /* Alignment = */ 4,
3086 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3087 MachineMemOperand::MOInvariant);
3088 Chain = FuncTLVGet.getValue(1);
3090 MachineFunction &F = DAG.getMachineFunction();
3091 MachineFrameInfo &MFI = F.getFrameInfo();
3092 MFI.setAdjustsStack(true);
3094 // TLS calls preserve all registers except those that absolutely must be
3095 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3096 // silly).
3097 auto TRI =
3098 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3099 auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3100 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3102 // Finally, we can make the call. This is just a degenerate version of a
3103 // normal AArch64 call node: r0 takes the address of the descriptor, and
3104 // returns the address of the variable in this thread.
3105 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3106 Chain =
3107 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3108 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3109 DAG.getRegisterMask(Mask), Chain.getValue(1));
3110 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3113 SDValue
3114 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3115 SelectionDAG &DAG) const {
3116 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3118 SDValue Chain = DAG.getEntryNode();
3119 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3120 SDLoc DL(Op);
3122 // Load the current TEB (thread environment block)
3123 SDValue Ops[] = {Chain,
3124 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3125 DAG.getTargetConstant(15, DL, MVT::i32),
3126 DAG.getTargetConstant(0, DL, MVT::i32),
3127 DAG.getTargetConstant(13, DL, MVT::i32),
3128 DAG.getTargetConstant(0, DL, MVT::i32),
3129 DAG.getTargetConstant(2, DL, MVT::i32)};
3130 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3131 DAG.getVTList(MVT::i32, MVT::Other), Ops);
3133 SDValue TEB = CurrentTEB.getValue(0);
3134 Chain = CurrentTEB.getValue(1);
3136 // Load the ThreadLocalStoragePointer from the TEB
3137 // A pointer to the TLS array is located at offset 0x2c from the TEB.
3138 SDValue TLSArray =
3139 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3140 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3142 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3143 // offset into the TLSArray.
3145 // Load the TLS index from the C runtime
3146 SDValue TLSIndex =
3147 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3148 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3149 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3151 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3152 DAG.getConstant(2, DL, MVT::i32));
3153 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3154 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3155 MachinePointerInfo());
3157 // Get the offset of the start of the .tls section (section base)
3158 const auto *GA = cast<GlobalAddressSDNode>(Op);
3159 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3160 SDValue Offset = DAG.getLoad(
3161 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3162 DAG.getTargetConstantPool(CPV, PtrVT, 4)),
3163 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3165 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3168 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3169 SDValue
3170 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3171 SelectionDAG &DAG) const {
3172 SDLoc dl(GA);
3173 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3174 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3175 MachineFunction &MF = DAG.getMachineFunction();
3176 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3177 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3178 ARMConstantPoolValue *CPV =
3179 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3180 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3181 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3182 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3183 Argument = DAG.getLoad(
3184 PtrVT, dl, DAG.getEntryNode(), Argument,
3185 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3186 SDValue Chain = Argument.getValue(1);
3188 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3189 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3191 // call __tls_get_addr.
3192 ArgListTy Args;
3193 ArgListEntry Entry;
3194 Entry.Node = Argument;
3195 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3196 Args.push_back(Entry);
3198 // FIXME: is there useful debug info available here?
3199 TargetLowering::CallLoweringInfo CLI(DAG);
3200 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3201 CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3202 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3204 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3205 return CallResult.first;
3208 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3209 // "local exec" model.
3210 SDValue
3211 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3212 SelectionDAG &DAG,
3213 TLSModel::Model model) const {
3214 const GlobalValue *GV = GA->getGlobal();
3215 SDLoc dl(GA);
3216 SDValue Offset;
3217 SDValue Chain = DAG.getEntryNode();
3218 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3219 // Get the Thread Pointer
3220 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3222 if (model == TLSModel::InitialExec) {
3223 MachineFunction &MF = DAG.getMachineFunction();
3224 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3225 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3226 // Initial exec model.
3227 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3228 ARMConstantPoolValue *CPV =
3229 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3230 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3231 true);
3232 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3233 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3234 Offset = DAG.getLoad(
3235 PtrVT, dl, Chain, Offset,
3236 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3237 Chain = Offset.getValue(1);
3239 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3240 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3242 Offset = DAG.getLoad(
3243 PtrVT, dl, Chain, Offset,
3244 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3245 } else {
3246 // local exec model
3247 assert(model == TLSModel::LocalExec);
3248 ARMConstantPoolValue *CPV =
3249 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3250 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3251 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3252 Offset = DAG.getLoad(
3253 PtrVT, dl, Chain, Offset,
3254 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3257 // The address of the thread local variable is the add of the thread
3258 // pointer with the offset of the variable.
3259 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3262 SDValue
3263 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3264 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3265 if (DAG.getTarget().useEmulatedTLS())
3266 return LowerToTLSEmulatedModel(GA, DAG);
3268 if (Subtarget->isTargetDarwin())
3269 return LowerGlobalTLSAddressDarwin(Op, DAG);
3271 if (Subtarget->isTargetWindows())
3272 return LowerGlobalTLSAddressWindows(Op, DAG);
3274 // TODO: implement the "local dynamic" model
3275 assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3276 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3278 switch (model) {
3279 case TLSModel::GeneralDynamic:
3280 case TLSModel::LocalDynamic:
3281 return LowerToTLSGeneralDynamicModel(GA, DAG);
3282 case TLSModel::InitialExec:
3283 case TLSModel::LocalExec:
3284 return LowerToTLSExecModels(GA, DAG, model);
3286 llvm_unreachable("bogus TLS model");
3289 /// Return true if all users of V are within function F, looking through
3290 /// ConstantExprs.
3291 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3292 SmallVector<const User*,4> Worklist;
3293 for (auto *U : V->users())
3294 Worklist.push_back(U);
3295 while (!Worklist.empty()) {
3296 auto *U = Worklist.pop_back_val();
3297 if (isa<ConstantExpr>(U)) {
3298 for (auto *UU : U->users())
3299 Worklist.push_back(UU);
3300 continue;
3303 auto *I = dyn_cast<Instruction>(U);
3304 if (!I || I->getParent()->getParent() != F)
3305 return false;
3307 return true;
3310 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3311 const GlobalValue *GV, SelectionDAG &DAG,
3312 EVT PtrVT, const SDLoc &dl) {
3313 // If we're creating a pool entry for a constant global with unnamed address,
3314 // and the global is small enough, we can emit it inline into the constant pool
3315 // to save ourselves an indirection.
3317 // This is a win if the constant is only used in one function (so it doesn't
3318 // need to be duplicated) or duplicating the constant wouldn't increase code
3319 // size (implying the constant is no larger than 4 bytes).
3320 const Function &F = DAG.getMachineFunction().getFunction();
3322 // We rely on this decision to inline being idemopotent and unrelated to the
3323 // use-site. We know that if we inline a variable at one use site, we'll
3324 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3325 // doesn't know about this optimization, so bail out if it's enabled else
3326 // we could decide to inline here (and thus never emit the GV) but require
3327 // the GV from fast-isel generated code.
3328 if (!EnableConstpoolPromotion ||
3329 DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3330 return SDValue();
3332 auto *GVar = dyn_cast<GlobalVariable>(GV);
3333 if (!GVar || !GVar->hasInitializer() ||
3334 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3335 !GVar->hasLocalLinkage())
3336 return SDValue();
3338 // If we inline a value that contains relocations, we move the relocations
3339 // from .data to .text. This is not allowed in position-independent code.
3340 auto *Init = GVar->getInitializer();
3341 if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3342 Init->needsRelocation())
3343 return SDValue();
3345 // The constant islands pass can only really deal with alignment requests
3346 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3347 // any type wanting greater alignment requirements than 4 bytes. We also
3348 // can only promote constants that are multiples of 4 bytes in size or
3349 // are paddable to a multiple of 4. Currently we only try and pad constants
3350 // that are strings for simplicity.
3351 auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3352 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3353 unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3354 unsigned RequiredPadding = 4 - (Size % 4);
3355 bool PaddingPossible =
3356 RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3357 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3358 Size == 0)
3359 return SDValue();
3361 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3362 MachineFunction &MF = DAG.getMachineFunction();
3363 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3365 // We can't bloat the constant pool too much, else the ConstantIslands pass
3366 // may fail to converge. If we haven't promoted this global yet (it may have
3367 // multiple uses), and promoting it would increase the constant pool size (Sz
3368 // > 4), ensure we have space to do so up to MaxTotal.
3369 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3370 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3371 ConstpoolPromotionMaxTotal)
3372 return SDValue();
3374 // This is only valid if all users are in a single function; we can't clone
3375 // the constant in general. The LLVM IR unnamed_addr allows merging
3376 // constants, but not cloning them.
3378 // We could potentially allow cloning if we could prove all uses of the
3379 // constant in the current function don't care about the address, like
3380 // printf format strings. But that isn't implemented for now.
3381 if (!allUsersAreInFunction(GVar, &F))
3382 return SDValue();
3384 // We're going to inline this global. Pad it out if needed.
3385 if (RequiredPadding != 4) {
3386 StringRef S = CDAInit->getAsString();
3388 SmallVector<uint8_t,16> V(S.size());
3389 std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3390 while (RequiredPadding--)
3391 V.push_back(0);
3392 Init = ConstantDataArray::get(*DAG.getContext(), V);
3395 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3396 SDValue CPAddr =
3397 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3398 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3399 AFI->markGlobalAsPromotedToConstantPool(GVar);
3400 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3401 PaddedSize - 4);
3403 ++NumConstpoolPromoted;
3404 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3407 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3408 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3409 if (!(GV = GA->getBaseObject()))
3410 return false;
3411 if (const auto *V = dyn_cast<GlobalVariable>(GV))
3412 return V->isConstant();
3413 return isa<Function>(GV);
3416 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3417 SelectionDAG &DAG) const {
3418 switch (Subtarget->getTargetTriple().getObjectFormat()) {
3419 default: llvm_unreachable("unknown object format");
3420 case Triple::COFF:
3421 return LowerGlobalAddressWindows(Op, DAG);
3422 case Triple::ELF:
3423 return LowerGlobalAddressELF(Op, DAG);
3424 case Triple::MachO:
3425 return LowerGlobalAddressDarwin(Op, DAG);
3429 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3430 SelectionDAG &DAG) const {
3431 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3432 SDLoc dl(Op);
3433 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3434 const TargetMachine &TM = getTargetMachine();
3435 bool IsRO = isReadOnly(GV);
3437 // promoteToConstantPool only if not generating XO text section
3438 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3439 if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3440 return V;
3442 if (isPositionIndependent()) {
3443 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3444 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3445 UseGOT_PREL ? ARMII::MO_GOT : 0);
3446 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3447 if (UseGOT_PREL)
3448 Result =
3449 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3450 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3451 return Result;
3452 } else if (Subtarget->isROPI() && IsRO) {
3453 // PC-relative.
3454 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3455 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3456 return Result;
3457 } else if (Subtarget->isRWPI() && !IsRO) {
3458 // SB-relative.
3459 SDValue RelAddr;
3460 if (Subtarget->useMovt()) {
3461 ++NumMovwMovt;
3462 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3463 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3464 } else { // use literal pool for address constant
3465 ARMConstantPoolValue *CPV =
3466 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3467 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3468 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3469 RelAddr = DAG.getLoad(
3470 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3471 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3473 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3474 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3475 return Result;
3478 // If we have T2 ops, we can materialize the address directly via movt/movw
3479 // pair. This is always cheaper.
3480 if (Subtarget->useMovt()) {
3481 ++NumMovwMovt;
3482 // FIXME: Once remat is capable of dealing with instructions with register
3483 // operands, expand this into two nodes.
3484 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3485 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3486 } else {
3487 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3488 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3489 return DAG.getLoad(
3490 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3491 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3495 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3496 SelectionDAG &DAG) const {
3497 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3498 "ROPI/RWPI not currently supported for Darwin");
3499 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3500 SDLoc dl(Op);
3501 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3503 if (Subtarget->useMovt())
3504 ++NumMovwMovt;
3506 // FIXME: Once remat is capable of dealing with instructions with register
3507 // operands, expand this into multiple nodes
3508 unsigned Wrapper =
3509 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3511 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3512 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3514 if (Subtarget->isGVIndirectSymbol(GV))
3515 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3516 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3517 return Result;
3520 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3521 SelectionDAG &DAG) const {
3522 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3523 assert(Subtarget->useMovt() &&
3524 "Windows on ARM expects to use movw/movt");
3525 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3526 "ROPI/RWPI not currently supported for Windows");
3528 const TargetMachine &TM = getTargetMachine();
3529 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3530 ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3531 if (GV->hasDLLImportStorageClass())
3532 TargetFlags = ARMII::MO_DLLIMPORT;
3533 else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3534 TargetFlags = ARMII::MO_COFFSTUB;
3535 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3536 SDValue Result;
3537 SDLoc DL(Op);
3539 ++NumMovwMovt;
3541 // FIXME: Once remat is capable of dealing with instructions with register
3542 // operands, expand this into two nodes.
3543 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3544 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3545 TargetFlags));
3546 if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3547 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3548 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3549 return Result;
3552 SDValue
3553 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3554 SDLoc dl(Op);
3555 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3556 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3557 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3558 Op.getOperand(1), Val);
3561 SDValue
3562 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3563 SDLoc dl(Op);
3564 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3565 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3568 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3569 SelectionDAG &DAG) const {
3570 SDLoc dl(Op);
3571 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3572 Op.getOperand(0));
3575 SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3576 SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3577 unsigned IntNo =
3578 cast<ConstantSDNode>(
3579 Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3580 ->getZExtValue();
3581 switch (IntNo) {
3582 default:
3583 return SDValue(); // Don't custom lower most intrinsics.
3584 case Intrinsic::arm_gnu_eabi_mcount: {
3585 MachineFunction &MF = DAG.getMachineFunction();
3586 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3587 SDLoc dl(Op);
3588 SDValue Chain = Op.getOperand(0);
3589 // call "\01__gnu_mcount_nc"
3590 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3591 const uint32_t *Mask =
3592 ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3593 assert(Mask && "Missing call preserved mask for calling convention");
3594 // Mark LR an implicit live-in.
3595 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3596 SDValue ReturnAddress =
3597 DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3598 std::vector<EVT> ResultTys = {MVT::Other, MVT::Glue};
3599 SDValue Callee =
3600 DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3601 SDValue RegisterMask = DAG.getRegisterMask(Mask);
3602 if (Subtarget->isThumb())
3603 return SDValue(
3604 DAG.getMachineNode(
3605 ARM::tBL_PUSHLR, dl, ResultTys,
3606 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3607 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3609 return SDValue(
3610 DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3611 {ReturnAddress, Callee, RegisterMask, Chain}),
3617 SDValue
3618 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3619 const ARMSubtarget *Subtarget) const {
3620 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3621 SDLoc dl(Op);
3622 switch (IntNo) {
3623 default: return SDValue(); // Don't custom lower most intrinsics.
3624 case Intrinsic::thread_pointer: {
3625 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3626 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3628 case Intrinsic::eh_sjlj_lsda: {
3629 MachineFunction &MF = DAG.getMachineFunction();
3630 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3631 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3632 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3633 SDValue CPAddr;
3634 bool IsPositionIndependent = isPositionIndependent();
3635 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3636 ARMConstantPoolValue *CPV =
3637 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3638 ARMCP::CPLSDA, PCAdj);
3639 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3640 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3641 SDValue Result = DAG.getLoad(
3642 PtrVT, dl, DAG.getEntryNode(), CPAddr,
3643 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3645 if (IsPositionIndependent) {
3646 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3647 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3649 return Result;
3651 case Intrinsic::arm_neon_vabs:
3652 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3653 Op.getOperand(1));
3654 case Intrinsic::arm_neon_vmulls:
3655 case Intrinsic::arm_neon_vmullu: {
3656 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3657 ? ARMISD::VMULLs : ARMISD::VMULLu;
3658 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3659 Op.getOperand(1), Op.getOperand(2));
3661 case Intrinsic::arm_neon_vminnm:
3662 case Intrinsic::arm_neon_vmaxnm: {
3663 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3664 ? ISD::FMINNUM : ISD::FMAXNUM;
3665 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3666 Op.getOperand(1), Op.getOperand(2));
3668 case Intrinsic::arm_neon_vminu:
3669 case Intrinsic::arm_neon_vmaxu: {
3670 if (Op.getValueType().isFloatingPoint())
3671 return SDValue();
3672 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3673 ? ISD::UMIN : ISD::UMAX;
3674 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3675 Op.getOperand(1), Op.getOperand(2));
3677 case Intrinsic::arm_neon_vmins:
3678 case Intrinsic::arm_neon_vmaxs: {
3679 // v{min,max}s is overloaded between signed integers and floats.
3680 if (!Op.getValueType().isFloatingPoint()) {
3681 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3682 ? ISD::SMIN : ISD::SMAX;
3683 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3684 Op.getOperand(1), Op.getOperand(2));
3686 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3687 ? ISD::FMINIMUM : ISD::FMAXIMUM;
3688 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3689 Op.getOperand(1), Op.getOperand(2));
3691 case Intrinsic::arm_neon_vtbl1:
3692 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3693 Op.getOperand(1), Op.getOperand(2));
3694 case Intrinsic::arm_neon_vtbl2:
3695 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3696 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3700 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3701 const ARMSubtarget *Subtarget) {
3702 SDLoc dl(Op);
3703 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3704 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3705 if (SSID == SyncScope::SingleThread)
3706 return Op;
3708 if (!Subtarget->hasDataBarrier()) {
3709 // Some ARMv6 cpus can support data barriers with an mcr instruction.
3710 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3711 // here.
3712 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3713 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3714 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3715 DAG.getConstant(0, dl, MVT::i32));
3718 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3719 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3720 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3721 if (Subtarget->isMClass()) {
3722 // Only a full system barrier exists in the M-class architectures.
3723 Domain = ARM_MB::SY;
3724 } else if (Subtarget->preferISHSTBarriers() &&
3725 Ord == AtomicOrdering::Release) {
3726 // Swift happens to implement ISHST barriers in a way that's compatible with
3727 // Release semantics but weaker than ISH so we'd be fools not to use
3728 // it. Beware: other processors probably don't!
3729 Domain = ARM_MB::ISHST;
3732 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3733 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3734 DAG.getConstant(Domain, dl, MVT::i32));
3737 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3738 const ARMSubtarget *Subtarget) {
3739 // ARM pre v5TE and Thumb1 does not have preload instructions.
3740 if (!(Subtarget->isThumb2() ||
3741 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3742 // Just preserve the chain.
3743 return Op.getOperand(0);
3745 SDLoc dl(Op);
3746 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3747 if (!isRead &&
3748 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3749 // ARMv7 with MP extension has PLDW.
3750 return Op.getOperand(0);
3752 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3753 if (Subtarget->isThumb()) {
3754 // Invert the bits.
3755 isRead = ~isRead & 1;
3756 isData = ~isData & 1;
3759 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3760 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3761 DAG.getConstant(isData, dl, MVT::i32));
3764 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3765 MachineFunction &MF = DAG.getMachineFunction();
3766 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3768 // vastart just stores the address of the VarArgsFrameIndex slot into the
3769 // memory location argument.
3770 SDLoc dl(Op);
3771 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3772 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3773 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3774 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3775 MachinePointerInfo(SV));
3778 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3779 CCValAssign &NextVA,
3780 SDValue &Root,
3781 SelectionDAG &DAG,
3782 const SDLoc &dl) const {
3783 MachineFunction &MF = DAG.getMachineFunction();
3784 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3786 const TargetRegisterClass *RC;
3787 if (AFI->isThumb1OnlyFunction())
3788 RC = &ARM::tGPRRegClass;
3789 else
3790 RC = &ARM::GPRRegClass;
3792 // Transform the arguments stored in physical registers into virtual ones.
3793 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3794 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3796 SDValue ArgValue2;
3797 if (NextVA.isMemLoc()) {
3798 MachineFrameInfo &MFI = MF.getFrameInfo();
3799 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3801 // Create load node to retrieve arguments from the stack.
3802 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3803 ArgValue2 = DAG.getLoad(
3804 MVT::i32, dl, Root, FIN,
3805 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3806 } else {
3807 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3808 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3810 if (!Subtarget->isLittle())
3811 std::swap (ArgValue, ArgValue2);
3812 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3815 // The remaining GPRs hold either the beginning of variable-argument
3816 // data, or the beginning of an aggregate passed by value (usually
3817 // byval). Either way, we allocate stack slots adjacent to the data
3818 // provided by our caller, and store the unallocated registers there.
3819 // If this is a variadic function, the va_list pointer will begin with
3820 // these values; otherwise, this reassembles a (byval) structure that
3821 // was split between registers and memory.
3822 // Return: The frame index registers were stored into.
3823 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3824 const SDLoc &dl, SDValue &Chain,
3825 const Value *OrigArg,
3826 unsigned InRegsParamRecordIdx,
3827 int ArgOffset, unsigned ArgSize) const {
3828 // Currently, two use-cases possible:
3829 // Case #1. Non-var-args function, and we meet first byval parameter.
3830 // Setup first unallocated register as first byval register;
3831 // eat all remained registers
3832 // (these two actions are performed by HandleByVal method).
3833 // Then, here, we initialize stack frame with
3834 // "store-reg" instructions.
3835 // Case #2. Var-args function, that doesn't contain byval parameters.
3836 // The same: eat all remained unallocated registers,
3837 // initialize stack frame.
3839 MachineFunction &MF = DAG.getMachineFunction();
3840 MachineFrameInfo &MFI = MF.getFrameInfo();
3841 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3842 unsigned RBegin, REnd;
3843 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3844 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3845 } else {
3846 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3847 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3848 REnd = ARM::R4;
3851 if (REnd != RBegin)
3852 ArgOffset = -4 * (ARM::R4 - RBegin);
3854 auto PtrVT = getPointerTy(DAG.getDataLayout());
3855 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3856 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3858 SmallVector<SDValue, 4> MemOps;
3859 const TargetRegisterClass *RC =
3860 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3862 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3863 unsigned VReg = MF.addLiveIn(Reg, RC);
3864 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3865 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3866 MachinePointerInfo(OrigArg, 4 * i));
3867 MemOps.push_back(Store);
3868 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3871 if (!MemOps.empty())
3872 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3873 return FrameIndex;
3876 // Setup stack frame, the va_list pointer will start from.
3877 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3878 const SDLoc &dl, SDValue &Chain,
3879 unsigned ArgOffset,
3880 unsigned TotalArgRegsSaveSize,
3881 bool ForceMutable) const {
3882 MachineFunction &MF = DAG.getMachineFunction();
3883 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3885 // Try to store any remaining integer argument regs
3886 // to their spots on the stack so that they may be loaded by dereferencing
3887 // the result of va_next.
3888 // If there is no regs to be stored, just point address after last
3889 // argument passed via stack.
3890 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3891 CCInfo.getInRegsParamsCount(),
3892 CCInfo.getNextStackOffset(),
3893 std::max(4U, TotalArgRegsSaveSize));
3894 AFI->setVarArgsFrameIndex(FrameIndex);
3897 SDValue ARMTargetLowering::LowerFormalArguments(
3898 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3899 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3900 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3901 MachineFunction &MF = DAG.getMachineFunction();
3902 MachineFrameInfo &MFI = MF.getFrameInfo();
3904 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3906 // Assign locations to all of the incoming arguments.
3907 SmallVector<CCValAssign, 16> ArgLocs;
3908 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3909 *DAG.getContext());
3910 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3912 SmallVector<SDValue, 16> ArgValues;
3913 SDValue ArgValue;
3914 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3915 unsigned CurArgIdx = 0;
3917 // Initially ArgRegsSaveSize is zero.
3918 // Then we increase this value each time we meet byval parameter.
3919 // We also increase this value in case of varargs function.
3920 AFI->setArgRegsSaveSize(0);
3922 // Calculate the amount of stack space that we need to allocate to store
3923 // byval and variadic arguments that are passed in registers.
3924 // We need to know this before we allocate the first byval or variadic
3925 // argument, as they will be allocated a stack slot below the CFA (Canonical
3926 // Frame Address, the stack pointer at entry to the function).
3927 unsigned ArgRegBegin = ARM::R4;
3928 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3929 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3930 break;
3932 CCValAssign &VA = ArgLocs[i];
3933 unsigned Index = VA.getValNo();
3934 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3935 if (!Flags.isByVal())
3936 continue;
3938 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3939 unsigned RBegin, REnd;
3940 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3941 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3943 CCInfo.nextInRegsParam();
3945 CCInfo.rewindByValRegsInfo();
3947 int lastInsIndex = -1;
3948 if (isVarArg && MFI.hasVAStart()) {
3949 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3950 if (RegIdx != array_lengthof(GPRArgRegs))
3951 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3954 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3955 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3956 auto PtrVT = getPointerTy(DAG.getDataLayout());
3958 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3959 CCValAssign &VA = ArgLocs[i];
3960 if (Ins[VA.getValNo()].isOrigArg()) {
3961 std::advance(CurOrigArg,
3962 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3963 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3965 // Arguments stored in registers.
3966 if (VA.isRegLoc()) {
3967 EVT RegVT = VA.getLocVT();
3969 if (VA.needsCustom()) {
3970 // f64 and vector types are split up into multiple registers or
3971 // combinations of registers and stack slots.
3972 if (VA.getLocVT() == MVT::v2f64) {
3973 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3974 Chain, DAG, dl);
3975 VA = ArgLocs[++i]; // skip ahead to next loc
3976 SDValue ArgValue2;
3977 if (VA.isMemLoc()) {
3978 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3979 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3980 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3981 MachinePointerInfo::getFixedStack(
3982 DAG.getMachineFunction(), FI));
3983 } else {
3984 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3985 Chain, DAG, dl);
3987 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3988 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3989 ArgValue, ArgValue1,
3990 DAG.getIntPtrConstant(0, dl));
3991 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3992 ArgValue, ArgValue2,
3993 DAG.getIntPtrConstant(1, dl));
3994 } else
3995 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3996 } else {
3997 const TargetRegisterClass *RC;
4000 if (RegVT == MVT::f16)
4001 RC = &ARM::HPRRegClass;
4002 else if (RegVT == MVT::f32)
4003 RC = &ARM::SPRRegClass;
4004 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
4005 RC = &ARM::DPRRegClass;
4006 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
4007 RC = &ARM::QPRRegClass;
4008 else if (RegVT == MVT::i32)
4009 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4010 : &ARM::GPRRegClass;
4011 else
4012 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4014 // Transform the arguments in physical registers into virtual ones.
4015 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4016 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4018 // If this value is passed in r0 and has the returned attribute (e.g.
4019 // C++ 'structors), record this fact for later use.
4020 if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4021 AFI->setPreservesR0();
4025 // If this is an 8 or 16-bit value, it is really passed promoted
4026 // to 32 bits. Insert an assert[sz]ext to capture this, then
4027 // truncate to the right size.
4028 switch (VA.getLocInfo()) {
4029 default: llvm_unreachable("Unknown loc info!");
4030 case CCValAssign::Full: break;
4031 case CCValAssign::BCvt:
4032 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4033 break;
4034 case CCValAssign::SExt:
4035 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4036 DAG.getValueType(VA.getValVT()));
4037 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4038 break;
4039 case CCValAssign::ZExt:
4040 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4041 DAG.getValueType(VA.getValVT()));
4042 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4043 break;
4046 InVals.push_back(ArgValue);
4047 } else { // VA.isRegLoc()
4048 // sanity check
4049 assert(VA.isMemLoc());
4050 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4052 int index = VA.getValNo();
4054 // Some Ins[] entries become multiple ArgLoc[] entries.
4055 // Process them only once.
4056 if (index != lastInsIndex)
4058 ISD::ArgFlagsTy Flags = Ins[index].Flags;
4059 // FIXME: For now, all byval parameter objects are marked mutable.
4060 // This can be changed with more analysis.
4061 // In case of tail call optimization mark all arguments mutable.
4062 // Since they could be overwritten by lowering of arguments in case of
4063 // a tail call.
4064 if (Flags.isByVal()) {
4065 assert(Ins[index].isOrigArg() &&
4066 "Byval arguments cannot be implicit");
4067 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4069 int FrameIndex = StoreByValRegs(
4070 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4071 VA.getLocMemOffset(), Flags.getByValSize());
4072 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4073 CCInfo.nextInRegsParam();
4074 } else {
4075 unsigned FIOffset = VA.getLocMemOffset();
4076 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4077 FIOffset, true);
4079 // Create load nodes to retrieve arguments from the stack.
4080 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4081 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4082 MachinePointerInfo::getFixedStack(
4083 DAG.getMachineFunction(), FI)));
4085 lastInsIndex = index;
4090 // varargs
4091 if (isVarArg && MFI.hasVAStart())
4092 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
4093 CCInfo.getNextStackOffset(),
4094 TotalArgRegsSaveSize);
4096 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4098 return Chain;
4101 /// isFloatingPointZero - Return true if this is +0.0.
4102 static bool isFloatingPointZero(SDValue Op) {
4103 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4104 return CFP->getValueAPF().isPosZero();
4105 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4106 // Maybe this has already been legalized into the constant pool?
4107 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4108 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4109 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4110 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4111 return CFP->getValueAPF().isPosZero();
4113 } else if (Op->getOpcode() == ISD::BITCAST &&
4114 Op->getValueType(0) == MVT::f64) {
4115 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4116 // created by LowerConstantFP().
4117 SDValue BitcastOp = Op->getOperand(0);
4118 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4119 isNullConstant(BitcastOp->getOperand(0)))
4120 return true;
4122 return false;
4125 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4126 /// the given operands.
4127 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4128 SDValue &ARMcc, SelectionDAG &DAG,
4129 const SDLoc &dl) const {
4130 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4131 unsigned C = RHSC->getZExtValue();
4132 if (!isLegalICmpImmediate((int32_t)C)) {
4133 // Constant does not fit, try adjusting it by one.
4134 switch (CC) {
4135 default: break;
4136 case ISD::SETLT:
4137 case ISD::SETGE:
4138 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4139 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4140 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4142 break;
4143 case ISD::SETULT:
4144 case ISD::SETUGE:
4145 if (C != 0 && isLegalICmpImmediate(C-1)) {
4146 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4147 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4149 break;
4150 case ISD::SETLE:
4151 case ISD::SETGT:
4152 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4153 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4154 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4156 break;
4157 case ISD::SETULE:
4158 case ISD::SETUGT:
4159 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4160 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4161 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4163 break;
4166 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4167 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4168 // In ARM and Thumb-2, the compare instructions can shift their second
4169 // operand.
4170 CC = ISD::getSetCCSwappedOperands(CC);
4171 std::swap(LHS, RHS);
4174 // Thumb1 has very limited immediate modes, so turning an "and" into a
4175 // shift can save multiple instructions.
4177 // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4178 // into "((x << n) >> n)". But that isn't necessarily profitable on its
4179 // own. If it's the operand to an unsigned comparison with an immediate,
4180 // we can eliminate one of the shifts: we transform
4181 // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4183 // We avoid transforming cases which aren't profitable due to encoding
4184 // details:
4186 // 1. C2 fits into the immediate field of a cmp, and the transformed version
4187 // would not; in that case, we're essentially trading one immediate load for
4188 // another.
4189 // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4190 // 3. C2 is zero; we have other code for this special case.
4192 // FIXME: Figure out profitability for Thumb2; we usually can't save an
4193 // instruction, since the AND is always one instruction anyway, but we could
4194 // use narrow instructions in some cases.
4195 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4196 LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4197 LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4198 !isSignedIntSetCC(CC)) {
4199 unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4200 auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4201 uint64_t RHSV = RHSC->getZExtValue();
4202 if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4203 unsigned ShiftBits = countLeadingZeros(Mask);
4204 if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4205 SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4206 LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4207 RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4212 // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4213 // single "lsls x, c+1". The shift sets the "C" and "Z" flags the same
4214 // way a cmp would.
4215 // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4216 // some tweaks to the heuristics for the previous and->shift transform.
4217 // FIXME: Optimize cases where the LHS isn't a shift.
4218 if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4219 isa<ConstantSDNode>(RHS) &&
4220 cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4221 CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4222 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4223 unsigned ShiftAmt =
4224 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4225 SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4226 DAG.getVTList(MVT::i32, MVT::i32),
4227 LHS.getOperand(0),
4228 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4229 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4230 Shift.getValue(1), SDValue());
4231 ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4232 return Chain.getValue(1);
4235 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4237 // If the RHS is a constant zero then the V (overflow) flag will never be
4238 // set. This can allow us to simplify GE to PL or LT to MI, which can be
4239 // simpler for other passes (like the peephole optimiser) to deal with.
4240 if (isNullConstant(RHS)) {
4241 switch (CondCode) {
4242 default: break;
4243 case ARMCC::GE:
4244 CondCode = ARMCC::PL;
4245 break;
4246 case ARMCC::LT:
4247 CondCode = ARMCC::MI;
4248 break;
4252 ARMISD::NodeType CompareType;
4253 switch (CondCode) {
4254 default:
4255 CompareType = ARMISD::CMP;
4256 break;
4257 case ARMCC::EQ:
4258 case ARMCC::NE:
4259 // Uses only Z Flag
4260 CompareType = ARMISD::CMPZ;
4261 break;
4263 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4264 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4267 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4268 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4269 SelectionDAG &DAG, const SDLoc &dl) const {
4270 assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4271 SDValue Cmp;
4272 if (!isFloatingPointZero(RHS))
4273 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
4274 else
4275 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
4276 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4279 /// duplicateCmp - Glue values can have only one use, so this function
4280 /// duplicates a comparison node.
4281 SDValue
4282 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4283 unsigned Opc = Cmp.getOpcode();
4284 SDLoc DL(Cmp);
4285 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4286 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4288 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4289 Cmp = Cmp.getOperand(0);
4290 Opc = Cmp.getOpcode();
4291 if (Opc == ARMISD::CMPFP)
4292 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4293 else {
4294 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4295 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
4297 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4300 // This function returns three things: the arithmetic computation itself
4301 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
4302 // comparison and the condition code define the case in which the arithmetic
4303 // computation *does not* overflow.
4304 std::pair<SDValue, SDValue>
4305 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4306 SDValue &ARMcc) const {
4307 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
4309 SDValue Value, OverflowCmp;
4310 SDValue LHS = Op.getOperand(0);
4311 SDValue RHS = Op.getOperand(1);
4312 SDLoc dl(Op);
4314 // FIXME: We are currently always generating CMPs because we don't support
4315 // generating CMN through the backend. This is not as good as the natural
4316 // CMP case because it causes a register dependency and cannot be folded
4317 // later.
4319 switch (Op.getOpcode()) {
4320 default:
4321 llvm_unreachable("Unknown overflow instruction!");
4322 case ISD::SADDO:
4323 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4324 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4325 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4326 break;
4327 case ISD::UADDO:
4328 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4329 // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4330 // We do not use it in the USUBO case as Value may not be used.
4331 Value = DAG.getNode(ARMISD::ADDC, dl,
4332 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4333 .getValue(0);
4334 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4335 break;
4336 case ISD::SSUBO:
4337 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4338 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4339 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4340 break;
4341 case ISD::USUBO:
4342 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4343 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4344 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4345 break;
4346 case ISD::UMULO:
4347 // We generate a UMUL_LOHI and then check if the high word is 0.
4348 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4349 Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4350 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4351 LHS, RHS);
4352 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4353 DAG.getConstant(0, dl, MVT::i32));
4354 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4355 break;
4356 case ISD::SMULO:
4357 // We generate a SMUL_LOHI and then check if all the bits of the high word
4358 // are the same as the sign bit of the low word.
4359 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4360 Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4361 DAG.getVTList(Op.getValueType(), Op.getValueType()),
4362 LHS, RHS);
4363 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4364 DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4365 Value.getValue(0),
4366 DAG.getConstant(31, dl, MVT::i32)));
4367 Value = Value.getValue(0); // We only want the low 32 bits for the result.
4368 break;
4369 } // switch (...)
4371 return std::make_pair(Value, OverflowCmp);
4374 SDValue
4375 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4376 // Let legalize expand this if it isn't a legal type yet.
4377 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4378 return SDValue();
4380 SDValue Value, OverflowCmp;
4381 SDValue ARMcc;
4382 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4383 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4384 SDLoc dl(Op);
4385 // We use 0 and 1 as false and true values.
4386 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4387 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4388 EVT VT = Op.getValueType();
4390 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4391 ARMcc, CCR, OverflowCmp);
4393 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4394 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4397 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4398 SelectionDAG &DAG) {
4399 SDLoc DL(BoolCarry);
4400 EVT CarryVT = BoolCarry.getValueType();
4402 // This converts the boolean value carry into the carry flag by doing
4403 // ARMISD::SUBC Carry, 1
4404 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4405 DAG.getVTList(CarryVT, MVT::i32),
4406 BoolCarry, DAG.getConstant(1, DL, CarryVT));
4407 return Carry.getValue(1);
4410 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4411 SelectionDAG &DAG) {
4412 SDLoc DL(Flags);
4414 // Now convert the carry flag into a boolean carry. We do this
4415 // using ARMISD:ADDE 0, 0, Carry
4416 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4417 DAG.getConstant(0, DL, MVT::i32),
4418 DAG.getConstant(0, DL, MVT::i32), Flags);
4421 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4422 SelectionDAG &DAG) const {
4423 // Let legalize expand this if it isn't a legal type yet.
4424 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4425 return SDValue();
4427 SDValue LHS = Op.getOperand(0);
4428 SDValue RHS = Op.getOperand(1);
4429 SDLoc dl(Op);
4431 EVT VT = Op.getValueType();
4432 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4433 SDValue Value;
4434 SDValue Overflow;
4435 switch (Op.getOpcode()) {
4436 default:
4437 llvm_unreachable("Unknown overflow instruction!");
4438 case ISD::UADDO:
4439 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4440 // Convert the carry flag into a boolean value.
4441 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4442 break;
4443 case ISD::USUBO: {
4444 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4445 // Convert the carry flag into a boolean value.
4446 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4447 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4448 // value. So compute 1 - C.
4449 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4450 DAG.getConstant(1, dl, MVT::i32), Overflow);
4451 break;
4455 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4458 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG,
4459 const ARMSubtarget *Subtarget) {
4460 EVT VT = Op.getValueType();
4461 if (!Subtarget->hasDSP())
4462 return SDValue();
4463 if (!VT.isSimple())
4464 return SDValue();
4466 unsigned NewOpcode;
4467 bool IsAdd = Op->getOpcode() == ISD::SADDSAT;
4468 switch (VT.getSimpleVT().SimpleTy) {
4469 default:
4470 return SDValue();
4471 case MVT::i8:
4472 NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b;
4473 break;
4474 case MVT::i16:
4475 NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b;
4476 break;
4479 SDLoc dl(Op);
4480 SDValue Add =
4481 DAG.getNode(NewOpcode, dl, MVT::i32,
4482 DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
4483 DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
4484 return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
4487 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4488 SDValue Cond = Op.getOperand(0);
4489 SDValue SelectTrue = Op.getOperand(1);
4490 SDValue SelectFalse = Op.getOperand(2);
4491 SDLoc dl(Op);
4492 unsigned Opc = Cond.getOpcode();
4494 if (Cond.getResNo() == 1 &&
4495 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4496 Opc == ISD::USUBO)) {
4497 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4498 return SDValue();
4500 SDValue Value, OverflowCmp;
4501 SDValue ARMcc;
4502 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4503 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4504 EVT VT = Op.getValueType();
4506 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4507 OverflowCmp, DAG);
4510 // Convert:
4512 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4513 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4515 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4516 const ConstantSDNode *CMOVTrue =
4517 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4518 const ConstantSDNode *CMOVFalse =
4519 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4521 if (CMOVTrue && CMOVFalse) {
4522 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4523 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4525 SDValue True;
4526 SDValue False;
4527 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4528 True = SelectTrue;
4529 False = SelectFalse;
4530 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4531 True = SelectFalse;
4532 False = SelectTrue;
4535 if (True.getNode() && False.getNode()) {
4536 EVT VT = Op.getValueType();
4537 SDValue ARMcc = Cond.getOperand(2);
4538 SDValue CCR = Cond.getOperand(3);
4539 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4540 assert(True.getValueType() == VT);
4541 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4546 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4547 // undefined bits before doing a full-word comparison with zero.
4548 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4549 DAG.getConstant(1, dl, Cond.getValueType()));
4551 return DAG.getSelectCC(dl, Cond,
4552 DAG.getConstant(0, dl, Cond.getValueType()),
4553 SelectTrue, SelectFalse, ISD::SETNE);
4556 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4557 bool &swpCmpOps, bool &swpVselOps) {
4558 // Start by selecting the GE condition code for opcodes that return true for
4559 // 'equality'
4560 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4561 CC == ISD::SETULE || CC == ISD::SETGE || CC == ISD::SETLE)
4562 CondCode = ARMCC::GE;
4564 // and GT for opcodes that return false for 'equality'.
4565 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4566 CC == ISD::SETULT || CC == ISD::SETGT || CC == ISD::SETLT)
4567 CondCode = ARMCC::GT;
4569 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4570 // to swap the compare operands.
4571 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4572 CC == ISD::SETULT || CC == ISD::SETLE || CC == ISD::SETLT)
4573 swpCmpOps = true;
4575 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4576 // If we have an unordered opcode, we need to swap the operands to the VSEL
4577 // instruction (effectively negating the condition).
4579 // This also has the effect of swapping which one of 'less' or 'greater'
4580 // returns true, so we also swap the compare operands. It also switches
4581 // whether we return true for 'equality', so we compensate by picking the
4582 // opposite condition code to our original choice.
4583 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4584 CC == ISD::SETUGT) {
4585 swpCmpOps = !swpCmpOps;
4586 swpVselOps = !swpVselOps;
4587 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4590 // 'ordered' is 'anything but unordered', so use the VS condition code and
4591 // swap the VSEL operands.
4592 if (CC == ISD::SETO) {
4593 CondCode = ARMCC::VS;
4594 swpVselOps = true;
4597 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4598 // code and swap the VSEL operands. Also do this if we don't care about the
4599 // unordered case.
4600 if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4601 CondCode = ARMCC::EQ;
4602 swpVselOps = true;
4606 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4607 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4608 SDValue Cmp, SelectionDAG &DAG) const {
4609 if (!Subtarget->hasFP64() && VT == MVT::f64) {
4610 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4611 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4612 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4613 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4615 SDValue TrueLow = TrueVal.getValue(0);
4616 SDValue TrueHigh = TrueVal.getValue(1);
4617 SDValue FalseLow = FalseVal.getValue(0);
4618 SDValue FalseHigh = FalseVal.getValue(1);
4620 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4621 ARMcc, CCR, Cmp);
4622 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4623 ARMcc, CCR, duplicateCmp(Cmp, DAG));
4625 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4626 } else {
4627 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4628 Cmp);
4632 static bool isGTorGE(ISD::CondCode CC) {
4633 return CC == ISD::SETGT || CC == ISD::SETGE;
4636 static bool isLTorLE(ISD::CondCode CC) {
4637 return CC == ISD::SETLT || CC == ISD::SETLE;
4640 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4641 // All of these conditions (and their <= and >= counterparts) will do:
4642 // x < k ? k : x
4643 // x > k ? x : k
4644 // k < x ? x : k
4645 // k > x ? k : x
4646 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4647 const SDValue TrueVal, const SDValue FalseVal,
4648 const ISD::CondCode CC, const SDValue K) {
4649 return (isGTorGE(CC) &&
4650 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4651 (isLTorLE(CC) &&
4652 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4655 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4656 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4657 const SDValue TrueVal, const SDValue FalseVal,
4658 const ISD::CondCode CC, const SDValue K) {
4659 return (isGTorGE(CC) &&
4660 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4661 (isLTorLE(CC) &&
4662 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4665 // Check if two chained conditionals could be converted into SSAT or USAT.
4667 // SSAT can replace a set of two conditional selectors that bound a number to an
4668 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4670 // x < -k ? -k : (x > k ? k : x)
4671 // x < -k ? -k : (x < k ? x : k)
4672 // x > -k ? (x > k ? k : x) : -k
4673 // x < k ? (x < -k ? -k : x) : k
4674 // etc.
4676 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4677 // a power of 2.
4679 // It returns true if the conversion can be done, false otherwise.
4680 // Additionally, the variable is returned in parameter V, the constant in K and
4681 // usat is set to true if the conditional represents an unsigned saturation
4682 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4683 uint64_t &K, bool &usat) {
4684 SDValue LHS1 = Op.getOperand(0);
4685 SDValue RHS1 = Op.getOperand(1);
4686 SDValue TrueVal1 = Op.getOperand(2);
4687 SDValue FalseVal1 = Op.getOperand(3);
4688 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4690 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4691 if (Op2.getOpcode() != ISD::SELECT_CC)
4692 return false;
4694 SDValue LHS2 = Op2.getOperand(0);
4695 SDValue RHS2 = Op2.getOperand(1);
4696 SDValue TrueVal2 = Op2.getOperand(2);
4697 SDValue FalseVal2 = Op2.getOperand(3);
4698 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4700 // Find out which are the constants and which are the variables
4701 // in each conditional
4702 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4703 ? &RHS1
4704 : nullptr;
4705 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4706 ? &RHS2
4707 : nullptr;
4708 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4709 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4710 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4711 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4713 // We must detect cases where the original operations worked with 16- or
4714 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4715 // must work with sign-extended values but the select operations return
4716 // the original non-extended value.
4717 SDValue V2TmpReg = V2Tmp;
4718 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4719 V2TmpReg = V2Tmp->getOperand(0);
4721 // Check that the registers and the constants have the correct values
4722 // in both conditionals
4723 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4724 V2TmpReg != V2)
4725 return false;
4727 // Figure out which conditional is saturating the lower/upper bound.
4728 const SDValue *LowerCheckOp =
4729 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4730 ? &Op
4731 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4732 ? &Op2
4733 : nullptr;
4734 const SDValue *UpperCheckOp =
4735 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4736 ? &Op
4737 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4738 ? &Op2
4739 : nullptr;
4741 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4742 return false;
4744 // Check that the constant in the lower-bound check is
4745 // the opposite of the constant in the upper-bound check
4746 // in 1's complement.
4747 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4748 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4749 int64_t PosVal = std::max(Val1, Val2);
4750 int64_t NegVal = std::min(Val1, Val2);
4752 if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4753 (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4754 isPowerOf2_64(PosVal + 1)) {
4756 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4757 if (Val1 == ~Val2)
4758 usat = false;
4759 else if (NegVal == 0)
4760 usat = true;
4761 else
4762 return false;
4764 V = V2;
4765 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4767 return true;
4770 return false;
4773 // Check if a condition of the type x < k ? k : x can be converted into a
4774 // bit operation instead of conditional moves.
4775 // Currently this is allowed given:
4776 // - The conditions and values match up
4777 // - k is 0 or -1 (all ones)
4778 // This function will not check the last condition, thats up to the caller
4779 // It returns true if the transformation can be made, and in such case
4780 // returns x in V, and k in SatK.
4781 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4782 SDValue &SatK)
4784 SDValue LHS = Op.getOperand(0);
4785 SDValue RHS = Op.getOperand(1);
4786 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4787 SDValue TrueVal = Op.getOperand(2);
4788 SDValue FalseVal = Op.getOperand(3);
4790 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4791 ? &RHS
4792 : nullptr;
4794 // No constant operation in comparison, early out
4795 if (!K)
4796 return false;
4798 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4799 V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4800 SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4802 // If the constant on left and right side, or variable on left and right,
4803 // does not match, early out
4804 if (*K != KTmp || V != VTmp)
4805 return false;
4807 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4808 SatK = *K;
4809 return true;
4812 return false;
4815 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
4816 if (VT == MVT::f32)
4817 return !Subtarget->hasVFP2Base();
4818 if (VT == MVT::f64)
4819 return !Subtarget->hasFP64();
4820 if (VT == MVT::f16)
4821 return !Subtarget->hasFullFP16();
4822 return false;
4825 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4826 EVT VT = Op.getValueType();
4827 SDLoc dl(Op);
4829 // Try to convert two saturating conditional selects into a single SSAT
4830 SDValue SatValue;
4831 uint64_t SatConstant;
4832 bool SatUSat;
4833 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4834 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4835 if (SatUSat)
4836 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4837 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4838 else
4839 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4840 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4843 // Try to convert expressions of the form x < k ? k : x (and similar forms)
4844 // into more efficient bit operations, which is possible when k is 0 or -1
4845 // On ARM and Thumb-2 which have flexible operand 2 this will result in
4846 // single instructions. On Thumb the shift and the bit operation will be two
4847 // instructions.
4848 // Only allow this transformation on full-width (32-bit) operations
4849 SDValue LowerSatConstant;
4850 if (VT == MVT::i32 &&
4851 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4852 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4853 DAG.getConstant(31, dl, VT));
4854 if (isNullConstant(LowerSatConstant)) {
4855 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4856 DAG.getAllOnesConstant(dl, VT));
4857 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4858 } else if (isAllOnesConstant(LowerSatConstant))
4859 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4862 SDValue LHS = Op.getOperand(0);
4863 SDValue RHS = Op.getOperand(1);
4864 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4865 SDValue TrueVal = Op.getOperand(2);
4866 SDValue FalseVal = Op.getOperand(3);
4867 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
4868 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
4870 if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
4871 LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
4872 unsigned TVal = CTVal->getZExtValue();
4873 unsigned FVal = CFVal->getZExtValue();
4874 unsigned Opcode = 0;
4876 if (TVal == ~FVal) {
4877 Opcode = ARMISD::CSINV;
4878 } else if (TVal == ~FVal + 1) {
4879 Opcode = ARMISD::CSNEG;
4880 } else if (TVal + 1 == FVal) {
4881 Opcode = ARMISD::CSINC;
4882 } else if (TVal == FVal + 1) {
4883 Opcode = ARMISD::CSINC;
4884 std::swap(TrueVal, FalseVal);
4885 std::swap(TVal, FVal);
4886 CC = ISD::getSetCCInverse(CC, true);
4889 if (Opcode) {
4890 // If one of the constants is cheaper than another, materialise the
4891 // cheaper one and let the csel generate the other.
4892 if (Opcode != ARMISD::CSINC &&
4893 HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
4894 std::swap(TrueVal, FalseVal);
4895 std::swap(TVal, FVal);
4896 CC = ISD::getSetCCInverse(CC, true);
4899 // Attempt to use ZR checking TVal is 0, possibly inverting the condition
4900 // to get there. CSINC not is invertable like the other two (~(~a) == a,
4901 // -(-a) == a, but (a+1)+1 != a).
4902 if (FVal == 0 && Opcode != ARMISD::CSINC) {
4903 std::swap(TrueVal, FalseVal);
4904 std::swap(TVal, FVal);
4905 CC = ISD::getSetCCInverse(CC, true);
4907 if (TVal == 0)
4908 TrueVal = DAG.getRegister(ARM::ZR, MVT::i32);
4910 // Drops F's value because we can get it by inverting/negating TVal.
4911 FalseVal = TrueVal;
4913 SDValue ARMcc;
4914 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4915 EVT VT = TrueVal.getValueType();
4916 return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
4920 if (isUnsupportedFloatingType(LHS.getValueType())) {
4921 DAG.getTargetLoweringInfo().softenSetCCOperands(
4922 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
4924 // If softenSetCCOperands only returned one value, we should compare it to
4925 // zero.
4926 if (!RHS.getNode()) {
4927 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4928 CC = ISD::SETNE;
4932 if (LHS.getValueType() == MVT::i32) {
4933 // Try to generate VSEL on ARMv8.
4934 // The VSEL instruction can't use all the usual ARM condition
4935 // codes: it only has two bits to select the condition code, so it's
4936 // constrained to use only GE, GT, VS and EQ.
4938 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4939 // swap the operands of the previous compare instruction (effectively
4940 // inverting the compare condition, swapping 'less' and 'greater') and
4941 // sometimes need to swap the operands to the VSEL (which inverts the
4942 // condition in the sense of firing whenever the previous condition didn't)
4943 if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
4944 TrueVal.getValueType() == MVT::f32 ||
4945 TrueVal.getValueType() == MVT::f64)) {
4946 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4947 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4948 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4949 CC = ISD::getSetCCInverse(CC, true);
4950 std::swap(TrueVal, FalseVal);
4954 SDValue ARMcc;
4955 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4956 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4957 // Choose GE over PL, which vsel does now support
4958 if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
4959 ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
4960 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4963 ARMCC::CondCodes CondCode, CondCode2;
4964 FPCCToARMCC(CC, CondCode, CondCode2);
4966 // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
4967 // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
4968 // must use VSEL (limited condition codes), due to not having conditional f16
4969 // moves.
4970 if (Subtarget->hasFPARMv8Base() &&
4971 !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
4972 (TrueVal.getValueType() == MVT::f16 ||
4973 TrueVal.getValueType() == MVT::f32 ||
4974 TrueVal.getValueType() == MVT::f64)) {
4975 bool swpCmpOps = false;
4976 bool swpVselOps = false;
4977 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4979 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4980 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4981 if (swpCmpOps)
4982 std::swap(LHS, RHS);
4983 if (swpVselOps)
4984 std::swap(TrueVal, FalseVal);
4988 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4989 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
4990 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4991 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4992 if (CondCode2 != ARMCC::AL) {
4993 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4994 // FIXME: Needs another CMP because flag can have but one use.
4995 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
4996 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4998 return Result;
5001 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
5002 /// to morph to an integer compare sequence.
5003 static bool canChangeToInt(SDValue Op, bool &SeenZero,
5004 const ARMSubtarget *Subtarget) {
5005 SDNode *N = Op.getNode();
5006 if (!N->hasOneUse())
5007 // Otherwise it requires moving the value from fp to integer registers.
5008 return false;
5009 if (!N->getNumValues())
5010 return false;
5011 EVT VT = Op.getValueType();
5012 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5013 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5014 // vmrs are very slow, e.g. cortex-a8.
5015 return false;
5017 if (isFloatingPointZero(Op)) {
5018 SeenZero = true;
5019 return true;
5021 return ISD::isNormalLoad(N);
5024 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
5025 if (isFloatingPointZero(Op))
5026 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5028 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
5029 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5030 Ld->getPointerInfo(), Ld->getAlignment(),
5031 Ld->getMemOperand()->getFlags());
5033 llvm_unreachable("Unknown VFP cmp argument!");
5036 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5037 SDValue &RetVal1, SDValue &RetVal2) {
5038 SDLoc dl(Op);
5040 if (isFloatingPointZero(Op)) {
5041 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5042 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5043 return;
5046 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5047 SDValue Ptr = Ld->getBasePtr();
5048 RetVal1 =
5049 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5050 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
5052 EVT PtrType = Ptr.getValueType();
5053 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
5054 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5055 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5056 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5057 Ld->getPointerInfo().getWithOffset(4), NewAlign,
5058 Ld->getMemOperand()->getFlags());
5059 return;
5062 llvm_unreachable("Unknown VFP cmp argument!");
5065 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5066 /// f32 and even f64 comparisons to integer ones.
5067 SDValue
5068 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5069 SDValue Chain = Op.getOperand(0);
5070 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5071 SDValue LHS = Op.getOperand(2);
5072 SDValue RHS = Op.getOperand(3);
5073 SDValue Dest = Op.getOperand(4);
5074 SDLoc dl(Op);
5076 bool LHSSeenZero = false;
5077 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5078 bool RHSSeenZero = false;
5079 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5080 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5081 // If unsafe fp math optimization is enabled and there are no other uses of
5082 // the CMP operands, and the condition code is EQ or NE, we can optimize it
5083 // to an integer comparison.
5084 if (CC == ISD::SETOEQ)
5085 CC = ISD::SETEQ;
5086 else if (CC == ISD::SETUNE)
5087 CC = ISD::SETNE;
5089 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5090 SDValue ARMcc;
5091 if (LHS.getValueType() == MVT::f32) {
5092 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5093 bitcastf32Toi32(LHS, DAG), Mask);
5094 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5095 bitcastf32Toi32(RHS, DAG), Mask);
5096 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5097 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5098 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5099 Chain, Dest, ARMcc, CCR, Cmp);
5102 SDValue LHS1, LHS2;
5103 SDValue RHS1, RHS2;
5104 expandf64Toi32(LHS, DAG, LHS1, LHS2);
5105 expandf64Toi32(RHS, DAG, RHS1, RHS2);
5106 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5107 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5108 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5109 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5110 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5111 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5112 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5115 return SDValue();
5118 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5119 SDValue Chain = Op.getOperand(0);
5120 SDValue Cond = Op.getOperand(1);
5121 SDValue Dest = Op.getOperand(2);
5122 SDLoc dl(Op);
5124 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5125 // instruction.
5126 unsigned Opc = Cond.getOpcode();
5127 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5128 !Subtarget->isThumb1Only();
5129 if (Cond.getResNo() == 1 &&
5130 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5131 Opc == ISD::USUBO || OptimizeMul)) {
5132 // Only lower legal XALUO ops.
5133 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5134 return SDValue();
5136 // The actual operation with overflow check.
5137 SDValue Value, OverflowCmp;
5138 SDValue ARMcc;
5139 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5141 // Reverse the condition code.
5142 ARMCC::CondCodes CondCode =
5143 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5144 CondCode = ARMCC::getOppositeCondition(CondCode);
5145 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5146 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5148 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5149 OverflowCmp);
5152 return SDValue();
5155 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5156 SDValue Chain = Op.getOperand(0);
5157 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5158 SDValue LHS = Op.getOperand(2);
5159 SDValue RHS = Op.getOperand(3);
5160 SDValue Dest = Op.getOperand(4);
5161 SDLoc dl(Op);
5163 if (isUnsupportedFloatingType(LHS.getValueType())) {
5164 DAG.getTargetLoweringInfo().softenSetCCOperands(
5165 DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5167 // If softenSetCCOperands only returned one value, we should compare it to
5168 // zero.
5169 if (!RHS.getNode()) {
5170 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5171 CC = ISD::SETNE;
5175 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5176 // instruction.
5177 unsigned Opc = LHS.getOpcode();
5178 bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5179 !Subtarget->isThumb1Only();
5180 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5181 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5182 Opc == ISD::USUBO || OptimizeMul) &&
5183 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5184 // Only lower legal XALUO ops.
5185 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5186 return SDValue();
5188 // The actual operation with overflow check.
5189 SDValue Value, OverflowCmp;
5190 SDValue ARMcc;
5191 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5193 if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5194 // Reverse the condition code.
5195 ARMCC::CondCodes CondCode =
5196 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5197 CondCode = ARMCC::getOppositeCondition(CondCode);
5198 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5200 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5202 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5203 OverflowCmp);
5206 if (LHS.getValueType() == MVT::i32) {
5207 SDValue ARMcc;
5208 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5209 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5210 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5211 Chain, Dest, ARMcc, CCR, Cmp);
5214 if (getTargetMachine().Options.UnsafeFPMath &&
5215 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5216 CC == ISD::SETNE || CC == ISD::SETUNE)) {
5217 if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5218 return Result;
5221 ARMCC::CondCodes CondCode, CondCode2;
5222 FPCCToARMCC(CC, CondCode, CondCode2);
5224 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5225 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5226 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5227 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5228 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5229 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5230 if (CondCode2 != ARMCC::AL) {
5231 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5232 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5233 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5235 return Res;
5238 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5239 SDValue Chain = Op.getOperand(0);
5240 SDValue Table = Op.getOperand(1);
5241 SDValue Index = Op.getOperand(2);
5242 SDLoc dl(Op);
5244 EVT PTy = getPointerTy(DAG.getDataLayout());
5245 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5246 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5247 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5248 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5249 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5250 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5251 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5252 // which does another jump to the destination. This also makes it easier
5253 // to translate it to TBB / TBH later (Thumb2 only).
5254 // FIXME: This might not work if the function is extremely large.
5255 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5256 Addr, Op.getOperand(2), JTI);
5258 if (isPositionIndependent() || Subtarget->isROPI()) {
5259 Addr =
5260 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5261 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5262 Chain = Addr.getValue(1);
5263 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5264 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5265 } else {
5266 Addr =
5267 DAG.getLoad(PTy, dl, Chain, Addr,
5268 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5269 Chain = Addr.getValue(1);
5270 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5274 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5275 EVT VT = Op.getValueType();
5276 SDLoc dl(Op);
5278 if (Op.getValueType().getVectorElementType() == MVT::i32) {
5279 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5280 return Op;
5281 return DAG.UnrollVectorOp(Op.getNode());
5284 const bool HasFullFP16 =
5285 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5287 EVT NewTy;
5288 const EVT OpTy = Op.getOperand(0).getValueType();
5289 if (OpTy == MVT::v4f32)
5290 NewTy = MVT::v4i32;
5291 else if (OpTy == MVT::v4f16 && HasFullFP16)
5292 NewTy = MVT::v4i16;
5293 else if (OpTy == MVT::v8f16 && HasFullFP16)
5294 NewTy = MVT::v8i16;
5295 else
5296 llvm_unreachable("Invalid type for custom lowering!");
5298 if (VT != MVT::v4i16 && VT != MVT::v8i16)
5299 return DAG.UnrollVectorOp(Op.getNode());
5301 Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5302 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5305 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5306 EVT VT = Op.getValueType();
5307 if (VT.isVector())
5308 return LowerVectorFP_TO_INT(Op, DAG);
5309 if (isUnsupportedFloatingType(Op.getOperand(0).getValueType())) {
5310 RTLIB::Libcall LC;
5311 if (Op.getOpcode() == ISD::FP_TO_SINT)
5312 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
5313 Op.getValueType());
5314 else
5315 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
5316 Op.getValueType());
5317 MakeLibCallOptions CallOptions;
5318 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5319 CallOptions, SDLoc(Op)).first;
5322 return Op;
5325 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5326 EVT VT = Op.getValueType();
5327 SDLoc dl(Op);
5329 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5330 if (VT.getVectorElementType() == MVT::f32)
5331 return Op;
5332 return DAG.UnrollVectorOp(Op.getNode());
5335 assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5336 Op.getOperand(0).getValueType() == MVT::v8i16) &&
5337 "Invalid type for custom lowering!");
5339 const bool HasFullFP16 =
5340 static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5342 EVT DestVecType;
5343 if (VT == MVT::v4f32)
5344 DestVecType = MVT::v4i32;
5345 else if (VT == MVT::v4f16 && HasFullFP16)
5346 DestVecType = MVT::v4i16;
5347 else if (VT == MVT::v8f16 && HasFullFP16)
5348 DestVecType = MVT::v8i16;
5349 else
5350 return DAG.UnrollVectorOp(Op.getNode());
5352 unsigned CastOpc;
5353 unsigned Opc;
5354 switch (Op.getOpcode()) {
5355 default: llvm_unreachable("Invalid opcode!");
5356 case ISD::SINT_TO_FP:
5357 CastOpc = ISD::SIGN_EXTEND;
5358 Opc = ISD::SINT_TO_FP;
5359 break;
5360 case ISD::UINT_TO_FP:
5361 CastOpc = ISD::ZERO_EXTEND;
5362 Opc = ISD::UINT_TO_FP;
5363 break;
5366 Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5367 return DAG.getNode(Opc, dl, VT, Op);
5370 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5371 EVT VT = Op.getValueType();
5372 if (VT.isVector())
5373 return LowerVectorINT_TO_FP(Op, DAG);
5374 if (isUnsupportedFloatingType(VT)) {
5375 RTLIB::Libcall LC;
5376 if (Op.getOpcode() == ISD::SINT_TO_FP)
5377 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5378 Op.getValueType());
5379 else
5380 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5381 Op.getValueType());
5382 MakeLibCallOptions CallOptions;
5383 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5384 CallOptions, SDLoc(Op)).first;
5387 return Op;
5390 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5391 // Implement fcopysign with a fabs and a conditional fneg.
5392 SDValue Tmp0 = Op.getOperand(0);
5393 SDValue Tmp1 = Op.getOperand(1);
5394 SDLoc dl(Op);
5395 EVT VT = Op.getValueType();
5396 EVT SrcVT = Tmp1.getValueType();
5397 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5398 Tmp0.getOpcode() == ARMISD::VMOVDRR;
5399 bool UseNEON = !InGPR && Subtarget->hasNEON();
5401 if (UseNEON) {
5402 // Use VBSL to copy the sign bit.
5403 unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5404 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5405 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5406 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5407 if (VT == MVT::f64)
5408 Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5409 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5410 DAG.getConstant(32, dl, MVT::i32));
5411 else /*if (VT == MVT::f32)*/
5412 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5413 if (SrcVT == MVT::f32) {
5414 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5415 if (VT == MVT::f64)
5416 Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5417 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5418 DAG.getConstant(32, dl, MVT::i32));
5419 } else if (VT == MVT::f32)
5420 Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5421 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5422 DAG.getConstant(32, dl, MVT::i32));
5423 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5424 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5426 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5427 dl, MVT::i32);
5428 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5429 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5430 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5432 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5433 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5434 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5435 if (VT == MVT::f32) {
5436 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5437 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5438 DAG.getConstant(0, dl, MVT::i32));
5439 } else {
5440 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5443 return Res;
5446 // Bitcast operand 1 to i32.
5447 if (SrcVT == MVT::f64)
5448 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5449 Tmp1).getValue(1);
5450 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5452 // Or in the signbit with integer operations.
5453 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5454 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5455 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5456 if (VT == MVT::f32) {
5457 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5458 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5459 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5460 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5463 // f64: Or the high part with signbit and then combine two parts.
5464 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5465 Tmp0);
5466 SDValue Lo = Tmp0.getValue(0);
5467 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5468 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5469 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5472 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5473 MachineFunction &MF = DAG.getMachineFunction();
5474 MachineFrameInfo &MFI = MF.getFrameInfo();
5475 MFI.setReturnAddressIsTaken(true);
5477 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5478 return SDValue();
5480 EVT VT = Op.getValueType();
5481 SDLoc dl(Op);
5482 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5483 if (Depth) {
5484 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5485 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5486 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5487 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5488 MachinePointerInfo());
5491 // Return LR, which contains the return address. Mark it an implicit live-in.
5492 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5493 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5496 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5497 const ARMBaseRegisterInfo &ARI =
5498 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5499 MachineFunction &MF = DAG.getMachineFunction();
5500 MachineFrameInfo &MFI = MF.getFrameInfo();
5501 MFI.setFrameAddressIsTaken(true);
5503 EVT VT = Op.getValueType();
5504 SDLoc dl(Op); // FIXME probably not meaningful
5505 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5506 Register FrameReg = ARI.getFrameRegister(MF);
5507 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5508 while (Depth--)
5509 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5510 MachinePointerInfo());
5511 return FrameAddr;
5514 // FIXME? Maybe this could be a TableGen attribute on some registers and
5515 // this table could be generated automatically from RegInfo.
5516 Register ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
5517 const MachineFunction &MF) const {
5518 Register Reg = StringSwitch<unsigned>(RegName)
5519 .Case("sp", ARM::SP)
5520 .Default(0);
5521 if (Reg)
5522 return Reg;
5523 report_fatal_error(Twine("Invalid register name \""
5524 + StringRef(RegName) + "\"."));
5527 // Result is 64 bit value so split into two 32 bit values and return as a
5528 // pair of values.
5529 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5530 SelectionDAG &DAG) {
5531 SDLoc DL(N);
5533 // This function is only supposed to be called for i64 type destination.
5534 assert(N->getValueType(0) == MVT::i64
5535 && "ExpandREAD_REGISTER called for non-i64 type result.");
5537 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5538 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5539 N->getOperand(0),
5540 N->getOperand(1));
5542 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5543 Read.getValue(1)));
5544 Results.push_back(Read.getOperand(0));
5547 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5548 /// When \p DstVT, the destination type of \p BC, is on the vector
5549 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5550 /// it might be possible to combine them, such that everything stays on the
5551 /// vector register bank.
5552 /// \p return The node that would replace \p BT, if the combine
5553 /// is possible.
5554 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5555 SelectionDAG &DAG) {
5556 SDValue Op = BC->getOperand(0);
5557 EVT DstVT = BC->getValueType(0);
5559 // The only vector instruction that can produce a scalar (remember,
5560 // since the bitcast was about to be turned into VMOVDRR, the source
5561 // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5562 // Moreover, we can do this combine only if there is one use.
5563 // Finally, if the destination type is not a vector, there is not
5564 // much point on forcing everything on the vector bank.
5565 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5566 !Op.hasOneUse())
5567 return SDValue();
5569 // If the index is not constant, we will introduce an additional
5570 // multiply that will stick.
5571 // Give up in that case.
5572 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5573 if (!Index)
5574 return SDValue();
5575 unsigned DstNumElt = DstVT.getVectorNumElements();
5577 // Compute the new index.
5578 const APInt &APIntIndex = Index->getAPIntValue();
5579 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5580 NewIndex *= APIntIndex;
5581 // Check if the new constant index fits into i32.
5582 if (NewIndex.getBitWidth() > 32)
5583 return SDValue();
5585 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5586 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5587 SDLoc dl(Op);
5588 SDValue ExtractSrc = Op.getOperand(0);
5589 EVT VecVT = EVT::getVectorVT(
5590 *DAG.getContext(), DstVT.getScalarType(),
5591 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5592 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5593 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5594 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5597 /// ExpandBITCAST - If the target supports VFP, this function is called to
5598 /// expand a bit convert where either the source or destination type is i64 to
5599 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
5600 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5601 /// vectors), since the legalizer won't know what to do with that.
5602 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5603 const ARMSubtarget *Subtarget) {
5604 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5605 SDLoc dl(N);
5606 SDValue Op = N->getOperand(0);
5608 // This function is only supposed to be called for i64 types, either as the
5609 // source or destination of the bit convert.
5610 EVT SrcVT = Op.getValueType();
5611 EVT DstVT = N->getValueType(0);
5612 const bool HasFullFP16 = Subtarget->hasFullFP16();
5614 if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5615 // FullFP16: half values are passed in S-registers, and we don't
5616 // need any of the bitcast and moves:
5618 // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5619 // t5: i32 = bitcast t2
5620 // t18: f16 = ARMISD::VMOVhr t5
5621 if (Op.getOpcode() != ISD::CopyFromReg ||
5622 Op.getValueType() != MVT::f32)
5623 return SDValue();
5625 auto Move = N->use_begin();
5626 if (Move->getOpcode() != ARMISD::VMOVhr)
5627 return SDValue();
5629 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5630 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5631 DAG.ReplaceAllUsesWith(*Move, &Copy);
5632 return Copy;
5635 if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5636 if (!HasFullFP16)
5637 return SDValue();
5638 // SoftFP: read half-precision arguments:
5640 // t2: i32,ch = ...
5641 // t7: i16 = truncate t2 <~~~~ Op
5642 // t8: f16 = bitcast t7 <~~~~ N
5644 if (Op.getOperand(0).getValueType() == MVT::i32)
5645 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5646 MVT::f16, Op.getOperand(0));
5648 return SDValue();
5651 // Half-precision return values
5652 if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5653 if (!HasFullFP16)
5654 return SDValue();
5656 // t11: f16 = fadd t8, t10
5657 // t12: i16 = bitcast t11 <~~~ SDNode N
5658 // t13: i32 = zero_extend t12
5659 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5660 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5662 // transform this into:
5664 // t20: i32 = ARMISD::VMOVrh t11
5665 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5667 auto ZeroExtend = N->use_begin();
5668 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5669 ZeroExtend->getValueType(0) != MVT::i32)
5670 return SDValue();
5672 auto Copy = ZeroExtend->use_begin();
5673 if (Copy->getOpcode() == ISD::CopyToReg &&
5674 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5675 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5676 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5677 return Cvt;
5679 return SDValue();
5682 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5683 return SDValue();
5685 // Turn i64->f64 into VMOVDRR.
5686 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5687 // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5688 // if we can combine the bitcast with its source.
5689 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5690 return Val;
5692 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5693 DAG.getConstant(0, dl, MVT::i32));
5694 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5695 DAG.getConstant(1, dl, MVT::i32));
5696 return DAG.getNode(ISD::BITCAST, dl, DstVT,
5697 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5700 // Turn f64->i64 into VMOVRRD.
5701 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5702 SDValue Cvt;
5703 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5704 SrcVT.getVectorNumElements() > 1)
5705 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5706 DAG.getVTList(MVT::i32, MVT::i32),
5707 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5708 else
5709 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5710 DAG.getVTList(MVT::i32, MVT::i32), Op);
5711 // Merge the pieces into a single i64 value.
5712 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5715 return SDValue();
5718 /// getZeroVector - Returns a vector of specified type with all zero elements.
5719 /// Zero vectors are used to represent vector negation and in those cases
5720 /// will be implemented with the NEON VNEG instruction. However, VNEG does
5721 /// not support i64 elements, so sometimes the zero vectors will need to be
5722 /// explicitly constructed. Regardless, use a canonical VMOV to create the
5723 /// zero vector.
5724 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5725 assert(VT.isVector() && "Expected a vector type");
5726 // The canonical modified immediate encoding of a zero vector is....0!
5727 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5728 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5729 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5730 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5733 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5734 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5735 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5736 SelectionDAG &DAG) const {
5737 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5738 EVT VT = Op.getValueType();
5739 unsigned VTBits = VT.getSizeInBits();
5740 SDLoc dl(Op);
5741 SDValue ShOpLo = Op.getOperand(0);
5742 SDValue ShOpHi = Op.getOperand(1);
5743 SDValue ShAmt = Op.getOperand(2);
5744 SDValue ARMcc;
5745 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5746 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5748 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_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, ShAmt);
5753 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5754 DAG.getConstant(VTBits, dl, MVT::i32));
5755 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5756 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5757 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5758 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5759 ISD::SETGE, ARMcc, DAG, dl);
5760 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5761 ARMcc, CCR, CmpLo);
5763 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5764 SDValue HiBigShift = Opc == ISD::SRA
5765 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5766 DAG.getConstant(VTBits - 1, dl, VT))
5767 : DAG.getConstant(0, dl, VT);
5768 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5769 ISD::SETGE, ARMcc, DAG, dl);
5770 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5771 ARMcc, CCR, CmpHi);
5773 SDValue Ops[2] = { Lo, Hi };
5774 return DAG.getMergeValues(Ops, dl);
5777 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5778 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5779 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5780 SelectionDAG &DAG) const {
5781 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5782 EVT VT = Op.getValueType();
5783 unsigned VTBits = VT.getSizeInBits();
5784 SDLoc dl(Op);
5785 SDValue ShOpLo = Op.getOperand(0);
5786 SDValue ShOpHi = Op.getOperand(1);
5787 SDValue ShAmt = Op.getOperand(2);
5788 SDValue ARMcc;
5789 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5791 assert(Op.getOpcode() == ISD::SHL_PARTS);
5792 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5793 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5794 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5795 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5796 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5798 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5799 DAG.getConstant(VTBits, dl, MVT::i32));
5800 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5801 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5802 ISD::SETGE, ARMcc, DAG, dl);
5803 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5804 ARMcc, CCR, CmpHi);
5806 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5807 ISD::SETGE, ARMcc, DAG, dl);
5808 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5809 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5810 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5812 SDValue Ops[2] = { Lo, Hi };
5813 return DAG.getMergeValues(Ops, dl);
5816 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5817 SelectionDAG &DAG) const {
5818 // The rounding mode is in bits 23:22 of the FPSCR.
5819 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5820 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5821 // so that the shift + and get folded into a bitfield extract.
5822 SDLoc dl(Op);
5823 SDValue Ops[] = { DAG.getEntryNode(),
5824 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5826 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5827 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5828 DAG.getConstant(1U << 22, dl, MVT::i32));
5829 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5830 DAG.getConstant(22, dl, MVT::i32));
5831 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5832 DAG.getConstant(3, dl, MVT::i32));
5835 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5836 const ARMSubtarget *ST) {
5837 SDLoc dl(N);
5838 EVT VT = N->getValueType(0);
5839 if (VT.isVector() && ST->hasNEON()) {
5841 // Compute the least significant set bit: LSB = X & -X
5842 SDValue X = N->getOperand(0);
5843 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5844 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5846 EVT ElemTy = VT.getVectorElementType();
5848 if (ElemTy == MVT::i8) {
5849 // Compute with: cttz(x) = ctpop(lsb - 1)
5850 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5851 DAG.getTargetConstant(1, dl, ElemTy));
5852 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5853 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5856 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5857 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5858 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5859 unsigned NumBits = ElemTy.getSizeInBits();
5860 SDValue WidthMinus1 =
5861 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5862 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5863 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5864 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5867 // Compute with: cttz(x) = ctpop(lsb - 1)
5869 // Compute LSB - 1.
5870 SDValue Bits;
5871 if (ElemTy == MVT::i64) {
5872 // Load constant 0xffff'ffff'ffff'ffff to register.
5873 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5874 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5875 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5876 } else {
5877 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5878 DAG.getTargetConstant(1, dl, ElemTy));
5879 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5881 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5884 if (!ST->hasV6T2Ops())
5885 return SDValue();
5887 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5888 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5891 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5892 const ARMSubtarget *ST) {
5893 EVT VT = N->getValueType(0);
5894 SDLoc DL(N);
5896 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5897 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5898 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5899 "Unexpected type for custom ctpop lowering");
5901 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5902 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5903 SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
5904 Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
5906 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5907 unsigned EltSize = 8;
5908 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5909 while (EltSize != VT.getScalarSizeInBits()) {
5910 SmallVector<SDValue, 8> Ops;
5911 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
5912 TLI.getPointerTy(DAG.getDataLayout())));
5913 Ops.push_back(Res);
5915 EltSize *= 2;
5916 NumElts /= 2;
5917 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5918 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
5921 return Res;
5924 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
5925 /// operand of a vector shift operation, where all the elements of the
5926 /// build_vector must have the same constant integer value.
5927 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5928 // Ignore bit_converts.
5929 while (Op.getOpcode() == ISD::BITCAST)
5930 Op = Op.getOperand(0);
5931 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5932 APInt SplatBits, SplatUndef;
5933 unsigned SplatBitSize;
5934 bool HasAnyUndefs;
5935 if (!BVN ||
5936 !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
5937 ElementBits) ||
5938 SplatBitSize > ElementBits)
5939 return false;
5940 Cnt = SplatBits.getSExtValue();
5941 return true;
5944 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5945 /// operand of a vector shift left operation. That value must be in the range:
5946 /// 0 <= Value < ElementBits for a left shift; or
5947 /// 0 <= Value <= ElementBits for a long left shift.
5948 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5949 assert(VT.isVector() && "vector shift count is not a vector type");
5950 int64_t ElementBits = VT.getScalarSizeInBits();
5951 if (!getVShiftImm(Op, ElementBits, Cnt))
5952 return false;
5953 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5956 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5957 /// operand of a vector shift right operation. For a shift opcode, the value
5958 /// is positive, but for an intrinsic the value count must be negative. The
5959 /// absolute value must be in the range:
5960 /// 1 <= |Value| <= ElementBits for a right shift; or
5961 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5962 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5963 int64_t &Cnt) {
5964 assert(VT.isVector() && "vector shift count is not a vector type");
5965 int64_t ElementBits = VT.getScalarSizeInBits();
5966 if (!getVShiftImm(Op, ElementBits, Cnt))
5967 return false;
5968 if (!isIntrinsic)
5969 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5970 if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
5971 Cnt = -Cnt;
5972 return true;
5974 return false;
5977 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5978 const ARMSubtarget *ST) {
5979 EVT VT = N->getValueType(0);
5980 SDLoc dl(N);
5981 int64_t Cnt;
5983 if (!VT.isVector())
5984 return SDValue();
5986 // We essentially have two forms here. Shift by an immediate and shift by a
5987 // vector register (there are also shift by a gpr, but that is just handled
5988 // with a tablegen pattern). We cannot easily match shift by an immediate in
5989 // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
5990 // For shifting by a vector, we don't have VSHR, only VSHL (which can be
5991 // signed or unsigned, and a negative shift indicates a shift right).
5992 if (N->getOpcode() == ISD::SHL) {
5993 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
5994 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
5995 DAG.getConstant(Cnt, dl, MVT::i32));
5996 return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
5997 N->getOperand(1));
6000 assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6001 "unexpected vector shift opcode");
6003 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6004 unsigned VShiftOpc =
6005 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6006 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6007 DAG.getConstant(Cnt, dl, MVT::i32));
6010 // Other right shifts we don't have operations for (we use a shift left by a
6011 // negative number).
6012 EVT ShiftVT = N->getOperand(1).getValueType();
6013 SDValue NegatedCount = DAG.getNode(
6014 ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6015 unsigned VShiftOpc =
6016 (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6017 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6020 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
6021 const ARMSubtarget *ST) {
6022 EVT VT = N->getValueType(0);
6023 SDLoc dl(N);
6025 // We can get here for a node like i32 = ISD::SHL i32, i64
6026 if (VT != MVT::i64)
6027 return SDValue();
6029 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6030 N->getOpcode() == ISD::SHL) &&
6031 "Unknown shift to lower!");
6033 unsigned ShOpc = N->getOpcode();
6034 if (ST->hasMVEIntegerOps()) {
6035 SDValue ShAmt = N->getOperand(1);
6036 unsigned ShPartsOpc = ARMISD::LSLL;
6037 ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
6039 // If the shift amount is greater than 32 or has a greater bitwidth than 64
6040 // then do the default optimisation
6041 if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6042 (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32)))
6043 return SDValue();
6045 // Extract the lower 32 bits of the shift amount if it's not an i32
6046 if (ShAmt->getValueType(0) != MVT::i32)
6047 ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6049 if (ShOpc == ISD::SRL) {
6050 if (!Con)
6051 // There is no t2LSRLr instruction so negate and perform an lsll if the
6052 // shift amount is in a register, emulating a right shift.
6053 ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6054 DAG.getConstant(0, dl, MVT::i32), ShAmt);
6055 else
6056 // Else generate an lsrl on the immediate shift amount
6057 ShPartsOpc = ARMISD::LSRL;
6058 } else if (ShOpc == ISD::SRA)
6059 ShPartsOpc = ARMISD::ASRL;
6061 // Lower 32 bits of the destination/source
6062 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6063 DAG.getConstant(0, dl, MVT::i32));
6064 // Upper 32 bits of the destination/source
6065 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6066 DAG.getConstant(1, dl, MVT::i32));
6068 // Generate the shift operation as computed above
6069 Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6070 ShAmt);
6071 // The upper 32 bits come from the second return value of lsll
6072 Hi = SDValue(Lo.getNode(), 1);
6073 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6076 // We only lower SRA, SRL of 1 here, all others use generic lowering.
6077 if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6078 return SDValue();
6080 // If we are in thumb mode, we don't have RRX.
6081 if (ST->isThumb1Only())
6082 return SDValue();
6084 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
6085 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6086 DAG.getConstant(0, dl, MVT::i32));
6087 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6088 DAG.getConstant(1, dl, MVT::i32));
6090 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6091 // captures the result into a carry flag.
6092 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6093 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6095 // The low part is an ARMISD::RRX operand, which shifts the carry in.
6096 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6098 // Merge the pieces into a single i64 value.
6099 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6102 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6103 const ARMSubtarget *ST) {
6104 bool Invert = false;
6105 bool Swap = false;
6106 unsigned Opc = ARMCC::AL;
6108 SDValue Op0 = Op.getOperand(0);
6109 SDValue Op1 = Op.getOperand(1);
6110 SDValue CC = Op.getOperand(2);
6111 EVT VT = Op.getValueType();
6112 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6113 SDLoc dl(Op);
6115 EVT CmpVT;
6116 if (ST->hasNEON())
6117 CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6118 else {
6119 assert(ST->hasMVEIntegerOps() &&
6120 "No hardware support for integer vector comparison!");
6122 if (Op.getValueType().getVectorElementType() != MVT::i1)
6123 return SDValue();
6125 // Make sure we expand floating point setcc to scalar if we do not have
6126 // mve.fp, so that we can handle them from there.
6127 if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6128 return SDValue();
6130 CmpVT = VT;
6133 if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6134 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6135 // Special-case integer 64-bit equality comparisons. They aren't legal,
6136 // but they can be lowered with a few vector instructions.
6137 unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6138 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6139 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6140 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6141 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6142 DAG.getCondCode(ISD::SETEQ));
6143 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6144 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6145 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6146 if (SetCCOpcode == ISD::SETNE)
6147 Merged = DAG.getNOT(dl, Merged, CmpVT);
6148 Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6149 return Merged;
6152 if (CmpVT.getVectorElementType() == MVT::i64)
6153 // 64-bit comparisons are not legal in general.
6154 return SDValue();
6156 if (Op1.getValueType().isFloatingPoint()) {
6157 switch (SetCCOpcode) {
6158 default: llvm_unreachable("Illegal FP comparison");
6159 case ISD::SETUNE:
6160 case ISD::SETNE:
6161 if (ST->hasMVEFloatOps()) {
6162 Opc = ARMCC::NE; break;
6163 } else {
6164 Invert = true; LLVM_FALLTHROUGH;
6166 case ISD::SETOEQ:
6167 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6168 case ISD::SETOLT:
6169 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6170 case ISD::SETOGT:
6171 case ISD::SETGT: Opc = ARMCC::GT; break;
6172 case ISD::SETOLE:
6173 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6174 case ISD::SETOGE:
6175 case ISD::SETGE: Opc = ARMCC::GE; break;
6176 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
6177 case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6178 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
6179 case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6180 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
6181 case ISD::SETONE: {
6182 // Expand this to (OLT | OGT).
6183 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6184 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6185 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6186 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6187 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6188 if (Invert)
6189 Result = DAG.getNOT(dl, Result, VT);
6190 return Result;
6192 case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH;
6193 case ISD::SETO: {
6194 // Expand this to (OLT | OGE).
6195 SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6196 DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6197 SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6198 DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6199 SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6200 if (Invert)
6201 Result = DAG.getNOT(dl, Result, VT);
6202 return Result;
6205 } else {
6206 // Integer comparisons.
6207 switch (SetCCOpcode) {
6208 default: llvm_unreachable("Illegal integer comparison");
6209 case ISD::SETNE:
6210 if (ST->hasMVEIntegerOps()) {
6211 Opc = ARMCC::NE; break;
6212 } else {
6213 Invert = true; LLVM_FALLTHROUGH;
6215 case ISD::SETEQ: Opc = ARMCC::EQ; break;
6216 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6217 case ISD::SETGT: Opc = ARMCC::GT; break;
6218 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH;
6219 case ISD::SETGE: Opc = ARMCC::GE; break;
6220 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
6221 case ISD::SETUGT: Opc = ARMCC::HI; break;
6222 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
6223 case ISD::SETUGE: Opc = ARMCC::HS; break;
6226 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6227 if (ST->hasNEON() && Opc == ARMCC::EQ) {
6228 SDValue AndOp;
6229 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6230 AndOp = Op0;
6231 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6232 AndOp = Op1;
6234 // Ignore bitconvert.
6235 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6236 AndOp = AndOp.getOperand(0);
6238 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6239 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6240 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6241 SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6242 if (!Invert)
6243 Result = DAG.getNOT(dl, Result, VT);
6244 return Result;
6249 if (Swap)
6250 std::swap(Op0, Op1);
6252 // If one of the operands is a constant vector zero, attempt to fold the
6253 // comparison to a specialized compare-against-zero form.
6254 SDValue SingleOp;
6255 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6256 SingleOp = Op0;
6257 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6258 if (Opc == ARMCC::GE)
6259 Opc = ARMCC::LE;
6260 else if (Opc == ARMCC::GT)
6261 Opc = ARMCC::LT;
6262 SingleOp = Op1;
6265 SDValue Result;
6266 if (SingleOp.getNode()) {
6267 Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6268 DAG.getConstant(Opc, dl, MVT::i32));
6269 } else {
6270 Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6271 DAG.getConstant(Opc, dl, MVT::i32));
6274 Result = DAG.getSExtOrTrunc(Result, dl, VT);
6276 if (Invert)
6277 Result = DAG.getNOT(dl, Result, VT);
6279 return Result;
6282 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6283 SDValue LHS = Op.getOperand(0);
6284 SDValue RHS = Op.getOperand(1);
6285 SDValue Carry = Op.getOperand(2);
6286 SDValue Cond = Op.getOperand(3);
6287 SDLoc DL(Op);
6289 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6291 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6292 // have to invert the carry first.
6293 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6294 DAG.getConstant(1, DL, MVT::i32), Carry);
6295 // This converts the boolean value carry into the carry flag.
6296 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6298 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6299 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6301 SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6302 SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6303 SDValue ARMcc = DAG.getConstant(
6304 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6305 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6306 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6307 Cmp.getValue(1), SDValue());
6308 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6309 CCR, Chain.getValue(1));
6312 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6313 /// valid vector constant for a NEON or MVE instruction with a "modified
6314 /// immediate" operand (e.g., VMOV). If so, return the encoded value.
6315 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6316 unsigned SplatBitSize, SelectionDAG &DAG,
6317 const SDLoc &dl, EVT &VT, bool is128Bits,
6318 VMOVModImmType type) {
6319 unsigned OpCmode, Imm;
6321 // SplatBitSize is set to the smallest size that splats the vector, so a
6322 // zero vector will always have SplatBitSize == 8. However, NEON modified
6323 // immediate instructions others than VMOV do not support the 8-bit encoding
6324 // of a zero vector, and the default encoding of zero is supposed to be the
6325 // 32-bit version.
6326 if (SplatBits == 0)
6327 SplatBitSize = 32;
6329 switch (SplatBitSize) {
6330 case 8:
6331 if (type != VMOVModImm)
6332 return SDValue();
6333 // Any 1-byte value is OK. Op=0, Cmode=1110.
6334 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6335 OpCmode = 0xe;
6336 Imm = SplatBits;
6337 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6338 break;
6340 case 16:
6341 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6342 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6343 if ((SplatBits & ~0xff) == 0) {
6344 // Value = 0x00nn: Op=x, Cmode=100x.
6345 OpCmode = 0x8;
6346 Imm = SplatBits;
6347 break;
6349 if ((SplatBits & ~0xff00) == 0) {
6350 // Value = 0xnn00: Op=x, Cmode=101x.
6351 OpCmode = 0xa;
6352 Imm = SplatBits >> 8;
6353 break;
6355 return SDValue();
6357 case 32:
6358 // NEON's 32-bit VMOV supports splat values where:
6359 // * only one byte is nonzero, or
6360 // * the least significant byte is 0xff and the second byte is nonzero, or
6361 // * the least significant 2 bytes are 0xff and the third is nonzero.
6362 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6363 if ((SplatBits & ~0xff) == 0) {
6364 // Value = 0x000000nn: Op=x, Cmode=000x.
6365 OpCmode = 0;
6366 Imm = SplatBits;
6367 break;
6369 if ((SplatBits & ~0xff00) == 0) {
6370 // Value = 0x0000nn00: Op=x, Cmode=001x.
6371 OpCmode = 0x2;
6372 Imm = SplatBits >> 8;
6373 break;
6375 if ((SplatBits & ~0xff0000) == 0) {
6376 // Value = 0x00nn0000: Op=x, Cmode=010x.
6377 OpCmode = 0x4;
6378 Imm = SplatBits >> 16;
6379 break;
6381 if ((SplatBits & ~0xff000000) == 0) {
6382 // Value = 0xnn000000: Op=x, Cmode=011x.
6383 OpCmode = 0x6;
6384 Imm = SplatBits >> 24;
6385 break;
6388 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6389 if (type == OtherModImm) return SDValue();
6391 if ((SplatBits & ~0xffff) == 0 &&
6392 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6393 // Value = 0x0000nnff: Op=x, Cmode=1100.
6394 OpCmode = 0xc;
6395 Imm = SplatBits >> 8;
6396 break;
6399 // cmode == 0b1101 is not supported for MVE VMVN
6400 if (type == MVEVMVNModImm)
6401 return SDValue();
6403 if ((SplatBits & ~0xffffff) == 0 &&
6404 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6405 // Value = 0x00nnffff: Op=x, Cmode=1101.
6406 OpCmode = 0xd;
6407 Imm = SplatBits >> 16;
6408 break;
6411 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6412 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6413 // VMOV.I32. A (very) minor optimization would be to replicate the value
6414 // and fall through here to test for a valid 64-bit splat. But, then the
6415 // caller would also need to check and handle the change in size.
6416 return SDValue();
6418 case 64: {
6419 if (type != VMOVModImm)
6420 return SDValue();
6421 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6422 uint64_t BitMask = 0xff;
6423 uint64_t Val = 0;
6424 unsigned ImmMask = 1;
6425 Imm = 0;
6426 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6427 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6428 Val |= BitMask;
6429 Imm |= ImmMask;
6430 } else if ((SplatBits & BitMask) != 0) {
6431 return SDValue();
6433 BitMask <<= 8;
6434 ImmMask <<= 1;
6437 if (DAG.getDataLayout().isBigEndian())
6438 // swap higher and lower 32 bit word
6439 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
6441 // Op=1, Cmode=1110.
6442 OpCmode = 0x1e;
6443 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6444 break;
6447 default:
6448 llvm_unreachable("unexpected size for isVMOVModifiedImm");
6451 unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6452 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6455 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6456 const ARMSubtarget *ST) const {
6457 EVT VT = Op.getValueType();
6458 bool IsDouble = (VT == MVT::f64);
6459 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6460 const APFloat &FPVal = CFP->getValueAPF();
6462 // Prevent floating-point constants from using literal loads
6463 // when execute-only is enabled.
6464 if (ST->genExecuteOnly()) {
6465 // If we can represent the constant as an immediate, don't lower it
6466 if (isFPImmLegal(FPVal, VT))
6467 return Op;
6468 // Otherwise, construct as integer, and move to float register
6469 APInt INTVal = FPVal.bitcastToAPInt();
6470 SDLoc DL(CFP);
6471 switch (VT.getSimpleVT().SimpleTy) {
6472 default:
6473 llvm_unreachable("Unknown floating point type!");
6474 break;
6475 case MVT::f64: {
6476 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6477 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6478 if (!ST->isLittle())
6479 std::swap(Lo, Hi);
6480 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6482 case MVT::f32:
6483 return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6484 DAG.getConstant(INTVal, DL, MVT::i32));
6488 if (!ST->hasVFP3Base())
6489 return SDValue();
6491 // Use the default (constant pool) lowering for double constants when we have
6492 // an SP-only FPU
6493 if (IsDouble && !Subtarget->hasFP64())
6494 return SDValue();
6496 // Try splatting with a VMOV.f32...
6497 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6499 if (ImmVal != -1) {
6500 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6501 // We have code in place to select a valid ConstantFP already, no need to
6502 // do any mangling.
6503 return Op;
6506 // It's a float and we are trying to use NEON operations where
6507 // possible. Lower it to a splat followed by an extract.
6508 SDLoc DL(Op);
6509 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6510 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6511 NewVal);
6512 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6513 DAG.getConstant(0, DL, MVT::i32));
6516 // The rest of our options are NEON only, make sure that's allowed before
6517 // proceeding..
6518 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6519 return SDValue();
6521 EVT VMovVT;
6522 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6524 // It wouldn't really be worth bothering for doubles except for one very
6525 // important value, which does happen to match: 0.0. So make sure we don't do
6526 // anything stupid.
6527 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6528 return SDValue();
6530 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6531 SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6532 VMovVT, false, VMOVModImm);
6533 if (NewVal != SDValue()) {
6534 SDLoc DL(Op);
6535 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6536 NewVal);
6537 if (IsDouble)
6538 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6540 // It's a float: cast and extract a vector element.
6541 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6542 VecConstant);
6543 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6544 DAG.getConstant(0, DL, MVT::i32));
6547 // Finally, try a VMVN.i32
6548 NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6549 false, VMVNModImm);
6550 if (NewVal != SDValue()) {
6551 SDLoc DL(Op);
6552 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6554 if (IsDouble)
6555 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6557 // It's a float: cast and extract a vector element.
6558 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6559 VecConstant);
6560 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6561 DAG.getConstant(0, DL, MVT::i32));
6564 return SDValue();
6567 // check if an VEXT instruction can handle the shuffle mask when the
6568 // vector sources of the shuffle are the same.
6569 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6570 unsigned NumElts = VT.getVectorNumElements();
6572 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6573 if (M[0] < 0)
6574 return false;
6576 Imm = M[0];
6578 // If this is a VEXT shuffle, the immediate value is the index of the first
6579 // element. The other shuffle indices must be the successive elements after
6580 // the first one.
6581 unsigned ExpectedElt = Imm;
6582 for (unsigned i = 1; i < NumElts; ++i) {
6583 // Increment the expected index. If it wraps around, just follow it
6584 // back to index zero and keep going.
6585 ++ExpectedElt;
6586 if (ExpectedElt == NumElts)
6587 ExpectedElt = 0;
6589 if (M[i] < 0) continue; // ignore UNDEF indices
6590 if (ExpectedElt != static_cast<unsigned>(M[i]))
6591 return false;
6594 return true;
6597 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6598 bool &ReverseVEXT, unsigned &Imm) {
6599 unsigned NumElts = VT.getVectorNumElements();
6600 ReverseVEXT = false;
6602 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6603 if (M[0] < 0)
6604 return false;
6606 Imm = M[0];
6608 // If this is a VEXT shuffle, the immediate value is the index of the first
6609 // element. The other shuffle indices must be the successive elements after
6610 // the first one.
6611 unsigned ExpectedElt = Imm;
6612 for (unsigned i = 1; i < NumElts; ++i) {
6613 // Increment the expected index. If it wraps around, it may still be
6614 // a VEXT but the source vectors must be swapped.
6615 ExpectedElt += 1;
6616 if (ExpectedElt == NumElts * 2) {
6617 ExpectedElt = 0;
6618 ReverseVEXT = true;
6621 if (M[i] < 0) continue; // ignore UNDEF indices
6622 if (ExpectedElt != static_cast<unsigned>(M[i]))
6623 return false;
6626 // Adjust the index value if the source operands will be swapped.
6627 if (ReverseVEXT)
6628 Imm -= NumElts;
6630 return true;
6633 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6634 /// instruction with the specified blocksize. (The order of the elements
6635 /// within each block of the vector is reversed.)
6636 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6637 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6638 "Only possible block sizes for VREV are: 16, 32, 64");
6640 unsigned EltSz = VT.getScalarSizeInBits();
6641 if (EltSz == 64)
6642 return false;
6644 unsigned NumElts = VT.getVectorNumElements();
6645 unsigned BlockElts = M[0] + 1;
6646 // If the first shuffle index is UNDEF, be optimistic.
6647 if (M[0] < 0)
6648 BlockElts = BlockSize / EltSz;
6650 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6651 return false;
6653 for (unsigned i = 0; i < NumElts; ++i) {
6654 if (M[i] < 0) continue; // ignore UNDEF indices
6655 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6656 return false;
6659 return true;
6662 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6663 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6664 // range, then 0 is placed into the resulting vector. So pretty much any mask
6665 // of 8 elements can work here.
6666 return VT == MVT::v8i8 && M.size() == 8;
6669 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6670 unsigned Index) {
6671 if (Mask.size() == Elements * 2)
6672 return Index / Elements;
6673 return Mask[Index] == 0 ? 0 : 1;
6676 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6677 // checking that pairs of elements in the shuffle mask represent the same index
6678 // in each vector, incrementing the expected index by 2 at each step.
6679 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6680 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6681 // v2={e,f,g,h}
6682 // WhichResult gives the offset for each element in the mask based on which
6683 // of the two results it belongs to.
6685 // The transpose can be represented either as:
6686 // result1 = shufflevector v1, v2, result1_shuffle_mask
6687 // result2 = shufflevector v1, v2, result2_shuffle_mask
6688 // where v1/v2 and the shuffle masks have the same number of elements
6689 // (here WhichResult (see below) indicates which result is being checked)
6691 // or as:
6692 // results = shufflevector v1, v2, shuffle_mask
6693 // where both results are returned in one vector and the shuffle mask has twice
6694 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6695 // want to check the low half and high half of the shuffle mask as if it were
6696 // the other case
6697 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6698 unsigned EltSz = VT.getScalarSizeInBits();
6699 if (EltSz == 64)
6700 return false;
6702 unsigned NumElts = VT.getVectorNumElements();
6703 if (M.size() != NumElts && M.size() != NumElts*2)
6704 return false;
6706 // If the mask is twice as long as the input vector then we need to check the
6707 // upper and lower parts of the mask with a matching value for WhichResult
6708 // FIXME: A mask with only even values will be rejected in case the first
6709 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6710 // M[0] is used to determine WhichResult
6711 for (unsigned i = 0; i < M.size(); i += NumElts) {
6712 WhichResult = SelectPairHalf(NumElts, M, i);
6713 for (unsigned j = 0; j < NumElts; j += 2) {
6714 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6715 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6716 return false;
6720 if (M.size() == NumElts*2)
6721 WhichResult = 0;
6723 return true;
6726 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6727 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6728 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6729 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6730 unsigned EltSz = VT.getScalarSizeInBits();
6731 if (EltSz == 64)
6732 return false;
6734 unsigned NumElts = VT.getVectorNumElements();
6735 if (M.size() != NumElts && M.size() != NumElts*2)
6736 return false;
6738 for (unsigned i = 0; i < M.size(); i += NumElts) {
6739 WhichResult = SelectPairHalf(NumElts, M, i);
6740 for (unsigned j = 0; j < NumElts; j += 2) {
6741 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6742 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6743 return false;
6747 if (M.size() == NumElts*2)
6748 WhichResult = 0;
6750 return true;
6753 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6754 // that the mask elements are either all even and in steps of size 2 or all odd
6755 // and in steps of size 2.
6756 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6757 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6758 // v2={e,f,g,h}
6759 // Requires similar checks to that of isVTRNMask with
6760 // respect the how results are returned.
6761 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6762 unsigned EltSz = VT.getScalarSizeInBits();
6763 if (EltSz == 64)
6764 return false;
6766 unsigned NumElts = VT.getVectorNumElements();
6767 if (M.size() != NumElts && M.size() != NumElts*2)
6768 return false;
6770 for (unsigned i = 0; i < M.size(); i += NumElts) {
6771 WhichResult = SelectPairHalf(NumElts, M, i);
6772 for (unsigned j = 0; j < NumElts; ++j) {
6773 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6774 return false;
6778 if (M.size() == NumElts*2)
6779 WhichResult = 0;
6781 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6782 if (VT.is64BitVector() && EltSz == 32)
6783 return false;
6785 return true;
6788 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6789 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6790 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6791 static bool isVUZP_v_undef_Mask(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 unsigned Half = NumElts / 2;
6801 for (unsigned i = 0; i < M.size(); i += NumElts) {
6802 WhichResult = SelectPairHalf(NumElts, M, i);
6803 for (unsigned j = 0; j < NumElts; j += Half) {
6804 unsigned Idx = WhichResult;
6805 for (unsigned k = 0; k < Half; ++k) {
6806 int MIdx = M[i + j + k];
6807 if (MIdx >= 0 && (unsigned) MIdx != Idx)
6808 return false;
6809 Idx += 2;
6814 if (M.size() == NumElts*2)
6815 WhichResult = 0;
6817 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6818 if (VT.is64BitVector() && EltSz == 32)
6819 return false;
6821 return true;
6824 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6825 // that pairs of elements of the shufflemask represent the same index in each
6826 // vector incrementing sequentially through the vectors.
6827 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6828 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6829 // v2={e,f,g,h}
6830 // Requires similar checks to that of isVTRNMask with respect the how results
6831 // are returned.
6832 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6833 unsigned EltSz = VT.getScalarSizeInBits();
6834 if (EltSz == 64)
6835 return false;
6837 unsigned NumElts = VT.getVectorNumElements();
6838 if (M.size() != NumElts && M.size() != NumElts*2)
6839 return false;
6841 for (unsigned i = 0; i < M.size(); i += NumElts) {
6842 WhichResult = SelectPairHalf(NumElts, M, i);
6843 unsigned Idx = WhichResult * NumElts / 2;
6844 for (unsigned j = 0; j < NumElts; j += 2) {
6845 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6846 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6847 return false;
6848 Idx += 1;
6852 if (M.size() == NumElts*2)
6853 WhichResult = 0;
6855 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6856 if (VT.is64BitVector() && EltSz == 32)
6857 return false;
6859 return true;
6862 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6863 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6864 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6865 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6866 unsigned EltSz = VT.getScalarSizeInBits();
6867 if (EltSz == 64)
6868 return false;
6870 unsigned NumElts = VT.getVectorNumElements();
6871 if (M.size() != NumElts && M.size() != NumElts*2)
6872 return false;
6874 for (unsigned i = 0; i < M.size(); i += NumElts) {
6875 WhichResult = SelectPairHalf(NumElts, M, i);
6876 unsigned Idx = WhichResult * NumElts / 2;
6877 for (unsigned j = 0; j < NumElts; j += 2) {
6878 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6879 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6880 return false;
6881 Idx += 1;
6885 if (M.size() == NumElts*2)
6886 WhichResult = 0;
6888 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6889 if (VT.is64BitVector() && EltSz == 32)
6890 return false;
6892 return true;
6895 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6896 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6897 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6898 unsigned &WhichResult,
6899 bool &isV_UNDEF) {
6900 isV_UNDEF = false;
6901 if (isVTRNMask(ShuffleMask, VT, WhichResult))
6902 return ARMISD::VTRN;
6903 if (isVUZPMask(ShuffleMask, VT, WhichResult))
6904 return ARMISD::VUZP;
6905 if (isVZIPMask(ShuffleMask, VT, WhichResult))
6906 return ARMISD::VZIP;
6908 isV_UNDEF = true;
6909 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6910 return ARMISD::VTRN;
6911 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6912 return ARMISD::VUZP;
6913 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6914 return ARMISD::VZIP;
6916 return 0;
6919 /// \return true if this is a reverse operation on an vector.
6920 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6921 unsigned NumElts = VT.getVectorNumElements();
6922 // Make sure the mask has the right size.
6923 if (NumElts != M.size())
6924 return false;
6926 // Look for <15, ..., 3, -1, 1, 0>.
6927 for (unsigned i = 0; i != NumElts; ++i)
6928 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6929 return false;
6931 return true;
6934 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top) {
6935 unsigned NumElts = VT.getVectorNumElements();
6936 // Make sure the mask has the right size.
6937 if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
6938 return false;
6940 // If Top
6941 // Look for <0, N, 2, N+2, 4, N+4, ..>.
6942 // This inserts Input2 into Input1
6943 // else if not Top
6944 // Look for <0, N+1, 2, N+3, 4, N+5, ..>
6945 // This inserts Input1 into Input2
6946 unsigned Offset = Top ? 0 : 1;
6947 for (unsigned i = 0; i < NumElts; i+=2) {
6948 if (M[i] >= 0 && M[i] != (int)i)
6949 return false;
6950 if (M[i+1] >= 0 && M[i+1] != (int)(NumElts + i + Offset))
6951 return false;
6954 return true;
6957 // If N is an integer constant that can be moved into a register in one
6958 // instruction, return an SDValue of such a constant (will become a MOV
6959 // instruction). Otherwise return null.
6960 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6961 const ARMSubtarget *ST, const SDLoc &dl) {
6962 uint64_t Val;
6963 if (!isa<ConstantSDNode>(N))
6964 return SDValue();
6965 Val = cast<ConstantSDNode>(N)->getZExtValue();
6967 if (ST->isThumb1Only()) {
6968 if (Val <= 255 || ~Val <= 255)
6969 return DAG.getConstant(Val, dl, MVT::i32);
6970 } else {
6971 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6972 return DAG.getConstant(Val, dl, MVT::i32);
6974 return SDValue();
6977 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
6978 const ARMSubtarget *ST) {
6979 SDLoc dl(Op);
6980 EVT VT = Op.getValueType();
6982 assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
6984 unsigned NumElts = VT.getVectorNumElements();
6985 unsigned BoolMask;
6986 unsigned BitsPerBool;
6987 if (NumElts == 4) {
6988 BitsPerBool = 4;
6989 BoolMask = 0xf;
6990 } else if (NumElts == 8) {
6991 BitsPerBool = 2;
6992 BoolMask = 0x3;
6993 } else if (NumElts == 16) {
6994 BitsPerBool = 1;
6995 BoolMask = 0x1;
6996 } else
6997 return SDValue();
6999 // If this is a single value copied into all lanes (a splat), we can just sign
7000 // extend that single value
7001 SDValue FirstOp = Op.getOperand(0);
7002 if (!isa<ConstantSDNode>(FirstOp) &&
7003 std::all_of(std::next(Op->op_begin()), Op->op_end(),
7004 [&FirstOp](SDUse &U) {
7005 return U.get().isUndef() || U.get() == FirstOp;
7006 })) {
7007 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7008 DAG.getValueType(MVT::i1));
7009 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7012 // First create base with bits set where known
7013 unsigned Bits32 = 0;
7014 for (unsigned i = 0; i < NumElts; ++i) {
7015 SDValue V = Op.getOperand(i);
7016 if (!isa<ConstantSDNode>(V) && !V.isUndef())
7017 continue;
7018 bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
7019 if (BitSet)
7020 Bits32 |= BoolMask << (i * BitsPerBool);
7023 // Add in unknown nodes
7024 SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7025 DAG.getConstant(Bits32, dl, MVT::i32));
7026 for (unsigned i = 0; i < NumElts; ++i) {
7027 SDValue V = Op.getOperand(i);
7028 if (isa<ConstantSDNode>(V) || V.isUndef())
7029 continue;
7030 Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7031 DAG.getConstant(i, dl, MVT::i32));
7034 return Base;
7037 // If this is a case we can't handle, return null and let the default
7038 // expansion code take care of it.
7039 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7040 const ARMSubtarget *ST) const {
7041 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7042 SDLoc dl(Op);
7043 EVT VT = Op.getValueType();
7045 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7046 return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7048 APInt SplatBits, SplatUndef;
7049 unsigned SplatBitSize;
7050 bool HasAnyUndefs;
7051 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7052 if (SplatUndef.isAllOnesValue())
7053 return DAG.getUNDEF(VT);
7055 if ((ST->hasNEON() && SplatBitSize <= 64) ||
7056 (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) {
7057 // Check if an immediate VMOV works.
7058 EVT VmovVT;
7059 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
7060 SplatUndef.getZExtValue(), SplatBitSize,
7061 DAG, dl, VmovVT, VT.is128BitVector(),
7062 VMOVModImm);
7064 if (Val.getNode()) {
7065 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7066 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7069 // Try an immediate VMVN.
7070 uint64_t NegatedImm = (~SplatBits).getZExtValue();
7071 Val = isVMOVModifiedImm(
7072 NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
7073 DAG, dl, VmovVT, VT.is128BitVector(),
7074 ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7075 if (Val.getNode()) {
7076 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7077 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7080 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7081 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7082 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7083 if (ImmVal != -1) {
7084 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7085 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7091 // Scan through the operands to see if only one value is used.
7093 // As an optimisation, even if more than one value is used it may be more
7094 // profitable to splat with one value then change some lanes.
7096 // Heuristically we decide to do this if the vector has a "dominant" value,
7097 // defined as splatted to more than half of the lanes.
7098 unsigned NumElts = VT.getVectorNumElements();
7099 bool isOnlyLowElement = true;
7100 bool usesOnlyOneValue = true;
7101 bool hasDominantValue = false;
7102 bool isConstant = true;
7104 // Map of the number of times a particular SDValue appears in the
7105 // element list.
7106 DenseMap<SDValue, unsigned> ValueCounts;
7107 SDValue Value;
7108 for (unsigned i = 0; i < NumElts; ++i) {
7109 SDValue V = Op.getOperand(i);
7110 if (V.isUndef())
7111 continue;
7112 if (i > 0)
7113 isOnlyLowElement = false;
7114 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7115 isConstant = false;
7117 ValueCounts.insert(std::make_pair(V, 0));
7118 unsigned &Count = ValueCounts[V];
7120 // Is this value dominant? (takes up more than half of the lanes)
7121 if (++Count > (NumElts / 2)) {
7122 hasDominantValue = true;
7123 Value = V;
7126 if (ValueCounts.size() != 1)
7127 usesOnlyOneValue = false;
7128 if (!Value.getNode() && !ValueCounts.empty())
7129 Value = ValueCounts.begin()->first;
7131 if (ValueCounts.empty())
7132 return DAG.getUNDEF(VT);
7134 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7135 // Keep going if we are hitting this case.
7136 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7137 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7139 unsigned EltSize = VT.getScalarSizeInBits();
7141 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
7142 // i32 and try again.
7143 if (hasDominantValue && EltSize <= 32) {
7144 if (!isConstant) {
7145 SDValue N;
7147 // If we are VDUPing a value that comes directly from a vector, that will
7148 // cause an unnecessary move to and from a GPR, where instead we could
7149 // just use VDUPLANE. We can only do this if the lane being extracted
7150 // is at a constant index, as the VDUP from lane instructions only have
7151 // constant-index forms.
7152 ConstantSDNode *constIndex;
7153 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7154 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7155 // We need to create a new undef vector to use for the VDUPLANE if the
7156 // size of the vector from which we get the value is different than the
7157 // size of the vector that we need to create. We will insert the element
7158 // such that the register coalescer will remove unnecessary copies.
7159 if (VT != Value->getOperand(0).getValueType()) {
7160 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7161 VT.getVectorNumElements();
7162 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7163 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7164 Value, DAG.getConstant(index, dl, MVT::i32)),
7165 DAG.getConstant(index, dl, MVT::i32));
7166 } else
7167 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7168 Value->getOperand(0), Value->getOperand(1));
7169 } else
7170 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7172 if (!usesOnlyOneValue) {
7173 // The dominant value was splatted as 'N', but we now have to insert
7174 // all differing elements.
7175 for (unsigned I = 0; I < NumElts; ++I) {
7176 if (Op.getOperand(I) == Value)
7177 continue;
7178 SmallVector<SDValue, 3> Ops;
7179 Ops.push_back(N);
7180 Ops.push_back(Op.getOperand(I));
7181 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7182 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7185 return N;
7187 if (VT.getVectorElementType().isFloatingPoint()) {
7188 SmallVector<SDValue, 8> Ops;
7189 MVT FVT = VT.getVectorElementType().getSimpleVT();
7190 assert(FVT == MVT::f32 || FVT == MVT::f16);
7191 MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7192 for (unsigned i = 0; i < NumElts; ++i)
7193 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7194 Op.getOperand(i)));
7195 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7196 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7197 Val = LowerBUILD_VECTOR(Val, DAG, ST);
7198 if (Val.getNode())
7199 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7201 if (usesOnlyOneValue) {
7202 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7203 if (isConstant && Val.getNode())
7204 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7208 // If all elements are constants and the case above didn't get hit, fall back
7209 // to the default expansion, which will generate a load from the constant
7210 // pool.
7211 if (isConstant)
7212 return SDValue();
7214 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7215 if (NumElts >= 4) {
7216 SDValue shuffle = ReconstructShuffle(Op, DAG);
7217 if (shuffle != SDValue())
7218 return shuffle;
7221 if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7222 // If we haven't found an efficient lowering, try splitting a 128-bit vector
7223 // into two 64-bit vectors; we might discover a better way to lower it.
7224 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7225 EVT ExtVT = VT.getVectorElementType();
7226 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7227 SDValue Lower =
7228 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7229 if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7230 Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7231 SDValue Upper = DAG.getBuildVector(
7232 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7233 if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7234 Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7235 if (Lower && Upper)
7236 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7239 // Vectors with 32- or 64-bit elements can be built by directly assigning
7240 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
7241 // will be legalized.
7242 if (EltSize >= 32) {
7243 // Do the expansion with floating-point types, since that is what the VFP
7244 // registers are defined to use, and since i64 is not legal.
7245 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7246 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7247 SmallVector<SDValue, 8> Ops;
7248 for (unsigned i = 0; i < NumElts; ++i)
7249 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7250 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7251 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7254 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7255 // know the default expansion would otherwise fall back on something even
7256 // worse. For a vector with one or two non-undef values, that's
7257 // scalar_to_vector for the elements followed by a shuffle (provided the
7258 // shuffle is valid for the target) and materialization element by element
7259 // on the stack followed by a load for everything else.
7260 if (!isConstant && !usesOnlyOneValue) {
7261 SDValue Vec = DAG.getUNDEF(VT);
7262 for (unsigned i = 0 ; i < NumElts; ++i) {
7263 SDValue V = Op.getOperand(i);
7264 if (V.isUndef())
7265 continue;
7266 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7267 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7269 return Vec;
7272 return SDValue();
7275 // Gather data to see if the operation can be modelled as a
7276 // shuffle in combination with VEXTs.
7277 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7278 SelectionDAG &DAG) const {
7279 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7280 SDLoc dl(Op);
7281 EVT VT = Op.getValueType();
7282 unsigned NumElts = VT.getVectorNumElements();
7284 struct ShuffleSourceInfo {
7285 SDValue Vec;
7286 unsigned MinElt = std::numeric_limits<unsigned>::max();
7287 unsigned MaxElt = 0;
7289 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7290 // be compatible with the shuffle we intend to construct. As a result
7291 // ShuffleVec will be some sliding window into the original Vec.
7292 SDValue ShuffleVec;
7294 // Code should guarantee that element i in Vec starts at element "WindowBase
7295 // + i * WindowScale in ShuffleVec".
7296 int WindowBase = 0;
7297 int WindowScale = 1;
7299 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7301 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7304 // First gather all vectors used as an immediate source for this BUILD_VECTOR
7305 // node.
7306 SmallVector<ShuffleSourceInfo, 2> Sources;
7307 for (unsigned i = 0; i < NumElts; ++i) {
7308 SDValue V = Op.getOperand(i);
7309 if (V.isUndef())
7310 continue;
7311 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7312 // A shuffle can only come from building a vector from various
7313 // elements of other vectors.
7314 return SDValue();
7315 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7316 // Furthermore, shuffles require a constant mask, whereas extractelts
7317 // accept variable indices.
7318 return SDValue();
7321 // Add this element source to the list if it's not already there.
7322 SDValue SourceVec = V.getOperand(0);
7323 auto Source = llvm::find(Sources, SourceVec);
7324 if (Source == Sources.end())
7325 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7327 // Update the minimum and maximum lane number seen.
7328 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7329 Source->MinElt = std::min(Source->MinElt, EltNo);
7330 Source->MaxElt = std::max(Source->MaxElt, EltNo);
7333 // Currently only do something sane when at most two source vectors
7334 // are involved.
7335 if (Sources.size() > 2)
7336 return SDValue();
7338 // Find out the smallest element size among result and two sources, and use
7339 // it as element size to build the shuffle_vector.
7340 EVT SmallestEltTy = VT.getVectorElementType();
7341 for (auto &Source : Sources) {
7342 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7343 if (SrcEltTy.bitsLT(SmallestEltTy))
7344 SmallestEltTy = SrcEltTy;
7346 unsigned ResMultiplier =
7347 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7348 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7349 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7351 // If the source vector is too wide or too narrow, we may nevertheless be able
7352 // to construct a compatible shuffle either by concatenating it with UNDEF or
7353 // extracting a suitable range of elements.
7354 for (auto &Src : Sources) {
7355 EVT SrcVT = Src.ShuffleVec.getValueType();
7357 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7358 continue;
7360 // This stage of the search produces a source with the same element type as
7361 // the original, but with a total width matching the BUILD_VECTOR output.
7362 EVT EltVT = SrcVT.getVectorElementType();
7363 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7364 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7366 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7367 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
7368 return SDValue();
7369 // We can pad out the smaller vector for free, so if it's part of a
7370 // shuffle...
7371 Src.ShuffleVec =
7372 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7373 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7374 continue;
7377 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
7378 return SDValue();
7380 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7381 // Span too large for a VEXT to cope
7382 return SDValue();
7385 if (Src.MinElt >= NumSrcElts) {
7386 // The extraction can just take the second half
7387 Src.ShuffleVec =
7388 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7389 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7390 Src.WindowBase = -NumSrcElts;
7391 } else if (Src.MaxElt < NumSrcElts) {
7392 // The extraction can just take the first half
7393 Src.ShuffleVec =
7394 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7395 DAG.getConstant(0, dl, MVT::i32));
7396 } else {
7397 // An actual VEXT is needed
7398 SDValue VEXTSrc1 =
7399 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7400 DAG.getConstant(0, dl, MVT::i32));
7401 SDValue VEXTSrc2 =
7402 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7403 DAG.getConstant(NumSrcElts, dl, MVT::i32));
7405 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7406 VEXTSrc2,
7407 DAG.getConstant(Src.MinElt, dl, MVT::i32));
7408 Src.WindowBase = -Src.MinElt;
7412 // Another possible incompatibility occurs from the vector element types. We
7413 // can fix this by bitcasting the source vectors to the same type we intend
7414 // for the shuffle.
7415 for (auto &Src : Sources) {
7416 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7417 if (SrcEltTy == SmallestEltTy)
7418 continue;
7419 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7420 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7421 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7422 Src.WindowBase *= Src.WindowScale;
7425 // Final sanity check before we try to actually produce a shuffle.
7426 LLVM_DEBUG(for (auto Src
7427 : Sources)
7428 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7430 // The stars all align, our next step is to produce the mask for the shuffle.
7431 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7432 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7433 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7434 SDValue Entry = Op.getOperand(i);
7435 if (Entry.isUndef())
7436 continue;
7438 auto Src = llvm::find(Sources, Entry.getOperand(0));
7439 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7441 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7442 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7443 // segment.
7444 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7445 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
7446 VT.getScalarSizeInBits());
7447 int LanesDefined = BitsDefined / BitsPerShuffleLane;
7449 // This source is expected to fill ResMultiplier lanes of the final shuffle,
7450 // starting at the appropriate offset.
7451 int *LaneMask = &Mask[i * ResMultiplier];
7453 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7454 ExtractBase += NumElts * (Src - Sources.begin());
7455 for (int j = 0; j < LanesDefined; ++j)
7456 LaneMask[j] = ExtractBase + j;
7460 // We can't handle more than two sources. This should have already
7461 // been checked before this point.
7462 assert(Sources.size() <= 2 && "Too many sources!");
7464 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7465 for (unsigned i = 0; i < Sources.size(); ++i)
7466 ShuffleOps[i] = Sources[i].ShuffleVec;
7468 SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7469 ShuffleOps[1], Mask, DAG);
7470 if (!Shuffle)
7471 return SDValue();
7472 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7475 enum ShuffleOpCodes {
7476 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7477 OP_VREV,
7478 OP_VDUP0,
7479 OP_VDUP1,
7480 OP_VDUP2,
7481 OP_VDUP3,
7482 OP_VEXT1,
7483 OP_VEXT2,
7484 OP_VEXT3,
7485 OP_VUZPL, // VUZP, left result
7486 OP_VUZPR, // VUZP, right result
7487 OP_VZIPL, // VZIP, left result
7488 OP_VZIPR, // VZIP, right result
7489 OP_VTRNL, // VTRN, left result
7490 OP_VTRNR // VTRN, right result
7493 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7494 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7495 switch (OpNum) {
7496 case OP_COPY:
7497 case OP_VREV:
7498 case OP_VDUP0:
7499 case OP_VDUP1:
7500 case OP_VDUP2:
7501 case OP_VDUP3:
7502 return true;
7504 return false;
7507 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7508 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7509 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7510 /// are assumed to be legal.
7511 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7512 if (VT.getVectorNumElements() == 4 &&
7513 (VT.is128BitVector() || VT.is64BitVector())) {
7514 unsigned PFIndexes[4];
7515 for (unsigned i = 0; i != 4; ++i) {
7516 if (M[i] < 0)
7517 PFIndexes[i] = 8;
7518 else
7519 PFIndexes[i] = M[i];
7522 // Compute the index in the perfect shuffle table.
7523 unsigned PFTableIndex =
7524 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7525 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7526 unsigned Cost = (PFEntry >> 30);
7528 if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7529 return true;
7532 bool ReverseVEXT, isV_UNDEF;
7533 unsigned Imm, WhichResult;
7535 unsigned EltSize = VT.getScalarSizeInBits();
7536 if (EltSize >= 32 ||
7537 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7538 ShuffleVectorInst::isIdentityMask(M) ||
7539 isVREVMask(M, VT, 64) ||
7540 isVREVMask(M, VT, 32) ||
7541 isVREVMask(M, VT, 16))
7542 return true;
7543 else if (Subtarget->hasNEON() &&
7544 (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7545 isVTBLMask(M, VT) ||
7546 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7547 return true;
7548 else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7549 isReverseMask(M, VT))
7550 return true;
7551 else if (Subtarget->hasMVEIntegerOps() &&
7552 (isVMOVNMask(M, VT, 0) || isVMOVNMask(M, VT, 1)))
7553 return true;
7554 else
7555 return false;
7558 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7559 /// the specified operations to build the shuffle.
7560 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7561 SDValue RHS, SelectionDAG &DAG,
7562 const SDLoc &dl) {
7563 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7564 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7565 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7567 if (OpNum == OP_COPY) {
7568 if (LHSID == (1*9+2)*9+3) return LHS;
7569 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7570 return RHS;
7573 SDValue OpLHS, OpRHS;
7574 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7575 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7576 EVT VT = OpLHS.getValueType();
7578 switch (OpNum) {
7579 default: llvm_unreachable("Unknown shuffle opcode!");
7580 case OP_VREV:
7581 // VREV divides the vector in half and swaps within the half.
7582 if (VT.getVectorElementType() == MVT::i32 ||
7583 VT.getVectorElementType() == MVT::f32)
7584 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
7585 // vrev <4 x i16> -> VREV32
7586 if (VT.getVectorElementType() == MVT::i16)
7587 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
7588 // vrev <4 x i8> -> VREV16
7589 assert(VT.getVectorElementType() == MVT::i8);
7590 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
7591 case OP_VDUP0:
7592 case OP_VDUP1:
7593 case OP_VDUP2:
7594 case OP_VDUP3:
7595 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7596 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
7597 case OP_VEXT1:
7598 case OP_VEXT2:
7599 case OP_VEXT3:
7600 return DAG.getNode(ARMISD::VEXT, dl, VT,
7601 OpLHS, OpRHS,
7602 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
7603 case OP_VUZPL:
7604 case OP_VUZPR:
7605 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
7606 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
7607 case OP_VZIPL:
7608 case OP_VZIPR:
7609 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
7610 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
7611 case OP_VTRNL:
7612 case OP_VTRNR:
7613 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
7614 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
7618 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
7619 ArrayRef<int> ShuffleMask,
7620 SelectionDAG &DAG) {
7621 // Check to see if we can use the VTBL instruction.
7622 SDValue V1 = Op.getOperand(0);
7623 SDValue V2 = Op.getOperand(1);
7624 SDLoc DL(Op);
7626 SmallVector<SDValue, 8> VTBLMask;
7627 for (ArrayRef<int>::iterator
7628 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
7629 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
7631 if (V2.getNode()->isUndef())
7632 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
7633 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7635 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
7636 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7639 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
7640 SelectionDAG &DAG) {
7641 SDLoc DL(Op);
7642 SDValue OpLHS = Op.getOperand(0);
7643 EVT VT = OpLHS.getValueType();
7645 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
7646 "Expect an v8i16/v16i8 type");
7647 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
7648 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
7649 // extract the first 8 bytes into the top double word and the last 8 bytes
7650 // into the bottom double word. The v8i16 case is similar.
7651 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
7652 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
7653 DAG.getConstant(ExtractNum, DL, MVT::i32));
7656 static EVT getVectorTyFromPredicateVector(EVT VT) {
7657 switch (VT.getSimpleVT().SimpleTy) {
7658 case MVT::v4i1:
7659 return MVT::v4i32;
7660 case MVT::v8i1:
7661 return MVT::v8i16;
7662 case MVT::v16i1:
7663 return MVT::v16i8;
7664 default:
7665 llvm_unreachable("Unexpected vector predicate type");
7669 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
7670 SelectionDAG &DAG) {
7671 // Converting from boolean predicates to integers involves creating a vector
7672 // of all ones or all zeroes and selecting the lanes based upon the real
7673 // predicate.
7674 SDValue AllOnes =
7675 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
7676 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
7678 SDValue AllZeroes =
7679 DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
7680 AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
7682 // Get full vector type from predicate type
7683 EVT NewVT = getVectorTyFromPredicateVector(VT);
7685 SDValue RecastV1;
7686 // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
7687 // this to a v16i1. This cannot be done with an ordinary bitcast because the
7688 // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
7689 // since we know in hardware the sizes are really the same.
7690 if (VT != MVT::v16i1)
7691 RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
7692 else
7693 RecastV1 = Pred;
7695 // Select either all ones or zeroes depending upon the real predicate bits.
7696 SDValue PredAsVector =
7697 DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
7699 // Recast our new predicate-as-integer v16i8 vector into something
7700 // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
7701 return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
7704 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
7705 const ARMSubtarget *ST) {
7706 EVT VT = Op.getValueType();
7707 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7708 ArrayRef<int> ShuffleMask = SVN->getMask();
7710 assert(ST->hasMVEIntegerOps() &&
7711 "No support for vector shuffle of boolean predicates");
7713 SDValue V1 = Op.getOperand(0);
7714 SDLoc dl(Op);
7715 if (isReverseMask(ShuffleMask, VT)) {
7716 SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
7717 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
7718 SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
7719 DAG.getConstant(16, dl, MVT::i32));
7720 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
7723 // Until we can come up with optimised cases for every single vector
7724 // shuffle in existence we have chosen the least painful strategy. This is
7725 // to essentially promote the boolean predicate to a 8-bit integer, where
7726 // each predicate represents a byte. Then we fall back on a normal integer
7727 // vector shuffle and convert the result back into a predicate vector. In
7728 // many cases the generated code might be even better than scalar code
7729 // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
7730 // fields in a register into 8 other arbitrary 2-bit fields!
7731 SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
7732 EVT NewVT = PredAsVector.getValueType();
7734 // Do the shuffle!
7735 SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
7736 DAG.getUNDEF(NewVT), ShuffleMask);
7738 // Now return the result of comparing the shuffled vector with zero,
7739 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7740 return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
7741 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
7744 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
7745 const ARMSubtarget *ST) {
7746 SDValue V1 = Op.getOperand(0);
7747 SDValue V2 = Op.getOperand(1);
7748 SDLoc dl(Op);
7749 EVT VT = Op.getValueType();
7750 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7751 unsigned EltSize = VT.getScalarSizeInBits();
7753 if (ST->hasMVEIntegerOps() && EltSize == 1)
7754 return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
7756 // Convert shuffles that are directly supported on NEON to target-specific
7757 // DAG nodes, instead of keeping them as shuffles and matching them again
7758 // during code selection. This is more efficient and avoids the possibility
7759 // of inconsistencies between legalization and selection.
7760 // FIXME: floating-point vectors should be canonicalized to integer vectors
7761 // of the same time so that they get CSEd properly.
7762 ArrayRef<int> ShuffleMask = SVN->getMask();
7764 if (EltSize <= 32) {
7765 if (SVN->isSplat()) {
7766 int Lane = SVN->getSplatIndex();
7767 // If this is undef splat, generate it via "just" vdup, if possible.
7768 if (Lane == -1) Lane = 0;
7770 // Test if V1 is a SCALAR_TO_VECTOR.
7771 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7772 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7774 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
7775 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
7776 // reaches it).
7777 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
7778 !isa<ConstantSDNode>(V1.getOperand(0))) {
7779 bool IsScalarToVector = true;
7780 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
7781 if (!V1.getOperand(i).isUndef()) {
7782 IsScalarToVector = false;
7783 break;
7785 if (IsScalarToVector)
7786 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7788 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
7789 DAG.getConstant(Lane, dl, MVT::i32));
7792 bool ReverseVEXT = false;
7793 unsigned Imm = 0;
7794 if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7795 if (ReverseVEXT)
7796 std::swap(V1, V2);
7797 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7798 DAG.getConstant(Imm, dl, MVT::i32));
7801 if (isVREVMask(ShuffleMask, VT, 64))
7802 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7803 if (isVREVMask(ShuffleMask, VT, 32))
7804 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7805 if (isVREVMask(ShuffleMask, VT, 16))
7806 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7808 if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7809 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7810 DAG.getConstant(Imm, dl, MVT::i32));
7813 // Check for Neon shuffles that modify both input vectors in place.
7814 // If both results are used, i.e., if there are two shuffles with the same
7815 // source operands and with masks corresponding to both results of one of
7816 // these operations, DAG memoization will ensure that a single node is
7817 // used for both shuffles.
7818 unsigned WhichResult = 0;
7819 bool isV_UNDEF = false;
7820 if (ST->hasNEON()) {
7821 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7822 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7823 if (isV_UNDEF)
7824 V2 = V1;
7825 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7826 .getValue(WhichResult);
7829 if (ST->hasMVEIntegerOps()) {
7830 if (isVMOVNMask(ShuffleMask, VT, 0))
7831 return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
7832 DAG.getConstant(0, dl, MVT::i32));
7833 if (isVMOVNMask(ShuffleMask, VT, 1))
7834 return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
7835 DAG.getConstant(1, dl, MVT::i32));
7838 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7839 // shuffles that produce a result larger than their operands with:
7840 // shuffle(concat(v1, undef), concat(v2, undef))
7841 // ->
7842 // shuffle(concat(v1, v2), undef)
7843 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7845 // This is useful in the general case, but there are special cases where
7846 // native shuffles produce larger results: the two-result ops.
7848 // Look through the concat when lowering them:
7849 // shuffle(concat(v1, v2), undef)
7850 // ->
7851 // concat(VZIP(v1, v2):0, :1)
7853 if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7854 SDValue SubV1 = V1->getOperand(0);
7855 SDValue SubV2 = V1->getOperand(1);
7856 EVT SubVT = SubV1.getValueType();
7858 // We expect these to have been canonicalized to -1.
7859 assert(llvm::all_of(ShuffleMask, [&](int i) {
7860 return i < (int)VT.getVectorNumElements();
7861 }) && "Unexpected shuffle index into UNDEF operand!");
7863 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7864 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7865 if (isV_UNDEF)
7866 SubV2 = SubV1;
7867 assert((WhichResult == 0) &&
7868 "In-place shuffle of concat can only have one result!");
7869 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7870 SubV1, SubV2);
7871 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7872 Res.getValue(1));
7877 // If the shuffle is not directly supported and it has 4 elements, use
7878 // the PerfectShuffle-generated table to synthesize it from other shuffles.
7879 unsigned NumElts = VT.getVectorNumElements();
7880 if (NumElts == 4) {
7881 unsigned PFIndexes[4];
7882 for (unsigned i = 0; i != 4; ++i) {
7883 if (ShuffleMask[i] < 0)
7884 PFIndexes[i] = 8;
7885 else
7886 PFIndexes[i] = ShuffleMask[i];
7889 // Compute the index in the perfect shuffle table.
7890 unsigned PFTableIndex =
7891 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7892 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7893 unsigned Cost = (PFEntry >> 30);
7895 if (Cost <= 4) {
7896 if (ST->hasNEON())
7897 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7898 else if (isLegalMVEShuffleOp(PFEntry)) {
7899 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7900 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7901 unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
7902 unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
7903 if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
7904 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7909 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7910 if (EltSize >= 32) {
7911 // Do the expansion with floating-point types, since that is what the VFP
7912 // registers are defined to use, and since i64 is not legal.
7913 EVT EltVT = EVT::getFloatingPointVT(EltSize);
7914 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7915 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7916 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7917 SmallVector<SDValue, 8> Ops;
7918 for (unsigned i = 0; i < NumElts; ++i) {
7919 if (ShuffleMask[i] < 0)
7920 Ops.push_back(DAG.getUNDEF(EltVT));
7921 else
7922 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7923 ShuffleMask[i] < (int)NumElts ? V1 : V2,
7924 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7925 dl, MVT::i32)));
7927 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7928 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7931 if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7932 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7934 if (ST->hasNEON() && VT == MVT::v8i8)
7935 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7936 return NewOp;
7938 return SDValue();
7941 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
7942 const ARMSubtarget *ST) {
7943 EVT VecVT = Op.getOperand(0).getValueType();
7944 SDLoc dl(Op);
7946 assert(ST->hasMVEIntegerOps() &&
7947 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
7949 SDValue Conv =
7950 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
7951 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7952 unsigned LaneWidth =
7953 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
7954 unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
7955 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
7956 Op.getOperand(1), DAG.getValueType(MVT::i1));
7957 SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
7958 DAG.getConstant(~Mask, dl, MVT::i32));
7959 return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
7962 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7963 SelectionDAG &DAG) const {
7964 // INSERT_VECTOR_ELT is legal only for immediate indexes.
7965 SDValue Lane = Op.getOperand(2);
7966 if (!isa<ConstantSDNode>(Lane))
7967 return SDValue();
7969 SDValue Elt = Op.getOperand(1);
7970 EVT EltVT = Elt.getValueType();
7972 if (Subtarget->hasMVEIntegerOps() &&
7973 Op.getValueType().getScalarSizeInBits() == 1)
7974 return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
7976 if (getTypeAction(*DAG.getContext(), EltVT) ==
7977 TargetLowering::TypePromoteFloat) {
7978 // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
7979 // but the type system will try to do that if we don't intervene.
7980 // Reinterpret any such vector-element insertion as one with the
7981 // corresponding integer types.
7983 SDLoc dl(Op);
7985 EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
7986 assert(getTypeAction(*DAG.getContext(), IEltVT) !=
7987 TargetLowering::TypePromoteFloat);
7989 SDValue VecIn = Op.getOperand(0);
7990 EVT VecVT = VecIn.getValueType();
7991 EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
7992 VecVT.getVectorNumElements());
7994 SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
7995 SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
7996 SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
7997 IVecIn, IElt, Lane);
7998 return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
8001 return Op;
8004 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8005 const ARMSubtarget *ST) {
8006 EVT VecVT = Op.getOperand(0).getValueType();
8007 SDLoc dl(Op);
8009 assert(ST->hasMVEIntegerOps() &&
8010 "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8012 SDValue Conv =
8013 DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8014 unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8015 unsigned LaneWidth =
8016 getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8017 SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
8018 DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
8019 return Shift;
8022 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
8023 const ARMSubtarget *ST) {
8024 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8025 SDValue Lane = Op.getOperand(1);
8026 if (!isa<ConstantSDNode>(Lane))
8027 return SDValue();
8029 SDValue Vec = Op.getOperand(0);
8030 EVT VT = Vec.getValueType();
8032 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8033 return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8035 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8036 SDLoc dl(Op);
8037 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
8040 return Op;
8043 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
8044 const ARMSubtarget *ST) {
8045 SDValue V1 = Op.getOperand(0);
8046 SDValue V2 = Op.getOperand(1);
8047 SDLoc dl(Op);
8048 EVT VT = Op.getValueType();
8049 EVT Op1VT = V1.getValueType();
8050 EVT Op2VT = V2.getValueType();
8051 unsigned NumElts = VT.getVectorNumElements();
8053 assert(Op1VT == Op2VT && "Operand types don't match!");
8054 assert(VT.getScalarSizeInBits() == 1 &&
8055 "Unexpected custom CONCAT_VECTORS lowering");
8056 assert(ST->hasMVEIntegerOps() &&
8057 "CONCAT_VECTORS lowering only supported for MVE");
8059 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8060 SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
8062 // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
8063 // promoted to v8i16, etc.
8065 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8067 // Extract the vector elements from Op1 and Op2 one by one and truncate them
8068 // to be the right size for the destination. For example, if Op1 is v4i1 then
8069 // the promoted vector is v4i32. The result of concatentation gives a v8i1,
8070 // which when promoted is v8i16. That means each i32 element from Op1 needs
8071 // truncating to i16 and inserting in the result.
8072 EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
8073 SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
8074 auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8075 EVT NewVT = NewV.getValueType();
8076 EVT ConcatVT = ConVec.getValueType();
8077 for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8078 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
8079 DAG.getIntPtrConstant(i, dl));
8080 ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
8081 DAG.getConstant(j, dl, MVT::i32));
8083 return ConVec;
8085 unsigned j = 0;
8086 ConVec = ExractInto(NewV1, ConVec, j);
8087 ConVec = ExractInto(NewV2, ConVec, j);
8089 // Now return the result of comparing the subvector with zero,
8090 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8091 return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8092 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8095 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8096 const ARMSubtarget *ST) {
8097 EVT VT = Op->getValueType(0);
8098 if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8099 return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8101 // The only time a CONCAT_VECTORS operation can have legal types is when
8102 // two 64-bit vectors are concatenated to a 128-bit vector.
8103 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8104 "unexpected CONCAT_VECTORS");
8105 SDLoc dl(Op);
8106 SDValue Val = DAG.getUNDEF(MVT::v2f64);
8107 SDValue Op0 = Op.getOperand(0);
8108 SDValue Op1 = Op.getOperand(1);
8109 if (!Op0.isUndef())
8110 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8111 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8112 DAG.getIntPtrConstant(0, dl));
8113 if (!Op1.isUndef())
8114 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8115 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8116 DAG.getIntPtrConstant(1, dl));
8117 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8120 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8121 const ARMSubtarget *ST) {
8122 SDValue V1 = Op.getOperand(0);
8123 SDValue V2 = Op.getOperand(1);
8124 SDLoc dl(Op);
8125 EVT VT = Op.getValueType();
8126 EVT Op1VT = V1.getValueType();
8127 unsigned NumElts = VT.getVectorNumElements();
8128 unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
8130 assert(VT.getScalarSizeInBits() == 1 &&
8131 "Unexpected custom EXTRACT_SUBVECTOR lowering");
8132 assert(ST->hasMVEIntegerOps() &&
8133 "EXTRACT_SUBVECTOR lowering only supported for MVE");
8135 SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8137 // We now have Op1 promoted to a vector of integers, where v8i1 gets
8138 // promoted to v8i16, etc.
8140 MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8142 EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8143 SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8144 for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8145 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8146 DAG.getIntPtrConstant(i, dl));
8147 SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8148 DAG.getConstant(j, dl, MVT::i32));
8151 // Now return the result of comparing the subvector with zero,
8152 // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8153 return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8154 DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8157 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
8158 /// element has been zero/sign-extended, depending on the isSigned parameter,
8159 /// from an integer type half its size.
8160 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
8161 bool isSigned) {
8162 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
8163 EVT VT = N->getValueType(0);
8164 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
8165 SDNode *BVN = N->getOperand(0).getNode();
8166 if (BVN->getValueType(0) != MVT::v4i32 ||
8167 BVN->getOpcode() != ISD::BUILD_VECTOR)
8168 return false;
8169 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8170 unsigned HiElt = 1 - LoElt;
8171 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
8172 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
8173 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
8174 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
8175 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
8176 return false;
8177 if (isSigned) {
8178 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
8179 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
8180 return true;
8181 } else {
8182 if (Hi0->isNullValue() && Hi1->isNullValue())
8183 return true;
8185 return false;
8188 if (N->getOpcode() != ISD::BUILD_VECTOR)
8189 return false;
8191 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8192 SDNode *Elt = N->getOperand(i).getNode();
8193 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
8194 unsigned EltSize = VT.getScalarSizeInBits();
8195 unsigned HalfSize = EltSize / 2;
8196 if (isSigned) {
8197 if (!isIntN(HalfSize, C->getSExtValue()))
8198 return false;
8199 } else {
8200 if (!isUIntN(HalfSize, C->getZExtValue()))
8201 return false;
8203 continue;
8205 return false;
8208 return true;
8211 /// isSignExtended - Check if a node is a vector value that is sign-extended
8212 /// or a constant BUILD_VECTOR with sign-extended elements.
8213 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
8214 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
8215 return true;
8216 if (isExtendedBUILD_VECTOR(N, DAG, true))
8217 return true;
8218 return false;
8221 /// isZeroExtended - Check if a node is a vector value that is zero-extended
8222 /// or a constant BUILD_VECTOR with zero-extended elements.
8223 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
8224 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
8225 return true;
8226 if (isExtendedBUILD_VECTOR(N, DAG, false))
8227 return true;
8228 return false;
8231 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
8232 if (OrigVT.getSizeInBits() >= 64)
8233 return OrigVT;
8235 assert(OrigVT.isSimple() && "Expecting a simple value type");
8237 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
8238 switch (OrigSimpleTy) {
8239 default: llvm_unreachable("Unexpected Vector Type");
8240 case MVT::v2i8:
8241 case MVT::v2i16:
8242 return MVT::v2i32;
8243 case MVT::v4i8:
8244 return MVT::v4i16;
8248 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
8249 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
8250 /// We insert the required extension here to get the vector to fill a D register.
8251 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
8252 const EVT &OrigTy,
8253 const EVT &ExtTy,
8254 unsigned ExtOpcode) {
8255 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
8256 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
8257 // 64-bits we need to insert a new extension so that it will be 64-bits.
8258 assert(ExtTy.is128BitVector() && "Unexpected extension size");
8259 if (OrigTy.getSizeInBits() >= 64)
8260 return N;
8262 // Must extend size to at least 64 bits to be used as an operand for VMULL.
8263 EVT NewVT = getExtensionTo64Bits(OrigTy);
8265 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
8268 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
8269 /// does not do any sign/zero extension. If the original vector is less
8270 /// than 64 bits, an appropriate extension will be added after the load to
8271 /// reach a total size of 64 bits. We have to add the extension separately
8272 /// because ARM does not have a sign/zero extending load for vectors.
8273 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
8274 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
8276 // The load already has the right type.
8277 if (ExtendedTy == LD->getMemoryVT())
8278 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
8279 LD->getBasePtr(), LD->getPointerInfo(),
8280 LD->getAlignment(), LD->getMemOperand()->getFlags());
8282 // We need to create a zextload/sextload. We cannot just create a load
8283 // followed by a zext/zext node because LowerMUL is also run during normal
8284 // operation legalization where we can't create illegal types.
8285 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8286 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8287 LD->getMemoryVT(), LD->getAlignment(),
8288 LD->getMemOperand()->getFlags());
8291 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8292 /// extending load, or BUILD_VECTOR with extended elements, return the
8293 /// unextended value. The unextended vector should be 64 bits so that it can
8294 /// be used as an operand to a VMULL instruction. If the original vector size
8295 /// before extension is less than 64 bits we add a an extension to resize
8296 /// the vector to 64 bits.
8297 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8298 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
8299 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8300 N->getOperand(0)->getValueType(0),
8301 N->getValueType(0),
8302 N->getOpcode());
8304 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8305 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8306 "Expected extending load");
8308 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8309 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8310 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8311 SDValue extLoad =
8312 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8313 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8315 return newLoad;
8318 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
8319 // have been legalized as a BITCAST from v4i32.
8320 if (N->getOpcode() == ISD::BITCAST) {
8321 SDNode *BVN = N->getOperand(0).getNode();
8322 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8323 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8324 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8325 return DAG.getBuildVector(
8326 MVT::v2i32, SDLoc(N),
8327 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8329 // Construct a new BUILD_VECTOR with elements truncated to half the size.
8330 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8331 EVT VT = N->getValueType(0);
8332 unsigned EltSize = VT.getScalarSizeInBits() / 2;
8333 unsigned NumElts = VT.getVectorNumElements();
8334 MVT TruncVT = MVT::getIntegerVT(EltSize);
8335 SmallVector<SDValue, 8> Ops;
8336 SDLoc dl(N);
8337 for (unsigned i = 0; i != NumElts; ++i) {
8338 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8339 const APInt &CInt = C->getAPIntValue();
8340 // Element types smaller than 32 bits are not legal, so use i32 elements.
8341 // The values are implicitly truncated so sext vs. zext doesn't matter.
8342 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8344 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8347 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8348 unsigned Opcode = N->getOpcode();
8349 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8350 SDNode *N0 = N->getOperand(0).getNode();
8351 SDNode *N1 = N->getOperand(1).getNode();
8352 return N0->hasOneUse() && N1->hasOneUse() &&
8353 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8355 return false;
8358 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8359 unsigned Opcode = N->getOpcode();
8360 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8361 SDNode *N0 = N->getOperand(0).getNode();
8362 SDNode *N1 = N->getOperand(1).getNode();
8363 return N0->hasOneUse() && N1->hasOneUse() &&
8364 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8366 return false;
8369 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8370 // Multiplications are only custom-lowered for 128-bit vectors so that
8371 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
8372 EVT VT = Op.getValueType();
8373 assert(VT.is128BitVector() && VT.isInteger() &&
8374 "unexpected type for custom-lowering ISD::MUL");
8375 SDNode *N0 = Op.getOperand(0).getNode();
8376 SDNode *N1 = Op.getOperand(1).getNode();
8377 unsigned NewOpc = 0;
8378 bool isMLA = false;
8379 bool isN0SExt = isSignExtended(N0, DAG);
8380 bool isN1SExt = isSignExtended(N1, DAG);
8381 if (isN0SExt && isN1SExt)
8382 NewOpc = ARMISD::VMULLs;
8383 else {
8384 bool isN0ZExt = isZeroExtended(N0, DAG);
8385 bool isN1ZExt = isZeroExtended(N1, DAG);
8386 if (isN0ZExt && isN1ZExt)
8387 NewOpc = ARMISD::VMULLu;
8388 else if (isN1SExt || isN1ZExt) {
8389 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8390 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8391 if (isN1SExt && isAddSubSExt(N0, DAG)) {
8392 NewOpc = ARMISD::VMULLs;
8393 isMLA = true;
8394 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8395 NewOpc = ARMISD::VMULLu;
8396 isMLA = true;
8397 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8398 std::swap(N0, N1);
8399 NewOpc = ARMISD::VMULLu;
8400 isMLA = true;
8404 if (!NewOpc) {
8405 if (VT == MVT::v2i64)
8406 // Fall through to expand this. It is not legal.
8407 return SDValue();
8408 else
8409 // Other vector multiplications are legal.
8410 return Op;
8414 // Legalize to a VMULL instruction.
8415 SDLoc DL(Op);
8416 SDValue Op0;
8417 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8418 if (!isMLA) {
8419 Op0 = SkipExtensionForVMULL(N0, DAG);
8420 assert(Op0.getValueType().is64BitVector() &&
8421 Op1.getValueType().is64BitVector() &&
8422 "unexpected types for extended operands to VMULL");
8423 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8426 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8427 // isel lowering to take advantage of no-stall back to back vmul + vmla.
8428 // vmull q0, d4, d6
8429 // vmlal q0, d5, d6
8430 // is faster than
8431 // vaddl q0, d4, d5
8432 // vmovl q1, d6
8433 // vmul q0, q0, q1
8434 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8435 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8436 EVT Op1VT = Op1.getValueType();
8437 return DAG.getNode(N0->getOpcode(), DL, VT,
8438 DAG.getNode(NewOpc, DL, VT,
8439 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8440 DAG.getNode(NewOpc, DL, VT,
8441 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8444 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8445 SelectionDAG &DAG) {
8446 // TODO: Should this propagate fast-math-flags?
8448 // Convert to float
8449 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8450 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8451 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8452 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8453 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8454 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8455 // Get reciprocal estimate.
8456 // float4 recip = vrecpeq_f32(yf);
8457 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8458 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8460 // Because char has a smaller range than uchar, we can actually get away
8461 // without any newton steps. This requires that we use a weird bias
8462 // of 0xb000, however (again, this has been exhaustively tested).
8463 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8464 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8465 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8466 Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8467 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8468 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8469 // Convert back to short.
8470 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8471 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8472 return X;
8475 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
8476 SelectionDAG &DAG) {
8477 // TODO: Should this propagate fast-math-flags?
8479 SDValue N2;
8480 // Convert to float.
8481 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
8482 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
8483 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
8484 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
8485 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8486 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8488 // Use reciprocal estimate and one refinement step.
8489 // float4 recip = vrecpeq_f32(yf);
8490 // recip *= vrecpsq_f32(yf, recip);
8491 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8492 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8493 N1);
8494 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8495 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8496 N1, N2);
8497 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8498 // Because short has a smaller range than ushort, we can actually get away
8499 // with only a single newton step. This requires that we use a weird bias
8500 // of 89, however (again, this has been exhaustively tested).
8501 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
8502 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8503 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8504 N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
8505 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8506 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8507 // Convert back to integer and return.
8508 // return vmovn_s32(vcvt_s32_f32(result));
8509 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8510 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8511 return N0;
8514 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
8515 const ARMSubtarget *ST) {
8516 EVT VT = Op.getValueType();
8517 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8518 "unexpected type for custom-lowering ISD::SDIV");
8520 SDLoc dl(Op);
8521 SDValue N0 = Op.getOperand(0);
8522 SDValue N1 = Op.getOperand(1);
8523 SDValue N2, N3;
8525 if (VT == MVT::v8i8) {
8526 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
8527 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
8529 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8530 DAG.getIntPtrConstant(4, dl));
8531 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8532 DAG.getIntPtrConstant(4, dl));
8533 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8534 DAG.getIntPtrConstant(0, dl));
8535 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8536 DAG.getIntPtrConstant(0, dl));
8538 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
8539 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
8541 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8542 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8544 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
8545 return N0;
8547 return LowerSDIV_v4i16(N0, N1, dl, DAG);
8550 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
8551 const ARMSubtarget *ST) {
8552 // TODO: Should this propagate fast-math-flags?
8553 EVT VT = Op.getValueType();
8554 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8555 "unexpected type for custom-lowering ISD::UDIV");
8557 SDLoc dl(Op);
8558 SDValue N0 = Op.getOperand(0);
8559 SDValue N1 = Op.getOperand(1);
8560 SDValue N2, N3;
8562 if (VT == MVT::v8i8) {
8563 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
8564 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
8566 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8567 DAG.getIntPtrConstant(4, dl));
8568 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8569 DAG.getIntPtrConstant(4, dl));
8570 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8571 DAG.getIntPtrConstant(0, dl));
8572 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8573 DAG.getIntPtrConstant(0, dl));
8575 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
8576 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
8578 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8579 N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8581 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
8582 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
8583 MVT::i32),
8584 N0);
8585 return N0;
8588 // v4i16 sdiv ... Convert to float.
8589 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
8590 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
8591 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
8592 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
8593 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8594 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8596 // Use reciprocal estimate and two refinement steps.
8597 // float4 recip = vrecpeq_f32(yf);
8598 // recip *= vrecpsq_f32(yf, recip);
8599 // recip *= vrecpsq_f32(yf, recip);
8600 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8601 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8602 BN1);
8603 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8604 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8605 BN1, N2);
8606 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8607 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8608 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8609 BN1, N2);
8610 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8611 // Simply multiplying by the reciprocal estimate can leave us a few ulps
8612 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
8613 // and that it will never cause us to return an answer too large).
8614 // float4 result = as_float4(as_int4(xf*recip) + 2);
8615 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8616 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8617 N1 = DAG.getConstant(2, dl, MVT::v4i32);
8618 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8619 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8620 // Convert back to integer and return.
8621 // return vmovn_u32(vcvt_s32_f32(result));
8622 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8623 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8624 return N0;
8627 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
8628 SDNode *N = Op.getNode();
8629 EVT VT = N->getValueType(0);
8630 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8632 SDValue Carry = Op.getOperand(2);
8634 SDLoc DL(Op);
8636 SDValue Result;
8637 if (Op.getOpcode() == ISD::ADDCARRY) {
8638 // This converts the boolean value carry into the carry flag.
8639 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8641 // Do the addition proper using the carry flag we wanted.
8642 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
8643 Op.getOperand(1), Carry);
8645 // Now convert the carry flag into a boolean value.
8646 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8647 } else {
8648 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
8649 // have to invert the carry first.
8650 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8651 DAG.getConstant(1, DL, MVT::i32), Carry);
8652 // This converts the boolean value carry into the carry flag.
8653 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8655 // Do the subtraction proper using the carry flag we wanted.
8656 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
8657 Op.getOperand(1), Carry);
8659 // Now convert the carry flag into a boolean value.
8660 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8661 // But the carry returned by ARMISD::SUBE is not a borrow as expected
8662 // by ISD::SUBCARRY, so compute 1 - C.
8663 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8664 DAG.getConstant(1, DL, MVT::i32), Carry);
8667 // Return both values.
8668 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
8671 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
8672 assert(Subtarget->isTargetDarwin());
8674 // For iOS, we want to call an alternative entry point: __sincos_stret,
8675 // return values are passed via sret.
8676 SDLoc dl(Op);
8677 SDValue Arg = Op.getOperand(0);
8678 EVT ArgVT = Arg.getValueType();
8679 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8680 auto PtrVT = getPointerTy(DAG.getDataLayout());
8682 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8683 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8685 // Pair of floats / doubles used to pass the result.
8686 Type *RetTy = StructType::get(ArgTy, ArgTy);
8687 auto &DL = DAG.getDataLayout();
8689 ArgListTy Args;
8690 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
8691 SDValue SRet;
8692 if (ShouldUseSRet) {
8693 // Create stack object for sret.
8694 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
8695 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
8696 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
8697 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
8699 ArgListEntry Entry;
8700 Entry.Node = SRet;
8701 Entry.Ty = RetTy->getPointerTo();
8702 Entry.IsSExt = false;
8703 Entry.IsZExt = false;
8704 Entry.IsSRet = true;
8705 Args.push_back(Entry);
8706 RetTy = Type::getVoidTy(*DAG.getContext());
8709 ArgListEntry Entry;
8710 Entry.Node = Arg;
8711 Entry.Ty = ArgTy;
8712 Entry.IsSExt = false;
8713 Entry.IsZExt = false;
8714 Args.push_back(Entry);
8716 RTLIB::Libcall LC =
8717 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
8718 const char *LibcallName = getLibcallName(LC);
8719 CallingConv::ID CC = getLibcallCallingConv(LC);
8720 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
8722 TargetLowering::CallLoweringInfo CLI(DAG);
8723 CLI.setDebugLoc(dl)
8724 .setChain(DAG.getEntryNode())
8725 .setCallee(CC, RetTy, Callee, std::move(Args))
8726 .setDiscardResult(ShouldUseSRet);
8727 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8729 if (!ShouldUseSRet)
8730 return CallResult.first;
8732 SDValue LoadSin =
8733 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
8735 // Address of cos field.
8736 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
8737 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
8738 SDValue LoadCos =
8739 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
8741 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
8742 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
8743 LoadSin.getValue(0), LoadCos.getValue(0));
8746 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
8747 bool Signed,
8748 SDValue &Chain) const {
8749 EVT VT = Op.getValueType();
8750 assert((VT == MVT::i32 || VT == MVT::i64) &&
8751 "unexpected type for custom lowering DIV");
8752 SDLoc dl(Op);
8754 const auto &DL = DAG.getDataLayout();
8755 const auto &TLI = DAG.getTargetLoweringInfo();
8757 const char *Name = nullptr;
8758 if (Signed)
8759 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
8760 else
8761 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
8763 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
8765 ARMTargetLowering::ArgListTy Args;
8767 for (auto AI : {1, 0}) {
8768 ArgListEntry Arg;
8769 Arg.Node = Op.getOperand(AI);
8770 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
8771 Args.push_back(Arg);
8774 CallLoweringInfo CLI(DAG);
8775 CLI.setDebugLoc(dl)
8776 .setChain(Chain)
8777 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
8778 ES, std::move(Args));
8780 return LowerCallTo(CLI).first;
8783 // This is a code size optimisation: return the original SDIV node to
8784 // DAGCombiner when we don't want to expand SDIV into a sequence of
8785 // instructions, and an empty node otherwise which will cause the
8786 // SDIV to be expanded in DAGCombine.
8787 SDValue
8788 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8789 SelectionDAG &DAG,
8790 SmallVectorImpl<SDNode *> &Created) const {
8791 // TODO: Support SREM
8792 if (N->getOpcode() != ISD::SDIV)
8793 return SDValue();
8795 const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
8796 const bool MinSize = ST.hasMinSize();
8797 const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
8798 : ST.hasDivideInARMMode();
8800 // Don't touch vector types; rewriting this may lead to scalarizing
8801 // the int divs.
8802 if (N->getOperand(0).getValueType().isVector())
8803 return SDValue();
8805 // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
8806 // hwdiv support for this to be really profitable.
8807 if (!(MinSize && HasDivide))
8808 return SDValue();
8810 // ARM mode is a bit simpler than Thumb: we can handle large power
8811 // of 2 immediates with 1 mov instruction; no further checks required,
8812 // just return the sdiv node.
8813 if (!ST.isThumb())
8814 return SDValue(N, 0);
8816 // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
8817 // and thus lose the code size benefits of a MOVS that requires only 2.
8818 // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
8819 // but as it's doing exactly this, it's not worth the trouble to get TTI.
8820 if (Divisor.sgt(128))
8821 return SDValue();
8823 return SDValue(N, 0);
8826 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
8827 bool Signed) const {
8828 assert(Op.getValueType() == MVT::i32 &&
8829 "unexpected type for custom lowering DIV");
8830 SDLoc dl(Op);
8832 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
8833 DAG.getEntryNode(), Op.getOperand(1));
8835 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8838 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
8839 SDLoc DL(N);
8840 SDValue Op = N->getOperand(1);
8841 if (N->getValueType(0) == MVT::i32)
8842 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
8843 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8844 DAG.getConstant(0, DL, MVT::i32));
8845 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
8846 DAG.getConstant(1, DL, MVT::i32));
8847 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
8848 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
8851 void ARMTargetLowering::ExpandDIV_Windows(
8852 SDValue Op, SelectionDAG &DAG, bool Signed,
8853 SmallVectorImpl<SDValue> &Results) const {
8854 const auto &DL = DAG.getDataLayout();
8855 const auto &TLI = DAG.getTargetLoweringInfo();
8857 assert(Op.getValueType() == MVT::i64 &&
8858 "unexpected type for custom lowering DIV");
8859 SDLoc dl(Op);
8861 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
8863 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
8865 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
8866 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
8867 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
8868 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
8870 Results.push_back(Lower);
8871 Results.push_back(Upper);
8874 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
8875 LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
8876 EVT MemVT = LD->getMemoryVT();
8877 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
8878 "Expected a predicate type!");
8879 assert(MemVT == Op.getValueType());
8880 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
8881 "Expected a non-extending load");
8882 assert(LD->isUnindexed() && "Expected a unindexed load");
8884 // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit
8885 // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
8886 // need to make sure that 8/4 bits are actually loaded into the correct
8887 // place, which means loading the value and then shuffling the values into
8888 // the bottom bits of the predicate.
8889 // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
8890 // for BE).
8892 SDLoc dl(Op);
8893 SDValue Load = DAG.getExtLoad(
8894 ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
8895 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
8896 LD->getMemOperand());
8897 SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load);
8898 if (MemVT != MVT::v16i1)
8899 Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
8900 DAG.getConstant(0, dl, MVT::i32));
8901 return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
8904 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
8905 StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
8906 EVT MemVT = ST->getMemoryVT();
8907 assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
8908 "Expected a predicate type!");
8909 assert(MemVT == ST->getValue().getValueType());
8910 assert(!ST->isTruncatingStore() && "Expected a non-extending store");
8911 assert(ST->isUnindexed() && "Expected a unindexed store");
8913 // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits
8914 // unset and a scalar store.
8915 SDLoc dl(Op);
8916 SDValue Build = ST->getValue();
8917 if (MemVT != MVT::v16i1) {
8918 SmallVector<SDValue, 16> Ops;
8919 for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++)
8920 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
8921 DAG.getConstant(I, dl, MVT::i32)));
8922 for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
8923 Ops.push_back(DAG.getUNDEF(MVT::i32));
8924 Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
8926 SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
8927 return DAG.getTruncStore(
8928 ST->getChain(), dl, GRP, ST->getBasePtr(),
8929 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
8930 ST->getMemOperand());
8933 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
8934 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
8935 MVT VT = Op.getSimpleValueType();
8936 SDValue Mask = N->getMask();
8937 SDValue PassThru = N->getPassThru();
8938 SDLoc dl(Op);
8940 auto IsZero = [](SDValue PassThru) {
8941 return (ISD::isBuildVectorAllZeros(PassThru.getNode()) ||
8942 (PassThru->getOpcode() == ARMISD::VMOVIMM &&
8943 isNullConstant(PassThru->getOperand(0))));
8946 if (IsZero(PassThru))
8947 return Op;
8949 // MVE Masked loads use zero as the passthru value. Here we convert undef to
8950 // zero too, and other values are lowered to a select.
8951 SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
8952 DAG.getTargetConstant(0, dl, MVT::i32));
8953 SDValue NewLoad = DAG.getMaskedLoad(
8954 VT, dl, N->getChain(), N->getBasePtr(), Mask, ZeroVec, N->getMemoryVT(),
8955 N->getMemOperand(), N->getExtensionType(), N->isExpandingLoad());
8956 SDValue Combo = NewLoad;
8957 if (!PassThru.isUndef() &&
8958 (PassThru.getOpcode() != ISD::BITCAST ||
8959 !IsZero(PassThru->getOperand(0))))
8960 Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
8961 return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
8964 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
8965 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
8966 // Acquire/Release load/store is not legal for targets without a dmb or
8967 // equivalent available.
8968 return SDValue();
8970 // Monotonic load/store is legal for all targets.
8971 return Op;
8974 static void ReplaceREADCYCLECOUNTER(SDNode *N,
8975 SmallVectorImpl<SDValue> &Results,
8976 SelectionDAG &DAG,
8977 const ARMSubtarget *Subtarget) {
8978 SDLoc DL(N);
8979 // Under Power Management extensions, the cycle-count is:
8980 // mrc p15, #0, <Rt>, c9, c13, #0
8981 SDValue Ops[] = { N->getOperand(0), // Chain
8982 DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
8983 DAG.getTargetConstant(15, DL, MVT::i32),
8984 DAG.getTargetConstant(0, DL, MVT::i32),
8985 DAG.getTargetConstant(9, DL, MVT::i32),
8986 DAG.getTargetConstant(13, DL, MVT::i32),
8987 DAG.getTargetConstant(0, DL, MVT::i32)
8990 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
8991 DAG.getVTList(MVT::i32, MVT::Other), Ops);
8992 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
8993 DAG.getConstant(0, DL, MVT::i32)));
8994 Results.push_back(Cycles32.getValue(1));
8997 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
8998 SDLoc dl(V.getNode());
8999 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
9000 SDValue VHi = DAG.getAnyExtOrTrunc(
9001 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
9002 dl, MVT::i32);
9003 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9004 if (isBigEndian)
9005 std::swap (VLo, VHi);
9006 SDValue RegClass =
9007 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
9008 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
9009 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
9010 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
9011 return SDValue(
9012 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
9015 static void ReplaceCMP_SWAP_64Results(SDNode *N,
9016 SmallVectorImpl<SDValue> & Results,
9017 SelectionDAG &DAG) {
9018 assert(N->getValueType(0) == MVT::i64 &&
9019 "AtomicCmpSwap on types less than 64 should be legal");
9020 SDValue Ops[] = {N->getOperand(1),
9021 createGPRPairNode(DAG, N->getOperand(2)),
9022 createGPRPairNode(DAG, N->getOperand(3)),
9023 N->getOperand(0)};
9024 SDNode *CmpSwap = DAG.getMachineNode(
9025 ARM::CMP_SWAP_64, SDLoc(N),
9026 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
9028 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
9029 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
9031 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9033 Results.push_back(
9034 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
9035 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
9036 Results.push_back(
9037 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
9038 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
9039 Results.push_back(SDValue(CmpSwap, 2));
9042 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
9043 SelectionDAG &DAG) {
9044 const auto &TLI = DAG.getTargetLoweringInfo();
9046 assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
9047 "Custom lowering is MSVCRT specific!");
9049 SDLoc dl(Op);
9050 SDValue Val = Op.getOperand(0);
9051 MVT Ty = Val->getSimpleValueType(0);
9052 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
9053 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
9054 TLI.getPointerTy(DAG.getDataLayout()));
9056 TargetLowering::ArgListTy Args;
9057 TargetLowering::ArgListEntry Entry;
9059 Entry.Node = Val;
9060 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
9061 Entry.IsZExt = true;
9062 Args.push_back(Entry);
9064 Entry.Node = Exponent;
9065 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
9066 Entry.IsZExt = true;
9067 Args.push_back(Entry);
9069 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
9071 // In the in-chain to the call is the entry node If we are emitting a
9072 // tailcall, the chain will be mutated if the node has a non-entry input
9073 // chain.
9074 SDValue InChain = DAG.getEntryNode();
9075 SDValue TCChain = InChain;
9077 const Function &F = DAG.getMachineFunction().getFunction();
9078 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
9079 F.getReturnType() == LCRTy;
9080 if (IsTC)
9081 InChain = TCChain;
9083 TargetLowering::CallLoweringInfo CLI(DAG);
9084 CLI.setDebugLoc(dl)
9085 .setChain(InChain)
9086 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
9087 .setTailCall(IsTC);
9088 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
9090 // Return the chain (the DAG root) if it is a tail call
9091 return !CI.second.getNode() ? DAG.getRoot() : CI.first;
9094 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9095 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
9096 switch (Op.getOpcode()) {
9097 default: llvm_unreachable("Don't know how to custom lower this!");
9098 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
9099 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9100 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9101 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9102 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9103 case ISD::SELECT: return LowerSELECT(Op, DAG);
9104 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
9105 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
9106 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
9107 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
9108 case ISD::VASTART: return LowerVASTART(Op, DAG);
9109 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
9110 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
9111 case ISD::SINT_TO_FP:
9112 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
9113 case ISD::FP_TO_SINT:
9114 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
9115 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
9116 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9117 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9118 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
9119 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
9120 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
9121 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
9122 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
9123 Subtarget);
9124 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
9125 case ISD::SHL:
9126 case ISD::SRL:
9127 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
9128 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
9129 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
9130 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
9131 case ISD::SRL_PARTS:
9132 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
9133 case ISD::CTTZ:
9134 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
9135 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
9136 case ISD::SETCC: return LowerVSETCC(Op, DAG, Subtarget);
9137 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
9138 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
9139 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
9140 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
9141 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
9142 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9143 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
9144 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
9145 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9146 case ISD::MUL: return LowerMUL(Op, DAG);
9147 case ISD::SDIV:
9148 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9149 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
9150 return LowerSDIV(Op, DAG, Subtarget);
9151 case ISD::UDIV:
9152 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9153 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
9154 return LowerUDIV(Op, DAG, Subtarget);
9155 case ISD::ADDCARRY:
9156 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG);
9157 case ISD::SADDO:
9158 case ISD::SSUBO:
9159 return LowerSignedALUO(Op, DAG);
9160 case ISD::UADDO:
9161 case ISD::USUBO:
9162 return LowerUnsignedALUO(Op, DAG);
9163 case ISD::SADDSAT:
9164 case ISD::SSUBSAT:
9165 return LowerSADDSUBSAT(Op, DAG, Subtarget);
9166 case ISD::LOAD:
9167 return LowerPredicateLoad(Op, DAG);
9168 case ISD::STORE:
9169 return LowerPredicateStore(Op, DAG);
9170 case ISD::MLOAD:
9171 return LowerMLOAD(Op, DAG);
9172 case ISD::ATOMIC_LOAD:
9173 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
9174 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
9175 case ISD::SDIVREM:
9176 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
9177 case ISD::DYNAMIC_STACKALLOC:
9178 if (Subtarget->isTargetWindows())
9179 return LowerDYNAMIC_STACKALLOC(Op, DAG);
9180 llvm_unreachable("Don't know how to custom lower this!");
9181 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
9182 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
9183 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
9184 case ARMISD::WIN__DBZCHK: return SDValue();
9188 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
9189 SelectionDAG &DAG) {
9190 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9191 unsigned Opc = 0;
9192 if (IntNo == Intrinsic::arm_smlald)
9193 Opc = ARMISD::SMLALD;
9194 else if (IntNo == Intrinsic::arm_smlaldx)
9195 Opc = ARMISD::SMLALDX;
9196 else if (IntNo == Intrinsic::arm_smlsld)
9197 Opc = ARMISD::SMLSLD;
9198 else if (IntNo == Intrinsic::arm_smlsldx)
9199 Opc = ARMISD::SMLSLDX;
9200 else
9201 return;
9203 SDLoc dl(N);
9204 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9205 N->getOperand(3),
9206 DAG.getConstant(0, dl, MVT::i32));
9207 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9208 N->getOperand(3),
9209 DAG.getConstant(1, dl, MVT::i32));
9211 SDValue LongMul = DAG.getNode(Opc, dl,
9212 DAG.getVTList(MVT::i32, MVT::i32),
9213 N->getOperand(1), N->getOperand(2),
9214 Lo, Hi);
9215 Results.push_back(LongMul.getValue(0));
9216 Results.push_back(LongMul.getValue(1));
9219 /// ReplaceNodeResults - Replace the results of node with an illegal result
9220 /// type with new values built out of custom code.
9221 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
9222 SmallVectorImpl<SDValue> &Results,
9223 SelectionDAG &DAG) const {
9224 SDValue Res;
9225 switch (N->getOpcode()) {
9226 default:
9227 llvm_unreachable("Don't know how to custom expand this!");
9228 case ISD::READ_REGISTER:
9229 ExpandREAD_REGISTER(N, Results, DAG);
9230 break;
9231 case ISD::BITCAST:
9232 Res = ExpandBITCAST(N, DAG, Subtarget);
9233 break;
9234 case ISD::SRL:
9235 case ISD::SRA:
9236 case ISD::SHL:
9237 Res = Expand64BitShift(N, DAG, Subtarget);
9238 break;
9239 case ISD::SREM:
9240 case ISD::UREM:
9241 Res = LowerREM(N, DAG);
9242 break;
9243 case ISD::SDIVREM:
9244 case ISD::UDIVREM:
9245 Res = LowerDivRem(SDValue(N, 0), DAG);
9246 assert(Res.getNumOperands() == 2 && "DivRem needs two values");
9247 Results.push_back(Res.getValue(0));
9248 Results.push_back(Res.getValue(1));
9249 return;
9250 case ISD::SADDSAT:
9251 case ISD::SSUBSAT:
9252 Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
9253 break;
9254 case ISD::READCYCLECOUNTER:
9255 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
9256 return;
9257 case ISD::UDIV:
9258 case ISD::SDIV:
9259 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
9260 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
9261 Results);
9262 case ISD::ATOMIC_CMP_SWAP:
9263 ReplaceCMP_SWAP_64Results(N, Results, DAG);
9264 return;
9265 case ISD::INTRINSIC_WO_CHAIN:
9266 return ReplaceLongIntrinsic(N, Results, DAG);
9267 case ISD::ABS:
9268 lowerABS(N, Results, DAG);
9269 return ;
9272 if (Res.getNode())
9273 Results.push_back(Res);
9276 //===----------------------------------------------------------------------===//
9277 // ARM Scheduler Hooks
9278 //===----------------------------------------------------------------------===//
9280 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
9281 /// registers the function context.
9282 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
9283 MachineBasicBlock *MBB,
9284 MachineBasicBlock *DispatchBB,
9285 int FI) const {
9286 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
9287 "ROPI/RWPI not currently supported with SjLj");
9288 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9289 DebugLoc dl = MI.getDebugLoc();
9290 MachineFunction *MF = MBB->getParent();
9291 MachineRegisterInfo *MRI = &MF->getRegInfo();
9292 MachineConstantPool *MCP = MF->getConstantPool();
9293 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
9294 const Function &F = MF->getFunction();
9296 bool isThumb = Subtarget->isThumb();
9297 bool isThumb2 = Subtarget->isThumb2();
9299 unsigned PCLabelId = AFI->createPICLabelUId();
9300 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
9301 ARMConstantPoolValue *CPV =
9302 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
9303 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
9305 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
9306 : &ARM::GPRRegClass;
9308 // Grab constant pool and fixed stack memory operands.
9309 MachineMemOperand *CPMMO =
9310 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9311 MachineMemOperand::MOLoad, 4, 4);
9313 MachineMemOperand *FIMMOSt =
9314 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
9315 MachineMemOperand::MOStore, 4, 4);
9317 // Load the address of the dispatch MBB into the jump buffer.
9318 if (isThumb2) {
9319 // Incoming value: jbuf
9320 // ldr.n r5, LCPI1_1
9321 // orr r5, r5, #1
9322 // add r5, pc
9323 // str r5, [$jbuf, #+4] ; &jbuf[1]
9324 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9325 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
9326 .addConstantPoolIndex(CPI)
9327 .addMemOperand(CPMMO)
9328 .add(predOps(ARMCC::AL));
9329 // Set the low bit because of thumb mode.
9330 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9331 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
9332 .addReg(NewVReg1, RegState::Kill)
9333 .addImm(0x01)
9334 .add(predOps(ARMCC::AL))
9335 .add(condCodeOp());
9336 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9337 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
9338 .addReg(NewVReg2, RegState::Kill)
9339 .addImm(PCLabelId);
9340 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
9341 .addReg(NewVReg3, RegState::Kill)
9342 .addFrameIndex(FI)
9343 .addImm(36) // &jbuf[1] :: pc
9344 .addMemOperand(FIMMOSt)
9345 .add(predOps(ARMCC::AL));
9346 } else if (isThumb) {
9347 // Incoming value: jbuf
9348 // ldr.n r1, LCPI1_4
9349 // add r1, pc
9350 // mov r2, #1
9351 // orrs r1, r2
9352 // add r2, $jbuf, #+4 ; &jbuf[1]
9353 // str r1, [r2]
9354 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9355 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
9356 .addConstantPoolIndex(CPI)
9357 .addMemOperand(CPMMO)
9358 .add(predOps(ARMCC::AL));
9359 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9360 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
9361 .addReg(NewVReg1, RegState::Kill)
9362 .addImm(PCLabelId);
9363 // Set the low bit because of thumb mode.
9364 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9365 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
9366 .addReg(ARM::CPSR, RegState::Define)
9367 .addImm(1)
9368 .add(predOps(ARMCC::AL));
9369 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9370 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
9371 .addReg(ARM::CPSR, RegState::Define)
9372 .addReg(NewVReg2, RegState::Kill)
9373 .addReg(NewVReg3, RegState::Kill)
9374 .add(predOps(ARMCC::AL));
9375 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9376 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
9377 .addFrameIndex(FI)
9378 .addImm(36); // &jbuf[1] :: pc
9379 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
9380 .addReg(NewVReg4, RegState::Kill)
9381 .addReg(NewVReg5, RegState::Kill)
9382 .addImm(0)
9383 .addMemOperand(FIMMOSt)
9384 .add(predOps(ARMCC::AL));
9385 } else {
9386 // Incoming value: jbuf
9387 // ldr r1, LCPI1_1
9388 // add r1, pc, r1
9389 // str r1, [$jbuf, #+4] ; &jbuf[1]
9390 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9391 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
9392 .addConstantPoolIndex(CPI)
9393 .addImm(0)
9394 .addMemOperand(CPMMO)
9395 .add(predOps(ARMCC::AL));
9396 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9397 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
9398 .addReg(NewVReg1, RegState::Kill)
9399 .addImm(PCLabelId)
9400 .add(predOps(ARMCC::AL));
9401 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
9402 .addReg(NewVReg2, RegState::Kill)
9403 .addFrameIndex(FI)
9404 .addImm(36) // &jbuf[1] :: pc
9405 .addMemOperand(FIMMOSt)
9406 .add(predOps(ARMCC::AL));
9410 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
9411 MachineBasicBlock *MBB) const {
9412 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9413 DebugLoc dl = MI.getDebugLoc();
9414 MachineFunction *MF = MBB->getParent();
9415 MachineRegisterInfo *MRI = &MF->getRegInfo();
9416 MachineFrameInfo &MFI = MF->getFrameInfo();
9417 int FI = MFI.getFunctionContextIndex();
9419 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
9420 : &ARM::GPRnopcRegClass;
9422 // Get a mapping of the call site numbers to all of the landing pads they're
9423 // associated with.
9424 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
9425 unsigned MaxCSNum = 0;
9426 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
9427 ++BB) {
9428 if (!BB->isEHPad()) continue;
9430 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
9431 // pad.
9432 for (MachineBasicBlock::iterator
9433 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
9434 if (!II->isEHLabel()) continue;
9436 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
9437 if (!MF->hasCallSiteLandingPad(Sym)) continue;
9439 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
9440 for (SmallVectorImpl<unsigned>::iterator
9441 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
9442 CSI != CSE; ++CSI) {
9443 CallSiteNumToLPad[*CSI].push_back(&*BB);
9444 MaxCSNum = std::max(MaxCSNum, *CSI);
9446 break;
9450 // Get an ordered list of the machine basic blocks for the jump table.
9451 std::vector<MachineBasicBlock*> LPadList;
9452 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
9453 LPadList.reserve(CallSiteNumToLPad.size());
9454 for (unsigned I = 1; I <= MaxCSNum; ++I) {
9455 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
9456 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9457 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
9458 LPadList.push_back(*II);
9459 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
9463 assert(!LPadList.empty() &&
9464 "No landing pad destinations for the dispatch jump table!");
9466 // Create the jump table and associated information.
9467 MachineJumpTableInfo *JTI =
9468 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
9469 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
9471 // Create the MBBs for the dispatch code.
9473 // Shove the dispatch's address into the return slot in the function context.
9474 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
9475 DispatchBB->setIsEHPad();
9477 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9478 unsigned trap_opcode;
9479 if (Subtarget->isThumb())
9480 trap_opcode = ARM::tTRAP;
9481 else
9482 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
9484 BuildMI(TrapBB, dl, TII->get(trap_opcode));
9485 DispatchBB->addSuccessor(TrapBB);
9487 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
9488 DispatchBB->addSuccessor(DispContBB);
9490 // Insert and MBBs.
9491 MF->insert(MF->end(), DispatchBB);
9492 MF->insert(MF->end(), DispContBB);
9493 MF->insert(MF->end(), TrapBB);
9495 // Insert code into the entry block that creates and registers the function
9496 // context.
9497 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
9499 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
9500 MachinePointerInfo::getFixedStack(*MF, FI),
9501 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
9503 MachineInstrBuilder MIB;
9504 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
9506 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
9507 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
9509 // Add a register mask with no preserved registers. This results in all
9510 // registers being marked as clobbered. This can't work if the dispatch block
9511 // is in a Thumb1 function and is linked with ARM code which uses the FP
9512 // registers, as there is no way to preserve the FP registers in Thumb1 mode.
9513 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
9515 bool IsPositionIndependent = isPositionIndependent();
9516 unsigned NumLPads = LPadList.size();
9517 if (Subtarget->isThumb2()) {
9518 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9519 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
9520 .addFrameIndex(FI)
9521 .addImm(4)
9522 .addMemOperand(FIMMOLd)
9523 .add(predOps(ARMCC::AL));
9525 if (NumLPads < 256) {
9526 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
9527 .addReg(NewVReg1)
9528 .addImm(LPadList.size())
9529 .add(predOps(ARMCC::AL));
9530 } else {
9531 Register VReg1 = MRI->createVirtualRegister(TRC);
9532 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
9533 .addImm(NumLPads & 0xFFFF)
9534 .add(predOps(ARMCC::AL));
9536 unsigned VReg2 = VReg1;
9537 if ((NumLPads & 0xFFFF0000) != 0) {
9538 VReg2 = MRI->createVirtualRegister(TRC);
9539 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
9540 .addReg(VReg1)
9541 .addImm(NumLPads >> 16)
9542 .add(predOps(ARMCC::AL));
9545 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
9546 .addReg(NewVReg1)
9547 .addReg(VReg2)
9548 .add(predOps(ARMCC::AL));
9551 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
9552 .addMBB(TrapBB)
9553 .addImm(ARMCC::HI)
9554 .addReg(ARM::CPSR);
9556 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9557 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
9558 .addJumpTableIndex(MJTI)
9559 .add(predOps(ARMCC::AL));
9561 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9562 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
9563 .addReg(NewVReg3, RegState::Kill)
9564 .addReg(NewVReg1)
9565 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9566 .add(predOps(ARMCC::AL))
9567 .add(condCodeOp());
9569 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
9570 .addReg(NewVReg4, RegState::Kill)
9571 .addReg(NewVReg1)
9572 .addJumpTableIndex(MJTI);
9573 } else if (Subtarget->isThumb()) {
9574 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9575 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
9576 .addFrameIndex(FI)
9577 .addImm(1)
9578 .addMemOperand(FIMMOLd)
9579 .add(predOps(ARMCC::AL));
9581 if (NumLPads < 256) {
9582 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
9583 .addReg(NewVReg1)
9584 .addImm(NumLPads)
9585 .add(predOps(ARMCC::AL));
9586 } else {
9587 MachineConstantPool *ConstantPool = MF->getConstantPool();
9588 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9589 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9591 // MachineConstantPool wants an explicit alignment.
9592 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9593 if (Align == 0)
9594 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9595 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9597 Register VReg1 = MRI->createVirtualRegister(TRC);
9598 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
9599 .addReg(VReg1, RegState::Define)
9600 .addConstantPoolIndex(Idx)
9601 .add(predOps(ARMCC::AL));
9602 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
9603 .addReg(NewVReg1)
9604 .addReg(VReg1)
9605 .add(predOps(ARMCC::AL));
9608 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
9609 .addMBB(TrapBB)
9610 .addImm(ARMCC::HI)
9611 .addReg(ARM::CPSR);
9613 Register NewVReg2 = MRI->createVirtualRegister(TRC);
9614 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
9615 .addReg(ARM::CPSR, RegState::Define)
9616 .addReg(NewVReg1)
9617 .addImm(2)
9618 .add(predOps(ARMCC::AL));
9620 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9621 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
9622 .addJumpTableIndex(MJTI)
9623 .add(predOps(ARMCC::AL));
9625 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9626 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
9627 .addReg(ARM::CPSR, RegState::Define)
9628 .addReg(NewVReg2, RegState::Kill)
9629 .addReg(NewVReg3)
9630 .add(predOps(ARMCC::AL));
9632 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9633 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9635 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9636 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
9637 .addReg(NewVReg4, RegState::Kill)
9638 .addImm(0)
9639 .addMemOperand(JTMMOLd)
9640 .add(predOps(ARMCC::AL));
9642 unsigned NewVReg6 = NewVReg5;
9643 if (IsPositionIndependent) {
9644 NewVReg6 = MRI->createVirtualRegister(TRC);
9645 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
9646 .addReg(ARM::CPSR, RegState::Define)
9647 .addReg(NewVReg5, RegState::Kill)
9648 .addReg(NewVReg3)
9649 .add(predOps(ARMCC::AL));
9652 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
9653 .addReg(NewVReg6, RegState::Kill)
9654 .addJumpTableIndex(MJTI);
9655 } else {
9656 Register NewVReg1 = MRI->createVirtualRegister(TRC);
9657 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
9658 .addFrameIndex(FI)
9659 .addImm(4)
9660 .addMemOperand(FIMMOLd)
9661 .add(predOps(ARMCC::AL));
9663 if (NumLPads < 256) {
9664 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
9665 .addReg(NewVReg1)
9666 .addImm(NumLPads)
9667 .add(predOps(ARMCC::AL));
9668 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
9669 Register VReg1 = MRI->createVirtualRegister(TRC);
9670 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
9671 .addImm(NumLPads & 0xFFFF)
9672 .add(predOps(ARMCC::AL));
9674 unsigned VReg2 = VReg1;
9675 if ((NumLPads & 0xFFFF0000) != 0) {
9676 VReg2 = MRI->createVirtualRegister(TRC);
9677 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
9678 .addReg(VReg1)
9679 .addImm(NumLPads >> 16)
9680 .add(predOps(ARMCC::AL));
9683 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9684 .addReg(NewVReg1)
9685 .addReg(VReg2)
9686 .add(predOps(ARMCC::AL));
9687 } else {
9688 MachineConstantPool *ConstantPool = MF->getConstantPool();
9689 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9690 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9692 // MachineConstantPool wants an explicit alignment.
9693 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9694 if (Align == 0)
9695 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9696 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9698 Register VReg1 = MRI->createVirtualRegister(TRC);
9699 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
9700 .addReg(VReg1, RegState::Define)
9701 .addConstantPoolIndex(Idx)
9702 .addImm(0)
9703 .add(predOps(ARMCC::AL));
9704 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9705 .addReg(NewVReg1)
9706 .addReg(VReg1, RegState::Kill)
9707 .add(predOps(ARMCC::AL));
9710 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
9711 .addMBB(TrapBB)
9712 .addImm(ARMCC::HI)
9713 .addReg(ARM::CPSR);
9715 Register NewVReg3 = MRI->createVirtualRegister(TRC);
9716 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
9717 .addReg(NewVReg1)
9718 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9719 .add(predOps(ARMCC::AL))
9720 .add(condCodeOp());
9721 Register NewVReg4 = MRI->createVirtualRegister(TRC);
9722 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
9723 .addJumpTableIndex(MJTI)
9724 .add(predOps(ARMCC::AL));
9726 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9727 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9728 Register NewVReg5 = MRI->createVirtualRegister(TRC);
9729 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
9730 .addReg(NewVReg3, RegState::Kill)
9731 .addReg(NewVReg4)
9732 .addImm(0)
9733 .addMemOperand(JTMMOLd)
9734 .add(predOps(ARMCC::AL));
9736 if (IsPositionIndependent) {
9737 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
9738 .addReg(NewVReg5, RegState::Kill)
9739 .addReg(NewVReg4)
9740 .addJumpTableIndex(MJTI);
9741 } else {
9742 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
9743 .addReg(NewVReg5, RegState::Kill)
9744 .addJumpTableIndex(MJTI);
9748 // Add the jump table entries as successors to the MBB.
9749 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
9750 for (std::vector<MachineBasicBlock*>::iterator
9751 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
9752 MachineBasicBlock *CurMBB = *I;
9753 if (SeenMBBs.insert(CurMBB).second)
9754 DispContBB->addSuccessor(CurMBB);
9757 // N.B. the order the invoke BBs are processed in doesn't matter here.
9758 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
9759 SmallVector<MachineBasicBlock*, 64> MBBLPads;
9760 for (MachineBasicBlock *BB : InvokeBBs) {
9762 // Remove the landing pad successor from the invoke block and replace it
9763 // with the new dispatch block.
9764 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
9765 BB->succ_end());
9766 while (!Successors.empty()) {
9767 MachineBasicBlock *SMBB = Successors.pop_back_val();
9768 if (SMBB->isEHPad()) {
9769 BB->removeSuccessor(SMBB);
9770 MBBLPads.push_back(SMBB);
9774 BB->addSuccessor(DispatchBB, BranchProbability::getZero());
9775 BB->normalizeSuccProbs();
9777 // Find the invoke call and mark all of the callee-saved registers as
9778 // 'implicit defined' so that they're spilled. This prevents code from
9779 // moving instructions to before the EH block, where they will never be
9780 // executed.
9781 for (MachineBasicBlock::reverse_iterator
9782 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
9783 if (!II->isCall()) continue;
9785 DenseMap<unsigned, bool> DefRegs;
9786 for (MachineInstr::mop_iterator
9787 OI = II->operands_begin(), OE = II->operands_end();
9788 OI != OE; ++OI) {
9789 if (!OI->isReg()) continue;
9790 DefRegs[OI->getReg()] = true;
9793 MachineInstrBuilder MIB(*MF, &*II);
9795 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
9796 unsigned Reg = SavedRegs[i];
9797 if (Subtarget->isThumb2() &&
9798 !ARM::tGPRRegClass.contains(Reg) &&
9799 !ARM::hGPRRegClass.contains(Reg))
9800 continue;
9801 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
9802 continue;
9803 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
9804 continue;
9805 if (!DefRegs[Reg])
9806 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
9809 break;
9813 // Mark all former landing pads as non-landing pads. The dispatch is the only
9814 // landing pad now.
9815 for (SmallVectorImpl<MachineBasicBlock*>::iterator
9816 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
9817 (*I)->setIsEHPad(false);
9819 // The instruction is gone now.
9820 MI.eraseFromParent();
9823 static
9824 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
9825 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
9826 E = MBB->succ_end(); I != E; ++I)
9827 if (*I != Succ)
9828 return *I;
9829 llvm_unreachable("Expecting a BB with two successors!");
9832 /// Return the load opcode for a given load size. If load size >= 8,
9833 /// neon opcode will be returned.
9834 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
9835 if (LdSize >= 8)
9836 return LdSize == 16 ? ARM::VLD1q32wb_fixed
9837 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
9838 if (IsThumb1)
9839 return LdSize == 4 ? ARM::tLDRi
9840 : LdSize == 2 ? ARM::tLDRHi
9841 : LdSize == 1 ? ARM::tLDRBi : 0;
9842 if (IsThumb2)
9843 return LdSize == 4 ? ARM::t2LDR_POST
9844 : LdSize == 2 ? ARM::t2LDRH_POST
9845 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
9846 return LdSize == 4 ? ARM::LDR_POST_IMM
9847 : LdSize == 2 ? ARM::LDRH_POST
9848 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
9851 /// Return the store opcode for a given store size. If store size >= 8,
9852 /// neon opcode will be returned.
9853 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
9854 if (StSize >= 8)
9855 return StSize == 16 ? ARM::VST1q32wb_fixed
9856 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
9857 if (IsThumb1)
9858 return StSize == 4 ? ARM::tSTRi
9859 : StSize == 2 ? ARM::tSTRHi
9860 : StSize == 1 ? ARM::tSTRBi : 0;
9861 if (IsThumb2)
9862 return StSize == 4 ? ARM::t2STR_POST
9863 : StSize == 2 ? ARM::t2STRH_POST
9864 : StSize == 1 ? ARM::t2STRB_POST : 0;
9865 return StSize == 4 ? ARM::STR_POST_IMM
9866 : StSize == 2 ? ARM::STRH_POST
9867 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
9870 /// Emit a post-increment load operation with given size. The instructions
9871 /// will be added to BB at Pos.
9872 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9873 const TargetInstrInfo *TII, const DebugLoc &dl,
9874 unsigned LdSize, unsigned Data, unsigned AddrIn,
9875 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9876 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
9877 assert(LdOpc != 0 && "Should have a load opcode");
9878 if (LdSize >= 8) {
9879 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9880 .addReg(AddrOut, RegState::Define)
9881 .addReg(AddrIn)
9882 .addImm(0)
9883 .add(predOps(ARMCC::AL));
9884 } else if (IsThumb1) {
9885 // load + update AddrIn
9886 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9887 .addReg(AddrIn)
9888 .addImm(0)
9889 .add(predOps(ARMCC::AL));
9890 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9891 .add(t1CondCodeOp())
9892 .addReg(AddrIn)
9893 .addImm(LdSize)
9894 .add(predOps(ARMCC::AL));
9895 } else if (IsThumb2) {
9896 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9897 .addReg(AddrOut, RegState::Define)
9898 .addReg(AddrIn)
9899 .addImm(LdSize)
9900 .add(predOps(ARMCC::AL));
9901 } else { // arm
9902 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
9903 .addReg(AddrOut, RegState::Define)
9904 .addReg(AddrIn)
9905 .addReg(0)
9906 .addImm(LdSize)
9907 .add(predOps(ARMCC::AL));
9911 /// Emit a post-increment store operation with given size. The instructions
9912 /// will be added to BB at Pos.
9913 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
9914 const TargetInstrInfo *TII, const DebugLoc &dl,
9915 unsigned StSize, unsigned Data, unsigned AddrIn,
9916 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
9917 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
9918 assert(StOpc != 0 && "Should have a store opcode");
9919 if (StSize >= 8) {
9920 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9921 .addReg(AddrIn)
9922 .addImm(0)
9923 .addReg(Data)
9924 .add(predOps(ARMCC::AL));
9925 } else if (IsThumb1) {
9926 // store + update AddrIn
9927 BuildMI(*BB, Pos, dl, TII->get(StOpc))
9928 .addReg(Data)
9929 .addReg(AddrIn)
9930 .addImm(0)
9931 .add(predOps(ARMCC::AL));
9932 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
9933 .add(t1CondCodeOp())
9934 .addReg(AddrIn)
9935 .addImm(StSize)
9936 .add(predOps(ARMCC::AL));
9937 } else if (IsThumb2) {
9938 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9939 .addReg(Data)
9940 .addReg(AddrIn)
9941 .addImm(StSize)
9942 .add(predOps(ARMCC::AL));
9943 } else { // arm
9944 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
9945 .addReg(Data)
9946 .addReg(AddrIn)
9947 .addReg(0)
9948 .addImm(StSize)
9949 .add(predOps(ARMCC::AL));
9953 MachineBasicBlock *
9954 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
9955 MachineBasicBlock *BB) const {
9956 // This pseudo instruction has 3 operands: dst, src, size
9957 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
9958 // Otherwise, we will generate unrolled scalar copies.
9959 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9960 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9961 MachineFunction::iterator It = ++BB->getIterator();
9963 Register dest = MI.getOperand(0).getReg();
9964 Register src = MI.getOperand(1).getReg();
9965 unsigned SizeVal = MI.getOperand(2).getImm();
9966 unsigned Align = MI.getOperand(3).getImm();
9967 DebugLoc dl = MI.getDebugLoc();
9969 MachineFunction *MF = BB->getParent();
9970 MachineRegisterInfo &MRI = MF->getRegInfo();
9971 unsigned UnitSize = 0;
9972 const TargetRegisterClass *TRC = nullptr;
9973 const TargetRegisterClass *VecTRC = nullptr;
9975 bool IsThumb1 = Subtarget->isThumb1Only();
9976 bool IsThumb2 = Subtarget->isThumb2();
9977 bool IsThumb = Subtarget->isThumb();
9979 if (Align & 1) {
9980 UnitSize = 1;
9981 } else if (Align & 2) {
9982 UnitSize = 2;
9983 } else {
9984 // Check whether we can use NEON instructions.
9985 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
9986 Subtarget->hasNEON()) {
9987 if ((Align % 16 == 0) && SizeVal >= 16)
9988 UnitSize = 16;
9989 else if ((Align % 8 == 0) && SizeVal >= 8)
9990 UnitSize = 8;
9992 // Can't use NEON instructions.
9993 if (UnitSize == 0)
9994 UnitSize = 4;
9997 // Select the correct opcode and register class for unit size load/store
9998 bool IsNeon = UnitSize >= 8;
9999 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
10000 if (IsNeon)
10001 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
10002 : UnitSize == 8 ? &ARM::DPRRegClass
10003 : nullptr;
10005 unsigned BytesLeft = SizeVal % UnitSize;
10006 unsigned LoopSize = SizeVal - BytesLeft;
10008 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
10009 // Use LDR and STR to copy.
10010 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
10011 // [destOut] = STR_POST(scratch, destIn, UnitSize)
10012 unsigned srcIn = src;
10013 unsigned destIn = dest;
10014 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
10015 Register srcOut = MRI.createVirtualRegister(TRC);
10016 Register destOut = MRI.createVirtualRegister(TRC);
10017 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10018 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
10019 IsThumb1, IsThumb2);
10020 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
10021 IsThumb1, IsThumb2);
10022 srcIn = srcOut;
10023 destIn = destOut;
10026 // Handle the leftover bytes with LDRB and STRB.
10027 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
10028 // [destOut] = STRB_POST(scratch, destIn, 1)
10029 for (unsigned i = 0; i < BytesLeft; i++) {
10030 Register srcOut = MRI.createVirtualRegister(TRC);
10031 Register destOut = MRI.createVirtualRegister(TRC);
10032 Register scratch = MRI.createVirtualRegister(TRC);
10033 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
10034 IsThumb1, IsThumb2);
10035 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
10036 IsThumb1, IsThumb2);
10037 srcIn = srcOut;
10038 destIn = destOut;
10040 MI.eraseFromParent(); // The instruction is gone now.
10041 return BB;
10044 // Expand the pseudo op to a loop.
10045 // thisMBB:
10046 // ...
10047 // movw varEnd, # --> with thumb2
10048 // movt varEnd, #
10049 // ldrcp varEnd, idx --> without thumb2
10050 // fallthrough --> loopMBB
10051 // loopMBB:
10052 // PHI varPhi, varEnd, varLoop
10053 // PHI srcPhi, src, srcLoop
10054 // PHI destPhi, dst, destLoop
10055 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10056 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
10057 // subs varLoop, varPhi, #UnitSize
10058 // bne loopMBB
10059 // fallthrough --> exitMBB
10060 // exitMBB:
10061 // epilogue to handle left-over bytes
10062 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10063 // [destOut] = STRB_POST(scratch, destLoop, 1)
10064 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10065 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10066 MF->insert(It, loopMBB);
10067 MF->insert(It, exitMBB);
10069 // Transfer the remainder of BB and its successor edges to exitMBB.
10070 exitMBB->splice(exitMBB->begin(), BB,
10071 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10072 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10074 // Load an immediate to varEnd.
10075 Register varEnd = MRI.createVirtualRegister(TRC);
10076 if (Subtarget->useMovt()) {
10077 unsigned Vtmp = varEnd;
10078 if ((LoopSize & 0xFFFF0000) != 0)
10079 Vtmp = MRI.createVirtualRegister(TRC);
10080 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
10081 .addImm(LoopSize & 0xFFFF)
10082 .add(predOps(ARMCC::AL));
10084 if ((LoopSize & 0xFFFF0000) != 0)
10085 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
10086 .addReg(Vtmp)
10087 .addImm(LoopSize >> 16)
10088 .add(predOps(ARMCC::AL));
10089 } else {
10090 MachineConstantPool *ConstantPool = MF->getConstantPool();
10091 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10092 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
10094 // MachineConstantPool wants an explicit alignment.
10095 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
10096 if (Align == 0)
10097 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
10098 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
10099 MachineMemOperand *CPMMO =
10100 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
10101 MachineMemOperand::MOLoad, 4, 4);
10103 if (IsThumb)
10104 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
10105 .addReg(varEnd, RegState::Define)
10106 .addConstantPoolIndex(Idx)
10107 .add(predOps(ARMCC::AL))
10108 .addMemOperand(CPMMO);
10109 else
10110 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
10111 .addReg(varEnd, RegState::Define)
10112 .addConstantPoolIndex(Idx)
10113 .addImm(0)
10114 .add(predOps(ARMCC::AL))
10115 .addMemOperand(CPMMO);
10117 BB->addSuccessor(loopMBB);
10119 // Generate the loop body:
10120 // varPhi = PHI(varLoop, varEnd)
10121 // srcPhi = PHI(srcLoop, src)
10122 // destPhi = PHI(destLoop, dst)
10123 MachineBasicBlock *entryBB = BB;
10124 BB = loopMBB;
10125 Register varLoop = MRI.createVirtualRegister(TRC);
10126 Register varPhi = MRI.createVirtualRegister(TRC);
10127 Register srcLoop = MRI.createVirtualRegister(TRC);
10128 Register srcPhi = MRI.createVirtualRegister(TRC);
10129 Register destLoop = MRI.createVirtualRegister(TRC);
10130 Register destPhi = MRI.createVirtualRegister(TRC);
10132 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
10133 .addReg(varLoop).addMBB(loopMBB)
10134 .addReg(varEnd).addMBB(entryBB);
10135 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
10136 .addReg(srcLoop).addMBB(loopMBB)
10137 .addReg(src).addMBB(entryBB);
10138 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
10139 .addReg(destLoop).addMBB(loopMBB)
10140 .addReg(dest).addMBB(entryBB);
10142 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10143 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
10144 Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10145 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
10146 IsThumb1, IsThumb2);
10147 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
10148 IsThumb1, IsThumb2);
10150 // Decrement loop variable by UnitSize.
10151 if (IsThumb1) {
10152 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
10153 .add(t1CondCodeOp())
10154 .addReg(varPhi)
10155 .addImm(UnitSize)
10156 .add(predOps(ARMCC::AL));
10157 } else {
10158 MachineInstrBuilder MIB =
10159 BuildMI(*BB, BB->end(), dl,
10160 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
10161 MIB.addReg(varPhi)
10162 .addImm(UnitSize)
10163 .add(predOps(ARMCC::AL))
10164 .add(condCodeOp());
10165 MIB->getOperand(5).setReg(ARM::CPSR);
10166 MIB->getOperand(5).setIsDef(true);
10168 BuildMI(*BB, BB->end(), dl,
10169 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
10170 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
10172 // loopMBB can loop back to loopMBB or fall through to exitMBB.
10173 BB->addSuccessor(loopMBB);
10174 BB->addSuccessor(exitMBB);
10176 // Add epilogue to handle BytesLeft.
10177 BB = exitMBB;
10178 auto StartOfExit = exitMBB->begin();
10180 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10181 // [destOut] = STRB_POST(scratch, destLoop, 1)
10182 unsigned srcIn = srcLoop;
10183 unsigned destIn = destLoop;
10184 for (unsigned i = 0; i < BytesLeft; i++) {
10185 Register srcOut = MRI.createVirtualRegister(TRC);
10186 Register destOut = MRI.createVirtualRegister(TRC);
10187 Register scratch = MRI.createVirtualRegister(TRC);
10188 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
10189 IsThumb1, IsThumb2);
10190 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
10191 IsThumb1, IsThumb2);
10192 srcIn = srcOut;
10193 destIn = destOut;
10196 MI.eraseFromParent(); // The instruction is gone now.
10197 return BB;
10200 MachineBasicBlock *
10201 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
10202 MachineBasicBlock *MBB) const {
10203 const TargetMachine &TM = getTargetMachine();
10204 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
10205 DebugLoc DL = MI.getDebugLoc();
10207 assert(Subtarget->isTargetWindows() &&
10208 "__chkstk is only supported on Windows");
10209 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
10211 // __chkstk takes the number of words to allocate on the stack in R4, and
10212 // returns the stack adjustment in number of bytes in R4. This will not
10213 // clober any other registers (other than the obvious lr).
10215 // Although, technically, IP should be considered a register which may be
10216 // clobbered, the call itself will not touch it. Windows on ARM is a pure
10217 // thumb-2 environment, so there is no interworking required. As a result, we
10218 // do not expect a veneer to be emitted by the linker, clobbering IP.
10220 // Each module receives its own copy of __chkstk, so no import thunk is
10221 // required, again, ensuring that IP is not clobbered.
10223 // Finally, although some linkers may theoretically provide a trampoline for
10224 // out of range calls (which is quite common due to a 32M range limitation of
10225 // branches for Thumb), we can generate the long-call version via
10226 // -mcmodel=large, alleviating the need for the trampoline which may clobber
10227 // IP.
10229 switch (TM.getCodeModel()) {
10230 case CodeModel::Tiny:
10231 llvm_unreachable("Tiny code model not available on ARM.");
10232 case CodeModel::Small:
10233 case CodeModel::Medium:
10234 case CodeModel::Kernel:
10235 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
10236 .add(predOps(ARMCC::AL))
10237 .addExternalSymbol("__chkstk")
10238 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10239 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10240 .addReg(ARM::R12,
10241 RegState::Implicit | RegState::Define | RegState::Dead)
10242 .addReg(ARM::CPSR,
10243 RegState::Implicit | RegState::Define | RegState::Dead);
10244 break;
10245 case CodeModel::Large: {
10246 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10247 Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
10249 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
10250 .addExternalSymbol("__chkstk");
10251 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
10252 .add(predOps(ARMCC::AL))
10253 .addReg(Reg, RegState::Kill)
10254 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10255 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10256 .addReg(ARM::R12,
10257 RegState::Implicit | RegState::Define | RegState::Dead)
10258 .addReg(ARM::CPSR,
10259 RegState::Implicit | RegState::Define | RegState::Dead);
10260 break;
10264 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
10265 .addReg(ARM::SP, RegState::Kill)
10266 .addReg(ARM::R4, RegState::Kill)
10267 .setMIFlags(MachineInstr::FrameSetup)
10268 .add(predOps(ARMCC::AL))
10269 .add(condCodeOp());
10271 MI.eraseFromParent();
10272 return MBB;
10275 MachineBasicBlock *
10276 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
10277 MachineBasicBlock *MBB) const {
10278 DebugLoc DL = MI.getDebugLoc();
10279 MachineFunction *MF = MBB->getParent();
10280 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10282 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
10283 MF->insert(++MBB->getIterator(), ContBB);
10284 ContBB->splice(ContBB->begin(), MBB,
10285 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10286 ContBB->transferSuccessorsAndUpdatePHIs(MBB);
10287 MBB->addSuccessor(ContBB);
10289 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10290 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
10291 MF->push_back(TrapBB);
10292 MBB->addSuccessor(TrapBB);
10294 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
10295 .addReg(MI.getOperand(0).getReg())
10296 .addImm(0)
10297 .add(predOps(ARMCC::AL));
10298 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
10299 .addMBB(TrapBB)
10300 .addImm(ARMCC::EQ)
10301 .addReg(ARM::CPSR);
10303 MI.eraseFromParent();
10304 return ContBB;
10307 // The CPSR operand of SelectItr might be missing a kill marker
10308 // because there were multiple uses of CPSR, and ISel didn't know
10309 // which to mark. Figure out whether SelectItr should have had a
10310 // kill marker, and set it if it should. Returns the correct kill
10311 // marker value.
10312 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
10313 MachineBasicBlock* BB,
10314 const TargetRegisterInfo* TRI) {
10315 // Scan forward through BB for a use/def of CPSR.
10316 MachineBasicBlock::iterator miI(std::next(SelectItr));
10317 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
10318 const MachineInstr& mi = *miI;
10319 if (mi.readsRegister(ARM::CPSR))
10320 return false;
10321 if (mi.definesRegister(ARM::CPSR))
10322 break; // Should have kill-flag - update below.
10325 // If we hit the end of the block, check whether CPSR is live into a
10326 // successor.
10327 if (miI == BB->end()) {
10328 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
10329 sEnd = BB->succ_end();
10330 sItr != sEnd; ++sItr) {
10331 MachineBasicBlock* succ = *sItr;
10332 if (succ->isLiveIn(ARM::CPSR))
10333 return false;
10337 // We found a def, or hit the end of the basic block and CPSR wasn't live
10338 // out. SelectMI should have a kill flag on CPSR.
10339 SelectItr->addRegisterKilled(ARM::CPSR, TRI);
10340 return true;
10343 MachineBasicBlock *
10344 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10345 MachineBasicBlock *BB) const {
10346 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10347 DebugLoc dl = MI.getDebugLoc();
10348 bool isThumb2 = Subtarget->isThumb2();
10349 switch (MI.getOpcode()) {
10350 default: {
10351 MI.print(errs());
10352 llvm_unreachable("Unexpected instr type to insert");
10355 // Thumb1 post-indexed loads are really just single-register LDMs.
10356 case ARM::tLDR_postidx: {
10357 MachineOperand Def(MI.getOperand(1));
10358 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
10359 .add(Def) // Rn_wb
10360 .add(MI.getOperand(2)) // Rn
10361 .add(MI.getOperand(3)) // PredImm
10362 .add(MI.getOperand(4)) // PredReg
10363 .add(MI.getOperand(0)) // Rt
10364 .cloneMemRefs(MI);
10365 MI.eraseFromParent();
10366 return BB;
10369 // The Thumb2 pre-indexed stores have the same MI operands, they just
10370 // define them differently in the .td files from the isel patterns, so
10371 // they need pseudos.
10372 case ARM::t2STR_preidx:
10373 MI.setDesc(TII->get(ARM::t2STR_PRE));
10374 return BB;
10375 case ARM::t2STRB_preidx:
10376 MI.setDesc(TII->get(ARM::t2STRB_PRE));
10377 return BB;
10378 case ARM::t2STRH_preidx:
10379 MI.setDesc(TII->get(ARM::t2STRH_PRE));
10380 return BB;
10382 case ARM::STRi_preidx:
10383 case ARM::STRBi_preidx: {
10384 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
10385 : ARM::STRB_PRE_IMM;
10386 // Decode the offset.
10387 unsigned Offset = MI.getOperand(4).getImm();
10388 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
10389 Offset = ARM_AM::getAM2Offset(Offset);
10390 if (isSub)
10391 Offset = -Offset;
10393 MachineMemOperand *MMO = *MI.memoperands_begin();
10394 BuildMI(*BB, MI, dl, TII->get(NewOpc))
10395 .add(MI.getOperand(0)) // Rn_wb
10396 .add(MI.getOperand(1)) // Rt
10397 .add(MI.getOperand(2)) // Rn
10398 .addImm(Offset) // offset (skip GPR==zero_reg)
10399 .add(MI.getOperand(5)) // pred
10400 .add(MI.getOperand(6))
10401 .addMemOperand(MMO);
10402 MI.eraseFromParent();
10403 return BB;
10405 case ARM::STRr_preidx:
10406 case ARM::STRBr_preidx:
10407 case ARM::STRH_preidx: {
10408 unsigned NewOpc;
10409 switch (MI.getOpcode()) {
10410 default: llvm_unreachable("unexpected opcode!");
10411 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
10412 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
10413 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
10415 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
10416 for (unsigned i = 0; i < MI.getNumOperands(); ++i)
10417 MIB.add(MI.getOperand(i));
10418 MI.eraseFromParent();
10419 return BB;
10422 case ARM::tMOVCCr_pseudo: {
10423 // To "insert" a SELECT_CC instruction, we actually have to insert the
10424 // diamond control-flow pattern. The incoming instruction knows the
10425 // destination vreg to set, the condition code register to branch on, the
10426 // true/false values to select between, and a branch opcode to use.
10427 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10428 MachineFunction::iterator It = ++BB->getIterator();
10430 // thisMBB:
10431 // ...
10432 // TrueVal = ...
10433 // cmpTY ccX, r1, r2
10434 // bCC copy1MBB
10435 // fallthrough --> copy0MBB
10436 MachineBasicBlock *thisMBB = BB;
10437 MachineFunction *F = BB->getParent();
10438 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10439 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10440 F->insert(It, copy0MBB);
10441 F->insert(It, sinkMBB);
10443 // Check whether CPSR is live past the tMOVCCr_pseudo.
10444 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
10445 if (!MI.killsRegister(ARM::CPSR) &&
10446 !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
10447 copy0MBB->addLiveIn(ARM::CPSR);
10448 sinkMBB->addLiveIn(ARM::CPSR);
10451 // Transfer the remainder of BB and its successor edges to sinkMBB.
10452 sinkMBB->splice(sinkMBB->begin(), BB,
10453 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10454 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10456 BB->addSuccessor(copy0MBB);
10457 BB->addSuccessor(sinkMBB);
10459 BuildMI(BB, dl, TII->get(ARM::tBcc))
10460 .addMBB(sinkMBB)
10461 .addImm(MI.getOperand(3).getImm())
10462 .addReg(MI.getOperand(4).getReg());
10464 // copy0MBB:
10465 // %FalseValue = ...
10466 // # fallthrough to sinkMBB
10467 BB = copy0MBB;
10469 // Update machine-CFG edges
10470 BB->addSuccessor(sinkMBB);
10472 // sinkMBB:
10473 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10474 // ...
10475 BB = sinkMBB;
10476 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
10477 .addReg(MI.getOperand(1).getReg())
10478 .addMBB(copy0MBB)
10479 .addReg(MI.getOperand(2).getReg())
10480 .addMBB(thisMBB);
10482 MI.eraseFromParent(); // The pseudo instruction is gone now.
10483 return BB;
10486 case ARM::BCCi64:
10487 case ARM::BCCZi64: {
10488 // If there is an unconditional branch to the other successor, remove it.
10489 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
10491 // Compare both parts that make up the double comparison separately for
10492 // equality.
10493 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
10495 Register LHS1 = MI.getOperand(1).getReg();
10496 Register LHS2 = MI.getOperand(2).getReg();
10497 if (RHSisZero) {
10498 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10499 .addReg(LHS1)
10500 .addImm(0)
10501 .add(predOps(ARMCC::AL));
10502 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10503 .addReg(LHS2).addImm(0)
10504 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10505 } else {
10506 Register RHS1 = MI.getOperand(3).getReg();
10507 Register RHS2 = MI.getOperand(4).getReg();
10508 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10509 .addReg(LHS1)
10510 .addReg(RHS1)
10511 .add(predOps(ARMCC::AL));
10512 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10513 .addReg(LHS2).addReg(RHS2)
10514 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10517 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
10518 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
10519 if (MI.getOperand(0).getImm() == ARMCC::NE)
10520 std::swap(destMBB, exitMBB);
10522 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
10523 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
10524 if (isThumb2)
10525 BuildMI(BB, dl, TII->get(ARM::t2B))
10526 .addMBB(exitMBB)
10527 .add(predOps(ARMCC::AL));
10528 else
10529 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
10531 MI.eraseFromParent(); // The pseudo instruction is gone now.
10532 return BB;
10535 case ARM::Int_eh_sjlj_setjmp:
10536 case ARM::Int_eh_sjlj_setjmp_nofp:
10537 case ARM::tInt_eh_sjlj_setjmp:
10538 case ARM::t2Int_eh_sjlj_setjmp:
10539 case ARM::t2Int_eh_sjlj_setjmp_nofp:
10540 return BB;
10542 case ARM::Int_eh_sjlj_setup_dispatch:
10543 EmitSjLjDispatchBlock(MI, BB);
10544 return BB;
10546 case ARM::ABS:
10547 case ARM::t2ABS: {
10548 // To insert an ABS instruction, we have to insert the
10549 // diamond control-flow pattern. The incoming instruction knows the
10550 // source vreg to test against 0, the destination vreg to set,
10551 // the condition code register to branch on, the
10552 // true/false values to select between, and a branch opcode to use.
10553 // It transforms
10554 // V1 = ABS V0
10555 // into
10556 // V2 = MOVS V0
10557 // BCC (branch to SinkBB if V0 >= 0)
10558 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
10559 // SinkBB: V1 = PHI(V2, V3)
10560 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10561 MachineFunction::iterator BBI = ++BB->getIterator();
10562 MachineFunction *Fn = BB->getParent();
10563 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10564 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10565 Fn->insert(BBI, RSBBB);
10566 Fn->insert(BBI, SinkBB);
10568 Register ABSSrcReg = MI.getOperand(1).getReg();
10569 Register ABSDstReg = MI.getOperand(0).getReg();
10570 bool ABSSrcKIll = MI.getOperand(1).isKill();
10571 bool isThumb2 = Subtarget->isThumb2();
10572 MachineRegisterInfo &MRI = Fn->getRegInfo();
10573 // In Thumb mode S must not be specified if source register is the SP or
10574 // PC and if destination register is the SP, so restrict register class
10575 Register NewRsbDstReg = MRI.createVirtualRegister(
10576 isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
10578 // Transfer the remainder of BB and its successor edges to sinkMBB.
10579 SinkBB->splice(SinkBB->begin(), BB,
10580 std::next(MachineBasicBlock::iterator(MI)), BB->end());
10581 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
10583 BB->addSuccessor(RSBBB);
10584 BB->addSuccessor(SinkBB);
10586 // fall through to SinkMBB
10587 RSBBB->addSuccessor(SinkBB);
10589 // insert a cmp at the end of BB
10590 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10591 .addReg(ABSSrcReg)
10592 .addImm(0)
10593 .add(predOps(ARMCC::AL));
10595 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
10596 BuildMI(BB, dl,
10597 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
10598 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
10600 // insert rsbri in RSBBB
10601 // Note: BCC and rsbri will be converted into predicated rsbmi
10602 // by if-conversion pass
10603 BuildMI(*RSBBB, RSBBB->begin(), dl,
10604 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
10605 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
10606 .addImm(0)
10607 .add(predOps(ARMCC::AL))
10608 .add(condCodeOp());
10610 // insert PHI in SinkBB,
10611 // reuse ABSDstReg to not change uses of ABS instruction
10612 BuildMI(*SinkBB, SinkBB->begin(), dl,
10613 TII->get(ARM::PHI), ABSDstReg)
10614 .addReg(NewRsbDstReg).addMBB(RSBBB)
10615 .addReg(ABSSrcReg).addMBB(BB);
10617 // remove ABS instruction
10618 MI.eraseFromParent();
10620 // return last added BB
10621 return SinkBB;
10623 case ARM::COPY_STRUCT_BYVAL_I32:
10624 ++NumLoopByVals;
10625 return EmitStructByval(MI, BB);
10626 case ARM::WIN__CHKSTK:
10627 return EmitLowered__chkstk(MI, BB);
10628 case ARM::WIN__DBZCHK:
10629 return EmitLowered__dbzchk(MI, BB);
10633 /// Attaches vregs to MEMCPY that it will use as scratch registers
10634 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
10635 /// instead of as a custom inserter because we need the use list from the SDNode.
10636 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
10637 MachineInstr &MI, const SDNode *Node) {
10638 bool isThumb1 = Subtarget->isThumb1Only();
10640 DebugLoc DL = MI.getDebugLoc();
10641 MachineFunction *MF = MI.getParent()->getParent();
10642 MachineRegisterInfo &MRI = MF->getRegInfo();
10643 MachineInstrBuilder MIB(*MF, MI);
10645 // If the new dst/src is unused mark it as dead.
10646 if (!Node->hasAnyUseOfValue(0)) {
10647 MI.getOperand(0).setIsDead(true);
10649 if (!Node->hasAnyUseOfValue(1)) {
10650 MI.getOperand(1).setIsDead(true);
10653 // The MEMCPY both defines and kills the scratch registers.
10654 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
10655 Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
10656 : &ARM::GPRRegClass);
10657 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
10661 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10662 SDNode *Node) const {
10663 if (MI.getOpcode() == ARM::MEMCPY) {
10664 attachMEMCPYScratchRegs(Subtarget, MI, Node);
10665 return;
10668 const MCInstrDesc *MCID = &MI.getDesc();
10669 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
10670 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
10671 // operand is still set to noreg. If needed, set the optional operand's
10672 // register to CPSR, and remove the redundant implicit def.
10674 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
10676 // Rename pseudo opcodes.
10677 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
10678 unsigned ccOutIdx;
10679 if (NewOpc) {
10680 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
10681 MCID = &TII->get(NewOpc);
10683 assert(MCID->getNumOperands() ==
10684 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
10685 && "converted opcode should be the same except for cc_out"
10686 " (and, on Thumb1, pred)");
10688 MI.setDesc(*MCID);
10690 // Add the optional cc_out operand
10691 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
10693 // On Thumb1, move all input operands to the end, then add the predicate
10694 if (Subtarget->isThumb1Only()) {
10695 for (unsigned c = MCID->getNumOperands() - 4; c--;) {
10696 MI.addOperand(MI.getOperand(1));
10697 MI.RemoveOperand(1);
10700 // Restore the ties
10701 for (unsigned i = MI.getNumOperands(); i--;) {
10702 const MachineOperand& op = MI.getOperand(i);
10703 if (op.isReg() && op.isUse()) {
10704 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
10705 if (DefIdx != -1)
10706 MI.tieOperands(DefIdx, i);
10710 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
10711 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
10712 ccOutIdx = 1;
10713 } else
10714 ccOutIdx = MCID->getNumOperands() - 1;
10715 } else
10716 ccOutIdx = MCID->getNumOperands() - 1;
10718 // Any ARM instruction that sets the 's' bit should specify an optional
10719 // "cc_out" operand in the last operand position.
10720 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
10721 assert(!NewOpc && "Optional cc_out operand required");
10722 return;
10724 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
10725 // since we already have an optional CPSR def.
10726 bool definesCPSR = false;
10727 bool deadCPSR = false;
10728 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
10729 ++i) {
10730 const MachineOperand &MO = MI.getOperand(i);
10731 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
10732 definesCPSR = true;
10733 if (MO.isDead())
10734 deadCPSR = true;
10735 MI.RemoveOperand(i);
10736 break;
10739 if (!definesCPSR) {
10740 assert(!NewOpc && "Optional cc_out operand required");
10741 return;
10743 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
10744 if (deadCPSR) {
10745 assert(!MI.getOperand(ccOutIdx).getReg() &&
10746 "expect uninitialized optional cc_out operand");
10747 // Thumb1 instructions must have the S bit even if the CPSR is dead.
10748 if (!Subtarget->isThumb1Only())
10749 return;
10752 // If this instruction was defined with an optional CPSR def and its dag node
10753 // had a live implicit CPSR def, then activate the optional CPSR def.
10754 MachineOperand &MO = MI.getOperand(ccOutIdx);
10755 MO.setReg(ARM::CPSR);
10756 MO.setIsDef(true);
10759 //===----------------------------------------------------------------------===//
10760 // ARM Optimization Hooks
10761 //===----------------------------------------------------------------------===//
10763 // Helper function that checks if N is a null or all ones constant.
10764 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
10765 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
10768 // Return true if N is conditionally 0 or all ones.
10769 // Detects these expressions where cc is an i1 value:
10771 // (select cc 0, y) [AllOnes=0]
10772 // (select cc y, 0) [AllOnes=0]
10773 // (zext cc) [AllOnes=0]
10774 // (sext cc) [AllOnes=0/1]
10775 // (select cc -1, y) [AllOnes=1]
10776 // (select cc y, -1) [AllOnes=1]
10778 // Invert is set when N is the null/all ones constant when CC is false.
10779 // OtherOp is set to the alternative value of N.
10780 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
10781 SDValue &CC, bool &Invert,
10782 SDValue &OtherOp,
10783 SelectionDAG &DAG) {
10784 switch (N->getOpcode()) {
10785 default: return false;
10786 case ISD::SELECT: {
10787 CC = N->getOperand(0);
10788 SDValue N1 = N->getOperand(1);
10789 SDValue N2 = N->getOperand(2);
10790 if (isZeroOrAllOnes(N1, AllOnes)) {
10791 Invert = false;
10792 OtherOp = N2;
10793 return true;
10795 if (isZeroOrAllOnes(N2, AllOnes)) {
10796 Invert = true;
10797 OtherOp = N1;
10798 return true;
10800 return false;
10802 case ISD::ZERO_EXTEND:
10803 // (zext cc) can never be the all ones value.
10804 if (AllOnes)
10805 return false;
10806 LLVM_FALLTHROUGH;
10807 case ISD::SIGN_EXTEND: {
10808 SDLoc dl(N);
10809 EVT VT = N->getValueType(0);
10810 CC = N->getOperand(0);
10811 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
10812 return false;
10813 Invert = !AllOnes;
10814 if (AllOnes)
10815 // When looking for an AllOnes constant, N is an sext, and the 'other'
10816 // value is 0.
10817 OtherOp = DAG.getConstant(0, dl, VT);
10818 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10819 // When looking for a 0 constant, N can be zext or sext.
10820 OtherOp = DAG.getConstant(1, dl, VT);
10821 else
10822 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
10823 VT);
10824 return true;
10829 // Combine a constant select operand into its use:
10831 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10832 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10833 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
10834 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10835 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10837 // The transform is rejected if the select doesn't have a constant operand that
10838 // is null, or all ones when AllOnes is set.
10840 // Also recognize sext/zext from i1:
10842 // (add (zext cc), x) -> (select cc (add x, 1), x)
10843 // (add (sext cc), x) -> (select cc (add x, -1), x)
10845 // These transformations eventually create predicated instructions.
10847 // @param N The node to transform.
10848 // @param Slct The N operand that is a select.
10849 // @param OtherOp The other N operand (x above).
10850 // @param DCI Context.
10851 // @param AllOnes Require the select constant to be all ones instead of null.
10852 // @returns The new node, or SDValue() on failure.
10853 static
10854 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
10855 TargetLowering::DAGCombinerInfo &DCI,
10856 bool AllOnes = false) {
10857 SelectionDAG &DAG = DCI.DAG;
10858 EVT VT = N->getValueType(0);
10859 SDValue NonConstantVal;
10860 SDValue CCOp;
10861 bool SwapSelectOps;
10862 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
10863 NonConstantVal, DAG))
10864 return SDValue();
10866 // Slct is now know to be the desired identity constant when CC is true.
10867 SDValue TrueVal = OtherOp;
10868 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10869 OtherOp, NonConstantVal);
10870 // Unless SwapSelectOps says CC should be false.
10871 if (SwapSelectOps)
10872 std::swap(TrueVal, FalseVal);
10874 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
10875 CCOp, TrueVal, FalseVal);
10878 // Attempt combineSelectAndUse on each operand of a commutative operator N.
10879 static
10880 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
10881 TargetLowering::DAGCombinerInfo &DCI) {
10882 SDValue N0 = N->getOperand(0);
10883 SDValue N1 = N->getOperand(1);
10884 if (N0.getNode()->hasOneUse())
10885 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
10886 return Result;
10887 if (N1.getNode()->hasOneUse())
10888 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
10889 return Result;
10890 return SDValue();
10893 static bool IsVUZPShuffleNode(SDNode *N) {
10894 // VUZP shuffle node.
10895 if (N->getOpcode() == ARMISD::VUZP)
10896 return true;
10898 // "VUZP" on i32 is an alias for VTRN.
10899 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
10900 return true;
10902 return false;
10905 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
10906 TargetLowering::DAGCombinerInfo &DCI,
10907 const ARMSubtarget *Subtarget) {
10908 // Look for ADD(VUZP.0, VUZP.1).
10909 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
10910 N0 == N1)
10911 return SDValue();
10913 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
10914 if (!N->getValueType(0).is64BitVector())
10915 return SDValue();
10917 // Generate vpadd.
10918 SelectionDAG &DAG = DCI.DAG;
10919 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10920 SDLoc dl(N);
10921 SDNode *Unzip = N0.getNode();
10922 EVT VT = N->getValueType(0);
10924 SmallVector<SDValue, 8> Ops;
10925 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
10926 TLI.getPointerTy(DAG.getDataLayout())));
10927 Ops.push_back(Unzip->getOperand(0));
10928 Ops.push_back(Unzip->getOperand(1));
10930 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10933 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10934 TargetLowering::DAGCombinerInfo &DCI,
10935 const ARMSubtarget *Subtarget) {
10936 // Check for two extended operands.
10937 if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
10938 N1.getOpcode() == ISD::SIGN_EXTEND) &&
10939 !(N0.getOpcode() == ISD::ZERO_EXTEND &&
10940 N1.getOpcode() == ISD::ZERO_EXTEND))
10941 return SDValue();
10943 SDValue N00 = N0.getOperand(0);
10944 SDValue N10 = N1.getOperand(0);
10946 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
10947 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
10948 N00 == N10)
10949 return SDValue();
10951 // We only recognize Q register paddl here; this can't be reached until
10952 // after type legalization.
10953 if (!N00.getValueType().is64BitVector() ||
10954 !N0.getValueType().is128BitVector())
10955 return SDValue();
10957 // Generate vpaddl.
10958 SelectionDAG &DAG = DCI.DAG;
10959 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10960 SDLoc dl(N);
10961 EVT VT = N->getValueType(0);
10963 SmallVector<SDValue, 8> Ops;
10964 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
10965 unsigned Opcode;
10966 if (N0.getOpcode() == ISD::SIGN_EXTEND)
10967 Opcode = Intrinsic::arm_neon_vpaddls;
10968 else
10969 Opcode = Intrinsic::arm_neon_vpaddlu;
10970 Ops.push_back(DAG.getConstant(Opcode, dl,
10971 TLI.getPointerTy(DAG.getDataLayout())));
10972 EVT ElemTy = N00.getValueType().getVectorElementType();
10973 unsigned NumElts = VT.getVectorNumElements();
10974 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
10975 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
10976 N00.getOperand(0), N00.getOperand(1));
10977 Ops.push_back(Concat);
10979 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
10982 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
10983 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
10984 // much easier to match.
10985 static SDValue
10986 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
10987 TargetLowering::DAGCombinerInfo &DCI,
10988 const ARMSubtarget *Subtarget) {
10989 // Only perform optimization if after legalize, and if NEON is available. We
10990 // also expected both operands to be BUILD_VECTORs.
10991 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
10992 || N0.getOpcode() != ISD::BUILD_VECTOR
10993 || N1.getOpcode() != ISD::BUILD_VECTOR)
10994 return SDValue();
10996 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
10997 EVT VT = N->getValueType(0);
10998 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
10999 return SDValue();
11001 // Check that the vector operands are of the right form.
11002 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
11003 // operands, where N is the size of the formed vector.
11004 // Each EXTRACT_VECTOR should have the same input vector and odd or even
11005 // index such that we have a pair wise add pattern.
11007 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
11008 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11009 return SDValue();
11010 SDValue Vec = N0->getOperand(0)->getOperand(0);
11011 SDNode *V = Vec.getNode();
11012 unsigned nextIndex = 0;
11014 // For each operands to the ADD which are BUILD_VECTORs,
11015 // check to see if each of their operands are an EXTRACT_VECTOR with
11016 // the same vector and appropriate index.
11017 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
11018 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
11019 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11021 SDValue ExtVec0 = N0->getOperand(i);
11022 SDValue ExtVec1 = N1->getOperand(i);
11024 // First operand is the vector, verify its the same.
11025 if (V != ExtVec0->getOperand(0).getNode() ||
11026 V != ExtVec1->getOperand(0).getNode())
11027 return SDValue();
11029 // Second is the constant, verify its correct.
11030 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
11031 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
11033 // For the constant, we want to see all the even or all the odd.
11034 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
11035 || C1->getZExtValue() != nextIndex+1)
11036 return SDValue();
11038 // Increment index.
11039 nextIndex+=2;
11040 } else
11041 return SDValue();
11044 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
11045 // we're using the entire input vector, otherwise there's a size/legality
11046 // mismatch somewhere.
11047 if (nextIndex != Vec.getValueType().getVectorNumElements() ||
11048 Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
11049 return SDValue();
11051 // Create VPADDL node.
11052 SelectionDAG &DAG = DCI.DAG;
11053 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11055 SDLoc dl(N);
11057 // Build operand list.
11058 SmallVector<SDValue, 8> Ops;
11059 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
11060 TLI.getPointerTy(DAG.getDataLayout())));
11062 // Input is the vector.
11063 Ops.push_back(Vec);
11065 // Get widened type and narrowed type.
11066 MVT widenType;
11067 unsigned numElem = VT.getVectorNumElements();
11069 EVT inputLaneType = Vec.getValueType().getVectorElementType();
11070 switch (inputLaneType.getSimpleVT().SimpleTy) {
11071 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
11072 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
11073 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
11074 default:
11075 llvm_unreachable("Invalid vector element type for padd optimization.");
11078 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
11079 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
11080 return DAG.getNode(ExtOp, dl, VT, tmp);
11083 static SDValue findMUL_LOHI(SDValue V) {
11084 if (V->getOpcode() == ISD::UMUL_LOHI ||
11085 V->getOpcode() == ISD::SMUL_LOHI)
11086 return V;
11087 return SDValue();
11090 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
11091 TargetLowering::DAGCombinerInfo &DCI,
11092 const ARMSubtarget *Subtarget) {
11093 if (Subtarget->isThumb()) {
11094 if (!Subtarget->hasDSP())
11095 return SDValue();
11096 } else if (!Subtarget->hasV5TEOps())
11097 return SDValue();
11099 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
11100 // accumulates the product into a 64-bit value. The 16-bit values will
11101 // be sign extended somehow or SRA'd into 32-bit values
11102 // (addc (adde (mul 16bit, 16bit), lo), hi)
11103 SDValue Mul = AddcNode->getOperand(0);
11104 SDValue Lo = AddcNode->getOperand(1);
11105 if (Mul.getOpcode() != ISD::MUL) {
11106 Lo = AddcNode->getOperand(0);
11107 Mul = AddcNode->getOperand(1);
11108 if (Mul.getOpcode() != ISD::MUL)
11109 return SDValue();
11112 SDValue SRA = AddeNode->getOperand(0);
11113 SDValue Hi = AddeNode->getOperand(1);
11114 if (SRA.getOpcode() != ISD::SRA) {
11115 SRA = AddeNode->getOperand(1);
11116 Hi = AddeNode->getOperand(0);
11117 if (SRA.getOpcode() != ISD::SRA)
11118 return SDValue();
11120 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
11121 if (Const->getZExtValue() != 31)
11122 return SDValue();
11123 } else
11124 return SDValue();
11126 if (SRA.getOperand(0) != Mul)
11127 return SDValue();
11129 SelectionDAG &DAG = DCI.DAG;
11130 SDLoc dl(AddcNode);
11131 unsigned Opcode = 0;
11132 SDValue Op0;
11133 SDValue Op1;
11135 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
11136 Opcode = ARMISD::SMLALBB;
11137 Op0 = Mul.getOperand(0);
11138 Op1 = Mul.getOperand(1);
11139 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
11140 Opcode = ARMISD::SMLALBT;
11141 Op0 = Mul.getOperand(0);
11142 Op1 = Mul.getOperand(1).getOperand(0);
11143 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
11144 Opcode = ARMISD::SMLALTB;
11145 Op0 = Mul.getOperand(0).getOperand(0);
11146 Op1 = Mul.getOperand(1);
11147 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
11148 Opcode = ARMISD::SMLALTT;
11149 Op0 = Mul->getOperand(0).getOperand(0);
11150 Op1 = Mul->getOperand(1).getOperand(0);
11153 if (!Op0 || !Op1)
11154 return SDValue();
11156 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
11157 Op0, Op1, Lo, Hi);
11158 // Replace the ADDs' nodes uses by the MLA node's values.
11159 SDValue HiMLALResult(SMLAL.getNode(), 1);
11160 SDValue LoMLALResult(SMLAL.getNode(), 0);
11162 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
11163 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
11165 // Return original node to notify the driver to stop replacing.
11166 SDValue resNode(AddcNode, 0);
11167 return resNode;
11170 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
11171 TargetLowering::DAGCombinerInfo &DCI,
11172 const ARMSubtarget *Subtarget) {
11173 // Look for multiply add opportunities.
11174 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
11175 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
11176 // a glue link from the first add to the second add.
11177 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
11178 // a S/UMLAL instruction.
11179 // UMUL_LOHI
11180 // / :lo \ :hi
11181 // V \ [no multiline comment]
11182 // loAdd -> ADDC |
11183 // \ :carry /
11184 // V V
11185 // ADDE <- hiAdd
11187 // In the special case where only the higher part of a signed result is used
11188 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
11189 // a constant with the exact value of 0x80000000, we recognize we are dealing
11190 // with a "rounded multiply and add" (or subtract) and transform it into
11191 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
11193 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
11194 AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
11195 "Expect an ADDE or SUBE");
11197 assert(AddeSubeNode->getNumOperands() == 3 &&
11198 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
11199 "ADDE node has the wrong inputs");
11201 // Check that we are chained to the right ADDC or SUBC node.
11202 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
11203 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11204 AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
11205 (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
11206 AddcSubcNode->getOpcode() != ARMISD::SUBC))
11207 return SDValue();
11209 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
11210 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
11212 // Check if the two operands are from the same mul_lohi node.
11213 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
11214 return SDValue();
11216 assert(AddcSubcNode->getNumValues() == 2 &&
11217 AddcSubcNode->getValueType(0) == MVT::i32 &&
11218 "Expect ADDC with two result values. First: i32");
11220 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
11221 // maybe a SMLAL which multiplies two 16-bit values.
11222 if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11223 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
11224 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
11225 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
11226 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
11227 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
11229 // Check for the triangle shape.
11230 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
11231 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
11233 // Make sure that the ADDE/SUBE operands are not coming from the same node.
11234 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
11235 return SDValue();
11237 // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
11238 bool IsLeftOperandMUL = false;
11239 SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
11240 if (MULOp == SDValue())
11241 MULOp = findMUL_LOHI(AddeSubeOp1);
11242 else
11243 IsLeftOperandMUL = true;
11244 if (MULOp == SDValue())
11245 return SDValue();
11247 // Figure out the right opcode.
11248 unsigned Opc = MULOp->getOpcode();
11249 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
11251 // Figure out the high and low input values to the MLAL node.
11252 SDValue *HiAddSub = nullptr;
11253 SDValue *LoMul = nullptr;
11254 SDValue *LowAddSub = nullptr;
11256 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
11257 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
11258 return SDValue();
11260 if (IsLeftOperandMUL)
11261 HiAddSub = &AddeSubeOp1;
11262 else
11263 HiAddSub = &AddeSubeOp0;
11265 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
11266 // whose low result is fed to the ADDC/SUBC we are checking.
11268 if (AddcSubcOp0 == MULOp.getValue(0)) {
11269 LoMul = &AddcSubcOp0;
11270 LowAddSub = &AddcSubcOp1;
11272 if (AddcSubcOp1 == MULOp.getValue(0)) {
11273 LoMul = &AddcSubcOp1;
11274 LowAddSub = &AddcSubcOp0;
11277 if (!LoMul)
11278 return SDValue();
11280 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
11281 // the replacement below will create a cycle.
11282 if (AddcSubcNode == HiAddSub->getNode() ||
11283 AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
11284 return SDValue();
11286 // Create the merged node.
11287 SelectionDAG &DAG = DCI.DAG;
11289 // Start building operand list.
11290 SmallVector<SDValue, 8> Ops;
11291 Ops.push_back(LoMul->getOperand(0));
11292 Ops.push_back(LoMul->getOperand(1));
11294 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be
11295 // the case, we must be doing signed multiplication and only use the higher
11296 // part of the result of the MLAL, furthermore the LowAddSub must be a constant
11297 // addition or subtraction with the value of 0x800000.
11298 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
11299 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
11300 LowAddSub->getNode()->getOpcode() == ISD::Constant &&
11301 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
11302 0x80000000) {
11303 Ops.push_back(*HiAddSub);
11304 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
11305 FinalOpc = ARMISD::SMMLSR;
11306 } else {
11307 FinalOpc = ARMISD::SMMLAR;
11309 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
11310 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
11312 return SDValue(AddeSubeNode, 0);
11313 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
11314 // SMMLS is generated during instruction selection and the rest of this
11315 // function can not handle the case where AddcSubcNode is a SUBC.
11316 return SDValue();
11318 // Finish building the operand list for {U/S}MLAL
11319 Ops.push_back(*LowAddSub);
11320 Ops.push_back(*HiAddSub);
11322 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
11323 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11325 // Replace the ADDs' nodes uses by the MLA node's values.
11326 SDValue HiMLALResult(MLALNode.getNode(), 1);
11327 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
11329 SDValue LoMLALResult(MLALNode.getNode(), 0);
11330 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
11332 // Return original node to notify the driver to stop replacing.
11333 return SDValue(AddeSubeNode, 0);
11336 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
11337 TargetLowering::DAGCombinerInfo &DCI,
11338 const ARMSubtarget *Subtarget) {
11339 // UMAAL is similar to UMLAL except that it adds two unsigned values.
11340 // While trying to combine for the other MLAL nodes, first search for the
11341 // chance to use UMAAL. Check if Addc uses a node which has already
11342 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
11343 // as the addend, and it's handled in PerformUMLALCombine.
11345 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11346 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11348 // Check that we have a glued ADDC node.
11349 SDNode* AddcNode = AddeNode->getOperand(2).getNode();
11350 if (AddcNode->getOpcode() != ARMISD::ADDC)
11351 return SDValue();
11353 // Find the converted UMAAL or quit if it doesn't exist.
11354 SDNode *UmlalNode = nullptr;
11355 SDValue AddHi;
11356 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
11357 UmlalNode = AddcNode->getOperand(0).getNode();
11358 AddHi = AddcNode->getOperand(1);
11359 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
11360 UmlalNode = AddcNode->getOperand(1).getNode();
11361 AddHi = AddcNode->getOperand(0);
11362 } else {
11363 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11366 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
11367 // the ADDC as well as Zero.
11368 if (!isNullConstant(UmlalNode->getOperand(3)))
11369 return SDValue();
11371 if ((isNullConstant(AddeNode->getOperand(0)) &&
11372 AddeNode->getOperand(1).getNode() == UmlalNode) ||
11373 (AddeNode->getOperand(0).getNode() == UmlalNode &&
11374 isNullConstant(AddeNode->getOperand(1)))) {
11375 SelectionDAG &DAG = DCI.DAG;
11376 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
11377 UmlalNode->getOperand(2), AddHi };
11378 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
11379 DAG.getVTList(MVT::i32, MVT::i32), Ops);
11381 // Replace the ADDs' nodes uses by the UMAAL node's values.
11382 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
11383 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
11385 // Return original node to notify the driver to stop replacing.
11386 return SDValue(AddeNode, 0);
11388 return SDValue();
11391 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
11392 const ARMSubtarget *Subtarget) {
11393 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11394 return SDValue();
11396 // Check that we have a pair of ADDC and ADDE as operands.
11397 // Both addends of the ADDE must be zero.
11398 SDNode* AddcNode = N->getOperand(2).getNode();
11399 SDNode* AddeNode = N->getOperand(3).getNode();
11400 if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
11401 (AddeNode->getOpcode() == ARMISD::ADDE) &&
11402 isNullConstant(AddeNode->getOperand(0)) &&
11403 isNullConstant(AddeNode->getOperand(1)) &&
11404 (AddeNode->getOperand(2).getNode() == AddcNode))
11405 return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
11406 DAG.getVTList(MVT::i32, MVT::i32),
11407 {N->getOperand(0), N->getOperand(1),
11408 AddcNode->getOperand(0), AddcNode->getOperand(1)});
11409 else
11410 return SDValue();
11413 static SDValue PerformAddcSubcCombine(SDNode *N,
11414 TargetLowering::DAGCombinerInfo &DCI,
11415 const ARMSubtarget *Subtarget) {
11416 SelectionDAG &DAG(DCI.DAG);
11418 if (N->getOpcode() == ARMISD::SUBC) {
11419 // (SUBC (ADDE 0, 0, C), 1) -> C
11420 SDValue LHS = N->getOperand(0);
11421 SDValue RHS = N->getOperand(1);
11422 if (LHS->getOpcode() == ARMISD::ADDE &&
11423 isNullConstant(LHS->getOperand(0)) &&
11424 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
11425 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
11429 if (Subtarget->isThumb1Only()) {
11430 SDValue RHS = N->getOperand(1);
11431 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11432 int32_t imm = C->getSExtValue();
11433 if (imm < 0 && imm > std::numeric_limits<int>::min()) {
11434 SDLoc DL(N);
11435 RHS = DAG.getConstant(-imm, DL, MVT::i32);
11436 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
11437 : ARMISD::ADDC;
11438 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
11443 return SDValue();
11446 static SDValue PerformAddeSubeCombine(SDNode *N,
11447 TargetLowering::DAGCombinerInfo &DCI,
11448 const ARMSubtarget *Subtarget) {
11449 if (Subtarget->isThumb1Only()) {
11450 SelectionDAG &DAG = DCI.DAG;
11451 SDValue RHS = N->getOperand(1);
11452 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11453 int64_t imm = C->getSExtValue();
11454 if (imm < 0) {
11455 SDLoc DL(N);
11457 // The with-carry-in form matches bitwise not instead of the negation.
11458 // Effectively, the inverse interpretation of the carry flag already
11459 // accounts for part of the negation.
11460 RHS = DAG.getConstant(~imm, DL, MVT::i32);
11462 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
11463 : ARMISD::ADDE;
11464 return DAG.getNode(Opcode, DL, N->getVTList(),
11465 N->getOperand(0), RHS, N->getOperand(2));
11468 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
11469 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
11471 return SDValue();
11474 static SDValue PerformABSCombine(SDNode *N,
11475 TargetLowering::DAGCombinerInfo &DCI,
11476 const ARMSubtarget *Subtarget) {
11477 SDValue res;
11478 SelectionDAG &DAG = DCI.DAG;
11479 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11481 if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
11482 return SDValue();
11484 if (!TLI.expandABS(N, res, DAG))
11485 return SDValue();
11487 return res;
11490 /// PerformADDECombine - Target-specific dag combine transform from
11491 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
11492 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
11493 static SDValue PerformADDECombine(SDNode *N,
11494 TargetLowering::DAGCombinerInfo &DCI,
11495 const ARMSubtarget *Subtarget) {
11496 // Only ARM and Thumb2 support UMLAL/SMLAL.
11497 if (Subtarget->isThumb1Only())
11498 return PerformAddeSubeCombine(N, DCI, Subtarget);
11500 // Only perform the checks after legalize when the pattern is available.
11501 if (DCI.isBeforeLegalize()) return SDValue();
11503 return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
11506 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
11507 /// operands N0 and N1. This is a helper for PerformADDCombine that is
11508 /// called with the default operands, and if that fails, with commuted
11509 /// operands.
11510 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
11511 TargetLowering::DAGCombinerInfo &DCI,
11512 const ARMSubtarget *Subtarget){
11513 // Attempt to create vpadd for this add.
11514 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
11515 return Result;
11517 // Attempt to create vpaddl for this add.
11518 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
11519 return Result;
11520 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
11521 Subtarget))
11522 return Result;
11524 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
11525 if (N0.getNode()->hasOneUse())
11526 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
11527 return Result;
11528 return SDValue();
11531 bool
11532 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
11533 CombineLevel Level) const {
11534 if (Level == BeforeLegalizeTypes)
11535 return true;
11537 if (N->getOpcode() != ISD::SHL)
11538 return true;
11540 if (Subtarget->isThumb1Only()) {
11541 // Avoid making expensive immediates by commuting shifts. (This logic
11542 // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
11543 // for free.)
11544 if (N->getOpcode() != ISD::SHL)
11545 return true;
11546 SDValue N1 = N->getOperand(0);
11547 if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
11548 N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
11549 return true;
11550 if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
11551 if (Const->getAPIntValue().ult(256))
11552 return false;
11553 if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
11554 Const->getAPIntValue().sgt(-256))
11555 return false;
11557 return true;
11560 // Turn off commute-with-shift transform after legalization, so it doesn't
11561 // conflict with PerformSHLSimplify. (We could try to detect when
11562 // PerformSHLSimplify would trigger more precisely, but it isn't
11563 // really necessary.)
11564 return false;
11567 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
11568 const SDNode *N, CombineLevel Level) const {
11569 if (!Subtarget->isThumb1Only())
11570 return true;
11572 if (Level == BeforeLegalizeTypes)
11573 return true;
11575 return false;
11578 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
11579 if (!Subtarget->hasNEON()) {
11580 if (Subtarget->isThumb1Only())
11581 return VT.getScalarSizeInBits() <= 32;
11582 return true;
11584 return VT.isScalarInteger();
11587 static SDValue PerformSHLSimplify(SDNode *N,
11588 TargetLowering::DAGCombinerInfo &DCI,
11589 const ARMSubtarget *ST) {
11590 // Allow the generic combiner to identify potential bswaps.
11591 if (DCI.isBeforeLegalize())
11592 return SDValue();
11594 // DAG combiner will fold:
11595 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
11596 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
11597 // Other code patterns that can be also be modified have the following form:
11598 // b + ((a << 1) | 510)
11599 // b + ((a << 1) & 510)
11600 // b + ((a << 1) ^ 510)
11601 // b + ((a << 1) + 510)
11603 // Many instructions can perform the shift for free, but it requires both
11604 // the operands to be registers. If c1 << c2 is too large, a mov immediate
11605 // instruction will needed. So, unfold back to the original pattern if:
11606 // - if c1 and c2 are small enough that they don't require mov imms.
11607 // - the user(s) of the node can perform an shl
11609 // No shifted operands for 16-bit instructions.
11610 if (ST->isThumb() && ST->isThumb1Only())
11611 return SDValue();
11613 // Check that all the users could perform the shl themselves.
11614 for (auto U : N->uses()) {
11615 switch(U->getOpcode()) {
11616 default:
11617 return SDValue();
11618 case ISD::SUB:
11619 case ISD::ADD:
11620 case ISD::AND:
11621 case ISD::OR:
11622 case ISD::XOR:
11623 case ISD::SETCC:
11624 case ARMISD::CMP:
11625 // Check that the user isn't already using a constant because there
11626 // aren't any instructions that support an immediate operand and a
11627 // shifted operand.
11628 if (isa<ConstantSDNode>(U->getOperand(0)) ||
11629 isa<ConstantSDNode>(U->getOperand(1)))
11630 return SDValue();
11632 // Check that it's not already using a shift.
11633 if (U->getOperand(0).getOpcode() == ISD::SHL ||
11634 U->getOperand(1).getOpcode() == ISD::SHL)
11635 return SDValue();
11636 break;
11640 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
11641 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
11642 return SDValue();
11644 if (N->getOperand(0).getOpcode() != ISD::SHL)
11645 return SDValue();
11647 SDValue SHL = N->getOperand(0);
11649 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
11650 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
11651 if (!C1ShlC2 || !C2)
11652 return SDValue();
11654 APInt C2Int = C2->getAPIntValue();
11655 APInt C1Int = C1ShlC2->getAPIntValue();
11657 // Check that performing a lshr will not lose any information.
11658 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
11659 C2Int.getBitWidth() - C2->getZExtValue());
11660 if ((C1Int & Mask) != C1Int)
11661 return SDValue();
11663 // Shift the first constant.
11664 C1Int.lshrInPlace(C2Int);
11666 // The immediates are encoded as an 8-bit value that can be rotated.
11667 auto LargeImm = [](const APInt &Imm) {
11668 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
11669 return Imm.getBitWidth() - Zeros > 8;
11672 if (LargeImm(C1Int) || LargeImm(C2Int))
11673 return SDValue();
11675 SelectionDAG &DAG = DCI.DAG;
11676 SDLoc dl(N);
11677 SDValue X = SHL.getOperand(0);
11678 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
11679 DAG.getConstant(C1Int, dl, MVT::i32));
11680 // Shift left to compensate for the lshr of C1Int.
11681 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
11683 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
11684 SHL.dump(); N->dump());
11685 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
11686 return Res;
11690 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
11692 static SDValue PerformADDCombine(SDNode *N,
11693 TargetLowering::DAGCombinerInfo &DCI,
11694 const ARMSubtarget *Subtarget) {
11695 SDValue N0 = N->getOperand(0);
11696 SDValue N1 = N->getOperand(1);
11698 // Only works one way, because it needs an immediate operand.
11699 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11700 return Result;
11702 // First try with the default operand order.
11703 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
11704 return Result;
11706 // If that didn't work, try again with the operands commuted.
11707 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
11710 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
11712 static SDValue PerformSUBCombine(SDNode *N,
11713 TargetLowering::DAGCombinerInfo &DCI) {
11714 SDValue N0 = N->getOperand(0);
11715 SDValue N1 = N->getOperand(1);
11717 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
11718 if (N1.getNode()->hasOneUse())
11719 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
11720 return Result;
11722 return SDValue();
11725 /// PerformVMULCombine
11726 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
11727 /// special multiplier accumulator forwarding.
11728 /// vmul d3, d0, d2
11729 /// vmla d3, d1, d2
11730 /// is faster than
11731 /// vadd d3, d0, d1
11732 /// vmul d3, d3, d2
11733 // However, for (A + B) * (A + B),
11734 // vadd d2, d0, d1
11735 // vmul d3, d0, d2
11736 // vmla d3, d1, d2
11737 // is slower than
11738 // vadd d2, d0, d1
11739 // vmul d3, d2, d2
11740 static SDValue PerformVMULCombine(SDNode *N,
11741 TargetLowering::DAGCombinerInfo &DCI,
11742 const ARMSubtarget *Subtarget) {
11743 if (!Subtarget->hasVMLxForwarding())
11744 return SDValue();
11746 SelectionDAG &DAG = DCI.DAG;
11747 SDValue N0 = N->getOperand(0);
11748 SDValue N1 = N->getOperand(1);
11749 unsigned Opcode = N0.getOpcode();
11750 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11751 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
11752 Opcode = N1.getOpcode();
11753 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11754 Opcode != ISD::FADD && Opcode != ISD::FSUB)
11755 return SDValue();
11756 std::swap(N0, N1);
11759 if (N0 == N1)
11760 return SDValue();
11762 EVT VT = N->getValueType(0);
11763 SDLoc DL(N);
11764 SDValue N00 = N0->getOperand(0);
11765 SDValue N01 = N0->getOperand(1);
11766 return DAG.getNode(Opcode, DL, VT,
11767 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
11768 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
11771 static SDValue PerformMULCombine(SDNode *N,
11772 TargetLowering::DAGCombinerInfo &DCI,
11773 const ARMSubtarget *Subtarget) {
11774 SelectionDAG &DAG = DCI.DAG;
11776 if (Subtarget->isThumb1Only())
11777 return SDValue();
11779 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11780 return SDValue();
11782 EVT VT = N->getValueType(0);
11783 if (VT.is64BitVector() || VT.is128BitVector())
11784 return PerformVMULCombine(N, DCI, Subtarget);
11785 if (VT != MVT::i32)
11786 return SDValue();
11788 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11789 if (!C)
11790 return SDValue();
11792 int64_t MulAmt = C->getSExtValue();
11793 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
11795 ShiftAmt = ShiftAmt & (32 - 1);
11796 SDValue V = N->getOperand(0);
11797 SDLoc DL(N);
11799 SDValue Res;
11800 MulAmt >>= ShiftAmt;
11802 if (MulAmt >= 0) {
11803 if (isPowerOf2_32(MulAmt - 1)) {
11804 // (mul x, 2^N + 1) => (add (shl x, N), x)
11805 Res = DAG.getNode(ISD::ADD, DL, VT,
11807 DAG.getNode(ISD::SHL, DL, VT,
11809 DAG.getConstant(Log2_32(MulAmt - 1), DL,
11810 MVT::i32)));
11811 } else if (isPowerOf2_32(MulAmt + 1)) {
11812 // (mul x, 2^N - 1) => (sub (shl x, N), x)
11813 Res = DAG.getNode(ISD::SUB, DL, VT,
11814 DAG.getNode(ISD::SHL, DL, VT,
11816 DAG.getConstant(Log2_32(MulAmt + 1), DL,
11817 MVT::i32)),
11819 } else
11820 return SDValue();
11821 } else {
11822 uint64_t MulAmtAbs = -MulAmt;
11823 if (isPowerOf2_32(MulAmtAbs + 1)) {
11824 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
11825 Res = DAG.getNode(ISD::SUB, DL, VT,
11827 DAG.getNode(ISD::SHL, DL, VT,
11829 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
11830 MVT::i32)));
11831 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
11832 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
11833 Res = DAG.getNode(ISD::ADD, DL, VT,
11835 DAG.getNode(ISD::SHL, DL, VT,
11837 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
11838 MVT::i32)));
11839 Res = DAG.getNode(ISD::SUB, DL, VT,
11840 DAG.getConstant(0, DL, MVT::i32), Res);
11841 } else
11842 return SDValue();
11845 if (ShiftAmt != 0)
11846 Res = DAG.getNode(ISD::SHL, DL, VT,
11847 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
11849 // Do not add new nodes to DAG combiner worklist.
11850 DCI.CombineTo(N, Res, false);
11851 return SDValue();
11854 static SDValue CombineANDShift(SDNode *N,
11855 TargetLowering::DAGCombinerInfo &DCI,
11856 const ARMSubtarget *Subtarget) {
11857 // Allow DAGCombine to pattern-match before we touch the canonical form.
11858 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11859 return SDValue();
11861 if (N->getValueType(0) != MVT::i32)
11862 return SDValue();
11864 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11865 if (!N1C)
11866 return SDValue();
11868 uint32_t C1 = (uint32_t)N1C->getZExtValue();
11869 // Don't transform uxtb/uxth.
11870 if (C1 == 255 || C1 == 65535)
11871 return SDValue();
11873 SDNode *N0 = N->getOperand(0).getNode();
11874 if (!N0->hasOneUse())
11875 return SDValue();
11877 if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
11878 return SDValue();
11880 bool LeftShift = N0->getOpcode() == ISD::SHL;
11882 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11883 if (!N01C)
11884 return SDValue();
11886 uint32_t C2 = (uint32_t)N01C->getZExtValue();
11887 if (!C2 || C2 >= 32)
11888 return SDValue();
11890 // Clear irrelevant bits in the mask.
11891 if (LeftShift)
11892 C1 &= (-1U << C2);
11893 else
11894 C1 &= (-1U >> C2);
11896 SelectionDAG &DAG = DCI.DAG;
11897 SDLoc DL(N);
11899 // We have a pattern of the form "(and (shl x, c2) c1)" or
11900 // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
11901 // transform to a pair of shifts, to save materializing c1.
11903 // First pattern: right shift, then mask off leading bits.
11904 // FIXME: Use demanded bits?
11905 if (!LeftShift && isMask_32(C1)) {
11906 uint32_t C3 = countLeadingZeros(C1);
11907 if (C2 < C3) {
11908 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11909 DAG.getConstant(C3 - C2, DL, MVT::i32));
11910 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11911 DAG.getConstant(C3, DL, MVT::i32));
11915 // First pattern, reversed: left shift, then mask off trailing bits.
11916 if (LeftShift && isMask_32(~C1)) {
11917 uint32_t C3 = countTrailingZeros(C1);
11918 if (C2 < C3) {
11919 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11920 DAG.getConstant(C3 - C2, DL, MVT::i32));
11921 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11922 DAG.getConstant(C3, DL, MVT::i32));
11926 // Second pattern: left shift, then mask off leading bits.
11927 // FIXME: Use demanded bits?
11928 if (LeftShift && isShiftedMask_32(C1)) {
11929 uint32_t Trailing = countTrailingZeros(C1);
11930 uint32_t C3 = countLeadingZeros(C1);
11931 if (Trailing == C2 && C2 + C3 < 32) {
11932 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
11933 DAG.getConstant(C2 + C3, DL, MVT::i32));
11934 return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
11935 DAG.getConstant(C3, DL, MVT::i32));
11939 // Second pattern, reversed: right shift, then mask off trailing bits.
11940 // FIXME: Handle other patterns of known/demanded bits.
11941 if (!LeftShift && isShiftedMask_32(C1)) {
11942 uint32_t Leading = countLeadingZeros(C1);
11943 uint32_t C3 = countTrailingZeros(C1);
11944 if (Leading == C2 && C2 + C3 < 32) {
11945 SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
11946 DAG.getConstant(C2 + C3, DL, MVT::i32));
11947 return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
11948 DAG.getConstant(C3, DL, MVT::i32));
11952 // FIXME: Transform "(and (shl x, c2) c1)" ->
11953 // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
11954 // c1.
11955 return SDValue();
11958 static SDValue PerformANDCombine(SDNode *N,
11959 TargetLowering::DAGCombinerInfo &DCI,
11960 const ARMSubtarget *Subtarget) {
11961 // Attempt to use immediate-form VBIC
11962 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11963 SDLoc dl(N);
11964 EVT VT = N->getValueType(0);
11965 SelectionDAG &DAG = DCI.DAG;
11967 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11968 return SDValue();
11970 APInt SplatBits, SplatUndef;
11971 unsigned SplatBitSize;
11972 bool HasAnyUndefs;
11973 if (BVN && Subtarget->hasNEON() &&
11974 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11975 if (SplatBitSize <= 64) {
11976 EVT VbicVT;
11977 SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
11978 SplatUndef.getZExtValue(), SplatBitSize,
11979 DAG, dl, VbicVT, VT.is128BitVector(),
11980 OtherModImm);
11981 if (Val.getNode()) {
11982 SDValue Input =
11983 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
11984 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
11985 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
11990 if (!Subtarget->isThumb1Only()) {
11991 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
11992 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
11993 return Result;
11995 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11996 return Result;
11999 if (Subtarget->isThumb1Only())
12000 if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
12001 return Result;
12003 return SDValue();
12006 // Try combining OR nodes to SMULWB, SMULWT.
12007 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
12008 TargetLowering::DAGCombinerInfo &DCI,
12009 const ARMSubtarget *Subtarget) {
12010 if (!Subtarget->hasV6Ops() ||
12011 (Subtarget->isThumb() &&
12012 (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
12013 return SDValue();
12015 SDValue SRL = OR->getOperand(0);
12016 SDValue SHL = OR->getOperand(1);
12018 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
12019 SRL = OR->getOperand(1);
12020 SHL = OR->getOperand(0);
12022 if (!isSRL16(SRL) || !isSHL16(SHL))
12023 return SDValue();
12025 // The first operands to the shifts need to be the two results from the
12026 // same smul_lohi node.
12027 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
12028 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
12029 return SDValue();
12031 SDNode *SMULLOHI = SRL.getOperand(0).getNode();
12032 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
12033 SHL.getOperand(0) != SDValue(SMULLOHI, 1))
12034 return SDValue();
12036 // Now we have:
12037 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
12038 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
12039 // For SMUWB the 16-bit value will signed extended somehow.
12040 // For SMULWT only the SRA is required.
12041 // Check both sides of SMUL_LOHI
12042 SDValue OpS16 = SMULLOHI->getOperand(0);
12043 SDValue OpS32 = SMULLOHI->getOperand(1);
12045 SelectionDAG &DAG = DCI.DAG;
12046 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
12047 OpS16 = OpS32;
12048 OpS32 = SMULLOHI->getOperand(0);
12051 SDLoc dl(OR);
12052 unsigned Opcode = 0;
12053 if (isS16(OpS16, DAG))
12054 Opcode = ARMISD::SMULWB;
12055 else if (isSRA16(OpS16)) {
12056 Opcode = ARMISD::SMULWT;
12057 OpS16 = OpS16->getOperand(0);
12059 else
12060 return SDValue();
12062 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
12063 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
12064 return SDValue(OR, 0);
12067 static SDValue PerformORCombineToBFI(SDNode *N,
12068 TargetLowering::DAGCombinerInfo &DCI,
12069 const ARMSubtarget *Subtarget) {
12070 // BFI is only available on V6T2+
12071 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
12072 return SDValue();
12074 EVT VT = N->getValueType(0);
12075 SDValue N0 = N->getOperand(0);
12076 SDValue N1 = N->getOperand(1);
12077 SelectionDAG &DAG = DCI.DAG;
12078 SDLoc DL(N);
12079 // 1) or (and A, mask), val => ARMbfi A, val, mask
12080 // iff (val & mask) == val
12082 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
12083 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
12084 // && mask == ~mask2
12085 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
12086 // && ~mask == mask2
12087 // (i.e., copy a bitfield value into another bitfield of the same width)
12089 if (VT != MVT::i32)
12090 return SDValue();
12092 SDValue N00 = N0.getOperand(0);
12094 // The value and the mask need to be constants so we can verify this is
12095 // actually a bitfield set. If the mask is 0xffff, we can do better
12096 // via a movt instruction, so don't use BFI in that case.
12097 SDValue MaskOp = N0.getOperand(1);
12098 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
12099 if (!MaskC)
12100 return SDValue();
12101 unsigned Mask = MaskC->getZExtValue();
12102 if (Mask == 0xffff)
12103 return SDValue();
12104 SDValue Res;
12105 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
12106 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12107 if (N1C) {
12108 unsigned Val = N1C->getZExtValue();
12109 if ((Val & ~Mask) != Val)
12110 return SDValue();
12112 if (ARM::isBitFieldInvertedMask(Mask)) {
12113 Val >>= countTrailingZeros(~Mask);
12115 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
12116 DAG.getConstant(Val, DL, MVT::i32),
12117 DAG.getConstant(Mask, DL, MVT::i32));
12119 DCI.CombineTo(N, Res, false);
12120 // Return value from the original node to inform the combiner than N is
12121 // now dead.
12122 return SDValue(N, 0);
12124 } else if (N1.getOpcode() == ISD::AND) {
12125 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
12126 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12127 if (!N11C)
12128 return SDValue();
12129 unsigned Mask2 = N11C->getZExtValue();
12131 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
12132 // as is to match.
12133 if (ARM::isBitFieldInvertedMask(Mask) &&
12134 (Mask == ~Mask2)) {
12135 // The pack halfword instruction works better for masks that fit it,
12136 // so use that when it's available.
12137 if (Subtarget->hasDSP() &&
12138 (Mask == 0xffff || Mask == 0xffff0000))
12139 return SDValue();
12140 // 2a
12141 unsigned amt = countTrailingZeros(Mask2);
12142 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
12143 DAG.getConstant(amt, DL, MVT::i32));
12144 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
12145 DAG.getConstant(Mask, DL, MVT::i32));
12146 DCI.CombineTo(N, Res, false);
12147 // Return value from the original node to inform the combiner than N is
12148 // now dead.
12149 return SDValue(N, 0);
12150 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
12151 (~Mask == Mask2)) {
12152 // The pack halfword instruction works better for masks that fit it,
12153 // so use that when it's available.
12154 if (Subtarget->hasDSP() &&
12155 (Mask2 == 0xffff || Mask2 == 0xffff0000))
12156 return SDValue();
12157 // 2b
12158 unsigned lsb = countTrailingZeros(Mask);
12159 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
12160 DAG.getConstant(lsb, DL, MVT::i32));
12161 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
12162 DAG.getConstant(Mask2, DL, MVT::i32));
12163 DCI.CombineTo(N, Res, false);
12164 // Return value from the original node to inform the combiner than N is
12165 // now dead.
12166 return SDValue(N, 0);
12170 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
12171 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
12172 ARM::isBitFieldInvertedMask(~Mask)) {
12173 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
12174 // where lsb(mask) == #shamt and masked bits of B are known zero.
12175 SDValue ShAmt = N00.getOperand(1);
12176 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
12177 unsigned LSB = countTrailingZeros(Mask);
12178 if (ShAmtC != LSB)
12179 return SDValue();
12181 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
12182 DAG.getConstant(~Mask, DL, MVT::i32));
12184 DCI.CombineTo(N, Res, false);
12185 // Return value from the original node to inform the combiner than N is
12186 // now dead.
12187 return SDValue(N, 0);
12190 return SDValue();
12193 static bool isValidMVECond(unsigned CC, bool IsFloat) {
12194 switch (CC) {
12195 case ARMCC::EQ:
12196 case ARMCC::NE:
12197 case ARMCC::LE:
12198 case ARMCC::GT:
12199 case ARMCC::GE:
12200 case ARMCC::LT:
12201 return true;
12202 case ARMCC::HS:
12203 case ARMCC::HI:
12204 return !IsFloat;
12205 default:
12206 return false;
12210 static SDValue PerformORCombine_i1(SDNode *N,
12211 TargetLowering::DAGCombinerInfo &DCI,
12212 const ARMSubtarget *Subtarget) {
12213 // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
12214 // together with predicates
12215 EVT VT = N->getValueType(0);
12216 SDValue N0 = N->getOperand(0);
12217 SDValue N1 = N->getOperand(1);
12219 ARMCC::CondCodes CondCode0 = ARMCC::AL;
12220 ARMCC::CondCodes CondCode1 = ARMCC::AL;
12221 if (N0->getOpcode() == ARMISD::VCMP)
12222 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(2))
12223 ->getZExtValue();
12224 else if (N0->getOpcode() == ARMISD::VCMPZ)
12225 CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(1))
12226 ->getZExtValue();
12227 if (N1->getOpcode() == ARMISD::VCMP)
12228 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(2))
12229 ->getZExtValue();
12230 else if (N1->getOpcode() == ARMISD::VCMPZ)
12231 CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(1))
12232 ->getZExtValue();
12234 if (CondCode0 == ARMCC::AL || CondCode1 == ARMCC::AL)
12235 return SDValue();
12237 unsigned Opposite0 = ARMCC::getOppositeCondition(CondCode0);
12238 unsigned Opposite1 = ARMCC::getOppositeCondition(CondCode1);
12240 if (!isValidMVECond(Opposite0,
12241 N0->getOperand(0)->getValueType(0).isFloatingPoint()) ||
12242 !isValidMVECond(Opposite1,
12243 N1->getOperand(0)->getValueType(0).isFloatingPoint()))
12244 return SDValue();
12246 SmallVector<SDValue, 4> Ops0;
12247 Ops0.push_back(N0->getOperand(0));
12248 if (N0->getOpcode() == ARMISD::VCMP)
12249 Ops0.push_back(N0->getOperand(1));
12250 Ops0.push_back(DCI.DAG.getConstant(Opposite0, SDLoc(N0), MVT::i32));
12251 SmallVector<SDValue, 4> Ops1;
12252 Ops1.push_back(N1->getOperand(0));
12253 if (N1->getOpcode() == ARMISD::VCMP)
12254 Ops1.push_back(N1->getOperand(1));
12255 Ops1.push_back(DCI.DAG.getConstant(Opposite1, SDLoc(N1), MVT::i32));
12257 SDValue NewN0 = DCI.DAG.getNode(N0->getOpcode(), SDLoc(N0), VT, Ops0);
12258 SDValue NewN1 = DCI.DAG.getNode(N1->getOpcode(), SDLoc(N1), VT, Ops1);
12259 SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1);
12260 return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And,
12261 DCI.DAG.getAllOnesConstant(SDLoc(N), VT));
12264 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
12265 static SDValue PerformORCombine(SDNode *N,
12266 TargetLowering::DAGCombinerInfo &DCI,
12267 const ARMSubtarget *Subtarget) {
12268 // Attempt to use immediate-form VORR
12269 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12270 SDLoc dl(N);
12271 EVT VT = N->getValueType(0);
12272 SelectionDAG &DAG = DCI.DAG;
12274 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12275 return SDValue();
12277 APInt SplatBits, SplatUndef;
12278 unsigned SplatBitSize;
12279 bool HasAnyUndefs;
12280 if (BVN && Subtarget->hasNEON() &&
12281 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12282 if (SplatBitSize <= 64) {
12283 EVT VorrVT;
12284 SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
12285 SplatUndef.getZExtValue(), SplatBitSize,
12286 DAG, dl, VorrVT, VT.is128BitVector(),
12287 OtherModImm);
12288 if (Val.getNode()) {
12289 SDValue Input =
12290 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
12291 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
12292 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
12297 if (!Subtarget->isThumb1Only()) {
12298 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12299 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12300 return Result;
12301 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
12302 return Result;
12305 SDValue N0 = N->getOperand(0);
12306 SDValue N1 = N->getOperand(1);
12308 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
12309 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
12310 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12312 // The code below optimizes (or (and X, Y), Z).
12313 // The AND operand needs to have a single user to make these optimizations
12314 // profitable.
12315 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
12316 return SDValue();
12318 APInt SplatUndef;
12319 unsigned SplatBitSize;
12320 bool HasAnyUndefs;
12322 APInt SplatBits0, SplatBits1;
12323 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
12324 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
12325 // Ensure that the second operand of both ands are constants
12326 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
12327 HasAnyUndefs) && !HasAnyUndefs) {
12328 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
12329 HasAnyUndefs) && !HasAnyUndefs) {
12330 // Ensure that the bit width of the constants are the same and that
12331 // the splat arguments are logical inverses as per the pattern we
12332 // are trying to simplify.
12333 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
12334 SplatBits0 == ~SplatBits1) {
12335 // Canonicalize the vector type to make instruction selection
12336 // simpler.
12337 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
12338 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
12339 N0->getOperand(1),
12340 N0->getOperand(0),
12341 N1->getOperand(0));
12342 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12348 if (Subtarget->hasMVEIntegerOps() &&
12349 (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
12350 return PerformORCombine_i1(N, DCI, Subtarget);
12352 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
12353 // reasonable.
12354 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
12355 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
12356 return Res;
12359 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12360 return Result;
12362 return SDValue();
12365 static SDValue PerformXORCombine(SDNode *N,
12366 TargetLowering::DAGCombinerInfo &DCI,
12367 const ARMSubtarget *Subtarget) {
12368 EVT VT = N->getValueType(0);
12369 SelectionDAG &DAG = DCI.DAG;
12371 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12372 return SDValue();
12374 if (!Subtarget->isThumb1Only()) {
12375 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12376 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12377 return Result;
12379 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12380 return Result;
12383 return SDValue();
12386 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
12387 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
12388 // their position in "to" (Rd).
12389 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
12390 assert(N->getOpcode() == ARMISD::BFI);
12392 SDValue From = N->getOperand(1);
12393 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
12394 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
12396 // If the Base came from a SHR #C, we can deduce that it is really testing bit
12397 // #C in the base of the SHR.
12398 if (From->getOpcode() == ISD::SRL &&
12399 isa<ConstantSDNode>(From->getOperand(1))) {
12400 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
12401 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
12402 FromMask <<= Shift.getLimitedValue(31);
12403 From = From->getOperand(0);
12406 return From;
12409 // If A and B contain one contiguous set of bits, does A | B == A . B?
12411 // Neither A nor B must be zero.
12412 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
12413 unsigned LastActiveBitInA = A.countTrailingZeros();
12414 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
12415 return LastActiveBitInA - 1 == FirstActiveBitInB;
12418 static SDValue FindBFIToCombineWith(SDNode *N) {
12419 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
12420 // if one exists.
12421 APInt ToMask, FromMask;
12422 SDValue From = ParseBFI(N, ToMask, FromMask);
12423 SDValue To = N->getOperand(0);
12425 // Now check for a compatible BFI to merge with. We can pass through BFIs that
12426 // aren't compatible, but not if they set the same bit in their destination as
12427 // we do (or that of any BFI we're going to combine with).
12428 SDValue V = To;
12429 APInt CombinedToMask = ToMask;
12430 while (V.getOpcode() == ARMISD::BFI) {
12431 APInt NewToMask, NewFromMask;
12432 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
12433 if (NewFrom != From) {
12434 // This BFI has a different base. Keep going.
12435 CombinedToMask |= NewToMask;
12436 V = V.getOperand(0);
12437 continue;
12440 // Do the written bits conflict with any we've seen so far?
12441 if ((NewToMask & CombinedToMask).getBoolValue())
12442 // Conflicting bits - bail out because going further is unsafe.
12443 return SDValue();
12445 // Are the new bits contiguous when combined with the old bits?
12446 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
12447 BitsProperlyConcatenate(FromMask, NewFromMask))
12448 return V;
12449 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
12450 BitsProperlyConcatenate(NewFromMask, FromMask))
12451 return V;
12453 // We've seen a write to some bits, so track it.
12454 CombinedToMask |= NewToMask;
12455 // Keep going...
12456 V = V.getOperand(0);
12459 return SDValue();
12462 static SDValue PerformBFICombine(SDNode *N,
12463 TargetLowering::DAGCombinerInfo &DCI) {
12464 SDValue N1 = N->getOperand(1);
12465 if (N1.getOpcode() == ISD::AND) {
12466 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
12467 // the bits being cleared by the AND are not demanded by the BFI.
12468 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12469 if (!N11C)
12470 return SDValue();
12471 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12472 unsigned LSB = countTrailingZeros(~InvMask);
12473 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
12474 assert(Width <
12475 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
12476 "undefined behavior");
12477 unsigned Mask = (1u << Width) - 1;
12478 unsigned Mask2 = N11C->getZExtValue();
12479 if ((Mask & (~Mask2)) == 0)
12480 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
12481 N->getOperand(0), N1.getOperand(0),
12482 N->getOperand(2));
12483 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
12484 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
12485 // Keep track of any consecutive bits set that all come from the same base
12486 // value. We can combine these together into a single BFI.
12487 SDValue CombineBFI = FindBFIToCombineWith(N);
12488 if (CombineBFI == SDValue())
12489 return SDValue();
12491 // We've found a BFI.
12492 APInt ToMask1, FromMask1;
12493 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
12495 APInt ToMask2, FromMask2;
12496 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
12497 assert(From1 == From2);
12498 (void)From2;
12500 // First, unlink CombineBFI.
12501 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
12502 // Then create a new BFI, combining the two together.
12503 APInt NewFromMask = FromMask1 | FromMask2;
12504 APInt NewToMask = ToMask1 | ToMask2;
12506 EVT VT = N->getValueType(0);
12507 SDLoc dl(N);
12509 if (NewFromMask[0] == 0)
12510 From1 = DCI.DAG.getNode(
12511 ISD::SRL, dl, VT, From1,
12512 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
12513 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
12514 DCI.DAG.getConstant(~NewToMask, dl, VT));
12516 return SDValue();
12519 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
12520 /// ARMISD::VMOVRRD.
12521 static SDValue PerformVMOVRRDCombine(SDNode *N,
12522 TargetLowering::DAGCombinerInfo &DCI,
12523 const ARMSubtarget *Subtarget) {
12524 // vmovrrd(vmovdrr x, y) -> x,y
12525 SDValue InDouble = N->getOperand(0);
12526 if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
12527 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
12529 // vmovrrd(load f64) -> (load i32), (load i32)
12530 SDNode *InNode = InDouble.getNode();
12531 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
12532 InNode->getValueType(0) == MVT::f64 &&
12533 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
12534 !cast<LoadSDNode>(InNode)->isVolatile()) {
12535 // TODO: Should this be done for non-FrameIndex operands?
12536 LoadSDNode *LD = cast<LoadSDNode>(InNode);
12538 SelectionDAG &DAG = DCI.DAG;
12539 SDLoc DL(LD);
12540 SDValue BasePtr = LD->getBasePtr();
12541 SDValue NewLD1 =
12542 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
12543 LD->getAlignment(), LD->getMemOperand()->getFlags());
12545 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12546 DAG.getConstant(4, DL, MVT::i32));
12548 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
12549 LD->getPointerInfo().getWithOffset(4),
12550 std::min(4U, LD->getAlignment()),
12551 LD->getMemOperand()->getFlags());
12553 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
12554 if (DCI.DAG.getDataLayout().isBigEndian())
12555 std::swap (NewLD1, NewLD2);
12556 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
12557 return Result;
12560 return SDValue();
12563 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
12564 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
12565 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
12566 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
12567 SDValue Op0 = N->getOperand(0);
12568 SDValue Op1 = N->getOperand(1);
12569 if (Op0.getOpcode() == ISD::BITCAST)
12570 Op0 = Op0.getOperand(0);
12571 if (Op1.getOpcode() == ISD::BITCAST)
12572 Op1 = Op1.getOperand(0);
12573 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
12574 Op0.getNode() == Op1.getNode() &&
12575 Op0.getResNo() == 0 && Op1.getResNo() == 1)
12576 return DAG.getNode(ISD::BITCAST, SDLoc(N),
12577 N->getValueType(0), Op0.getOperand(0));
12578 return SDValue();
12581 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
12582 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
12583 /// i64 vector to have f64 elements, since the value can then be loaded
12584 /// directly into a VFP register.
12585 static bool hasNormalLoadOperand(SDNode *N) {
12586 unsigned NumElts = N->getValueType(0).getVectorNumElements();
12587 for (unsigned i = 0; i < NumElts; ++i) {
12588 SDNode *Elt = N->getOperand(i).getNode();
12589 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
12590 return true;
12592 return false;
12595 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
12596 /// ISD::BUILD_VECTOR.
12597 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
12598 TargetLowering::DAGCombinerInfo &DCI,
12599 const ARMSubtarget *Subtarget) {
12600 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
12601 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
12602 // into a pair of GPRs, which is fine when the value is used as a scalar,
12603 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
12604 SelectionDAG &DAG = DCI.DAG;
12605 if (N->getNumOperands() == 2)
12606 if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
12607 return RV;
12609 // Load i64 elements as f64 values so that type legalization does not split
12610 // them up into i32 values.
12611 EVT VT = N->getValueType(0);
12612 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
12613 return SDValue();
12614 SDLoc dl(N);
12615 SmallVector<SDValue, 8> Ops;
12616 unsigned NumElts = VT.getVectorNumElements();
12617 for (unsigned i = 0; i < NumElts; ++i) {
12618 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
12619 Ops.push_back(V);
12620 // Make the DAGCombiner fold the bitcast.
12621 DCI.AddToWorklist(V.getNode());
12623 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
12624 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
12625 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12628 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
12629 static SDValue
12630 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12631 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
12632 // At that time, we may have inserted bitcasts from integer to float.
12633 // If these bitcasts have survived DAGCombine, change the lowering of this
12634 // BUILD_VECTOR in something more vector friendly, i.e., that does not
12635 // force to use floating point types.
12637 // Make sure we can change the type of the vector.
12638 // This is possible iff:
12639 // 1. The vector is only used in a bitcast to a integer type. I.e.,
12640 // 1.1. Vector is used only once.
12641 // 1.2. Use is a bit convert to an integer type.
12642 // 2. The size of its operands are 32-bits (64-bits are not legal).
12643 EVT VT = N->getValueType(0);
12644 EVT EltVT = VT.getVectorElementType();
12646 // Check 1.1. and 2.
12647 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
12648 return SDValue();
12650 // By construction, the input type must be float.
12651 assert(EltVT == MVT::f32 && "Unexpected type!");
12653 // Check 1.2.
12654 SDNode *Use = *N->use_begin();
12655 if (Use->getOpcode() != ISD::BITCAST ||
12656 Use->getValueType(0).isFloatingPoint())
12657 return SDValue();
12659 // Check profitability.
12660 // Model is, if more than half of the relevant operands are bitcast from
12661 // i32, turn the build_vector into a sequence of insert_vector_elt.
12662 // Relevant operands are everything that is not statically
12663 // (i.e., at compile time) bitcasted.
12664 unsigned NumOfBitCastedElts = 0;
12665 unsigned NumElts = VT.getVectorNumElements();
12666 unsigned NumOfRelevantElts = NumElts;
12667 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
12668 SDValue Elt = N->getOperand(Idx);
12669 if (Elt->getOpcode() == ISD::BITCAST) {
12670 // Assume only bit cast to i32 will go away.
12671 if (Elt->getOperand(0).getValueType() == MVT::i32)
12672 ++NumOfBitCastedElts;
12673 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
12674 // Constants are statically casted, thus do not count them as
12675 // relevant operands.
12676 --NumOfRelevantElts;
12679 // Check if more than half of the elements require a non-free bitcast.
12680 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
12681 return SDValue();
12683 SelectionDAG &DAG = DCI.DAG;
12684 // Create the new vector type.
12685 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
12686 // Check if the type is legal.
12687 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12688 if (!TLI.isTypeLegal(VecVT))
12689 return SDValue();
12691 // Combine:
12692 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
12693 // => BITCAST INSERT_VECTOR_ELT
12694 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
12695 // (BITCAST EN), N.
12696 SDValue Vec = DAG.getUNDEF(VecVT);
12697 SDLoc dl(N);
12698 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
12699 SDValue V = N->getOperand(Idx);
12700 if (V.isUndef())
12701 continue;
12702 if (V.getOpcode() == ISD::BITCAST &&
12703 V->getOperand(0).getValueType() == MVT::i32)
12704 // Fold obvious case.
12705 V = V.getOperand(0);
12706 else {
12707 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
12708 // Make the DAGCombiner fold the bitcasts.
12709 DCI.AddToWorklist(V.getNode());
12711 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
12712 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
12714 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
12715 // Make the DAGCombiner fold the bitcasts.
12716 DCI.AddToWorklist(Vec.getNode());
12717 return Vec;
12720 static SDValue
12721 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12722 EVT VT = N->getValueType(0);
12723 SDValue Op = N->getOperand(0);
12724 SDLoc dl(N);
12726 // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
12727 if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
12728 // If the valuetypes are the same, we can remove the cast entirely.
12729 if (Op->getOperand(0).getValueType() == VT)
12730 return Op->getOperand(0);
12731 return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl,
12732 Op->getOperand(0).getValueType(), Op->getOperand(0));
12735 return SDValue();
12738 /// PerformInsertEltCombine - Target-specific dag combine xforms for
12739 /// ISD::INSERT_VECTOR_ELT.
12740 static SDValue PerformInsertEltCombine(SDNode *N,
12741 TargetLowering::DAGCombinerInfo &DCI) {
12742 // Bitcast an i64 load inserted into a vector to f64.
12743 // Otherwise, the i64 value will be legalized to a pair of i32 values.
12744 EVT VT = N->getValueType(0);
12745 SDNode *Elt = N->getOperand(1).getNode();
12746 if (VT.getVectorElementType() != MVT::i64 ||
12747 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
12748 return SDValue();
12750 SelectionDAG &DAG = DCI.DAG;
12751 SDLoc dl(N);
12752 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12753 VT.getVectorNumElements());
12754 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
12755 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
12756 // Make the DAGCombiner fold the bitcasts.
12757 DCI.AddToWorklist(Vec.getNode());
12758 DCI.AddToWorklist(V.getNode());
12759 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
12760 Vec, V, N->getOperand(2));
12761 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
12764 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
12765 /// ISD::VECTOR_SHUFFLE.
12766 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
12767 // The LLVM shufflevector instruction does not require the shuffle mask
12768 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
12769 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
12770 // operands do not match the mask length, they are extended by concatenating
12771 // them with undef vectors. That is probably the right thing for other
12772 // targets, but for NEON it is better to concatenate two double-register
12773 // size vector operands into a single quad-register size vector. Do that
12774 // transformation here:
12775 // shuffle(concat(v1, undef), concat(v2, undef)) ->
12776 // shuffle(concat(v1, v2), undef)
12777 SDValue Op0 = N->getOperand(0);
12778 SDValue Op1 = N->getOperand(1);
12779 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
12780 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
12781 Op0.getNumOperands() != 2 ||
12782 Op1.getNumOperands() != 2)
12783 return SDValue();
12784 SDValue Concat0Op1 = Op0.getOperand(1);
12785 SDValue Concat1Op1 = Op1.getOperand(1);
12786 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
12787 return SDValue();
12788 // Skip the transformation if any of the types are illegal.
12789 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12790 EVT VT = N->getValueType(0);
12791 if (!TLI.isTypeLegal(VT) ||
12792 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
12793 !TLI.isTypeLegal(Concat1Op1.getValueType()))
12794 return SDValue();
12796 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12797 Op0.getOperand(0), Op1.getOperand(0));
12798 // Translate the shuffle mask.
12799 SmallVector<int, 16> NewMask;
12800 unsigned NumElts = VT.getVectorNumElements();
12801 unsigned HalfElts = NumElts/2;
12802 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12803 for (unsigned n = 0; n < NumElts; ++n) {
12804 int MaskElt = SVN->getMaskElt(n);
12805 int NewElt = -1;
12806 if (MaskElt < (int)HalfElts)
12807 NewElt = MaskElt;
12808 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
12809 NewElt = HalfElts + MaskElt - NumElts;
12810 NewMask.push_back(NewElt);
12812 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
12813 DAG.getUNDEF(VT), NewMask);
12816 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
12817 /// NEON load/store intrinsics, and generic vector load/stores, to merge
12818 /// base address updates.
12819 /// For generic load/stores, the memory type is assumed to be a vector.
12820 /// The caller is assumed to have checked legality.
12821 static SDValue CombineBaseUpdate(SDNode *N,
12822 TargetLowering::DAGCombinerInfo &DCI) {
12823 SelectionDAG &DAG = DCI.DAG;
12824 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
12825 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
12826 const bool isStore = N->getOpcode() == ISD::STORE;
12827 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
12828 SDValue Addr = N->getOperand(AddrOpIdx);
12829 MemSDNode *MemN = cast<MemSDNode>(N);
12830 SDLoc dl(N);
12832 // Search for a use of the address operand that is an increment.
12833 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
12834 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
12835 SDNode *User = *UI;
12836 if (User->getOpcode() != ISD::ADD ||
12837 UI.getUse().getResNo() != Addr.getResNo())
12838 continue;
12840 // Check that the add is independent of the load/store. Otherwise, folding
12841 // it would create a cycle. We can avoid searching through Addr as it's a
12842 // predecessor to both.
12843 SmallPtrSet<const SDNode *, 32> Visited;
12844 SmallVector<const SDNode *, 16> Worklist;
12845 Visited.insert(Addr.getNode());
12846 Worklist.push_back(N);
12847 Worklist.push_back(User);
12848 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
12849 SDNode::hasPredecessorHelper(User, Visited, Worklist))
12850 continue;
12852 // Find the new opcode for the updating load/store.
12853 bool isLoadOp = true;
12854 bool isLaneOp = false;
12855 unsigned NewOpc = 0;
12856 unsigned NumVecs = 0;
12857 if (isIntrinsic) {
12858 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
12859 switch (IntNo) {
12860 default: llvm_unreachable("unexpected intrinsic for Neon base update");
12861 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
12862 NumVecs = 1; break;
12863 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
12864 NumVecs = 2; break;
12865 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
12866 NumVecs = 3; break;
12867 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
12868 NumVecs = 4; break;
12869 case Intrinsic::arm_neon_vld2dup:
12870 case Intrinsic::arm_neon_vld3dup:
12871 case Intrinsic::arm_neon_vld4dup:
12872 // TODO: Support updating VLDxDUP nodes. For now, we just skip
12873 // combining base updates for such intrinsics.
12874 continue;
12875 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
12876 NumVecs = 2; isLaneOp = true; break;
12877 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
12878 NumVecs = 3; isLaneOp = true; break;
12879 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
12880 NumVecs = 4; isLaneOp = true; break;
12881 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
12882 NumVecs = 1; isLoadOp = false; break;
12883 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
12884 NumVecs = 2; isLoadOp = false; break;
12885 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
12886 NumVecs = 3; isLoadOp = false; break;
12887 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
12888 NumVecs = 4; isLoadOp = false; break;
12889 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
12890 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
12891 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
12892 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
12893 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
12894 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
12896 } else {
12897 isLaneOp = true;
12898 switch (N->getOpcode()) {
12899 default: llvm_unreachable("unexpected opcode for Neon base update");
12900 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
12901 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
12902 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
12903 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
12904 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
12905 NumVecs = 1; isLaneOp = false; break;
12906 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
12907 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
12911 // Find the size of memory referenced by the load/store.
12912 EVT VecTy;
12913 if (isLoadOp) {
12914 VecTy = N->getValueType(0);
12915 } else if (isIntrinsic) {
12916 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
12917 } else {
12918 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
12919 VecTy = N->getOperand(1).getValueType();
12922 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
12923 if (isLaneOp)
12924 NumBytes /= VecTy.getVectorNumElements();
12926 // If the increment is a constant, it must match the memory ref size.
12927 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12928 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
12929 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
12930 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
12931 // separate instructions that make it harder to use a non-constant update.
12932 continue;
12935 // OK, we found an ADD we can fold into the base update.
12936 // Now, create a _UPD node, taking care of not breaking alignment.
12938 EVT AlignedVecTy = VecTy;
12939 unsigned Alignment = MemN->getAlignment();
12941 // If this is a less-than-standard-aligned load/store, change the type to
12942 // match the standard alignment.
12943 // The alignment is overlooked when selecting _UPD variants; and it's
12944 // easier to introduce bitcasts here than fix that.
12945 // There are 3 ways to get to this base-update combine:
12946 // - intrinsics: they are assumed to be properly aligned (to the standard
12947 // alignment of the memory type), so we don't need to do anything.
12948 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
12949 // intrinsics, so, likewise, there's nothing to do.
12950 // - generic load/store instructions: the alignment is specified as an
12951 // explicit operand, rather than implicitly as the standard alignment
12952 // of the memory type (like the intrisics). We need to change the
12953 // memory type to match the explicit alignment. That way, we don't
12954 // generate non-standard-aligned ARMISD::VLDx nodes.
12955 if (isa<LSBaseSDNode>(N)) {
12956 if (Alignment == 0)
12957 Alignment = 1;
12958 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
12959 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
12960 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
12961 assert(!isLaneOp && "Unexpected generic load/store lane.");
12962 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
12963 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
12965 // Don't set an explicit alignment on regular load/stores that we want
12966 // to transform to VLD/VST 1_UPD nodes.
12967 // This matches the behavior of regular load/stores, which only get an
12968 // explicit alignment if the MMO alignment is larger than the standard
12969 // alignment of the memory type.
12970 // Intrinsics, however, always get an explicit alignment, set to the
12971 // alignment of the MMO.
12972 Alignment = 1;
12975 // Create the new updating load/store node.
12976 // First, create an SDVTList for the new updating node's results.
12977 EVT Tys[6];
12978 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
12979 unsigned n;
12980 for (n = 0; n < NumResultVecs; ++n)
12981 Tys[n] = AlignedVecTy;
12982 Tys[n++] = MVT::i32;
12983 Tys[n] = MVT::Other;
12984 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
12986 // Then, gather the new node's operands.
12987 SmallVector<SDValue, 8> Ops;
12988 Ops.push_back(N->getOperand(0)); // incoming chain
12989 Ops.push_back(N->getOperand(AddrOpIdx));
12990 Ops.push_back(Inc);
12992 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
12993 // Try to match the intrinsic's signature
12994 Ops.push_back(StN->getValue());
12995 } else {
12996 // Loads (and of course intrinsics) match the intrinsics' signature,
12997 // so just add all but the alignment operand.
12998 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
12999 Ops.push_back(N->getOperand(i));
13002 // For all node types, the alignment operand is always the last one.
13003 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
13005 // If this is a non-standard-aligned STORE, the penultimate operand is the
13006 // stored value. Bitcast it to the aligned type.
13007 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
13008 SDValue &StVal = Ops[Ops.size()-2];
13009 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
13012 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
13013 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
13014 MemN->getMemOperand());
13016 // Update the uses.
13017 SmallVector<SDValue, 5> NewResults;
13018 for (unsigned i = 0; i < NumResultVecs; ++i)
13019 NewResults.push_back(SDValue(UpdN.getNode(), i));
13021 // If this is an non-standard-aligned LOAD, the first result is the loaded
13022 // value. Bitcast it to the expected result type.
13023 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
13024 SDValue &LdVal = NewResults[0];
13025 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
13028 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
13029 DCI.CombineTo(N, NewResults);
13030 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
13032 break;
13034 return SDValue();
13037 static SDValue PerformVLDCombine(SDNode *N,
13038 TargetLowering::DAGCombinerInfo &DCI) {
13039 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13040 return SDValue();
13042 return CombineBaseUpdate(N, DCI);
13045 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
13046 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
13047 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
13048 /// return true.
13049 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13050 SelectionDAG &DAG = DCI.DAG;
13051 EVT VT = N->getValueType(0);
13052 // vldN-dup instructions only support 64-bit vectors for N > 1.
13053 if (!VT.is64BitVector())
13054 return false;
13056 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
13057 SDNode *VLD = N->getOperand(0).getNode();
13058 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
13059 return false;
13060 unsigned NumVecs = 0;
13061 unsigned NewOpc = 0;
13062 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
13063 if (IntNo == Intrinsic::arm_neon_vld2lane) {
13064 NumVecs = 2;
13065 NewOpc = ARMISD::VLD2DUP;
13066 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
13067 NumVecs = 3;
13068 NewOpc = ARMISD::VLD3DUP;
13069 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
13070 NumVecs = 4;
13071 NewOpc = ARMISD::VLD4DUP;
13072 } else {
13073 return false;
13076 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
13077 // numbers match the load.
13078 unsigned VLDLaneNo =
13079 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
13080 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
13081 UI != UE; ++UI) {
13082 // Ignore uses of the chain result.
13083 if (UI.getUse().getResNo() == NumVecs)
13084 continue;
13085 SDNode *User = *UI;
13086 if (User->getOpcode() != ARMISD::VDUPLANE ||
13087 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
13088 return false;
13091 // Create the vldN-dup node.
13092 EVT Tys[5];
13093 unsigned n;
13094 for (n = 0; n < NumVecs; ++n)
13095 Tys[n] = VT;
13096 Tys[n] = MVT::Other;
13097 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
13098 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
13099 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
13100 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
13101 Ops, VLDMemInt->getMemoryVT(),
13102 VLDMemInt->getMemOperand());
13104 // Update the uses.
13105 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
13106 UI != UE; ++UI) {
13107 unsigned ResNo = UI.getUse().getResNo();
13108 // Ignore uses of the chain result.
13109 if (ResNo == NumVecs)
13110 continue;
13111 SDNode *User = *UI;
13112 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
13115 // Now the vldN-lane intrinsic is dead except for its chain result.
13116 // Update uses of the chain.
13117 std::vector<SDValue> VLDDupResults;
13118 for (unsigned n = 0; n < NumVecs; ++n)
13119 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
13120 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
13121 DCI.CombineTo(VLD, VLDDupResults);
13123 return true;
13126 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
13127 /// ARMISD::VDUPLANE.
13128 static SDValue PerformVDUPLANECombine(SDNode *N,
13129 TargetLowering::DAGCombinerInfo &DCI) {
13130 SDValue Op = N->getOperand(0);
13132 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
13133 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
13134 if (CombineVLDDUP(N, DCI))
13135 return SDValue(N, 0);
13137 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
13138 // redundant. Ignore bit_converts for now; element sizes are checked below.
13139 while (Op.getOpcode() == ISD::BITCAST)
13140 Op = Op.getOperand(0);
13141 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
13142 return SDValue();
13144 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
13145 unsigned EltSize = Op.getScalarValueSizeInBits();
13146 // The canonical VMOV for a zero vector uses a 32-bit element size.
13147 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13148 unsigned EltBits;
13149 if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
13150 EltSize = 8;
13151 EVT VT = N->getValueType(0);
13152 if (EltSize > VT.getScalarSizeInBits())
13153 return SDValue();
13155 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
13158 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
13159 static SDValue PerformVDUPCombine(SDNode *N,
13160 TargetLowering::DAGCombinerInfo &DCI,
13161 const ARMSubtarget *Subtarget) {
13162 SelectionDAG &DAG = DCI.DAG;
13163 SDValue Op = N->getOperand(0);
13165 if (!Subtarget->hasNEON())
13166 return SDValue();
13168 // Match VDUP(LOAD) -> VLD1DUP.
13169 // We match this pattern here rather than waiting for isel because the
13170 // transform is only legal for unindexed loads.
13171 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
13172 if (LD && Op.hasOneUse() && LD->isUnindexed() &&
13173 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
13174 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
13175 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
13176 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
13177 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
13178 Ops, LD->getMemoryVT(),
13179 LD->getMemOperand());
13180 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
13181 return VLDDup;
13184 return SDValue();
13187 static SDValue PerformLOADCombine(SDNode *N,
13188 TargetLowering::DAGCombinerInfo &DCI) {
13189 EVT VT = N->getValueType(0);
13191 // If this is a legal vector load, try to combine it into a VLD1_UPD.
13192 if (ISD::isNormalLoad(N) && VT.isVector() &&
13193 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13194 return CombineBaseUpdate(N, DCI);
13196 return SDValue();
13199 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
13200 // pack all of the elements in one place. Next, store to memory in fewer
13201 // chunks.
13202 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St,
13203 SelectionDAG &DAG) {
13204 SDValue StVal = St->getValue();
13205 EVT VT = StVal.getValueType();
13206 if (!St->isTruncatingStore() || !VT.isVector())
13207 return SDValue();
13208 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13209 EVT StVT = St->getMemoryVT();
13210 unsigned NumElems = VT.getVectorNumElements();
13211 assert(StVT != VT && "Cannot truncate to the same type");
13212 unsigned FromEltSz = VT.getScalarSizeInBits();
13213 unsigned ToEltSz = StVT.getScalarSizeInBits();
13215 // From, To sizes and ElemCount must be pow of two
13216 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
13217 return SDValue();
13219 // We are going to use the original vector elt for storing.
13220 // Accumulated smaller vector elements must be a multiple of the store size.
13221 if (0 != (NumElems * FromEltSz) % ToEltSz)
13222 return SDValue();
13224 unsigned SizeRatio = FromEltSz / ToEltSz;
13225 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
13227 // Create a type on which we perform the shuffle.
13228 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
13229 NumElems * SizeRatio);
13230 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13232 SDLoc DL(St);
13233 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
13234 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13235 for (unsigned i = 0; i < NumElems; ++i)
13236 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
13237 : i * SizeRatio;
13239 // Can't shuffle using an illegal type.
13240 if (!TLI.isTypeLegal(WideVecVT))
13241 return SDValue();
13243 SDValue Shuff = DAG.getVectorShuffle(
13244 WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
13245 // At this point all of the data is stored at the bottom of the
13246 // register. We now need to save it to mem.
13248 // Find the largest store unit
13249 MVT StoreType = MVT::i8;
13250 for (MVT Tp : MVT::integer_valuetypes()) {
13251 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
13252 StoreType = Tp;
13254 // Didn't find a legal store type.
13255 if (!TLI.isTypeLegal(StoreType))
13256 return SDValue();
13258 // Bitcast the original vector into a vector of store-size units
13259 EVT StoreVecVT =
13260 EVT::getVectorVT(*DAG.getContext(), StoreType,
13261 VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
13262 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13263 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
13264 SmallVector<SDValue, 8> Chains;
13265 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
13266 TLI.getPointerTy(DAG.getDataLayout()));
13267 SDValue BasePtr = St->getBasePtr();
13269 // Perform one or more big stores into memory.
13270 unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
13271 for (unsigned I = 0; I < E; I++) {
13272 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
13273 ShuffWide, DAG.getIntPtrConstant(I, DL));
13274 SDValue Ch =
13275 DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
13276 St->getAlignment(), St->getMemOperand()->getFlags());
13277 BasePtr =
13278 DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
13279 Chains.push_back(Ch);
13281 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
13284 // Try taking a single vector store from an truncate (which would otherwise turn
13285 // into an expensive buildvector) and splitting it into a series of narrowing
13286 // stores.
13287 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St,
13288 SelectionDAG &DAG) {
13289 if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
13290 return SDValue();
13291 SDValue Trunc = St->getValue();
13292 if (Trunc->getOpcode() != ISD::TRUNCATE)
13293 return SDValue();
13294 EVT FromVT = Trunc->getOperand(0).getValueType();
13295 EVT ToVT = Trunc.getValueType();
13296 if (!ToVT.isVector())
13297 return SDValue();
13298 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
13299 EVT ToEltVT = ToVT.getVectorElementType();
13300 EVT FromEltVT = FromVT.getVectorElementType();
13302 unsigned NumElements = 0;
13303 if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8))
13304 NumElements = 4;
13305 if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8)
13306 NumElements = 8;
13307 if (NumElements == 0 || FromVT.getVectorNumElements() == NumElements ||
13308 FromVT.getVectorNumElements() % NumElements != 0)
13309 return SDValue();
13311 SDLoc DL(St);
13312 // Details about the old store
13313 SDValue Ch = St->getChain();
13314 SDValue BasePtr = St->getBasePtr();
13315 unsigned Alignment = St->getOriginalAlignment();
13316 MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
13317 AAMDNodes AAInfo = St->getAAInfo();
13319 EVT NewFromVT = EVT::getVectorVT(*DAG.getContext(), FromEltVT, NumElements);
13320 EVT NewToVT = EVT::getVectorVT(*DAG.getContext(), ToEltVT, NumElements);
13322 SmallVector<SDValue, 4> Stores;
13323 for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
13324 unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
13325 SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset);
13327 SDValue Extract =
13328 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
13329 DAG.getConstant(i * NumElements, DL, MVT::i32));
13330 SDValue Store = DAG.getTruncStore(
13331 Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
13332 NewToVT, Alignment, MMOFlags, AAInfo);
13333 Stores.push_back(Store);
13335 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
13338 /// PerformSTORECombine - Target-specific dag combine xforms for
13339 /// ISD::STORE.
13340 static SDValue PerformSTORECombine(SDNode *N,
13341 TargetLowering::DAGCombinerInfo &DCI,
13342 const ARMSubtarget *Subtarget) {
13343 StoreSDNode *St = cast<StoreSDNode>(N);
13344 if (St->isVolatile())
13345 return SDValue();
13346 SDValue StVal = St->getValue();
13347 EVT VT = StVal.getValueType();
13349 if (Subtarget->hasNEON())
13350 if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG))
13351 return Store;
13353 if (Subtarget->hasMVEIntegerOps())
13354 if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
13355 return NewToken;
13357 if (!ISD::isNormalStore(St))
13358 return SDValue();
13360 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
13361 // ARM stores of arguments in the same cache line.
13362 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
13363 StVal.getNode()->hasOneUse()) {
13364 SelectionDAG &DAG = DCI.DAG;
13365 bool isBigEndian = DAG.getDataLayout().isBigEndian();
13366 SDLoc DL(St);
13367 SDValue BasePtr = St->getBasePtr();
13368 SDValue NewST1 = DAG.getStore(
13369 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
13370 BasePtr, St->getPointerInfo(), St->getAlignment(),
13371 St->getMemOperand()->getFlags());
13373 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
13374 DAG.getConstant(4, DL, MVT::i32));
13375 return DAG.getStore(NewST1.getValue(0), DL,
13376 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
13377 OffsetPtr, St->getPointerInfo(),
13378 std::min(4U, St->getAlignment() / 2),
13379 St->getMemOperand()->getFlags());
13382 if (StVal.getValueType() == MVT::i64 &&
13383 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13385 // Bitcast an i64 store extracted from a vector to f64.
13386 // Otherwise, the i64 value will be legalized to a pair of i32 values.
13387 SelectionDAG &DAG = DCI.DAG;
13388 SDLoc dl(StVal);
13389 SDValue IntVec = StVal.getOperand(0);
13390 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
13391 IntVec.getValueType().getVectorNumElements());
13392 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
13393 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13394 Vec, StVal.getOperand(1));
13395 dl = SDLoc(N);
13396 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
13397 // Make the DAGCombiner fold the bitcasts.
13398 DCI.AddToWorklist(Vec.getNode());
13399 DCI.AddToWorklist(ExtElt.getNode());
13400 DCI.AddToWorklist(V.getNode());
13401 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
13402 St->getPointerInfo(), St->getAlignment(),
13403 St->getMemOperand()->getFlags(), St->getAAInfo());
13406 // If this is a legal vector store, try to combine it into a VST1_UPD.
13407 if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
13408 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13409 return CombineBaseUpdate(N, DCI);
13411 return SDValue();
13414 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
13415 /// can replace combinations of VMUL and VCVT (floating-point to integer)
13416 /// when the VMUL has a constant operand that is a power of 2.
13418 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13419 /// vmul.f32 d16, d17, d16
13420 /// vcvt.s32.f32 d16, d16
13421 /// becomes:
13422 /// vcvt.s32.f32 d16, d16, #3
13423 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
13424 const ARMSubtarget *Subtarget) {
13425 if (!Subtarget->hasNEON())
13426 return SDValue();
13428 SDValue Op = N->getOperand(0);
13429 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
13430 Op.getOpcode() != ISD::FMUL)
13431 return SDValue();
13433 SDValue ConstVec = Op->getOperand(1);
13434 if (!isa<BuildVectorSDNode>(ConstVec))
13435 return SDValue();
13437 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
13438 uint32_t FloatBits = FloatTy.getSizeInBits();
13439 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
13440 uint32_t IntBits = IntTy.getSizeInBits();
13441 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13442 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13443 // These instructions only exist converting from f32 to i32. We can handle
13444 // smaller integers by generating an extra truncate, but larger ones would
13445 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13446 // these intructions only support v2i32/v4i32 types.
13447 return SDValue();
13450 BitVector UndefElements;
13451 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13452 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13453 if (C == -1 || C == 0 || C > 32)
13454 return SDValue();
13456 SDLoc dl(N);
13457 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
13458 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
13459 Intrinsic::arm_neon_vcvtfp2fxu;
13460 SDValue FixConv = DAG.getNode(
13461 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13462 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
13463 DAG.getConstant(C, dl, MVT::i32));
13465 if (IntBits < FloatBits)
13466 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
13468 return FixConv;
13471 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
13472 /// can replace combinations of VCVT (integer to floating-point) and VDIV
13473 /// when the VDIV has a constant operand that is a power of 2.
13475 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13476 /// vcvt.f32.s32 d16, d16
13477 /// vdiv.f32 d16, d17, d16
13478 /// becomes:
13479 /// vcvt.f32.s32 d16, d16, #3
13480 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
13481 const ARMSubtarget *Subtarget) {
13482 if (!Subtarget->hasNEON())
13483 return SDValue();
13485 SDValue Op = N->getOperand(0);
13486 unsigned OpOpcode = Op.getNode()->getOpcode();
13487 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
13488 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
13489 return SDValue();
13491 SDValue ConstVec = N->getOperand(1);
13492 if (!isa<BuildVectorSDNode>(ConstVec))
13493 return SDValue();
13495 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
13496 uint32_t FloatBits = FloatTy.getSizeInBits();
13497 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
13498 uint32_t IntBits = IntTy.getSizeInBits();
13499 unsigned NumLanes = Op.getValueType().getVectorNumElements();
13500 if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13501 // These instructions only exist converting from i32 to f32. We can handle
13502 // smaller integers by generating an extra extend, but larger ones would
13503 // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13504 // these intructions only support v2i32/v4i32 types.
13505 return SDValue();
13508 BitVector UndefElements;
13509 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13510 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13511 if (C == -1 || C == 0 || C > 32)
13512 return SDValue();
13514 SDLoc dl(N);
13515 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
13516 SDValue ConvInput = Op.getOperand(0);
13517 if (IntBits < FloatBits)
13518 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
13519 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13520 ConvInput);
13522 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
13523 Intrinsic::arm_neon_vcvtfxu2fp;
13524 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
13525 Op.getValueType(),
13526 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
13527 ConvInput, DAG.getConstant(C, dl, MVT::i32));
13530 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
13531 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
13532 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13533 switch (IntNo) {
13534 default:
13535 // Don't do anything for most intrinsics.
13536 break;
13538 // Vector shifts: check for immediate versions and lower them.
13539 // Note: This is done during DAG combining instead of DAG legalizing because
13540 // the build_vectors for 64-bit vector element shift counts are generally
13541 // not legal, and it is hard to see their values after they get legalized to
13542 // loads from a constant pool.
13543 case Intrinsic::arm_neon_vshifts:
13544 case Intrinsic::arm_neon_vshiftu:
13545 case Intrinsic::arm_neon_vrshifts:
13546 case Intrinsic::arm_neon_vrshiftu:
13547 case Intrinsic::arm_neon_vrshiftn:
13548 case Intrinsic::arm_neon_vqshifts:
13549 case Intrinsic::arm_neon_vqshiftu:
13550 case Intrinsic::arm_neon_vqshiftsu:
13551 case Intrinsic::arm_neon_vqshiftns:
13552 case Intrinsic::arm_neon_vqshiftnu:
13553 case Intrinsic::arm_neon_vqshiftnsu:
13554 case Intrinsic::arm_neon_vqrshiftns:
13555 case Intrinsic::arm_neon_vqrshiftnu:
13556 case Intrinsic::arm_neon_vqrshiftnsu: {
13557 EVT VT = N->getOperand(1).getValueType();
13558 int64_t Cnt;
13559 unsigned VShiftOpc = 0;
13561 switch (IntNo) {
13562 case Intrinsic::arm_neon_vshifts:
13563 case Intrinsic::arm_neon_vshiftu:
13564 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
13565 VShiftOpc = ARMISD::VSHLIMM;
13566 break;
13568 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
13569 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
13570 : ARMISD::VSHRuIMM);
13571 break;
13573 return SDValue();
13575 case Intrinsic::arm_neon_vrshifts:
13576 case Intrinsic::arm_neon_vrshiftu:
13577 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
13578 break;
13579 return SDValue();
13581 case Intrinsic::arm_neon_vqshifts:
13582 case Intrinsic::arm_neon_vqshiftu:
13583 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13584 break;
13585 return SDValue();
13587 case Intrinsic::arm_neon_vqshiftsu:
13588 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13589 break;
13590 llvm_unreachable("invalid shift count for vqshlu intrinsic");
13592 case Intrinsic::arm_neon_vrshiftn:
13593 case Intrinsic::arm_neon_vqshiftns:
13594 case Intrinsic::arm_neon_vqshiftnu:
13595 case Intrinsic::arm_neon_vqshiftnsu:
13596 case Intrinsic::arm_neon_vqrshiftns:
13597 case Intrinsic::arm_neon_vqrshiftnu:
13598 case Intrinsic::arm_neon_vqrshiftnsu:
13599 // Narrowing shifts require an immediate right shift.
13600 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
13601 break;
13602 llvm_unreachable("invalid shift count for narrowing vector shift "
13603 "intrinsic");
13605 default:
13606 llvm_unreachable("unhandled vector shift");
13609 switch (IntNo) {
13610 case Intrinsic::arm_neon_vshifts:
13611 case Intrinsic::arm_neon_vshiftu:
13612 // Opcode already set above.
13613 break;
13614 case Intrinsic::arm_neon_vrshifts:
13615 VShiftOpc = ARMISD::VRSHRsIMM;
13616 break;
13617 case Intrinsic::arm_neon_vrshiftu:
13618 VShiftOpc = ARMISD::VRSHRuIMM;
13619 break;
13620 case Intrinsic::arm_neon_vrshiftn:
13621 VShiftOpc = ARMISD::VRSHRNIMM;
13622 break;
13623 case Intrinsic::arm_neon_vqshifts:
13624 VShiftOpc = ARMISD::VQSHLsIMM;
13625 break;
13626 case Intrinsic::arm_neon_vqshiftu:
13627 VShiftOpc = ARMISD::VQSHLuIMM;
13628 break;
13629 case Intrinsic::arm_neon_vqshiftsu:
13630 VShiftOpc = ARMISD::VQSHLsuIMM;
13631 break;
13632 case Intrinsic::arm_neon_vqshiftns:
13633 VShiftOpc = ARMISD::VQSHRNsIMM;
13634 break;
13635 case Intrinsic::arm_neon_vqshiftnu:
13636 VShiftOpc = ARMISD::VQSHRNuIMM;
13637 break;
13638 case Intrinsic::arm_neon_vqshiftnsu:
13639 VShiftOpc = ARMISD::VQSHRNsuIMM;
13640 break;
13641 case Intrinsic::arm_neon_vqrshiftns:
13642 VShiftOpc = ARMISD::VQRSHRNsIMM;
13643 break;
13644 case Intrinsic::arm_neon_vqrshiftnu:
13645 VShiftOpc = ARMISD::VQRSHRNuIMM;
13646 break;
13647 case Intrinsic::arm_neon_vqrshiftnsu:
13648 VShiftOpc = ARMISD::VQRSHRNsuIMM;
13649 break;
13652 SDLoc dl(N);
13653 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13654 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
13657 case Intrinsic::arm_neon_vshiftins: {
13658 EVT VT = N->getOperand(1).getValueType();
13659 int64_t Cnt;
13660 unsigned VShiftOpc = 0;
13662 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
13663 VShiftOpc = ARMISD::VSLIIMM;
13664 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
13665 VShiftOpc = ARMISD::VSRIIMM;
13666 else {
13667 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
13670 SDLoc dl(N);
13671 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13672 N->getOperand(1), N->getOperand(2),
13673 DAG.getConstant(Cnt, dl, MVT::i32));
13676 case Intrinsic::arm_neon_vqrshifts:
13677 case Intrinsic::arm_neon_vqrshiftu:
13678 // No immediate versions of these to check for.
13679 break;
13682 return SDValue();
13685 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
13686 /// lowers them. As with the vector shift intrinsics, this is done during DAG
13687 /// combining instead of DAG legalizing because the build_vectors for 64-bit
13688 /// vector element shift counts are generally not legal, and it is hard to see
13689 /// their values after they get legalized to loads from a constant pool.
13690 static SDValue PerformShiftCombine(SDNode *N,
13691 TargetLowering::DAGCombinerInfo &DCI,
13692 const ARMSubtarget *ST) {
13693 SelectionDAG &DAG = DCI.DAG;
13694 EVT VT = N->getValueType(0);
13695 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
13696 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
13697 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
13698 SDValue N1 = N->getOperand(1);
13699 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
13700 SDValue N0 = N->getOperand(0);
13701 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
13702 DAG.MaskedValueIsZero(N0.getOperand(0),
13703 APInt::getHighBitsSet(32, 16)))
13704 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
13708 if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
13709 N->getOperand(0)->getOpcode() == ISD::AND &&
13710 N->getOperand(0)->hasOneUse()) {
13711 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13712 return SDValue();
13713 // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
13714 // usually show up because instcombine prefers to canonicalize it to
13715 // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
13716 // out of GEP lowering in some cases.
13717 SDValue N0 = N->getOperand(0);
13718 ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
13719 if (!ShiftAmtNode)
13720 return SDValue();
13721 uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
13722 ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13723 if (!AndMaskNode)
13724 return SDValue();
13725 uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
13726 // Don't transform uxtb/uxth.
13727 if (AndMask == 255 || AndMask == 65535)
13728 return SDValue();
13729 if (isMask_32(AndMask)) {
13730 uint32_t MaskedBits = countLeadingZeros(AndMask);
13731 if (MaskedBits > ShiftAmt) {
13732 SDLoc DL(N);
13733 SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
13734 DAG.getConstant(MaskedBits, DL, MVT::i32));
13735 return DAG.getNode(
13736 ISD::SRL, DL, MVT::i32, SHL,
13737 DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
13742 // Nothing to be done for scalar shifts.
13743 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13744 if (!VT.isVector() || !TLI.isTypeLegal(VT))
13745 return SDValue();
13746 if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
13747 return SDValue();
13749 int64_t Cnt;
13751 switch (N->getOpcode()) {
13752 default: llvm_unreachable("unexpected shift opcode");
13754 case ISD::SHL:
13755 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
13756 SDLoc dl(N);
13757 return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
13758 DAG.getConstant(Cnt, dl, MVT::i32));
13760 break;
13762 case ISD::SRA:
13763 case ISD::SRL:
13764 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
13765 unsigned VShiftOpc =
13766 (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
13767 SDLoc dl(N);
13768 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
13769 DAG.getConstant(Cnt, dl, MVT::i32));
13772 return SDValue();
13775 // Look for a sign/zero extend of a larger than legal load. This can be split
13776 // into two extending loads, which are simpler to deal with than an arbitrary
13777 // sign extend.
13778 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
13779 SDValue N0 = N->getOperand(0);
13780 if (N0.getOpcode() != ISD::LOAD)
13781 return SDValue();
13782 LoadSDNode *LD = cast<LoadSDNode>(N0.getNode());
13783 if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
13784 LD->getExtensionType() != ISD::NON_EXTLOAD)
13785 return SDValue();
13786 EVT FromVT = LD->getValueType(0);
13787 EVT ToVT = N->getValueType(0);
13788 if (!ToVT.isVector())
13789 return SDValue();
13790 assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
13791 EVT ToEltVT = ToVT.getVectorElementType();
13792 EVT FromEltVT = FromVT.getVectorElementType();
13794 unsigned NumElements = 0;
13795 if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
13796 NumElements = 4;
13797 if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
13798 NumElements = 8;
13799 if (NumElements == 0 ||
13800 FromVT.getVectorNumElements() == NumElements ||
13801 FromVT.getVectorNumElements() % NumElements != 0 ||
13802 !isPowerOf2_32(NumElements))
13803 return SDValue();
13805 SDLoc DL(LD);
13806 // Details about the old load
13807 SDValue Ch = LD->getChain();
13808 SDValue BasePtr = LD->getBasePtr();
13809 unsigned Alignment = LD->getOriginalAlignment();
13810 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
13811 AAMDNodes AAInfo = LD->getAAInfo();
13813 ISD::LoadExtType NewExtType =
13814 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
13815 SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
13816 EVT NewFromVT = FromVT.getHalfNumVectorElementsVT(*DAG.getContext());
13817 EVT NewToVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext());
13818 unsigned NewOffset = NewFromVT.getSizeInBits() / 8;
13819 SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset);
13821 // Split the load in half, each side of which is extended separately. This
13822 // is good enough, as legalisation will take it from there. They are either
13823 // already legal or they will be split further into something that is
13824 // legal.
13825 SDValue NewLoad1 =
13826 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, BasePtr, Offset,
13827 LD->getPointerInfo(), NewFromVT, Alignment, MMOFlags, AAInfo);
13828 SDValue NewLoad2 =
13829 DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
13830 LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
13831 Alignment, MMOFlags, AAInfo);
13833 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
13834 SDValue(NewLoad1.getNode(), 1),
13835 SDValue(NewLoad2.getNode(), 1));
13836 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
13837 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, NewLoad1, NewLoad2);
13840 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
13841 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
13842 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
13843 const ARMSubtarget *ST) {
13844 SDValue N0 = N->getOperand(0);
13846 // Check for sign- and zero-extensions of vector extract operations of 8-
13847 // and 16-bit vector elements. NEON supports these directly. They are
13848 // handled during DAG combining because type legalization will promote them
13849 // to 32-bit types and it is messy to recognize the operations after that.
13850 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13851 SDValue Vec = N0.getOperand(0);
13852 SDValue Lane = N0.getOperand(1);
13853 EVT VT = N->getValueType(0);
13854 EVT EltVT = N0.getValueType();
13855 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13857 if (VT == MVT::i32 &&
13858 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
13859 TLI.isTypeLegal(Vec.getValueType()) &&
13860 isa<ConstantSDNode>(Lane)) {
13862 unsigned Opc = 0;
13863 switch (N->getOpcode()) {
13864 default: llvm_unreachable("unexpected opcode");
13865 case ISD::SIGN_EXTEND:
13866 Opc = ARMISD::VGETLANEs;
13867 break;
13868 case ISD::ZERO_EXTEND:
13869 case ISD::ANY_EXTEND:
13870 Opc = ARMISD::VGETLANEu;
13871 break;
13873 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
13877 if (ST->hasMVEIntegerOps())
13878 if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
13879 return NewLoad;
13881 return SDValue();
13884 static const APInt *isPowerOf2Constant(SDValue V) {
13885 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13886 if (!C)
13887 return nullptr;
13888 const APInt *CV = &C->getAPIntValue();
13889 return CV->isPowerOf2() ? CV : nullptr;
13892 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
13893 // If we have a CMOV, OR and AND combination such as:
13894 // if (x & CN)
13895 // y |= CM;
13897 // And:
13898 // * CN is a single bit;
13899 // * All bits covered by CM are known zero in y
13901 // Then we can convert this into a sequence of BFI instructions. This will
13902 // always be a win if CM is a single bit, will always be no worse than the
13903 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
13904 // three bits (due to the extra IT instruction).
13906 SDValue Op0 = CMOV->getOperand(0);
13907 SDValue Op1 = CMOV->getOperand(1);
13908 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
13909 auto CC = CCNode->getAPIntValue().getLimitedValue();
13910 SDValue CmpZ = CMOV->getOperand(4);
13912 // The compare must be against zero.
13913 if (!isNullConstant(CmpZ->getOperand(1)))
13914 return SDValue();
13916 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
13917 SDValue And = CmpZ->getOperand(0);
13918 if (And->getOpcode() != ISD::AND)
13919 return SDValue();
13920 const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
13921 if (!AndC)
13922 return SDValue();
13923 SDValue X = And->getOperand(0);
13925 if (CC == ARMCC::EQ) {
13926 // We're performing an "equal to zero" compare. Swap the operands so we
13927 // canonicalize on a "not equal to zero" compare.
13928 std::swap(Op0, Op1);
13929 } else {
13930 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
13933 if (Op1->getOpcode() != ISD::OR)
13934 return SDValue();
13936 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
13937 if (!OrC)
13938 return SDValue();
13939 SDValue Y = Op1->getOperand(0);
13941 if (Op0 != Y)
13942 return SDValue();
13944 // Now, is it profitable to continue?
13945 APInt OrCI = OrC->getAPIntValue();
13946 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
13947 if (OrCI.countPopulation() > Heuristic)
13948 return SDValue();
13950 // Lastly, can we determine that the bits defined by OrCI
13951 // are zero in Y?
13952 KnownBits Known = DAG.computeKnownBits(Y);
13953 if ((OrCI & Known.Zero) != OrCI)
13954 return SDValue();
13956 // OK, we can do the combine.
13957 SDValue V = Y;
13958 SDLoc dl(X);
13959 EVT VT = X.getValueType();
13960 unsigned BitInX = AndC->logBase2();
13962 if (BitInX != 0) {
13963 // We must shift X first.
13964 X = DAG.getNode(ISD::SRL, dl, VT, X,
13965 DAG.getConstant(BitInX, dl, VT));
13968 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
13969 BitInY < NumActiveBits; ++BitInY) {
13970 if (OrCI[BitInY] == 0)
13971 continue;
13972 APInt Mask(VT.getSizeInBits(), 0);
13973 Mask.setBit(BitInY);
13974 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
13975 // Confusingly, the operand is an *inverted* mask.
13976 DAG.getConstant(~Mask, dl, VT));
13979 return V;
13982 // Given N, the value controlling the conditional branch, search for the loop
13983 // intrinsic, returning it, along with how the value is used. We need to handle
13984 // patterns such as the following:
13985 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
13986 // (brcond (setcc (loop.decrement), 0, eq), exit)
13987 // (brcond (setcc (loop.decrement), 0, ne), header)
13988 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
13989 bool &Negate) {
13990 switch (N->getOpcode()) {
13991 default:
13992 break;
13993 case ISD::XOR: {
13994 if (!isa<ConstantSDNode>(N.getOperand(1)))
13995 return SDValue();
13996 if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
13997 return SDValue();
13998 Negate = !Negate;
13999 return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
14001 case ISD::SETCC: {
14002 auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
14003 if (!Const)
14004 return SDValue();
14005 if (Const->isNullValue())
14006 Imm = 0;
14007 else if (Const->isOne())
14008 Imm = 1;
14009 else
14010 return SDValue();
14011 CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
14012 return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
14014 case ISD::INTRINSIC_W_CHAIN: {
14015 unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
14016 if (IntOp != Intrinsic::test_set_loop_iterations &&
14017 IntOp != Intrinsic::loop_decrement_reg)
14018 return SDValue();
14019 return N;
14022 return SDValue();
14025 static SDValue PerformHWLoopCombine(SDNode *N,
14026 TargetLowering::DAGCombinerInfo &DCI,
14027 const ARMSubtarget *ST) {
14029 // The hwloop intrinsics that we're interested are used for control-flow,
14030 // either for entering or exiting the loop:
14031 // - test.set.loop.iterations will test whether its operand is zero. If it
14032 // is zero, the proceeding branch should not enter the loop.
14033 // - loop.decrement.reg also tests whether its operand is zero. If it is
14034 // zero, the proceeding branch should not branch back to the beginning of
14035 // the loop.
14036 // So here, we need to check that how the brcond is using the result of each
14037 // of the intrinsics to ensure that we're branching to the right place at the
14038 // right time.
14040 ISD::CondCode CC;
14041 SDValue Cond;
14042 int Imm = 1;
14043 bool Negate = false;
14044 SDValue Chain = N->getOperand(0);
14045 SDValue Dest;
14047 if (N->getOpcode() == ISD::BRCOND) {
14048 CC = ISD::SETEQ;
14049 Cond = N->getOperand(1);
14050 Dest = N->getOperand(2);
14051 } else {
14052 assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
14053 CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14054 Cond = N->getOperand(2);
14055 Dest = N->getOperand(4);
14056 if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
14057 if (!Const->isOne() && !Const->isNullValue())
14058 return SDValue();
14059 Imm = Const->getZExtValue();
14060 } else
14061 return SDValue();
14064 SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
14065 if (!Int)
14066 return SDValue();
14068 if (Negate)
14069 CC = ISD::getSetCCInverse(CC, true);
14071 auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
14072 return (CC == ISD::SETEQ && Imm == 0) ||
14073 (CC == ISD::SETNE && Imm == 1) ||
14074 (CC == ISD::SETLT && Imm == 1) ||
14075 (CC == ISD::SETULT && Imm == 1);
14078 auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
14079 return (CC == ISD::SETEQ && Imm == 1) ||
14080 (CC == ISD::SETNE && Imm == 0) ||
14081 (CC == ISD::SETGT && Imm == 0) ||
14082 (CC == ISD::SETUGT && Imm == 0) ||
14083 (CC == ISD::SETGE && Imm == 1) ||
14084 (CC == ISD::SETUGE && Imm == 1);
14087 assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
14088 "unsupported condition");
14090 SDLoc dl(Int);
14091 SelectionDAG &DAG = DCI.DAG;
14092 SDValue Elements = Int.getOperand(2);
14093 unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
14094 assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
14095 && "expected single br user");
14096 SDNode *Br = *N->use_begin();
14097 SDValue OtherTarget = Br->getOperand(1);
14099 // Update the unconditional branch to branch to the given Dest.
14100 auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
14101 SDValue NewBrOps[] = { Br->getOperand(0), Dest };
14102 SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
14103 DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
14106 if (IntOp == Intrinsic::test_set_loop_iterations) {
14107 SDValue Res;
14108 // We expect this 'instruction' to branch when the counter is zero.
14109 if (IsTrueIfZero(CC, Imm)) {
14110 SDValue Ops[] = { Chain, Elements, Dest };
14111 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
14112 } else {
14113 // The logic is the reverse of what we need for WLS, so find the other
14114 // basic block target: the target of the proceeding br.
14115 UpdateUncondBr(Br, Dest, DAG);
14117 SDValue Ops[] = { Chain, Elements, OtherTarget };
14118 Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
14120 DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
14121 return Res;
14122 } else {
14123 SDValue Size = DAG.getTargetConstant(
14124 cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
14125 SDValue Args[] = { Int.getOperand(0), Elements, Size, };
14126 SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
14127 DAG.getVTList(MVT::i32, MVT::Other), Args);
14128 DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
14130 // We expect this instruction to branch when the count is not zero.
14131 SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
14133 // Update the unconditional branch to target the loop preheader if we've
14134 // found the condition has been reversed.
14135 if (Target == OtherTarget)
14136 UpdateUncondBr(Br, Dest, DAG);
14138 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14139 SDValue(LoopDec.getNode(), 1), Chain);
14141 SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
14142 return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
14144 return SDValue();
14147 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
14148 SDValue
14149 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
14150 SDValue Cmp = N->getOperand(4);
14151 if (Cmp.getOpcode() != ARMISD::CMPZ)
14152 // Only looking at NE cases.
14153 return SDValue();
14155 EVT VT = N->getValueType(0);
14156 SDLoc dl(N);
14157 SDValue LHS = Cmp.getOperand(0);
14158 SDValue RHS = Cmp.getOperand(1);
14159 SDValue Chain = N->getOperand(0);
14160 SDValue BB = N->getOperand(1);
14161 SDValue ARMcc = N->getOperand(2);
14162 ARMCC::CondCodes CC =
14163 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
14165 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
14166 // -> (brcond Chain BB CC CPSR Cmp)
14167 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
14168 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
14169 LHS->getOperand(0)->hasOneUse()) {
14170 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
14171 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
14172 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
14173 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
14174 if ((LHS00C && LHS00C->getZExtValue() == 0) &&
14175 (LHS01C && LHS01C->getZExtValue() == 1) &&
14176 (LHS1C && LHS1C->getZExtValue() == 1) &&
14177 (RHSC && RHSC->getZExtValue() == 0)) {
14178 return DAG.getNode(
14179 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
14180 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
14184 return SDValue();
14187 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
14188 SDValue
14189 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
14190 SDValue Cmp = N->getOperand(4);
14191 if (Cmp.getOpcode() != ARMISD::CMPZ)
14192 // Only looking at EQ and NE cases.
14193 return SDValue();
14195 EVT VT = N->getValueType(0);
14196 SDLoc dl(N);
14197 SDValue LHS = Cmp.getOperand(0);
14198 SDValue RHS = Cmp.getOperand(1);
14199 SDValue FalseVal = N->getOperand(0);
14200 SDValue TrueVal = N->getOperand(1);
14201 SDValue ARMcc = N->getOperand(2);
14202 ARMCC::CondCodes CC =
14203 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
14205 // BFI is only available on V6T2+.
14206 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
14207 SDValue R = PerformCMOVToBFICombine(N, DAG);
14208 if (R)
14209 return R;
14212 // Simplify
14213 // mov r1, r0
14214 // cmp r1, x
14215 // mov r0, y
14216 // moveq r0, x
14217 // to
14218 // cmp r0, x
14219 // movne r0, y
14221 // mov r1, r0
14222 // cmp r1, x
14223 // mov r0, x
14224 // movne r0, y
14225 // to
14226 // cmp r0, x
14227 // movne r0, y
14228 /// FIXME: Turn this into a target neutral optimization?
14229 SDValue Res;
14230 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
14231 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
14232 N->getOperand(3), Cmp);
14233 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
14234 SDValue ARMcc;
14235 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
14236 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
14237 N->getOperand(3), NewCmp);
14240 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
14241 // -> (cmov F T CC CPSR Cmp)
14242 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
14243 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
14244 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
14245 auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
14246 if ((LHS0C && LHS0C->getZExtValue() == 0) &&
14247 (LHS1C && LHS1C->getZExtValue() == 1) &&
14248 (RHSC && RHSC->getZExtValue() == 0)) {
14249 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
14250 LHS->getOperand(2), LHS->getOperand(3),
14251 LHS->getOperand(4));
14255 if (!VT.isInteger())
14256 return SDValue();
14258 // Materialize a boolean comparison for integers so we can avoid branching.
14259 if (isNullConstant(FalseVal)) {
14260 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
14261 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
14262 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
14263 // right 5 bits will make that 32 be 1, otherwise it will be 0.
14264 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
14265 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
14266 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
14267 DAG.getConstant(5, dl, MVT::i32));
14268 } else {
14269 // CMOV 0, 1, ==, (CMPZ x, y) ->
14270 // (ADDCARRY (SUB x, y), t:0, t:1)
14271 // where t = (SUBCARRY 0, (SUB x, y), 0)
14273 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
14274 // x != y. In other words, a carry C == 1 when x == y, C == 0
14275 // otherwise.
14276 // The final ADDCARRY computes
14277 // x - y + (0 - (x - y)) + C == C
14278 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
14279 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14280 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
14281 // ISD::SUBCARRY returns a borrow but we want the carry here
14282 // actually.
14283 SDValue Carry =
14284 DAG.getNode(ISD::SUB, dl, MVT::i32,
14285 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
14286 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
14288 } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
14289 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
14290 // This seems pointless but will allow us to combine it further below.
14291 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
14292 SDValue Sub =
14293 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
14294 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
14295 Sub.getValue(1), SDValue());
14296 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
14297 N->getOperand(3), CPSRGlue.getValue(1));
14298 FalseVal = Sub;
14300 } else if (isNullConstant(TrueVal)) {
14301 if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
14302 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
14303 // This seems pointless but will allow us to combine it further below
14304 // Note that we change == for != as this is the dual for the case above.
14305 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
14306 SDValue Sub =
14307 DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
14308 SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
14309 Sub.getValue(1), SDValue());
14310 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
14311 DAG.getConstant(ARMCC::NE, dl, MVT::i32),
14312 N->getOperand(3), CPSRGlue.getValue(1));
14313 FalseVal = Sub;
14317 // On Thumb1, the DAG above may be further combined if z is a power of 2
14318 // (z == 2 ^ K).
14319 // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
14320 // t1 = (USUBO (SUB x, y), 1)
14321 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
14322 // Result = if K != 0 then (SHL t2:0, K) else t2:0
14324 // This also handles the special case of comparing against zero; it's
14325 // essentially, the same pattern, except there's no SUBS:
14326 // CMOV x, z, !=, (CMPZ x, 0) ->
14327 // t1 = (USUBO x, 1)
14328 // t2 = (SUBCARRY x, t1:0, t1:1)
14329 // Result = if K != 0 then (SHL t2:0, K) else t2:0
14330 const APInt *TrueConst;
14331 if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
14332 ((FalseVal.getOpcode() == ARMISD::SUBS &&
14333 FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
14334 (FalseVal == LHS && isNullConstant(RHS))) &&
14335 (TrueConst = isPowerOf2Constant(TrueVal))) {
14336 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14337 unsigned ShiftAmount = TrueConst->logBase2();
14338 if (ShiftAmount)
14339 TrueVal = DAG.getConstant(1, dl, VT);
14340 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
14341 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
14343 if (ShiftAmount)
14344 Res = DAG.getNode(ISD::SHL, dl, VT, Res,
14345 DAG.getConstant(ShiftAmount, dl, MVT::i32));
14348 if (Res.getNode()) {
14349 KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
14350 // Capture demanded bits information that would be otherwise lost.
14351 if (Known.Zero == 0xfffffffe)
14352 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14353 DAG.getValueType(MVT::i1));
14354 else if (Known.Zero == 0xffffff00)
14355 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14356 DAG.getValueType(MVT::i8));
14357 else if (Known.Zero == 0xffff0000)
14358 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14359 DAG.getValueType(MVT::i16));
14362 return Res;
14365 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
14366 DAGCombinerInfo &DCI) const {
14367 switch (N->getOpcode()) {
14368 default: break;
14369 case ISD::ABS: return PerformABSCombine(N, DCI, Subtarget);
14370 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget);
14371 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget);
14372 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
14373 case ISD::SUB: return PerformSUBCombine(N, DCI);
14374 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
14375 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
14376 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
14377 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
14378 case ISD::BRCOND:
14379 case ISD::BR_CC: return PerformHWLoopCombine(N, DCI, Subtarget);
14380 case ARMISD::ADDC:
14381 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget);
14382 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget);
14383 case ARMISD::BFI: return PerformBFICombine(N, DCI);
14384 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
14385 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
14386 case ISD::STORE: return PerformSTORECombine(N, DCI, Subtarget);
14387 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
14388 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
14389 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
14390 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
14391 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
14392 case ISD::FP_TO_SINT:
14393 case ISD::FP_TO_UINT:
14394 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
14395 case ISD::FDIV:
14396 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
14397 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
14398 case ISD::SHL:
14399 case ISD::SRA:
14400 case ISD::SRL:
14401 return PerformShiftCombine(N, DCI, Subtarget);
14402 case ISD::SIGN_EXTEND:
14403 case ISD::ZERO_EXTEND:
14404 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
14405 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
14406 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
14407 case ISD::LOAD: return PerformLOADCombine(N, DCI);
14408 case ARMISD::VLD1DUP:
14409 case ARMISD::VLD2DUP:
14410 case ARMISD::VLD3DUP:
14411 case ARMISD::VLD4DUP:
14412 return PerformVLDCombine(N, DCI);
14413 case ARMISD::BUILD_VECTOR:
14414 return PerformARMBUILD_VECTORCombine(N, DCI);
14415 case ARMISD::PREDICATE_CAST:
14416 return PerformPREDICATE_CASTCombine(N, DCI);
14417 case ARMISD::SMULWB: {
14418 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14419 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14420 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14421 return SDValue();
14422 break;
14424 case ARMISD::SMULWT: {
14425 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14426 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14427 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14428 return SDValue();
14429 break;
14431 case ARMISD::SMLALBB:
14432 case ARMISD::QADD16b:
14433 case ARMISD::QSUB16b: {
14434 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14435 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14436 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14437 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14438 return SDValue();
14439 break;
14441 case ARMISD::SMLALBT: {
14442 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
14443 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14444 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
14445 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14446 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
14447 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
14448 return SDValue();
14449 break;
14451 case ARMISD::SMLALTB: {
14452 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
14453 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14454 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
14455 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14456 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
14457 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
14458 return SDValue();
14459 break;
14461 case ARMISD::SMLALTT: {
14462 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14463 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14464 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14465 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14466 return SDValue();
14467 break;
14469 case ARMISD::QADD8b:
14470 case ARMISD::QSUB8b: {
14471 unsigned BitWidth = N->getValueType(0).getSizeInBits();
14472 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
14473 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14474 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14475 return SDValue();
14476 break;
14478 case ISD::INTRINSIC_VOID:
14479 case ISD::INTRINSIC_W_CHAIN:
14480 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14481 case Intrinsic::arm_neon_vld1:
14482 case Intrinsic::arm_neon_vld1x2:
14483 case Intrinsic::arm_neon_vld1x3:
14484 case Intrinsic::arm_neon_vld1x4:
14485 case Intrinsic::arm_neon_vld2:
14486 case Intrinsic::arm_neon_vld3:
14487 case Intrinsic::arm_neon_vld4:
14488 case Intrinsic::arm_neon_vld2lane:
14489 case Intrinsic::arm_neon_vld3lane:
14490 case Intrinsic::arm_neon_vld4lane:
14491 case Intrinsic::arm_neon_vld2dup:
14492 case Intrinsic::arm_neon_vld3dup:
14493 case Intrinsic::arm_neon_vld4dup:
14494 case Intrinsic::arm_neon_vst1:
14495 case Intrinsic::arm_neon_vst1x2:
14496 case Intrinsic::arm_neon_vst1x3:
14497 case Intrinsic::arm_neon_vst1x4:
14498 case Intrinsic::arm_neon_vst2:
14499 case Intrinsic::arm_neon_vst3:
14500 case Intrinsic::arm_neon_vst4:
14501 case Intrinsic::arm_neon_vst2lane:
14502 case Intrinsic::arm_neon_vst3lane:
14503 case Intrinsic::arm_neon_vst4lane:
14504 return PerformVLDCombine(N, DCI);
14505 default: break;
14507 break;
14509 return SDValue();
14512 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
14513 EVT VT) const {
14514 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
14517 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
14518 unsigned Alignment,
14519 MachineMemOperand::Flags,
14520 bool *Fast) const {
14521 // Depends what it gets converted into if the type is weird.
14522 if (!VT.isSimple())
14523 return false;
14525 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
14526 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
14527 auto Ty = VT.getSimpleVT().SimpleTy;
14529 if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
14530 // Unaligned access can use (for example) LRDB, LRDH, LDR
14531 if (AllowsUnaligned) {
14532 if (Fast)
14533 *Fast = Subtarget->hasV7Ops();
14534 return true;
14538 if (Ty == MVT::f64 || Ty == MVT::v2f64) {
14539 // For any little-endian targets with neon, we can support unaligned ld/st
14540 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
14541 // A big-endian target may also explicitly support unaligned accesses
14542 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
14543 if (Fast)
14544 *Fast = true;
14545 return true;
14549 if (!Subtarget->hasMVEIntegerOps())
14550 return false;
14552 // These are for predicates
14553 if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
14554 if (Fast)
14555 *Fast = true;
14556 return true;
14559 // These are for truncated stores/narrowing loads. They are fine so long as
14560 // the alignment is at least the size of the item being loaded
14561 if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
14562 Alignment >= VT.getScalarSizeInBits() / 8) {
14563 if (Fast)
14564 *Fast = true;
14565 return true;
14568 // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
14569 // VSTRW.U32 all store the vector register in exactly the same format, and
14570 // differ only in the range of their immediate offset field and the required
14571 // alignment. So there is always a store that can be used, regardless of
14572 // actual type.
14574 // For big endian, that is not the case. But can still emit a (VSTRB.U8;
14575 // VREV64.8) pair and get the same effect. This will likely be better than
14576 // aligning the vector through the stack.
14577 if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
14578 Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
14579 Ty == MVT::v2f64) {
14580 if (Fast)
14581 *Fast = true;
14582 return true;
14585 return false;
14588 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
14589 unsigned AlignCheck) {
14590 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
14591 (DstAlign == 0 || DstAlign % AlignCheck == 0));
14594 EVT ARMTargetLowering::getOptimalMemOpType(
14595 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14596 bool ZeroMemset, bool MemcpyStrSrc,
14597 const AttributeList &FuncAttributes) const {
14598 // See if we can use NEON instructions for this...
14599 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
14600 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
14601 bool Fast;
14602 if (Size >= 16 &&
14603 (memOpAlign(SrcAlign, DstAlign, 16) ||
14604 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
14605 MachineMemOperand::MONone, &Fast) &&
14606 Fast))) {
14607 return MVT::v2f64;
14608 } else if (Size >= 8 &&
14609 (memOpAlign(SrcAlign, DstAlign, 8) ||
14610 (allowsMisalignedMemoryAccesses(
14611 MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
14612 Fast))) {
14613 return MVT::f64;
14617 // Let the target-independent logic figure it out.
14618 return MVT::Other;
14621 // 64-bit integers are split into their high and low parts and held in two
14622 // different registers, so the trunc is free since the low register can just
14623 // be used.
14624 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
14625 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
14626 return false;
14627 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
14628 unsigned DestBits = DstTy->getPrimitiveSizeInBits();
14629 return (SrcBits == 64 && DestBits == 32);
14632 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
14633 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
14634 !DstVT.isInteger())
14635 return false;
14636 unsigned SrcBits = SrcVT.getSizeInBits();
14637 unsigned DestBits = DstVT.getSizeInBits();
14638 return (SrcBits == 64 && DestBits == 32);
14641 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14642 if (Val.getOpcode() != ISD::LOAD)
14643 return false;
14645 EVT VT1 = Val.getValueType();
14646 if (!VT1.isSimple() || !VT1.isInteger() ||
14647 !VT2.isSimple() || !VT2.isInteger())
14648 return false;
14650 switch (VT1.getSimpleVT().SimpleTy) {
14651 default: break;
14652 case MVT::i1:
14653 case MVT::i8:
14654 case MVT::i16:
14655 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
14656 return true;
14659 return false;
14662 bool ARMTargetLowering::isFNegFree(EVT VT) const {
14663 if (!VT.isSimple())
14664 return false;
14666 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
14667 // negate values directly (fneg is free). So, we don't want to let the DAG
14668 // combiner rewrite fneg into xors and some other instructions. For f16 and
14669 // FullFP16 argument passing, some bitcast nodes may be introduced,
14670 // triggering this DAG combine rewrite, so we are avoiding that with this.
14671 switch (VT.getSimpleVT().SimpleTy) {
14672 default: break;
14673 case MVT::f16:
14674 return Subtarget->hasFullFP16();
14677 return false;
14680 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
14681 /// of the vector elements.
14682 static bool areExtractExts(Value *Ext1, Value *Ext2) {
14683 auto areExtDoubled = [](Instruction *Ext) {
14684 return Ext->getType()->getScalarSizeInBits() ==
14685 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
14688 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
14689 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
14690 !areExtDoubled(cast<Instruction>(Ext1)) ||
14691 !areExtDoubled(cast<Instruction>(Ext2)))
14692 return false;
14694 return true;
14697 /// Check if sinking \p I's operands to I's basic block is profitable, because
14698 /// the operands can be folded into a target instruction, e.g.
14699 /// sext/zext can be folded into vsubl.
14700 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
14701 SmallVectorImpl<Use *> &Ops) const {
14702 if (!I->getType()->isVectorTy())
14703 return false;
14705 if (Subtarget->hasNEON()) {
14706 switch (I->getOpcode()) {
14707 case Instruction::Sub:
14708 case Instruction::Add: {
14709 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
14710 return false;
14711 Ops.push_back(&I->getOperandUse(0));
14712 Ops.push_back(&I->getOperandUse(1));
14713 return true;
14715 default:
14716 return false;
14720 if (!Subtarget->hasMVEIntegerOps())
14721 return false;
14723 auto IsSinker = [](Instruction *I, int Operand) {
14724 switch (I->getOpcode()) {
14725 case Instruction::Add:
14726 case Instruction::Mul:
14727 return true;
14728 case Instruction::Sub:
14729 return Operand == 1;
14730 default:
14731 return false;
14735 int Op = 0;
14736 if (!isa<ShuffleVectorInst>(I->getOperand(Op)))
14737 Op = 1;
14738 if (!IsSinker(I, Op))
14739 return false;
14740 if (!match(I->getOperand(Op),
14741 m_ShuffleVector(m_InsertElement(m_Undef(), m_Value(), m_ZeroInt()),
14742 m_Undef(), m_Zero()))) {
14743 return false;
14745 Instruction *Shuffle = cast<Instruction>(I->getOperand(Op));
14746 // All uses of the shuffle should be sunk to avoid duplicating it across gpr
14747 // and vector registers
14748 for (Use &U : Shuffle->uses()) {
14749 Instruction *Insn = cast<Instruction>(U.getUser());
14750 if (!IsSinker(Insn, U.getOperandNo()))
14751 return false;
14753 Ops.push_back(&Shuffle->getOperandUse(0));
14754 Ops.push_back(&I->getOperandUse(Op));
14755 return true;
14758 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
14759 EVT VT = ExtVal.getValueType();
14761 if (!isTypeLegal(VT))
14762 return false;
14764 if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
14765 if (Ld->isExpandingLoad())
14766 return false;
14769 // Don't create a loadext if we can fold the extension into a wide/long
14770 // instruction.
14771 // If there's more than one user instruction, the loadext is desirable no
14772 // matter what. There can be two uses by the same instruction.
14773 if (ExtVal->use_empty() ||
14774 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
14775 return true;
14777 SDNode *U = *ExtVal->use_begin();
14778 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
14779 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
14780 return false;
14782 return true;
14785 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14786 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14787 return false;
14789 if (!isTypeLegal(EVT::getEVT(Ty1)))
14790 return false;
14792 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14794 // Assuming the caller doesn't have a zeroext or signext return parameter,
14795 // truncation all the way down to i1 is valid.
14796 return true;
14799 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
14800 const AddrMode &AM, Type *Ty,
14801 unsigned AS) const {
14802 if (isLegalAddressingMode(DL, AM, Ty, AS)) {
14803 if (Subtarget->hasFPAO())
14804 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
14805 return 0;
14807 return -1;
14810 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
14811 if (V < 0)
14812 return false;
14814 unsigned Scale = 1;
14815 switch (VT.getSimpleVT().SimpleTy) {
14816 case MVT::i1:
14817 case MVT::i8:
14818 // Scale == 1;
14819 break;
14820 case MVT::i16:
14821 // Scale == 2;
14822 Scale = 2;
14823 break;
14824 default:
14825 // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
14826 // Scale == 4;
14827 Scale = 4;
14828 break;
14831 if ((V & (Scale - 1)) != 0)
14832 return false;
14833 return isUInt<5>(V / Scale);
14836 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
14837 const ARMSubtarget *Subtarget) {
14838 if (!VT.isInteger() && !VT.isFloatingPoint())
14839 return false;
14840 if (VT.isVector() && Subtarget->hasNEON())
14841 return false;
14842 if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
14843 !Subtarget->hasMVEFloatOps())
14844 return false;
14846 bool IsNeg = false;
14847 if (V < 0) {
14848 IsNeg = true;
14849 V = -V;
14852 unsigned NumBytes = std::max(VT.getSizeInBits() / 8, 1U);
14854 // MVE: size * imm7
14855 if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
14856 switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
14857 case MVT::i32:
14858 case MVT::f32:
14859 return isShiftedUInt<7,2>(V);
14860 case MVT::i16:
14861 case MVT::f16:
14862 return isShiftedUInt<7,1>(V);
14863 case MVT::i8:
14864 return isUInt<7>(V);
14865 default:
14866 return false;
14870 // half VLDR: 2 * imm8
14871 if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
14872 return isShiftedUInt<8, 1>(V);
14873 // VLDR and LDRD: 4 * imm8
14874 if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
14875 return isShiftedUInt<8, 2>(V);
14877 if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
14878 // + imm12 or - imm8
14879 if (IsNeg)
14880 return isUInt<8>(V);
14881 return isUInt<12>(V);
14884 return false;
14887 /// isLegalAddressImmediate - Return true if the integer value can be used
14888 /// as the offset of the target addressing mode for load / store of the
14889 /// given type.
14890 static bool isLegalAddressImmediate(int64_t V, EVT VT,
14891 const ARMSubtarget *Subtarget) {
14892 if (V == 0)
14893 return true;
14895 if (!VT.isSimple())
14896 return false;
14898 if (Subtarget->isThumb1Only())
14899 return isLegalT1AddressImmediate(V, VT);
14900 else if (Subtarget->isThumb2())
14901 return isLegalT2AddressImmediate(V, VT, Subtarget);
14903 // ARM mode.
14904 if (V < 0)
14905 V = - V;
14906 switch (VT.getSimpleVT().SimpleTy) {
14907 default: return false;
14908 case MVT::i1:
14909 case MVT::i8:
14910 case MVT::i32:
14911 // +- imm12
14912 return isUInt<12>(V);
14913 case MVT::i16:
14914 // +- imm8
14915 return isUInt<8>(V);
14916 case MVT::f32:
14917 case MVT::f64:
14918 if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
14919 return false;
14920 return isShiftedUInt<8, 2>(V);
14924 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
14925 EVT VT) const {
14926 int Scale = AM.Scale;
14927 if (Scale < 0)
14928 return false;
14930 switch (VT.getSimpleVT().SimpleTy) {
14931 default: return false;
14932 case MVT::i1:
14933 case MVT::i8:
14934 case MVT::i16:
14935 case MVT::i32:
14936 if (Scale == 1)
14937 return true;
14938 // r + r << imm
14939 Scale = Scale & ~1;
14940 return Scale == 2 || Scale == 4 || Scale == 8;
14941 case MVT::i64:
14942 // FIXME: What are we trying to model here? ldrd doesn't have an r + r
14943 // version in Thumb mode.
14944 // r + r
14945 if (Scale == 1)
14946 return true;
14947 // r * 2 (this can be lowered to r + r).
14948 if (!AM.HasBaseReg && Scale == 2)
14949 return true;
14950 return false;
14951 case MVT::isVoid:
14952 // Note, we allow "void" uses (basically, uses that aren't loads or
14953 // stores), because arm allows folding a scale into many arithmetic
14954 // operations. This should be made more precise and revisited later.
14956 // Allow r << imm, but the imm has to be a multiple of two.
14957 if (Scale & 1) return false;
14958 return isPowerOf2_32(Scale);
14962 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
14963 EVT VT) const {
14964 const int Scale = AM.Scale;
14966 // Negative scales are not supported in Thumb1.
14967 if (Scale < 0)
14968 return false;
14970 // Thumb1 addressing modes do not support register scaling excepting the
14971 // following cases:
14972 // 1. Scale == 1 means no scaling.
14973 // 2. Scale == 2 this can be lowered to r + r if there is no base register.
14974 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
14977 /// isLegalAddressingMode - Return true if the addressing mode represented
14978 /// by AM is legal for this target, for a load/store of the specified type.
14979 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14980 const AddrMode &AM, Type *Ty,
14981 unsigned AS, Instruction *I) const {
14982 EVT VT = getValueType(DL, Ty, true);
14983 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
14984 return false;
14986 // Can never fold addr of global into load/store.
14987 if (AM.BaseGV)
14988 return false;
14990 switch (AM.Scale) {
14991 case 0: // no scale reg, must be "r+i" or "r", or "i".
14992 break;
14993 default:
14994 // ARM doesn't support any R+R*scale+imm addr modes.
14995 if (AM.BaseOffs)
14996 return false;
14998 if (!VT.isSimple())
14999 return false;
15001 if (Subtarget->isThumb1Only())
15002 return isLegalT1ScaledAddressingMode(AM, VT);
15004 if (Subtarget->isThumb2())
15005 return isLegalT2ScaledAddressingMode(AM, VT);
15007 int Scale = AM.Scale;
15008 switch (VT.getSimpleVT().SimpleTy) {
15009 default: return false;
15010 case MVT::i1:
15011 case MVT::i8:
15012 case MVT::i32:
15013 if (Scale < 0) Scale = -Scale;
15014 if (Scale == 1)
15015 return true;
15016 // r + r << imm
15017 return isPowerOf2_32(Scale & ~1);
15018 case MVT::i16:
15019 case MVT::i64:
15020 // r +/- r
15021 if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
15022 return true;
15023 // r * 2 (this can be lowered to r + r).
15024 if (!AM.HasBaseReg && Scale == 2)
15025 return true;
15026 return false;
15028 case MVT::isVoid:
15029 // Note, we allow "void" uses (basically, uses that aren't loads or
15030 // stores), because arm allows folding a scale into many arithmetic
15031 // operations. This should be made more precise and revisited later.
15033 // Allow r << imm, but the imm has to be a multiple of two.
15034 if (Scale & 1) return false;
15035 return isPowerOf2_32(Scale);
15038 return true;
15041 /// isLegalICmpImmediate - Return true if the specified immediate is legal
15042 /// icmp immediate, that is the target has icmp instructions which can compare
15043 /// a register against the immediate without having to materialize the
15044 /// immediate into a register.
15045 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15046 // Thumb2 and ARM modes can use cmn for negative immediates.
15047 if (!Subtarget->isThumb())
15048 return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
15049 ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
15050 if (Subtarget->isThumb2())
15051 return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
15052 ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
15053 // Thumb1 doesn't have cmn, and only 8-bit immediates.
15054 return Imm >= 0 && Imm <= 255;
15057 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
15058 /// *or sub* immediate, that is the target has add or sub instructions which can
15059 /// add a register with the immediate without having to materialize the
15060 /// immediate into a register.
15061 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15062 // Same encoding for add/sub, just flip the sign.
15063 int64_t AbsImm = std::abs(Imm);
15064 if (!Subtarget->isThumb())
15065 return ARM_AM::getSOImmVal(AbsImm) != -1;
15066 if (Subtarget->isThumb2())
15067 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
15068 // Thumb1 only has 8-bit unsigned immediate.
15069 return AbsImm >= 0 && AbsImm <= 255;
15072 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
15073 bool isSEXTLoad, SDValue &Base,
15074 SDValue &Offset, bool &isInc,
15075 SelectionDAG &DAG) {
15076 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
15077 return false;
15079 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
15080 // AddressingMode 3
15081 Base = Ptr->getOperand(0);
15082 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
15083 int RHSC = (int)RHS->getZExtValue();
15084 if (RHSC < 0 && RHSC > -256) {
15085 assert(Ptr->getOpcode() == ISD::ADD);
15086 isInc = false;
15087 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
15088 return true;
15091 isInc = (Ptr->getOpcode() == ISD::ADD);
15092 Offset = Ptr->getOperand(1);
15093 return true;
15094 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
15095 // AddressingMode 2
15096 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
15097 int RHSC = (int)RHS->getZExtValue();
15098 if (RHSC < 0 && RHSC > -0x1000) {
15099 assert(Ptr->getOpcode() == ISD::ADD);
15100 isInc = false;
15101 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
15102 Base = Ptr->getOperand(0);
15103 return true;
15107 if (Ptr->getOpcode() == ISD::ADD) {
15108 isInc = true;
15109 ARM_AM::ShiftOpc ShOpcVal=
15110 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
15111 if (ShOpcVal != ARM_AM::no_shift) {
15112 Base = Ptr->getOperand(1);
15113 Offset = Ptr->getOperand(0);
15114 } else {
15115 Base = Ptr->getOperand(0);
15116 Offset = Ptr->getOperand(1);
15118 return true;
15121 isInc = (Ptr->getOpcode() == ISD::ADD);
15122 Base = Ptr->getOperand(0);
15123 Offset = Ptr->getOperand(1);
15124 return true;
15127 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
15128 return false;
15131 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
15132 bool isSEXTLoad, SDValue &Base,
15133 SDValue &Offset, bool &isInc,
15134 SelectionDAG &DAG) {
15135 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
15136 return false;
15138 Base = Ptr->getOperand(0);
15139 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
15140 int RHSC = (int)RHS->getZExtValue();
15141 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
15142 assert(Ptr->getOpcode() == ISD::ADD);
15143 isInc = false;
15144 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
15145 return true;
15146 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
15147 isInc = Ptr->getOpcode() == ISD::ADD;
15148 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
15149 return true;
15153 return false;
15156 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, unsigned Align,
15157 bool isSEXTLoad, bool isLE, SDValue &Base,
15158 SDValue &Offset, bool &isInc,
15159 SelectionDAG &DAG) {
15160 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
15161 return false;
15162 if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
15163 return false;
15165 ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
15166 int RHSC = (int)RHS->getZExtValue();
15168 auto IsInRange = [&](int RHSC, int Limit, int Scale) {
15169 if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
15170 assert(Ptr->getOpcode() == ISD::ADD);
15171 isInc = false;
15172 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
15173 return true;
15174 } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
15175 isInc = Ptr->getOpcode() == ISD::ADD;
15176 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
15177 return true;
15179 return false;
15182 // Try to find a matching instruction based on s/zext, Alignment, Offset and
15183 // (in BE) type.
15184 Base = Ptr->getOperand(0);
15185 if (VT == MVT::v4i16) {
15186 if (Align >= 2 && IsInRange(RHSC, 0x80, 2))
15187 return true;
15188 } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
15189 if (IsInRange(RHSC, 0x80, 1))
15190 return true;
15191 } else if (Align >= 4 && (isLE || VT == MVT::v4i32 || VT == MVT::v4f32) &&
15192 IsInRange(RHSC, 0x80, 4))
15193 return true;
15194 else if (Align >= 2 && (isLE || VT == MVT::v8i16 || VT == MVT::v8f16) &&
15195 IsInRange(RHSC, 0x80, 2))
15196 return true;
15197 else if ((isLE || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
15198 return true;
15199 return false;
15202 /// getPreIndexedAddressParts - returns true by value, base pointer and
15203 /// offset pointer and addressing mode by reference if the node's address
15204 /// can be legally represented as pre-indexed load / store address.
15205 bool
15206 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
15207 SDValue &Offset,
15208 ISD::MemIndexedMode &AM,
15209 SelectionDAG &DAG) const {
15210 if (Subtarget->isThumb1Only())
15211 return false;
15213 EVT VT;
15214 SDValue Ptr;
15215 unsigned Align;
15216 bool isSEXTLoad = false;
15217 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
15218 Ptr = LD->getBasePtr();
15219 VT = LD->getMemoryVT();
15220 Align = LD->getAlignment();
15221 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
15222 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
15223 Ptr = ST->getBasePtr();
15224 VT = ST->getMemoryVT();
15225 Align = ST->getAlignment();
15226 } else
15227 return false;
15229 bool isInc;
15230 bool isLegal = false;
15231 if (VT.isVector())
15232 isLegal = Subtarget->hasMVEIntegerOps() &&
15233 getMVEIndexedAddressParts(Ptr.getNode(), VT, Align, isSEXTLoad,
15234 Subtarget->isLittle(), Base, Offset,
15235 isInc, DAG);
15236 else {
15237 if (Subtarget->isThumb2())
15238 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
15239 Offset, isInc, DAG);
15240 else
15241 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
15242 Offset, isInc, DAG);
15244 if (!isLegal)
15245 return false;
15247 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
15248 return true;
15251 /// getPostIndexedAddressParts - returns true by value, base pointer and
15252 /// offset pointer and addressing mode by reference if this node can be
15253 /// combined with a load / store to form a post-indexed load / store.
15254 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
15255 SDValue &Base,
15256 SDValue &Offset,
15257 ISD::MemIndexedMode &AM,
15258 SelectionDAG &DAG) const {
15259 EVT VT;
15260 SDValue Ptr;
15261 unsigned Align;
15262 bool isSEXTLoad = false, isNonExt;
15263 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
15264 VT = LD->getMemoryVT();
15265 Ptr = LD->getBasePtr();
15266 Align = LD->getAlignment();
15267 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
15268 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
15269 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
15270 VT = ST->getMemoryVT();
15271 Ptr = ST->getBasePtr();
15272 Align = ST->getAlignment();
15273 isNonExt = !ST->isTruncatingStore();
15274 } else
15275 return false;
15277 if (Subtarget->isThumb1Only()) {
15278 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
15279 // must be non-extending/truncating, i32, with an offset of 4.
15280 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
15281 if (Op->getOpcode() != ISD::ADD || !isNonExt)
15282 return false;
15283 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15284 if (!RHS || RHS->getZExtValue() != 4)
15285 return false;
15287 Offset = Op->getOperand(1);
15288 Base = Op->getOperand(0);
15289 AM = ISD::POST_INC;
15290 return true;
15293 bool isInc;
15294 bool isLegal = false;
15295 if (VT.isVector())
15296 isLegal = Subtarget->hasMVEIntegerOps() &&
15297 getMVEIndexedAddressParts(Op, VT, Align, isSEXTLoad,
15298 Subtarget->isLittle(), Base, Offset,
15299 isInc, DAG);
15300 else {
15301 if (Subtarget->isThumb2())
15302 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
15303 isInc, DAG);
15304 else
15305 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
15306 isInc, DAG);
15308 if (!isLegal)
15309 return false;
15311 if (Ptr != Base) {
15312 // Swap base ptr and offset to catch more post-index load / store when
15313 // it's legal. In Thumb2 mode, offset must be an immediate.
15314 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
15315 !Subtarget->isThumb2())
15316 std::swap(Base, Offset);
15318 // Post-indexed load / store update the base pointer.
15319 if (Ptr != Base)
15320 return false;
15323 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
15324 return true;
15327 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15328 KnownBits &Known,
15329 const APInt &DemandedElts,
15330 const SelectionDAG &DAG,
15331 unsigned Depth) const {
15332 unsigned BitWidth = Known.getBitWidth();
15333 Known.resetAll();
15334 switch (Op.getOpcode()) {
15335 default: break;
15336 case ARMISD::ADDC:
15337 case ARMISD::ADDE:
15338 case ARMISD::SUBC:
15339 case ARMISD::SUBE:
15340 // Special cases when we convert a carry to a boolean.
15341 if (Op.getResNo() == 0) {
15342 SDValue LHS = Op.getOperand(0);
15343 SDValue RHS = Op.getOperand(1);
15344 // (ADDE 0, 0, C) will give us a single bit.
15345 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
15346 isNullConstant(RHS)) {
15347 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15348 return;
15351 break;
15352 case ARMISD::CMOV: {
15353 // Bits are known zero/one if known on the LHS and RHS.
15354 Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
15355 if (Known.isUnknown())
15356 return;
15358 KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
15359 Known.Zero &= KnownRHS.Zero;
15360 Known.One &= KnownRHS.One;
15361 return;
15363 case ISD::INTRINSIC_W_CHAIN: {
15364 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
15365 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
15366 switch (IntID) {
15367 default: return;
15368 case Intrinsic::arm_ldaex:
15369 case Intrinsic::arm_ldrex: {
15370 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
15371 unsigned MemBits = VT.getScalarSizeInBits();
15372 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
15373 return;
15377 case ARMISD::BFI: {
15378 // Conservatively, we can recurse down the first operand
15379 // and just mask out all affected bits.
15380 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
15382 // The operand to BFI is already a mask suitable for removing the bits it
15383 // sets.
15384 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
15385 const APInt &Mask = CI->getAPIntValue();
15386 Known.Zero &= Mask;
15387 Known.One &= Mask;
15388 return;
15390 case ARMISD::VGETLANEs:
15391 case ARMISD::VGETLANEu: {
15392 const SDValue &SrcSV = Op.getOperand(0);
15393 EVT VecVT = SrcSV.getValueType();
15394 assert(VecVT.isVector() && "VGETLANE expected a vector type");
15395 const unsigned NumSrcElts = VecVT.getVectorNumElements();
15396 ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
15397 assert(Pos->getAPIntValue().ult(NumSrcElts) &&
15398 "VGETLANE index out of bounds");
15399 unsigned Idx = Pos->getZExtValue();
15400 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
15401 Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
15403 EVT VT = Op.getValueType();
15404 const unsigned DstSz = VT.getScalarSizeInBits();
15405 const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
15406 (void)SrcSz;
15407 assert(SrcSz == Known.getBitWidth());
15408 assert(DstSz > SrcSz);
15409 if (Op.getOpcode() == ARMISD::VGETLANEs)
15410 Known = Known.sext(DstSz);
15411 else {
15412 Known = Known.zext(DstSz, true /* extended bits are known zero */);
15414 assert(DstSz == Known.getBitWidth());
15415 break;
15420 bool
15421 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
15422 const APInt &DemandedAPInt,
15423 TargetLoweringOpt &TLO) const {
15424 // Delay optimization, so we don't have to deal with illegal types, or block
15425 // optimizations.
15426 if (!TLO.LegalOps)
15427 return false;
15429 // Only optimize AND for now.
15430 if (Op.getOpcode() != ISD::AND)
15431 return false;
15433 EVT VT = Op.getValueType();
15435 // Ignore vectors.
15436 if (VT.isVector())
15437 return false;
15439 assert(VT == MVT::i32 && "Unexpected integer type");
15441 // Make sure the RHS really is a constant.
15442 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15443 if (!C)
15444 return false;
15446 unsigned Mask = C->getZExtValue();
15448 unsigned Demanded = DemandedAPInt.getZExtValue();
15449 unsigned ShrunkMask = Mask & Demanded;
15450 unsigned ExpandedMask = Mask | ~Demanded;
15452 // If the mask is all zeros, let the target-independent code replace the
15453 // result with zero.
15454 if (ShrunkMask == 0)
15455 return false;
15457 // If the mask is all ones, erase the AND. (Currently, the target-independent
15458 // code won't do this, so we have to do it explicitly to avoid an infinite
15459 // loop in obscure cases.)
15460 if (ExpandedMask == ~0U)
15461 return TLO.CombineTo(Op, Op.getOperand(0));
15463 auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
15464 return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
15466 auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
15467 if (NewMask == Mask)
15468 return true;
15469 SDLoc DL(Op);
15470 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
15471 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
15472 return TLO.CombineTo(Op, NewOp);
15475 // Prefer uxtb mask.
15476 if (IsLegalMask(0xFF))
15477 return UseMask(0xFF);
15479 // Prefer uxth mask.
15480 if (IsLegalMask(0xFFFF))
15481 return UseMask(0xFFFF);
15483 // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
15484 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15485 if (ShrunkMask < 256)
15486 return UseMask(ShrunkMask);
15488 // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
15489 // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15490 if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
15491 return UseMask(ExpandedMask);
15493 // Potential improvements:
15495 // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
15496 // We could try to prefer Thumb1 immediates which can be lowered to a
15497 // two-instruction sequence.
15498 // We could try to recognize more legal ARM/Thumb2 immediates here.
15500 return false;
15504 //===----------------------------------------------------------------------===//
15505 // ARM Inline Assembly Support
15506 //===----------------------------------------------------------------------===//
15508 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
15509 // Looking for "rev" which is V6+.
15510 if (!Subtarget->hasV6Ops())
15511 return false;
15513 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15514 std::string AsmStr = IA->getAsmString();
15515 SmallVector<StringRef, 4> AsmPieces;
15516 SplitString(AsmStr, AsmPieces, ";\n");
15518 switch (AsmPieces.size()) {
15519 default: return false;
15520 case 1:
15521 AsmStr = AsmPieces[0];
15522 AsmPieces.clear();
15523 SplitString(AsmStr, AsmPieces, " \t,");
15525 // rev $0, $1
15526 if (AsmPieces.size() == 3 &&
15527 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
15528 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
15529 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15530 if (Ty && Ty->getBitWidth() == 32)
15531 return IntrinsicLowering::LowerToByteSwap(CI);
15533 break;
15536 return false;
15539 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
15540 // At this point, we have to lower this constraint to something else, so we
15541 // lower it to an "r" or "w". However, by doing this we will force the result
15542 // to be in register, while the X constraint is much more permissive.
15544 // Although we are correct (we are free to emit anything, without
15545 // constraints), we might break use cases that would expect us to be more
15546 // efficient and emit something else.
15547 if (!Subtarget->hasVFP2Base())
15548 return "r";
15549 if (ConstraintVT.isFloatingPoint())
15550 return "w";
15551 if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
15552 (ConstraintVT.getSizeInBits() == 64 ||
15553 ConstraintVT.getSizeInBits() == 128))
15554 return "w";
15556 return "r";
15559 /// getConstraintType - Given a constraint letter, return the type of
15560 /// constraint it is for this target.
15561 ARMTargetLowering::ConstraintType
15562 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
15563 unsigned S = Constraint.size();
15564 if (S == 1) {
15565 switch (Constraint[0]) {
15566 default: break;
15567 case 'l': return C_RegisterClass;
15568 case 'w': return C_RegisterClass;
15569 case 'h': return C_RegisterClass;
15570 case 'x': return C_RegisterClass;
15571 case 't': return C_RegisterClass;
15572 case 'j': return C_Immediate; // Constant for movw.
15573 // An address with a single base register. Due to the way we
15574 // currently handle addresses it is the same as an 'r' memory constraint.
15575 case 'Q': return C_Memory;
15577 } else if (S == 2) {
15578 switch (Constraint[0]) {
15579 default: break;
15580 case 'T': return C_RegisterClass;
15581 // All 'U+' constraints are addresses.
15582 case 'U': return C_Memory;
15585 return TargetLowering::getConstraintType(Constraint);
15588 /// Examine constraint type and operand type and determine a weight value.
15589 /// This object must already have been set up with the operand type
15590 /// and the current alternative constraint selected.
15591 TargetLowering::ConstraintWeight
15592 ARMTargetLowering::getSingleConstraintMatchWeight(
15593 AsmOperandInfo &info, const char *constraint) const {
15594 ConstraintWeight weight = CW_Invalid;
15595 Value *CallOperandVal = info.CallOperandVal;
15596 // If we don't have a value, we can't do a match,
15597 // but allow it at the lowest weight.
15598 if (!CallOperandVal)
15599 return CW_Default;
15600 Type *type = CallOperandVal->getType();
15601 // Look at the constraint type.
15602 switch (*constraint) {
15603 default:
15604 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15605 break;
15606 case 'l':
15607 if (type->isIntegerTy()) {
15608 if (Subtarget->isThumb())
15609 weight = CW_SpecificReg;
15610 else
15611 weight = CW_Register;
15613 break;
15614 case 'w':
15615 if (type->isFloatingPointTy())
15616 weight = CW_Register;
15617 break;
15619 return weight;
15622 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
15624 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
15625 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
15626 switch (Constraint.size()) {
15627 case 1:
15628 // GCC ARM Constraint Letters
15629 switch (Constraint[0]) {
15630 case 'l': // Low regs or general regs.
15631 if (Subtarget->isThumb())
15632 return RCPair(0U, &ARM::tGPRRegClass);
15633 return RCPair(0U, &ARM::GPRRegClass);
15634 case 'h': // High regs or no regs.
15635 if (Subtarget->isThumb())
15636 return RCPair(0U, &ARM::hGPRRegClass);
15637 break;
15638 case 'r':
15639 if (Subtarget->isThumb1Only())
15640 return RCPair(0U, &ARM::tGPRRegClass);
15641 return RCPair(0U, &ARM::GPRRegClass);
15642 case 'w':
15643 if (VT == MVT::Other)
15644 break;
15645 if (VT == MVT::f32)
15646 return RCPair(0U, &ARM::SPRRegClass);
15647 if (VT.getSizeInBits() == 64)
15648 return RCPair(0U, &ARM::DPRRegClass);
15649 if (VT.getSizeInBits() == 128)
15650 return RCPair(0U, &ARM::QPRRegClass);
15651 break;
15652 case 'x':
15653 if (VT == MVT::Other)
15654 break;
15655 if (VT == MVT::f32)
15656 return RCPair(0U, &ARM::SPR_8RegClass);
15657 if (VT.getSizeInBits() == 64)
15658 return RCPair(0U, &ARM::DPR_8RegClass);
15659 if (VT.getSizeInBits() == 128)
15660 return RCPair(0U, &ARM::QPR_8RegClass);
15661 break;
15662 case 't':
15663 if (VT == MVT::Other)
15664 break;
15665 if (VT == MVT::f32 || VT == MVT::i32)
15666 return RCPair(0U, &ARM::SPRRegClass);
15667 if (VT.getSizeInBits() == 64)
15668 return RCPair(0U, &ARM::DPR_VFP2RegClass);
15669 if (VT.getSizeInBits() == 128)
15670 return RCPair(0U, &ARM::QPR_VFP2RegClass);
15671 break;
15673 break;
15675 case 2:
15676 if (Constraint[0] == 'T') {
15677 switch (Constraint[1]) {
15678 default:
15679 break;
15680 case 'e':
15681 return RCPair(0U, &ARM::tGPREvenRegClass);
15682 case 'o':
15683 return RCPair(0U, &ARM::tGPROddRegClass);
15686 break;
15688 default:
15689 break;
15692 if (StringRef("{cc}").equals_lower(Constraint))
15693 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
15695 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15698 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15699 /// vector. If it is invalid, don't add anything to Ops.
15700 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15701 std::string &Constraint,
15702 std::vector<SDValue>&Ops,
15703 SelectionDAG &DAG) const {
15704 SDValue Result;
15706 // Currently only support length 1 constraints.
15707 if (Constraint.length() != 1) return;
15709 char ConstraintLetter = Constraint[0];
15710 switch (ConstraintLetter) {
15711 default: break;
15712 case 'j':
15713 case 'I': case 'J': case 'K': case 'L':
15714 case 'M': case 'N': case 'O':
15715 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
15716 if (!C)
15717 return;
15719 int64_t CVal64 = C->getSExtValue();
15720 int CVal = (int) CVal64;
15721 // None of these constraints allow values larger than 32 bits. Check
15722 // that the value fits in an int.
15723 if (CVal != CVal64)
15724 return;
15726 switch (ConstraintLetter) {
15727 case 'j':
15728 // Constant suitable for movw, must be between 0 and
15729 // 65535.
15730 if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
15731 if (CVal >= 0 && CVal <= 65535)
15732 break;
15733 return;
15734 case 'I':
15735 if (Subtarget->isThumb1Only()) {
15736 // This must be a constant between 0 and 255, for ADD
15737 // immediates.
15738 if (CVal >= 0 && CVal <= 255)
15739 break;
15740 } else if (Subtarget->isThumb2()) {
15741 // A constant that can be used as an immediate value in a
15742 // data-processing instruction.
15743 if (ARM_AM::getT2SOImmVal(CVal) != -1)
15744 break;
15745 } else {
15746 // A constant that can be used as an immediate value in a
15747 // data-processing instruction.
15748 if (ARM_AM::getSOImmVal(CVal) != -1)
15749 break;
15751 return;
15753 case 'J':
15754 if (Subtarget->isThumb1Only()) {
15755 // This must be a constant between -255 and -1, for negated ADD
15756 // immediates. This can be used in GCC with an "n" modifier that
15757 // prints the negated value, for use with SUB instructions. It is
15758 // not useful otherwise but is implemented for compatibility.
15759 if (CVal >= -255 && CVal <= -1)
15760 break;
15761 } else {
15762 // This must be a constant between -4095 and 4095. It is not clear
15763 // what this constraint is intended for. Implemented for
15764 // compatibility with GCC.
15765 if (CVal >= -4095 && CVal <= 4095)
15766 break;
15768 return;
15770 case 'K':
15771 if (Subtarget->isThumb1Only()) {
15772 // A 32-bit value where only one byte has a nonzero value. Exclude
15773 // zero to match GCC. This constraint is used by GCC internally for
15774 // constants that can be loaded with a move/shift combination.
15775 // It is not useful otherwise but is implemented for compatibility.
15776 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
15777 break;
15778 } else if (Subtarget->isThumb2()) {
15779 // A constant whose bitwise inverse can be used as an immediate
15780 // value in a data-processing instruction. This can be used in GCC
15781 // with a "B" modifier that prints the inverted value, for use with
15782 // BIC and MVN instructions. It is not useful otherwise but is
15783 // implemented for compatibility.
15784 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
15785 break;
15786 } else {
15787 // A constant whose bitwise inverse can be used as an immediate
15788 // value in a data-processing instruction. This can be used in GCC
15789 // with a "B" modifier that prints the inverted value, for use with
15790 // BIC and MVN instructions. It is not useful otherwise but is
15791 // implemented for compatibility.
15792 if (ARM_AM::getSOImmVal(~CVal) != -1)
15793 break;
15795 return;
15797 case 'L':
15798 if (Subtarget->isThumb1Only()) {
15799 // This must be a constant between -7 and 7,
15800 // for 3-operand ADD/SUB immediate instructions.
15801 if (CVal >= -7 && CVal < 7)
15802 break;
15803 } else if (Subtarget->isThumb2()) {
15804 // A constant whose negation can be used as an immediate value in a
15805 // data-processing instruction. This can be used in GCC with an "n"
15806 // modifier that prints the negated value, for use with SUB
15807 // instructions. It is not useful otherwise but is implemented for
15808 // compatibility.
15809 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
15810 break;
15811 } else {
15812 // A constant whose negation can be used as an immediate value in a
15813 // data-processing instruction. This can be used in GCC with an "n"
15814 // modifier that prints the negated value, for use with SUB
15815 // instructions. It is not useful otherwise but is implemented for
15816 // compatibility.
15817 if (ARM_AM::getSOImmVal(-CVal) != -1)
15818 break;
15820 return;
15822 case 'M':
15823 if (Subtarget->isThumb1Only()) {
15824 // This must be a multiple of 4 between 0 and 1020, for
15825 // ADD sp + immediate.
15826 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
15827 break;
15828 } else {
15829 // A power of two or a constant between 0 and 32. This is used in
15830 // GCC for the shift amount on shifted register operands, but it is
15831 // useful in general for any shift amounts.
15832 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
15833 break;
15835 return;
15837 case 'N':
15838 if (Subtarget->isThumb1Only()) {
15839 // This must be a constant between 0 and 31, for shift amounts.
15840 if (CVal >= 0 && CVal <= 31)
15841 break;
15843 return;
15845 case 'O':
15846 if (Subtarget->isThumb1Only()) {
15847 // This must be a multiple of 4 between -508 and 508, for
15848 // ADD/SUB sp = sp + immediate.
15849 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
15850 break;
15852 return;
15854 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
15855 break;
15858 if (Result.getNode()) {
15859 Ops.push_back(Result);
15860 return;
15862 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15865 static RTLIB::Libcall getDivRemLibcall(
15866 const SDNode *N, MVT::SimpleValueType SVT) {
15867 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15868 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15869 "Unhandled Opcode in getDivRemLibcall");
15870 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15871 N->getOpcode() == ISD::SREM;
15872 RTLIB::Libcall LC;
15873 switch (SVT) {
15874 default: llvm_unreachable("Unexpected request for libcall!");
15875 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
15876 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
15877 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
15878 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
15880 return LC;
15883 static TargetLowering::ArgListTy getDivRemArgList(
15884 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
15885 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
15886 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
15887 "Unhandled Opcode in getDivRemArgList");
15888 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
15889 N->getOpcode() == ISD::SREM;
15890 TargetLowering::ArgListTy Args;
15891 TargetLowering::ArgListEntry Entry;
15892 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
15893 EVT ArgVT = N->getOperand(i).getValueType();
15894 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
15895 Entry.Node = N->getOperand(i);
15896 Entry.Ty = ArgTy;
15897 Entry.IsSExt = isSigned;
15898 Entry.IsZExt = !isSigned;
15899 Args.push_back(Entry);
15901 if (Subtarget->isTargetWindows() && Args.size() >= 2)
15902 std::swap(Args[0], Args[1]);
15903 return Args;
15906 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
15907 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
15908 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
15909 Subtarget->isTargetWindows()) &&
15910 "Register-based DivRem lowering only");
15911 unsigned Opcode = Op->getOpcode();
15912 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
15913 "Invalid opcode for Div/Rem lowering");
15914 bool isSigned = (Opcode == ISD::SDIVREM);
15915 EVT VT = Op->getValueType(0);
15916 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
15917 SDLoc dl(Op);
15919 // If the target has hardware divide, use divide + multiply + subtract:
15920 // div = a / b
15921 // rem = a - b * div
15922 // return {div, rem}
15923 // This should be lowered into UDIV/SDIV + MLS later on.
15924 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
15925 : Subtarget->hasDivideInARMMode();
15926 if (hasDivide && Op->getValueType(0).isSimple() &&
15927 Op->getSimpleValueType(0) == MVT::i32) {
15928 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
15929 const SDValue Dividend = Op->getOperand(0);
15930 const SDValue Divisor = Op->getOperand(1);
15931 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
15932 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
15933 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
15935 SDValue Values[2] = {Div, Rem};
15936 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
15939 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
15940 VT.getSimpleVT().SimpleTy);
15941 SDValue InChain = DAG.getEntryNode();
15943 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
15944 DAG.getContext(),
15945 Subtarget);
15947 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15948 getPointerTy(DAG.getDataLayout()));
15950 Type *RetTy = StructType::get(Ty, Ty);
15952 if (Subtarget->isTargetWindows())
15953 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
15955 TargetLowering::CallLoweringInfo CLI(DAG);
15956 CLI.setDebugLoc(dl).setChain(InChain)
15957 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
15958 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15960 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15961 return CallInfo.first;
15964 // Lowers REM using divmod helpers
15965 // see RTABI section 4.2/4.3
15966 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
15967 // Build return types (div and rem)
15968 std::vector<Type*> RetTyParams;
15969 Type *RetTyElement;
15971 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
15972 default: llvm_unreachable("Unexpected request for libcall!");
15973 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
15974 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
15975 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
15976 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
15979 RetTyParams.push_back(RetTyElement);
15980 RetTyParams.push_back(RetTyElement);
15981 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
15982 Type *RetTy = StructType::get(*DAG.getContext(), ret);
15984 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
15985 SimpleTy);
15986 SDValue InChain = DAG.getEntryNode();
15987 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
15988 Subtarget);
15989 bool isSigned = N->getOpcode() == ISD::SREM;
15990 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15991 getPointerTy(DAG.getDataLayout()));
15993 if (Subtarget->isTargetWindows())
15994 InChain = WinDBZCheckDenominator(DAG, N, InChain);
15996 // Lower call
15997 CallLoweringInfo CLI(DAG);
15998 CLI.setChain(InChain)
15999 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
16000 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
16001 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
16003 // Return second (rem) result operand (first contains div)
16004 SDNode *ResNode = CallResult.first.getNode();
16005 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
16006 return ResNode->getOperand(1);
16009 SDValue
16010 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
16011 assert(Subtarget->isTargetWindows() && "unsupported target platform");
16012 SDLoc DL(Op);
16014 // Get the inputs.
16015 SDValue Chain = Op.getOperand(0);
16016 SDValue Size = Op.getOperand(1);
16018 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
16019 "no-stack-arg-probe")) {
16020 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
16021 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
16022 Chain = SP.getValue(1);
16023 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
16024 if (Align)
16025 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
16026 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
16027 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
16028 SDValue Ops[2] = { SP, Chain };
16029 return DAG.getMergeValues(Ops, DL);
16032 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
16033 DAG.getConstant(2, DL, MVT::i32));
16035 SDValue Flag;
16036 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
16037 Flag = Chain.getValue(1);
16039 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16040 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
16042 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
16043 Chain = NewSP.getValue(1);
16045 SDValue Ops[2] = { NewSP, Chain };
16046 return DAG.getMergeValues(Ops, DL);
16049 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
16050 SDValue SrcVal = Op.getOperand(0);
16051 const unsigned DstSz = Op.getValueType().getSizeInBits();
16052 const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
16053 assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
16054 "Unexpected type for custom-lowering FP_EXTEND");
16056 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
16057 "With both FP DP and 16, any FP conversion is legal!");
16059 assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
16060 "With FP16, 16 to 32 conversion is legal!");
16062 // Either we are converting from 16 -> 64, without FP16 and/or
16063 // FP.double-precision or without Armv8-fp. So we must do it in two
16064 // steps.
16065 // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
16066 // without FP16. So we must do a function call.
16067 SDLoc Loc(Op);
16068 RTLIB::Libcall LC;
16069 MakeLibCallOptions CallOptions;
16070 if (SrcSz == 16) {
16071 // Instruction from 16 -> 32
16072 if (Subtarget->hasFP16())
16073 SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f32, SrcVal);
16074 // Lib call from 16 -> 32
16075 else {
16076 LC = RTLIB::getFPEXT(MVT::f16, MVT::f32);
16077 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
16078 "Unexpected type for custom-lowering FP_EXTEND");
16079 SrcVal =
16080 makeLibCall(DAG, LC, MVT::f32, SrcVal, CallOptions, Loc).first;
16084 if (DstSz != 64)
16085 return SrcVal;
16086 // For sure now SrcVal is 32 bits
16087 if (Subtarget->hasFP64()) // Instruction from 32 -> 64
16088 return DAG.getNode(ISD::FP_EXTEND, Loc, MVT::f64, SrcVal);
16090 LC = RTLIB::getFPEXT(MVT::f32, MVT::f64);
16091 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
16092 "Unexpected type for custom-lowering FP_EXTEND");
16093 return makeLibCall(DAG, LC, MVT::f64, SrcVal, CallOptions, Loc).first;
16096 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
16097 SDValue SrcVal = Op.getOperand(0);
16098 EVT SrcVT = SrcVal.getValueType();
16099 EVT DstVT = Op.getValueType();
16100 const unsigned DstSz = Op.getValueType().getSizeInBits();
16101 const unsigned SrcSz = SrcVT.getSizeInBits();
16102 (void)DstSz;
16103 assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
16104 "Unexpected type for custom-lowering FP_ROUND");
16106 assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
16107 "With both FP DP and 16, any FP conversion is legal!");
16109 SDLoc Loc(Op);
16111 // Instruction from 32 -> 16 if hasFP16 is valid
16112 if (SrcSz == 32 && Subtarget->hasFP16())
16113 return Op;
16115 // Lib call from 32 -> 16 / 64 -> [32, 16]
16116 RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
16117 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
16118 "Unexpected type for custom-lowering FP_ROUND");
16119 MakeLibCallOptions CallOptions;
16120 return makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions, Loc).first;
16123 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
16124 SelectionDAG &DAG) const {
16125 assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
16126 MVT HalfT = MVT::i32;
16127 SDLoc dl(N);
16128 SDValue Hi, Lo, Tmp;
16130 if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
16131 !isOperationLegalOrCustom(ISD::UADDO, HalfT))
16132 return ;
16134 unsigned OpTypeBits = HalfT.getScalarSizeInBits();
16135 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
16137 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
16138 DAG.getConstant(0, dl, HalfT));
16139 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
16140 DAG.getConstant(1, dl, HalfT));
16142 Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
16143 DAG.getConstant(OpTypeBits - 1, dl,
16144 getShiftAmountTy(HalfT, DAG.getDataLayout())));
16145 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
16146 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
16147 SDValue(Lo.getNode(), 1));
16148 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
16149 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
16151 Results.push_back(Lo);
16152 Results.push_back(Hi);
16155 bool
16156 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16157 // The ARM target isn't yet aware of offsets.
16158 return false;
16161 bool ARM::isBitFieldInvertedMask(unsigned v) {
16162 if (v == 0xffffffff)
16163 return false;
16165 // there can be 1's on either or both "outsides", all the "inside"
16166 // bits must be 0's
16167 return isShiftedMask_32(~v);
16170 /// isFPImmLegal - Returns true if the target can instruction select the
16171 /// specified FP immediate natively. If false, the legalizer will
16172 /// materialize the FP immediate as a load from a constant pool.
16173 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16174 bool ForCodeSize) const {
16175 if (!Subtarget->hasVFP3Base())
16176 return false;
16177 if (VT == MVT::f16 && Subtarget->hasFullFP16())
16178 return ARM_AM::getFP16Imm(Imm) != -1;
16179 if (VT == MVT::f32)
16180 return ARM_AM::getFP32Imm(Imm) != -1;
16181 if (VT == MVT::f64 && Subtarget->hasFP64())
16182 return ARM_AM::getFP64Imm(Imm) != -1;
16183 return false;
16186 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
16187 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
16188 /// specified in the intrinsic calls.
16189 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16190 const CallInst &I,
16191 MachineFunction &MF,
16192 unsigned Intrinsic) const {
16193 switch (Intrinsic) {
16194 case Intrinsic::arm_neon_vld1:
16195 case Intrinsic::arm_neon_vld2:
16196 case Intrinsic::arm_neon_vld3:
16197 case Intrinsic::arm_neon_vld4:
16198 case Intrinsic::arm_neon_vld2lane:
16199 case Intrinsic::arm_neon_vld3lane:
16200 case Intrinsic::arm_neon_vld4lane:
16201 case Intrinsic::arm_neon_vld2dup:
16202 case Intrinsic::arm_neon_vld3dup:
16203 case Intrinsic::arm_neon_vld4dup: {
16204 Info.opc = ISD::INTRINSIC_W_CHAIN;
16205 // Conservatively set memVT to the entire set of vectors loaded.
16206 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16207 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
16208 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
16209 Info.ptrVal = I.getArgOperand(0);
16210 Info.offset = 0;
16211 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
16212 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
16213 // volatile loads with NEON intrinsics not supported
16214 Info.flags = MachineMemOperand::MOLoad;
16215 return true;
16217 case Intrinsic::arm_neon_vld1x2:
16218 case Intrinsic::arm_neon_vld1x3:
16219 case Intrinsic::arm_neon_vld1x4: {
16220 Info.opc = ISD::INTRINSIC_W_CHAIN;
16221 // Conservatively set memVT to the entire set of vectors loaded.
16222 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16223 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
16224 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
16225 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
16226 Info.offset = 0;
16227 Info.align.reset();
16228 // volatile loads with NEON intrinsics not supported
16229 Info.flags = MachineMemOperand::MOLoad;
16230 return true;
16232 case Intrinsic::arm_neon_vst1:
16233 case Intrinsic::arm_neon_vst2:
16234 case Intrinsic::arm_neon_vst3:
16235 case Intrinsic::arm_neon_vst4:
16236 case Intrinsic::arm_neon_vst2lane:
16237 case Intrinsic::arm_neon_vst3lane:
16238 case Intrinsic::arm_neon_vst4lane: {
16239 Info.opc = ISD::INTRINSIC_VOID;
16240 // Conservatively set memVT to the entire set of vectors stored.
16241 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16242 unsigned NumElts = 0;
16243 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
16244 Type *ArgTy = I.getArgOperand(ArgI)->getType();
16245 if (!ArgTy->isVectorTy())
16246 break;
16247 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
16249 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
16250 Info.ptrVal = I.getArgOperand(0);
16251 Info.offset = 0;
16252 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
16253 Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
16254 // volatile stores with NEON intrinsics not supported
16255 Info.flags = MachineMemOperand::MOStore;
16256 return true;
16258 case Intrinsic::arm_neon_vst1x2:
16259 case Intrinsic::arm_neon_vst1x3:
16260 case Intrinsic::arm_neon_vst1x4: {
16261 Info.opc = ISD::INTRINSIC_VOID;
16262 // Conservatively set memVT to the entire set of vectors stored.
16263 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16264 unsigned NumElts = 0;
16265 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
16266 Type *ArgTy = I.getArgOperand(ArgI)->getType();
16267 if (!ArgTy->isVectorTy())
16268 break;
16269 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
16271 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
16272 Info.ptrVal = I.getArgOperand(0);
16273 Info.offset = 0;
16274 Info.align.reset();
16275 // volatile stores with NEON intrinsics not supported
16276 Info.flags = MachineMemOperand::MOStore;
16277 return true;
16279 case Intrinsic::arm_ldaex:
16280 case Intrinsic::arm_ldrex: {
16281 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16282 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
16283 Info.opc = ISD::INTRINSIC_W_CHAIN;
16284 Info.memVT = MVT::getVT(PtrTy->getElementType());
16285 Info.ptrVal = I.getArgOperand(0);
16286 Info.offset = 0;
16287 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
16288 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16289 return true;
16291 case Intrinsic::arm_stlex:
16292 case Intrinsic::arm_strex: {
16293 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16294 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
16295 Info.opc = ISD::INTRINSIC_W_CHAIN;
16296 Info.memVT = MVT::getVT(PtrTy->getElementType());
16297 Info.ptrVal = I.getArgOperand(1);
16298 Info.offset = 0;
16299 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
16300 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16301 return true;
16303 case Intrinsic::arm_stlexd:
16304 case Intrinsic::arm_strexd:
16305 Info.opc = ISD::INTRINSIC_W_CHAIN;
16306 Info.memVT = MVT::i64;
16307 Info.ptrVal = I.getArgOperand(2);
16308 Info.offset = 0;
16309 Info.align = Align(8);
16310 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16311 return true;
16313 case Intrinsic::arm_ldaexd:
16314 case Intrinsic::arm_ldrexd:
16315 Info.opc = ISD::INTRINSIC_W_CHAIN;
16316 Info.memVT = MVT::i64;
16317 Info.ptrVal = I.getArgOperand(0);
16318 Info.offset = 0;
16319 Info.align = Align(8);
16320 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16321 return true;
16323 default:
16324 break;
16327 return false;
16330 /// Returns true if it is beneficial to convert a load of a constant
16331 /// to just the constant itself.
16332 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16333 Type *Ty) const {
16334 assert(Ty->isIntegerTy());
16336 unsigned Bits = Ty->getPrimitiveSizeInBits();
16337 if (Bits == 0 || Bits > 32)
16338 return false;
16339 return true;
16342 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
16343 unsigned Index) const {
16344 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
16345 return false;
16347 return (Index == 0 || Index == ResVT.getVectorNumElements());
16350 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
16351 ARM_MB::MemBOpt Domain) const {
16352 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16354 // First, if the target has no DMB, see what fallback we can use.
16355 if (!Subtarget->hasDataBarrier()) {
16356 // Some ARMv6 cpus can support data barriers with an mcr instruction.
16357 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
16358 // here.
16359 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
16360 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
16361 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
16362 Builder.getInt32(0), Builder.getInt32(7),
16363 Builder.getInt32(10), Builder.getInt32(5)};
16364 return Builder.CreateCall(MCR, args);
16365 } else {
16366 // Instead of using barriers, atomic accesses on these subtargets use
16367 // libcalls.
16368 llvm_unreachable("makeDMB on a target so old that it has no barriers");
16370 } else {
16371 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
16372 // Only a full system barrier exists in the M-class architectures.
16373 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
16374 Constant *CDomain = Builder.getInt32(Domain);
16375 return Builder.CreateCall(DMB, CDomain);
16379 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
16380 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
16381 Instruction *Inst,
16382 AtomicOrdering Ord) const {
16383 switch (Ord) {
16384 case AtomicOrdering::NotAtomic:
16385 case AtomicOrdering::Unordered:
16386 llvm_unreachable("Invalid fence: unordered/non-atomic");
16387 case AtomicOrdering::Monotonic:
16388 case AtomicOrdering::Acquire:
16389 return nullptr; // Nothing to do
16390 case AtomicOrdering::SequentiallyConsistent:
16391 if (!Inst->hasAtomicStore())
16392 return nullptr; // Nothing to do
16393 LLVM_FALLTHROUGH;
16394 case AtomicOrdering::Release:
16395 case AtomicOrdering::AcquireRelease:
16396 if (Subtarget->preferISHSTBarriers())
16397 return makeDMB(Builder, ARM_MB::ISHST);
16398 // FIXME: add a comment with a link to documentation justifying this.
16399 else
16400 return makeDMB(Builder, ARM_MB::ISH);
16402 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
16405 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
16406 Instruction *Inst,
16407 AtomicOrdering Ord) const {
16408 switch (Ord) {
16409 case AtomicOrdering::NotAtomic:
16410 case AtomicOrdering::Unordered:
16411 llvm_unreachable("Invalid fence: unordered/not-atomic");
16412 case AtomicOrdering::Monotonic:
16413 case AtomicOrdering::Release:
16414 return nullptr; // Nothing to do
16415 case AtomicOrdering::Acquire:
16416 case AtomicOrdering::AcquireRelease:
16417 case AtomicOrdering::SequentiallyConsistent:
16418 return makeDMB(Builder, ARM_MB::ISH);
16420 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
16423 // Loads and stores less than 64-bits are already atomic; ones above that
16424 // are doomed anyway, so defer to the default libcall and blame the OS when
16425 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
16426 // anything for those.
16427 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16428 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
16429 return (Size == 64) && !Subtarget->isMClass();
16432 // Loads and stores less than 64-bits are already atomic; ones above that
16433 // are doomed anyway, so defer to the default libcall and blame the OS when
16434 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
16435 // anything for those.
16436 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
16437 // guarantee, see DDI0406C ARM architecture reference manual,
16438 // sections A8.8.72-74 LDRD)
16439 TargetLowering::AtomicExpansionKind
16440 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16441 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
16442 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
16443 : AtomicExpansionKind::None;
16446 // For the real atomic operations, we have ldrex/strex up to 32 bits,
16447 // and up to 64 bits on the non-M profiles
16448 TargetLowering::AtomicExpansionKind
16449 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16450 if (AI->isFloatingPointOperation())
16451 return AtomicExpansionKind::CmpXChg;
16453 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
16454 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
16455 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
16456 ? AtomicExpansionKind::LLSC
16457 : AtomicExpansionKind::None;
16460 TargetLowering::AtomicExpansionKind
16461 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
16462 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
16463 // implement cmpxchg without spilling. If the address being exchanged is also
16464 // on the stack and close enough to the spill slot, this can lead to a
16465 // situation where the monitor always gets cleared and the atomic operation
16466 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
16467 bool HasAtomicCmpXchg =
16468 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
16469 if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
16470 return AtomicExpansionKind::LLSC;
16471 return AtomicExpansionKind::None;
16474 bool ARMTargetLowering::shouldInsertFencesForAtomic(
16475 const Instruction *I) const {
16476 return InsertFencesForAtomic;
16479 // This has so far only been implemented for MachO.
16480 bool ARMTargetLowering::useLoadStackGuardNode() const {
16481 return Subtarget->isTargetMachO();
16484 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
16485 if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16486 return TargetLowering::insertSSPDeclarations(M);
16488 // MSVC CRT has a global variable holding security cookie.
16489 M.getOrInsertGlobal("__security_cookie",
16490 Type::getInt8PtrTy(M.getContext()));
16492 // MSVC CRT has a function to validate security cookie.
16493 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
16494 "__security_check_cookie", Type::getVoidTy(M.getContext()),
16495 Type::getInt8PtrTy(M.getContext()));
16496 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
16497 F->addAttribute(1, Attribute::AttrKind::InReg);
16500 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
16501 // MSVC CRT has a global variable holding security cookie.
16502 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16503 return M.getGlobalVariable("__security_cookie");
16504 return TargetLowering::getSDagStackGuard(M);
16507 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
16508 // MSVC CRT has a function to validate security cookie.
16509 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16510 return M.getFunction("__security_check_cookie");
16511 return TargetLowering::getSSPStackGuardCheck(M);
16514 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
16515 unsigned &Cost) const {
16516 // If we do not have NEON, vector types are not natively supported.
16517 if (!Subtarget->hasNEON())
16518 return false;
16520 // Floating point values and vector values map to the same register file.
16521 // Therefore, although we could do a store extract of a vector type, this is
16522 // better to leave at float as we have more freedom in the addressing mode for
16523 // those.
16524 if (VectorTy->isFPOrFPVectorTy())
16525 return false;
16527 // If the index is unknown at compile time, this is very expensive to lower
16528 // and it is not possible to combine the store with the extract.
16529 if (!isa<ConstantInt>(Idx))
16530 return false;
16532 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
16533 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
16534 // We can do a store + vector extract on any vector that fits perfectly in a D
16535 // or Q register.
16536 if (BitWidth == 64 || BitWidth == 128) {
16537 Cost = 0;
16538 return true;
16540 return false;
16543 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
16544 return Subtarget->hasV6T2Ops();
16547 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
16548 return Subtarget->hasV6T2Ops();
16551 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
16552 return !Subtarget->hasMinSize();
16555 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
16556 AtomicOrdering Ord) const {
16557 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16558 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
16559 bool IsAcquire = isAcquireOrStronger(Ord);
16561 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
16562 // intrinsic must return {i32, i32} and we have to recombine them into a
16563 // single i64 here.
16564 if (ValTy->getPrimitiveSizeInBits() == 64) {
16565 Intrinsic::ID Int =
16566 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
16567 Function *Ldrex = Intrinsic::getDeclaration(M, Int);
16569 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16570 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
16572 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
16573 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
16574 if (!Subtarget->isLittle())
16575 std::swap (Lo, Hi);
16576 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
16577 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
16578 return Builder.CreateOr(
16579 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
16582 Type *Tys[] = { Addr->getType() };
16583 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
16584 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
16586 return Builder.CreateTruncOrBitCast(
16587 Builder.CreateCall(Ldrex, Addr),
16588 cast<PointerType>(Addr->getType())->getElementType());
16591 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
16592 IRBuilder<> &Builder) const {
16593 if (!Subtarget->hasV7Ops())
16594 return;
16595 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16596 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
16599 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
16600 Value *Addr,
16601 AtomicOrdering Ord) const {
16602 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16603 bool IsRelease = isReleaseOrStronger(Ord);
16605 // Since the intrinsics must have legal type, the i64 intrinsics take two
16606 // parameters: "i32, i32". We must marshal Val into the appropriate form
16607 // before the call.
16608 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
16609 Intrinsic::ID Int =
16610 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
16611 Function *Strex = Intrinsic::getDeclaration(M, Int);
16612 Type *Int32Ty = Type::getInt32Ty(M->getContext());
16614 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
16615 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
16616 if (!Subtarget->isLittle())
16617 std::swap(Lo, Hi);
16618 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16619 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
16622 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
16623 Type *Tys[] = { Addr->getType() };
16624 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
16626 return Builder.CreateCall(
16627 Strex, {Builder.CreateZExtOrBitCast(
16628 Val, Strex->getFunctionType()->getParamType(0)),
16629 Addr});
16633 bool ARMTargetLowering::alignLoopsWithOptSize() const {
16634 return Subtarget->isMClass();
16637 /// A helper function for determining the number of interleaved accesses we
16638 /// will generate when lowering accesses of the given type.
16639 unsigned
16640 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
16641 const DataLayout &DL) const {
16642 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
16645 bool ARMTargetLowering::isLegalInterleavedAccessType(
16646 VectorType *VecTy, const DataLayout &DL) const {
16648 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
16649 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
16651 // Ensure the vector doesn't have f16 elements. Even though we could do an
16652 // i16 vldN, we can't hold the f16 vectors and will end up converting via
16653 // f32.
16654 if (VecTy->getElementType()->isHalfTy())
16655 return false;
16657 // Ensure the number of vector elements is greater than 1.
16658 if (VecTy->getNumElements() < 2)
16659 return false;
16661 // Ensure the element type is legal.
16662 if (ElSize != 8 && ElSize != 16 && ElSize != 32)
16663 return false;
16665 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
16666 // 128 will be split into multiple interleaved accesses.
16667 return VecSize == 64 || VecSize % 128 == 0;
16670 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
16671 if (Subtarget->hasNEON())
16672 return 4;
16673 return TargetLoweringBase::getMaxSupportedInterleaveFactor();
16676 /// Lower an interleaved load into a vldN intrinsic.
16678 /// E.g. Lower an interleaved load (Factor = 2):
16679 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
16680 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
16681 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
16683 /// Into:
16684 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
16685 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
16686 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
16687 bool ARMTargetLowering::lowerInterleavedLoad(
16688 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
16689 ArrayRef<unsigned> Indices, unsigned Factor) const {
16690 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16691 "Invalid interleave factor");
16692 assert(!Shuffles.empty() && "Empty shufflevector input");
16693 assert(Shuffles.size() == Indices.size() &&
16694 "Unmatched number of shufflevectors and indices");
16696 VectorType *VecTy = Shuffles[0]->getType();
16697 Type *EltTy = VecTy->getVectorElementType();
16699 const DataLayout &DL = LI->getModule()->getDataLayout();
16701 // Skip if we do not have NEON and skip illegal vector types. We can
16702 // "legalize" wide vector types into multiple interleaved accesses as long as
16703 // the vector types are divisible by 128.
16704 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
16705 return false;
16707 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
16709 // A pointer vector can not be the return type of the ldN intrinsics. Need to
16710 // load integer vectors first and then convert to pointer vectors.
16711 if (EltTy->isPointerTy())
16712 VecTy =
16713 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
16715 IRBuilder<> Builder(LI);
16717 // The base address of the load.
16718 Value *BaseAddr = LI->getPointerOperand();
16720 if (NumLoads > 1) {
16721 // If we're going to generate more than one load, reset the sub-vector type
16722 // to something legal.
16723 VecTy = VectorType::get(VecTy->getVectorElementType(),
16724 VecTy->getVectorNumElements() / NumLoads);
16726 // We will compute the pointer operand of each load from the original base
16727 // address using GEPs. Cast the base address to a pointer to the scalar
16728 // element type.
16729 BaseAddr = Builder.CreateBitCast(
16730 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
16731 LI->getPointerAddressSpace()));
16734 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
16736 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
16737 Type *Tys[] = {VecTy, Int8Ptr};
16738 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
16739 Intrinsic::arm_neon_vld3,
16740 Intrinsic::arm_neon_vld4};
16741 Function *VldnFunc =
16742 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
16744 // Holds sub-vectors extracted from the load intrinsic return values. The
16745 // sub-vectors are associated with the shufflevector instructions they will
16746 // replace.
16747 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
16749 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
16750 // If we're generating more than one load, compute the base address of
16751 // subsequent loads as an offset from the previous.
16752 if (LoadCount > 0)
16753 BaseAddr =
16754 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
16755 VecTy->getVectorNumElements() * Factor);
16757 SmallVector<Value *, 2> Ops;
16758 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16759 Ops.push_back(Builder.getInt32(LI->getAlignment()));
16761 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
16763 // Replace uses of each shufflevector with the corresponding vector loaded
16764 // by ldN.
16765 for (unsigned i = 0; i < Shuffles.size(); i++) {
16766 ShuffleVectorInst *SV = Shuffles[i];
16767 unsigned Index = Indices[i];
16769 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
16771 // Convert the integer vector to pointer vector if the element is pointer.
16772 if (EltTy->isPointerTy())
16773 SubVec = Builder.CreateIntToPtr(
16774 SubVec, VectorType::get(SV->getType()->getVectorElementType(),
16775 VecTy->getVectorNumElements()));
16777 SubVecs[SV].push_back(SubVec);
16781 // Replace uses of the shufflevector instructions with the sub-vectors
16782 // returned by the load intrinsic. If a shufflevector instruction is
16783 // associated with more than one sub-vector, those sub-vectors will be
16784 // concatenated into a single wide vector.
16785 for (ShuffleVectorInst *SVI : Shuffles) {
16786 auto &SubVec = SubVecs[SVI];
16787 auto *WideVec =
16788 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
16789 SVI->replaceAllUsesWith(WideVec);
16792 return true;
16795 /// Lower an interleaved store into a vstN intrinsic.
16797 /// E.g. Lower an interleaved store (Factor = 3):
16798 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
16799 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
16800 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
16802 /// Into:
16803 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
16804 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
16805 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
16806 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16808 /// Note that the new shufflevectors will be removed and we'll only generate one
16809 /// vst3 instruction in CodeGen.
16811 /// Example for a more general valid mask (Factor 3). Lower:
16812 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
16813 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
16814 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
16816 /// Into:
16817 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
16818 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
16819 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
16820 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
16821 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
16822 ShuffleVectorInst *SVI,
16823 unsigned Factor) const {
16824 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16825 "Invalid interleave factor");
16827 VectorType *VecTy = SVI->getType();
16828 assert(VecTy->getVectorNumElements() % Factor == 0 &&
16829 "Invalid interleaved store");
16831 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
16832 Type *EltTy = VecTy->getVectorElementType();
16833 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
16835 const DataLayout &DL = SI->getModule()->getDataLayout();
16837 // Skip if we do not have NEON and skip illegal vector types. We can
16838 // "legalize" wide vector types into multiple interleaved accesses as long as
16839 // the vector types are divisible by 128.
16840 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
16841 return false;
16843 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
16845 Value *Op0 = SVI->getOperand(0);
16846 Value *Op1 = SVI->getOperand(1);
16847 IRBuilder<> Builder(SI);
16849 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
16850 // vectors to integer vectors.
16851 if (EltTy->isPointerTy()) {
16852 Type *IntTy = DL.getIntPtrType(EltTy);
16854 // Convert to the corresponding integer vector.
16855 Type *IntVecTy =
16856 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
16857 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
16858 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
16860 SubVecTy = VectorType::get(IntTy, LaneLen);
16863 // The base address of the store.
16864 Value *BaseAddr = SI->getPointerOperand();
16866 if (NumStores > 1) {
16867 // If we're going to generate more than one store, reset the lane length
16868 // and sub-vector type to something legal.
16869 LaneLen /= NumStores;
16870 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
16872 // We will compute the pointer operand of each store from the original base
16873 // address using GEPs. Cast the base address to a pointer to the scalar
16874 // element type.
16875 BaseAddr = Builder.CreateBitCast(
16876 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
16877 SI->getPointerAddressSpace()));
16880 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
16882 auto Mask = SVI->getShuffleMask();
16884 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
16885 Type *Tys[] = {Int8Ptr, SubVecTy};
16886 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
16887 Intrinsic::arm_neon_vst3,
16888 Intrinsic::arm_neon_vst4};
16890 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
16891 // If we generating more than one store, we compute the base address of
16892 // subsequent stores as an offset from the previous.
16893 if (StoreCount > 0)
16894 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
16895 BaseAddr, LaneLen * Factor);
16897 SmallVector<Value *, 6> Ops;
16898 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
16900 Function *VstNFunc =
16901 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
16903 // Split the shufflevector operands into sub vectors for the new vstN call.
16904 for (unsigned i = 0; i < Factor; i++) {
16905 unsigned IdxI = StoreCount * LaneLen * Factor + i;
16906 if (Mask[IdxI] >= 0) {
16907 Ops.push_back(Builder.CreateShuffleVector(
16908 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
16909 } else {
16910 unsigned StartMask = 0;
16911 for (unsigned j = 1; j < LaneLen; j++) {
16912 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
16913 if (Mask[IdxJ * Factor + IdxI] >= 0) {
16914 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
16915 break;
16918 // Note: If all elements in a chunk are undefs, StartMask=0!
16919 // Note: Filling undef gaps with random elements is ok, since
16920 // those elements were being written anyway (with undefs).
16921 // In the case of all undefs we're defaulting to using elems from 0
16922 // Note: StartMask cannot be negative, it's checked in
16923 // isReInterleaveMask
16924 Ops.push_back(Builder.CreateShuffleVector(
16925 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
16929 Ops.push_back(Builder.getInt32(SI->getAlignment()));
16930 Builder.CreateCall(VstNFunc, Ops);
16932 return true;
16935 enum HABaseType {
16936 HA_UNKNOWN = 0,
16937 HA_FLOAT,
16938 HA_DOUBLE,
16939 HA_VECT64,
16940 HA_VECT128
16943 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
16944 uint64_t &Members) {
16945 if (auto *ST = dyn_cast<StructType>(Ty)) {
16946 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
16947 uint64_t SubMembers = 0;
16948 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
16949 return false;
16950 Members += SubMembers;
16952 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
16953 uint64_t SubMembers = 0;
16954 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
16955 return false;
16956 Members += SubMembers * AT->getNumElements();
16957 } else if (Ty->isFloatTy()) {
16958 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
16959 return false;
16960 Members = 1;
16961 Base = HA_FLOAT;
16962 } else if (Ty->isDoubleTy()) {
16963 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
16964 return false;
16965 Members = 1;
16966 Base = HA_DOUBLE;
16967 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
16968 Members = 1;
16969 switch (Base) {
16970 case HA_FLOAT:
16971 case HA_DOUBLE:
16972 return false;
16973 case HA_VECT64:
16974 return VT->getBitWidth() == 64;
16975 case HA_VECT128:
16976 return VT->getBitWidth() == 128;
16977 case HA_UNKNOWN:
16978 switch (VT->getBitWidth()) {
16979 case 64:
16980 Base = HA_VECT64;
16981 return true;
16982 case 128:
16983 Base = HA_VECT128;
16984 return true;
16985 default:
16986 return false;
16991 return (Members > 0 && Members <= 4);
16994 /// Return the correct alignment for the current calling convention.
16995 unsigned
16996 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
16997 DataLayout DL) const {
16998 if (!ArgTy->isVectorTy())
16999 return DL.getABITypeAlignment(ArgTy);
17001 // Avoid over-aligning vector parameters. It would require realigning the
17002 // stack and waste space for no real benefit.
17003 return std::min(DL.getABITypeAlignment(ArgTy),
17004 (unsigned)DL.getStackAlignment().value());
17007 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
17008 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
17009 /// passing according to AAPCS rules.
17010 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
17011 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
17012 if (getEffectiveCallingConv(CallConv, isVarArg) !=
17013 CallingConv::ARM_AAPCS_VFP)
17014 return false;
17016 HABaseType Base = HA_UNKNOWN;
17017 uint64_t Members = 0;
17018 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
17019 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
17021 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
17022 return IsHA || IsIntArray;
17025 unsigned ARMTargetLowering::getExceptionPointerRegister(
17026 const Constant *PersonalityFn) const {
17027 // Platforms which do not use SjLj EH may return values in these registers
17028 // via the personality function.
17029 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
17032 unsigned ARMTargetLowering::getExceptionSelectorRegister(
17033 const Constant *PersonalityFn) const {
17034 // Platforms which do not use SjLj EH may return values in these registers
17035 // via the personality function.
17036 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
17039 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
17040 // Update IsSplitCSR in ARMFunctionInfo.
17041 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
17042 AFI->setIsSplitCSR(true);
17045 void ARMTargetLowering::insertCopiesSplitCSR(
17046 MachineBasicBlock *Entry,
17047 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
17048 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
17049 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
17050 if (!IStart)
17051 return;
17053 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17054 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
17055 MachineBasicBlock::iterator MBBI = Entry->begin();
17056 for (const MCPhysReg *I = IStart; *I; ++I) {
17057 const TargetRegisterClass *RC = nullptr;
17058 if (ARM::GPRRegClass.contains(*I))
17059 RC = &ARM::GPRRegClass;
17060 else if (ARM::DPRRegClass.contains(*I))
17061 RC = &ARM::DPRRegClass;
17062 else
17063 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
17065 Register NewVR = MRI->createVirtualRegister(RC);
17066 // Create copy from CSR to a virtual register.
17067 // FIXME: this currently does not emit CFI pseudo-instructions, it works
17068 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
17069 // nounwind. If we want to generalize this later, we may need to emit
17070 // CFI pseudo-instructions.
17071 assert(Entry->getParent()->getFunction().hasFnAttribute(
17072 Attribute::NoUnwind) &&
17073 "Function should be nounwind in insertCopiesSplitCSR!");
17074 Entry->addLiveIn(*I);
17075 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
17076 .addReg(*I);
17078 // Insert the copy-back instructions right before the terminator.
17079 for (auto *Exit : Exits)
17080 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
17081 TII->get(TargetOpcode::COPY), *I)
17082 .addReg(NewVR);
17086 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
17087 MF.getFrameInfo().computeMaxCallFrameSize(MF);
17088 TargetLoweringBase::finalizeLowering(MF);